CGStmtOpenMP.cpp 209 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997
  1. //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit OpenMP nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCleanup.h"
  14. #include "CGOpenMPRuntime.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenModule.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/Stmt.h"
  19. #include "clang/AST/StmtOpenMP.h"
  20. #include "clang/AST/DeclOpenMP.h"
  21. #include "llvm/IR/CallSite.h"
  22. using namespace clang;
  23. using namespace CodeGen;
  24. namespace {
  25. /// Lexical scope for OpenMP executable constructs, that handles correct codegen
  26. /// for captured expressions.
  27. class OMPLexicalScope : public CodeGenFunction::LexicalScope {
  28. void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  29. for (const auto *C : S.clauses()) {
  30. if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
  31. if (const auto *PreInit =
  32. cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
  33. for (const auto *I : PreInit->decls()) {
  34. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  35. CGF.EmitVarDecl(cast<VarDecl>(*I));
  36. } else {
  37. CodeGenFunction::AutoVarEmission Emission =
  38. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  39. CGF.EmitAutoVarCleanups(Emission);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. }
  46. CodeGenFunction::OMPPrivateScope InlinedShareds;
  47. static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
  48. return CGF.LambdaCaptureFields.lookup(VD) ||
  49. (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
  50. (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl));
  51. }
  52. public:
  53. OMPLexicalScope(
  54. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  55. const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None,
  56. const bool EmitPreInitStmt = true)
  57. : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
  58. InlinedShareds(CGF) {
  59. if (EmitPreInitStmt)
  60. emitPreInitStmt(CGF, S);
  61. if (!CapturedRegion.hasValue())
  62. return;
  63. assert(S.hasAssociatedStmt() &&
  64. "Expected associated statement for inlined directive.");
  65. const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion);
  66. for (const auto &C : CS->captures()) {
  67. if (C.capturesVariable() || C.capturesVariableByCopy()) {
  68. auto *VD = C.getCapturedVar();
  69. assert(VD == VD->getCanonicalDecl() &&
  70. "Canonical decl must be captured.");
  71. DeclRefExpr DRE(
  72. const_cast<VarDecl *>(VD),
  73. isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo &&
  74. InlinedShareds.isGlobalVarCaptured(VD)),
  75. VD->getType().getNonReferenceType(), VK_LValue, C.getLocation());
  76. InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
  77. return CGF.EmitLValue(&DRE).getAddress();
  78. });
  79. }
  80. }
  81. (void)InlinedShareds.Privatize();
  82. }
  83. };
  84. /// Lexical scope for OpenMP parallel construct, that handles correct codegen
  85. /// for captured expressions.
  86. class OMPParallelScope final : public OMPLexicalScope {
  87. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  88. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  89. return !(isOpenMPTargetExecutionDirective(Kind) ||
  90. isOpenMPLoopBoundSharingDirective(Kind)) &&
  91. isOpenMPParallelDirective(Kind);
  92. }
  93. public:
  94. OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  95. : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
  96. EmitPreInitStmt(S)) {}
  97. };
  98. /// Lexical scope for OpenMP teams construct, that handles correct codegen
  99. /// for captured expressions.
  100. class OMPTeamsScope final : public OMPLexicalScope {
  101. bool EmitPreInitStmt(const OMPExecutableDirective &S) {
  102. OpenMPDirectiveKind Kind = S.getDirectiveKind();
  103. return !isOpenMPTargetExecutionDirective(Kind) &&
  104. isOpenMPTeamsDirective(Kind);
  105. }
  106. public:
  107. OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  108. : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None,
  109. EmitPreInitStmt(S)) {}
  110. };
  111. /// Private scope for OpenMP loop-based directives, that supports capturing
  112. /// of used expression from loop statement.
  113. class OMPLoopScope : public CodeGenFunction::RunCleanupsScope {
  114. void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) {
  115. CodeGenFunction::OMPMapVars PreCondVars;
  116. for (const auto *E : S.counters()) {
  117. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  118. (void)PreCondVars.setVarAddr(
  119. CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType()));
  120. }
  121. (void)PreCondVars.apply(CGF);
  122. if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) {
  123. for (const auto *I : PreInits->decls())
  124. CGF.EmitVarDecl(cast<VarDecl>(*I));
  125. }
  126. PreCondVars.restore(CGF);
  127. }
  128. public:
  129. OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S)
  130. : CodeGenFunction::RunCleanupsScope(CGF) {
  131. emitPreInitStmt(CGF, S);
  132. }
  133. };
  134. class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
  135. CodeGenFunction::OMPPrivateScope InlinedShareds;
  136. static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) {
  137. return CGF.LambdaCaptureFields.lookup(VD) ||
  138. (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) ||
  139. (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) &&
  140. cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD));
  141. }
  142. public:
  143. OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S)
  144. : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()),
  145. InlinedShareds(CGF) {
  146. for (const auto *C : S.clauses()) {
  147. if (const auto *CPI = OMPClauseWithPreInit::get(C)) {
  148. if (const auto *PreInit =
  149. cast_or_null<DeclStmt>(CPI->getPreInitStmt())) {
  150. for (const auto *I : PreInit->decls()) {
  151. if (!I->hasAttr<OMPCaptureNoInitAttr>()) {
  152. CGF.EmitVarDecl(cast<VarDecl>(*I));
  153. } else {
  154. CodeGenFunction::AutoVarEmission Emission =
  155. CGF.EmitAutoVarAlloca(cast<VarDecl>(*I));
  156. CGF.EmitAutoVarCleanups(Emission);
  157. }
  158. }
  159. }
  160. } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) {
  161. for (const Expr *E : UDP->varlists()) {
  162. const Decl *D = cast<DeclRefExpr>(E)->getDecl();
  163. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D))
  164. CGF.EmitVarDecl(*OED);
  165. }
  166. }
  167. }
  168. if (!isOpenMPSimdDirective(S.getDirectiveKind()))
  169. CGF.EmitOMPPrivateClause(S, InlinedShareds);
  170. if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
  171. if (const Expr *E = TG->getReductionRef())
  172. CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()));
  173. }
  174. const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt());
  175. while (CS) {
  176. for (auto &C : CS->captures()) {
  177. if (C.capturesVariable() || C.capturesVariableByCopy()) {
  178. auto *VD = C.getCapturedVar();
  179. assert(VD == VD->getCanonicalDecl() &&
  180. "Canonical decl must be captured.");
  181. DeclRefExpr DRE(const_cast<VarDecl *>(VD),
  182. isCapturedVar(CGF, VD) ||
  183. (CGF.CapturedStmtInfo &&
  184. InlinedShareds.isGlobalVarCaptured(VD)),
  185. VD->getType().getNonReferenceType(), VK_LValue,
  186. C.getLocation());
  187. InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address {
  188. return CGF.EmitLValue(&DRE).getAddress();
  189. });
  190. }
  191. }
  192. CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt());
  193. }
  194. (void)InlinedShareds.Privatize();
  195. }
  196. };
  197. } // namespace
  198. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  199. const OMPExecutableDirective &S,
  200. const RegionCodeGenTy &CodeGen);
  201. LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) {
  202. if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) {
  203. if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) {
  204. OrigVD = OrigVD->getCanonicalDecl();
  205. bool IsCaptured =
  206. LambdaCaptureFields.lookup(OrigVD) ||
  207. (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) ||
  208. (CurCodeDecl && isa<BlockDecl>(CurCodeDecl));
  209. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD), IsCaptured,
  210. OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc());
  211. return EmitLValue(&DRE);
  212. }
  213. }
  214. return EmitLValue(E);
  215. }
  216. llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) {
  217. ASTContext &C = getContext();
  218. llvm::Value *Size = nullptr;
  219. auto SizeInChars = C.getTypeSizeInChars(Ty);
  220. if (SizeInChars.isZero()) {
  221. // getTypeSizeInChars() returns 0 for a VLA.
  222. while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) {
  223. VlaSizePair VlaSize = getVLASize(VAT);
  224. Ty = VlaSize.Type;
  225. Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts)
  226. : VlaSize.NumElts;
  227. }
  228. SizeInChars = C.getTypeSizeInChars(Ty);
  229. if (SizeInChars.isZero())
  230. return llvm::ConstantInt::get(SizeTy, /*V=*/0);
  231. return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars));
  232. }
  233. return CGM.getSize(SizeInChars);
  234. }
  235. void CodeGenFunction::GenerateOpenMPCapturedVars(
  236. const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) {
  237. const RecordDecl *RD = S.getCapturedRecordDecl();
  238. auto CurField = RD->field_begin();
  239. auto CurCap = S.captures().begin();
  240. for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
  241. E = S.capture_init_end();
  242. I != E; ++I, ++CurField, ++CurCap) {
  243. if (CurField->hasCapturedVLAType()) {
  244. const VariableArrayType *VAT = CurField->getCapturedVLAType();
  245. llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()];
  246. CapturedVars.push_back(Val);
  247. } else if (CurCap->capturesThis()) {
  248. CapturedVars.push_back(CXXThisValue);
  249. } else if (CurCap->capturesVariableByCopy()) {
  250. llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation());
  251. // If the field is not a pointer, we need to save the actual value
  252. // and load it as a void pointer.
  253. if (!CurField->getType()->isAnyPointerType()) {
  254. ASTContext &Ctx = getContext();
  255. Address DstAddr = CreateMemTemp(
  256. Ctx.getUIntPtrType(),
  257. Twine(CurCap->getCapturedVar()->getName(), ".casted"));
  258. LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
  259. llvm::Value *SrcAddrVal = EmitScalarConversion(
  260. DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
  261. Ctx.getPointerType(CurField->getType()), CurCap->getLocation());
  262. LValue SrcLV =
  263. MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType());
  264. // Store the value using the source type pointer.
  265. EmitStoreThroughLValue(RValue::get(CV), SrcLV);
  266. // Load the value using the destination type pointer.
  267. CV = EmitLoadOfScalar(DstLV, CurCap->getLocation());
  268. }
  269. CapturedVars.push_back(CV);
  270. } else {
  271. assert(CurCap->capturesVariable() && "Expected capture by reference.");
  272. CapturedVars.push_back(EmitLValue(*I).getAddress().getPointer());
  273. }
  274. }
  275. }
  276. static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc,
  277. QualType DstType, StringRef Name,
  278. LValue AddrLV,
  279. bool isReferenceType = false) {
  280. ASTContext &Ctx = CGF.getContext();
  281. llvm::Value *CastedPtr = CGF.EmitScalarConversion(
  282. AddrLV.getAddress().getPointer(), Ctx.getUIntPtrType(),
  283. Ctx.getPointerType(DstType), Loc);
  284. Address TmpAddr =
  285. CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType))
  286. .getAddress();
  287. // If we are dealing with references we need to return the address of the
  288. // reference instead of the reference of the value.
  289. if (isReferenceType) {
  290. QualType RefType = Ctx.getLValueReferenceType(DstType);
  291. llvm::Value *RefVal = TmpAddr.getPointer();
  292. TmpAddr = CGF.CreateMemTemp(RefType, Twine(Name, ".ref"));
  293. LValue TmpLVal = CGF.MakeAddrLValue(TmpAddr, RefType);
  294. CGF.EmitStoreThroughLValue(RValue::get(RefVal), TmpLVal, /*isInit=*/true);
  295. }
  296. return TmpAddr;
  297. }
  298. static QualType getCanonicalParamType(ASTContext &C, QualType T) {
  299. if (T->isLValueReferenceType())
  300. return C.getLValueReferenceType(
  301. getCanonicalParamType(C, T.getNonReferenceType()),
  302. /*SpelledAsLValue=*/false);
  303. if (T->isPointerType())
  304. return C.getPointerType(getCanonicalParamType(C, T->getPointeeType()));
  305. if (const ArrayType *A = T->getAsArrayTypeUnsafe()) {
  306. if (const auto *VLA = dyn_cast<VariableArrayType>(A))
  307. return getCanonicalParamType(C, VLA->getElementType());
  308. if (!A->isVariablyModifiedType())
  309. return C.getCanonicalType(T);
  310. }
  311. return C.getCanonicalParamType(T);
  312. }
  313. namespace {
  314. /// Contains required data for proper outlined function codegen.
  315. struct FunctionOptions {
  316. /// Captured statement for which the function is generated.
  317. const CapturedStmt *S = nullptr;
  318. /// true if cast to/from UIntPtr is required for variables captured by
  319. /// value.
  320. const bool UIntPtrCastRequired = true;
  321. /// true if only casted arguments must be registered as local args or VLA
  322. /// sizes.
  323. const bool RegisterCastedArgsOnly = false;
  324. /// Name of the generated function.
  325. const StringRef FunctionName;
  326. explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired,
  327. bool RegisterCastedArgsOnly,
  328. StringRef FunctionName)
  329. : S(S), UIntPtrCastRequired(UIntPtrCastRequired),
  330. RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly),
  331. FunctionName(FunctionName) {}
  332. };
  333. }
  334. static llvm::Function *emitOutlinedFunctionPrologue(
  335. CodeGenFunction &CGF, FunctionArgList &Args,
  336. llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>>
  337. &LocalAddrs,
  338. llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>>
  339. &VLASizes,
  340. llvm::Value *&CXXThisValue, const FunctionOptions &FO) {
  341. const CapturedDecl *CD = FO.S->getCapturedDecl();
  342. const RecordDecl *RD = FO.S->getCapturedRecordDecl();
  343. assert(CD->hasBody() && "missing CapturedDecl body");
  344. CXXThisValue = nullptr;
  345. // Build the argument list.
  346. CodeGenModule &CGM = CGF.CGM;
  347. ASTContext &Ctx = CGM.getContext();
  348. FunctionArgList TargetArgs;
  349. Args.append(CD->param_begin(),
  350. std::next(CD->param_begin(), CD->getContextParamPosition()));
  351. TargetArgs.append(
  352. CD->param_begin(),
  353. std::next(CD->param_begin(), CD->getContextParamPosition()));
  354. auto I = FO.S->captures().begin();
  355. FunctionDecl *DebugFunctionDecl = nullptr;
  356. if (!FO.UIntPtrCastRequired) {
  357. FunctionProtoType::ExtProtoInfo EPI;
  358. DebugFunctionDecl = FunctionDecl::Create(
  359. Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(),
  360. SourceLocation(), DeclarationName(), Ctx.VoidTy,
  361. Ctx.getTrivialTypeSourceInfo(
  362. Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI)),
  363. SC_Static, /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false);
  364. }
  365. for (const FieldDecl *FD : RD->fields()) {
  366. QualType ArgType = FD->getType();
  367. IdentifierInfo *II = nullptr;
  368. VarDecl *CapVar = nullptr;
  369. // If this is a capture by copy and the type is not a pointer, the outlined
  370. // function argument type should be uintptr and the value properly casted to
  371. // uintptr. This is necessary given that the runtime library is only able to
  372. // deal with pointers. We can pass in the same way the VLA type sizes to the
  373. // outlined function.
  374. if (FO.UIntPtrCastRequired &&
  375. ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) ||
  376. I->capturesVariableArrayType()))
  377. ArgType = Ctx.getUIntPtrType();
  378. if (I->capturesVariable() || I->capturesVariableByCopy()) {
  379. CapVar = I->getCapturedVar();
  380. II = CapVar->getIdentifier();
  381. } else if (I->capturesThis()) {
  382. II = &Ctx.Idents.get("this");
  383. } else {
  384. assert(I->capturesVariableArrayType());
  385. II = &Ctx.Idents.get("vla");
  386. }
  387. if (ArgType->isVariablyModifiedType())
  388. ArgType = getCanonicalParamType(Ctx, ArgType);
  389. VarDecl *Arg;
  390. if (DebugFunctionDecl && (CapVar || I->capturesThis())) {
  391. Arg = ParmVarDecl::Create(
  392. Ctx, DebugFunctionDecl,
  393. CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(),
  394. CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType,
  395. /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
  396. } else {
  397. Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(),
  398. II, ArgType, ImplicitParamDecl::Other);
  399. }
  400. Args.emplace_back(Arg);
  401. // Do not cast arguments if we emit function with non-original types.
  402. TargetArgs.emplace_back(
  403. FO.UIntPtrCastRequired
  404. ? Arg
  405. : CGM.getOpenMPRuntime().translateParameter(FD, Arg));
  406. ++I;
  407. }
  408. Args.append(
  409. std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
  410. CD->param_end());
  411. TargetArgs.append(
  412. std::next(CD->param_begin(), CD->getContextParamPosition() + 1),
  413. CD->param_end());
  414. // Create the function declaration.
  415. const CGFunctionInfo &FuncInfo =
  416. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs);
  417. llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
  418. auto *F =
  419. llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
  420. FO.FunctionName, &CGM.getModule());
  421. CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
  422. if (CD->isNothrow())
  423. F->setDoesNotThrow();
  424. F->setDoesNotRecurse();
  425. // Generate the function.
  426. CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs,
  427. FO.S->getBeginLoc(), CD->getBody()->getBeginLoc());
  428. unsigned Cnt = CD->getContextParamPosition();
  429. I = FO.S->captures().begin();
  430. for (const FieldDecl *FD : RD->fields()) {
  431. // Do not map arguments if we emit function with non-original types.
  432. Address LocalAddr(Address::invalid());
  433. if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) {
  434. LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt],
  435. TargetArgs[Cnt]);
  436. } else {
  437. LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]);
  438. }
  439. // If we are capturing a pointer by copy we don't need to do anything, just
  440. // use the value that we get from the arguments.
  441. if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) {
  442. const VarDecl *CurVD = I->getCapturedVar();
  443. // If the variable is a reference we need to materialize it here.
  444. if (CurVD->getType()->isReferenceType()) {
  445. Address RefAddr = CGF.CreateMemTemp(
  446. CurVD->getType(), CGM.getPointerAlign(), ".materialized_ref");
  447. CGF.EmitStoreOfScalar(LocalAddr.getPointer(), RefAddr,
  448. /*Volatile=*/false, CurVD->getType());
  449. LocalAddr = RefAddr;
  450. }
  451. if (!FO.RegisterCastedArgsOnly)
  452. LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}});
  453. ++Cnt;
  454. ++I;
  455. continue;
  456. }
  457. LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(),
  458. AlignmentSource::Decl);
  459. if (FD->hasCapturedVLAType()) {
  460. if (FO.UIntPtrCastRequired) {
  461. ArgLVal = CGF.MakeAddrLValue(
  462. castValueFromUintptr(CGF, I->getLocation(), FD->getType(),
  463. Args[Cnt]->getName(), ArgLVal),
  464. FD->getType(), AlignmentSource::Decl);
  465. }
  466. llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
  467. const VariableArrayType *VAT = FD->getCapturedVLAType();
  468. VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg);
  469. } else if (I->capturesVariable()) {
  470. const VarDecl *Var = I->getCapturedVar();
  471. QualType VarTy = Var->getType();
  472. Address ArgAddr = ArgLVal.getAddress();
  473. if (!VarTy->isReferenceType()) {
  474. if (ArgLVal.getType()->isLValueReferenceType()) {
  475. ArgAddr = CGF.EmitLoadOfReference(ArgLVal);
  476. } else if (!VarTy->isVariablyModifiedType() ||
  477. !VarTy->isPointerType()) {
  478. assert(ArgLVal.getType()->isPointerType());
  479. ArgAddr = CGF.EmitLoadOfPointer(
  480. ArgAddr, ArgLVal.getType()->castAs<PointerType>());
  481. }
  482. }
  483. if (!FO.RegisterCastedArgsOnly) {
  484. LocalAddrs.insert(
  485. {Args[Cnt],
  486. {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}});
  487. }
  488. } else if (I->capturesVariableByCopy()) {
  489. assert(!FD->getType()->isAnyPointerType() &&
  490. "Not expecting a captured pointer.");
  491. const VarDecl *Var = I->getCapturedVar();
  492. QualType VarTy = Var->getType();
  493. LocalAddrs.insert(
  494. {Args[Cnt],
  495. {Var, FO.UIntPtrCastRequired
  496. ? castValueFromUintptr(CGF, I->getLocation(),
  497. FD->getType(), Args[Cnt]->getName(),
  498. ArgLVal, VarTy->isReferenceType())
  499. : ArgLVal.getAddress()}});
  500. } else {
  501. // If 'this' is captured, load it into CXXThisValue.
  502. assert(I->capturesThis());
  503. CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation());
  504. LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress()}});
  505. }
  506. ++Cnt;
  507. ++I;
  508. }
  509. return F;
  510. }
  511. llvm::Function *
  512. CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S) {
  513. assert(
  514. CapturedStmtInfo &&
  515. "CapturedStmtInfo should be set when generating the captured function");
  516. const CapturedDecl *CD = S.getCapturedDecl();
  517. // Build the argument list.
  518. bool NeedWrapperFunction =
  519. getDebugInfo() &&
  520. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo;
  521. FunctionArgList Args;
  522. llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs;
  523. llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes;
  524. SmallString<256> Buffer;
  525. llvm::raw_svector_ostream Out(Buffer);
  526. Out << CapturedStmtInfo->getHelperName();
  527. if (NeedWrapperFunction)
  528. Out << "_debug__";
  529. FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false,
  530. Out.str());
  531. llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs,
  532. VLASizes, CXXThisValue, FO);
  533. for (const auto &LocalAddrPair : LocalAddrs) {
  534. if (LocalAddrPair.second.first) {
  535. setAddrOfLocalVar(LocalAddrPair.second.first,
  536. LocalAddrPair.second.second);
  537. }
  538. }
  539. for (const auto &VLASizePair : VLASizes)
  540. VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second;
  541. PGO.assignRegionCounters(GlobalDecl(CD), F);
  542. CapturedStmtInfo->EmitBody(*this, CD->getBody());
  543. FinishFunction(CD->getBodyRBrace());
  544. if (!NeedWrapperFunction)
  545. return F;
  546. FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true,
  547. /*RegisterCastedArgsOnly=*/true,
  548. CapturedStmtInfo->getHelperName());
  549. CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true);
  550. WrapperCGF.CapturedStmtInfo = CapturedStmtInfo;
  551. Args.clear();
  552. LocalAddrs.clear();
  553. VLASizes.clear();
  554. llvm::Function *WrapperF =
  555. emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes,
  556. WrapperCGF.CXXThisValue, WrapperFO);
  557. llvm::SmallVector<llvm::Value *, 4> CallArgs;
  558. for (const auto *Arg : Args) {
  559. llvm::Value *CallArg;
  560. auto I = LocalAddrs.find(Arg);
  561. if (I != LocalAddrs.end()) {
  562. LValue LV = WrapperCGF.MakeAddrLValue(
  563. I->second.second,
  564. I->second.first ? I->second.first->getType() : Arg->getType(),
  565. AlignmentSource::Decl);
  566. CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
  567. } else {
  568. auto EI = VLASizes.find(Arg);
  569. if (EI != VLASizes.end()) {
  570. CallArg = EI->second.second;
  571. } else {
  572. LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg),
  573. Arg->getType(),
  574. AlignmentSource::Decl);
  575. CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
  576. }
  577. }
  578. CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType()));
  579. }
  580. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, S.getBeginLoc(),
  581. F, CallArgs);
  582. WrapperCGF.FinishFunction();
  583. return WrapperF;
  584. }
  585. //===----------------------------------------------------------------------===//
  586. // OpenMP Directive Emission
  587. //===----------------------------------------------------------------------===//
  588. void CodeGenFunction::EmitOMPAggregateAssign(
  589. Address DestAddr, Address SrcAddr, QualType OriginalType,
  590. const llvm::function_ref<void(Address, Address)> CopyGen) {
  591. // Perform element-by-element initialization.
  592. QualType ElementTy;
  593. // Drill down to the base element type on both arrays.
  594. const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe();
  595. llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr);
  596. SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
  597. llvm::Value *SrcBegin = SrcAddr.getPointer();
  598. llvm::Value *DestBegin = DestAddr.getPointer();
  599. // Cast from pointer to array type to pointer to single element.
  600. llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements);
  601. // The basic structure here is a while-do loop.
  602. llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body");
  603. llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done");
  604. llvm::Value *IsEmpty =
  605. Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty");
  606. Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
  607. // Enter the loop body, making that address the current address.
  608. llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
  609. EmitBlock(BodyBB);
  610. CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy);
  611. llvm::PHINode *SrcElementPHI =
  612. Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast");
  613. SrcElementPHI->addIncoming(SrcBegin, EntryBB);
  614. Address SrcElementCurrent =
  615. Address(SrcElementPHI,
  616. SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  617. llvm::PHINode *DestElementPHI =
  618. Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
  619. DestElementPHI->addIncoming(DestBegin, EntryBB);
  620. Address DestElementCurrent =
  621. Address(DestElementPHI,
  622. DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
  623. // Emit copy.
  624. CopyGen(DestElementCurrent, SrcElementCurrent);
  625. // Shift the address forward by one element.
  626. llvm::Value *DestElementNext = Builder.CreateConstGEP1_32(
  627. DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
  628. llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32(
  629. SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
  630. // Check whether we've reached the end.
  631. llvm::Value *Done =
  632. Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
  633. Builder.CreateCondBr(Done, DoneBB, BodyBB);
  634. DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock());
  635. SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock());
  636. // Done.
  637. EmitBlock(DoneBB, /*IsFinished=*/true);
  638. }
  639. void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr,
  640. Address SrcAddr, const VarDecl *DestVD,
  641. const VarDecl *SrcVD, const Expr *Copy) {
  642. if (OriginalType->isArrayType()) {
  643. const auto *BO = dyn_cast<BinaryOperator>(Copy);
  644. if (BO && BO->getOpcode() == BO_Assign) {
  645. // Perform simple memcpy for simple copying.
  646. LValue Dest = MakeAddrLValue(DestAddr, OriginalType);
  647. LValue Src = MakeAddrLValue(SrcAddr, OriginalType);
  648. EmitAggregateAssign(Dest, Src, OriginalType);
  649. } else {
  650. // For arrays with complex element types perform element by element
  651. // copying.
  652. EmitOMPAggregateAssign(
  653. DestAddr, SrcAddr, OriginalType,
  654. [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) {
  655. // Working with the single array element, so have to remap
  656. // destination and source variables to corresponding array
  657. // elements.
  658. CodeGenFunction::OMPPrivateScope Remap(*this);
  659. Remap.addPrivate(DestVD, [DestElement]() { return DestElement; });
  660. Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; });
  661. (void)Remap.Privatize();
  662. EmitIgnoredExpr(Copy);
  663. });
  664. }
  665. } else {
  666. // Remap pseudo source variable to private copy.
  667. CodeGenFunction::OMPPrivateScope Remap(*this);
  668. Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; });
  669. Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; });
  670. (void)Remap.Privatize();
  671. // Emit copying of the whole variable.
  672. EmitIgnoredExpr(Copy);
  673. }
  674. }
  675. bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  676. OMPPrivateScope &PrivateScope) {
  677. if (!HaveInsertPoint())
  678. return false;
  679. bool FirstprivateIsLastprivate = false;
  680. llvm::DenseSet<const VarDecl *> Lastprivates;
  681. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  682. for (const auto *D : C->varlists())
  683. Lastprivates.insert(
  684. cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
  685. }
  686. llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate;
  687. llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  688. getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind());
  689. // Force emission of the firstprivate copy if the directive does not emit
  690. // outlined function, like omp for, omp simd, omp distribute etc.
  691. bool MustEmitFirstprivateCopy =
  692. CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown;
  693. for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) {
  694. auto IRef = C->varlist_begin();
  695. auto InitsRef = C->inits().begin();
  696. for (const Expr *IInit : C->private_copies()) {
  697. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  698. bool ThisFirstprivateIsLastprivate =
  699. Lastprivates.count(OrigVD->getCanonicalDecl()) > 0;
  700. const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD);
  701. if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD &&
  702. !FD->getType()->isReferenceType()) {
  703. EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
  704. ++IRef;
  705. ++InitsRef;
  706. continue;
  707. }
  708. FirstprivateIsLastprivate =
  709. FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
  710. if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
  711. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  712. const auto *VDInit =
  713. cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl());
  714. bool IsRegistered;
  715. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  716. /*RefersToEnclosingVariableOrCapture=*/FD != nullptr,
  717. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  718. LValue OriginalLVal = EmitLValue(&DRE);
  719. QualType Type = VD->getType();
  720. if (Type->isArrayType()) {
  721. // Emit VarDecl with copy init for arrays.
  722. // Get the address of the original variable captured in current
  723. // captured region.
  724. IsRegistered = PrivateScope.addPrivate(
  725. OrigVD, [this, VD, Type, OriginalLVal, VDInit]() {
  726. AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
  727. const Expr *Init = VD->getInit();
  728. if (!isa<CXXConstructExpr>(Init) ||
  729. isTrivialInitializer(Init)) {
  730. // Perform simple memcpy.
  731. LValue Dest =
  732. MakeAddrLValue(Emission.getAllocatedAddress(), Type);
  733. EmitAggregateAssign(Dest, OriginalLVal, Type);
  734. } else {
  735. EmitOMPAggregateAssign(
  736. Emission.getAllocatedAddress(), OriginalLVal.getAddress(),
  737. Type,
  738. [this, VDInit, Init](Address DestElement,
  739. Address SrcElement) {
  740. // Clean up any temporaries needed by the
  741. // initialization.
  742. RunCleanupsScope InitScope(*this);
  743. // Emit initialization for single element.
  744. setAddrOfLocalVar(VDInit, SrcElement);
  745. EmitAnyExprToMem(Init, DestElement,
  746. Init->getType().getQualifiers(),
  747. /*IsInitializer*/ false);
  748. LocalDeclMap.erase(VDInit);
  749. });
  750. }
  751. EmitAutoVarCleanups(Emission);
  752. return Emission.getAllocatedAddress();
  753. });
  754. } else {
  755. Address OriginalAddr = OriginalLVal.getAddress();
  756. IsRegistered = PrivateScope.addPrivate(
  757. OrigVD, [this, VDInit, OriginalAddr, VD]() {
  758. // Emit private VarDecl with copy init.
  759. // Remap temp VDInit variable to the address of the original
  760. // variable (for proper handling of captured global variables).
  761. setAddrOfLocalVar(VDInit, OriginalAddr);
  762. EmitDecl(*VD);
  763. LocalDeclMap.erase(VDInit);
  764. return GetAddrOfLocalVar(VD);
  765. });
  766. }
  767. assert(IsRegistered &&
  768. "firstprivate var already registered as private");
  769. // Silence the warning about unused variable.
  770. (void)IsRegistered;
  771. }
  772. ++IRef;
  773. ++InitsRef;
  774. }
  775. }
  776. return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty();
  777. }
  778. void CodeGenFunction::EmitOMPPrivateClause(
  779. const OMPExecutableDirective &D,
  780. CodeGenFunction::OMPPrivateScope &PrivateScope) {
  781. if (!HaveInsertPoint())
  782. return;
  783. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  784. for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) {
  785. auto IRef = C->varlist_begin();
  786. for (const Expr *IInit : C->private_copies()) {
  787. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  788. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  789. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  790. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
  791. // Emit private VarDecl with copy init.
  792. EmitDecl(*VD);
  793. return GetAddrOfLocalVar(VD);
  794. });
  795. assert(IsRegistered && "private var already registered as private");
  796. // Silence the warning about unused variable.
  797. (void)IsRegistered;
  798. }
  799. ++IRef;
  800. }
  801. }
  802. }
  803. bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) {
  804. if (!HaveInsertPoint())
  805. return false;
  806. // threadprivate_var1 = master_threadprivate_var1;
  807. // operator=(threadprivate_var2, master_threadprivate_var2);
  808. // ...
  809. // __kmpc_barrier(&loc, global_tid);
  810. llvm::DenseSet<const VarDecl *> CopiedVars;
  811. llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr;
  812. for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) {
  813. auto IRef = C->varlist_begin();
  814. auto ISrcRef = C->source_exprs().begin();
  815. auto IDestRef = C->destination_exprs().begin();
  816. for (const Expr *AssignOp : C->assignment_ops()) {
  817. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  818. QualType Type = VD->getType();
  819. if (CopiedVars.insert(VD->getCanonicalDecl()).second) {
  820. // Get the address of the master variable. If we are emitting code with
  821. // TLS support, the address is passed from the master as field in the
  822. // captured declaration.
  823. Address MasterAddr = Address::invalid();
  824. if (getLangOpts().OpenMPUseTLS &&
  825. getContext().getTargetInfo().isTLSSupported()) {
  826. assert(CapturedStmtInfo->lookup(VD) &&
  827. "Copyin threadprivates should have been captured!");
  828. DeclRefExpr DRE(const_cast<VarDecl *>(VD), true, (*IRef)->getType(),
  829. VK_LValue, (*IRef)->getExprLoc());
  830. MasterAddr = EmitLValue(&DRE).getAddress();
  831. LocalDeclMap.erase(VD);
  832. } else {
  833. MasterAddr =
  834. Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD)
  835. : CGM.GetAddrOfGlobal(VD),
  836. getContext().getDeclAlign(VD));
  837. }
  838. // Get the address of the threadprivate variable.
  839. Address PrivateAddr = EmitLValue(*IRef).getAddress();
  840. if (CopiedVars.size() == 1) {
  841. // At first check if current thread is a master thread. If it is, no
  842. // need to copy data.
  843. CopyBegin = createBasicBlock("copyin.not.master");
  844. CopyEnd = createBasicBlock("copyin.not.master.end");
  845. Builder.CreateCondBr(
  846. Builder.CreateICmpNE(
  847. Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy),
  848. Builder.CreatePtrToInt(PrivateAddr.getPointer(),
  849. CGM.IntPtrTy)),
  850. CopyBegin, CopyEnd);
  851. EmitBlock(CopyBegin);
  852. }
  853. const auto *SrcVD =
  854. cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  855. const auto *DestVD =
  856. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  857. EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp);
  858. }
  859. ++IRef;
  860. ++ISrcRef;
  861. ++IDestRef;
  862. }
  863. }
  864. if (CopyEnd) {
  865. // Exit out of copying procedure for non-master thread.
  866. EmitBlock(CopyEnd, /*IsFinished=*/true);
  867. return true;
  868. }
  869. return false;
  870. }
  871. bool CodeGenFunction::EmitOMPLastprivateClauseInit(
  872. const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) {
  873. if (!HaveInsertPoint())
  874. return false;
  875. bool HasAtLeastOneLastprivate = false;
  876. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  877. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  878. const auto *LoopDirective = cast<OMPLoopDirective>(&D);
  879. for (const Expr *C : LoopDirective->counters()) {
  880. SIMDLCVs.insert(
  881. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  882. }
  883. }
  884. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  885. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  886. HasAtLeastOneLastprivate = true;
  887. if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
  888. !getLangOpts().OpenMPSimd)
  889. break;
  890. auto IRef = C->varlist_begin();
  891. auto IDestRef = C->destination_exprs().begin();
  892. for (const Expr *IInit : C->private_copies()) {
  893. // Keep the address of the original variable for future update at the end
  894. // of the loop.
  895. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  896. // Taskloops do not require additional initialization, it is done in
  897. // runtime support library.
  898. if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) {
  899. const auto *DestVD =
  900. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  901. PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() {
  902. DeclRefExpr DRE(
  903. const_cast<VarDecl *>(OrigVD),
  904. /*RefersToEnclosingVariableOrCapture=*/CapturedStmtInfo->lookup(
  905. OrigVD) != nullptr,
  906. (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc());
  907. return EmitLValue(&DRE).getAddress();
  908. });
  909. // Check if the variable is also a firstprivate: in this case IInit is
  910. // not generated. Initialization of this variable will happen in codegen
  911. // for 'firstprivate' clause.
  912. if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) {
  913. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl());
  914. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() {
  915. // Emit private VarDecl with copy init.
  916. EmitDecl(*VD);
  917. return GetAddrOfLocalVar(VD);
  918. });
  919. assert(IsRegistered &&
  920. "lastprivate var already registered as private");
  921. (void)IsRegistered;
  922. }
  923. }
  924. ++IRef;
  925. ++IDestRef;
  926. }
  927. }
  928. return HasAtLeastOneLastprivate;
  929. }
  930. void CodeGenFunction::EmitOMPLastprivateClauseFinal(
  931. const OMPExecutableDirective &D, bool NoFinals,
  932. llvm::Value *IsLastIterCond) {
  933. if (!HaveInsertPoint())
  934. return;
  935. // Emit following code:
  936. // if (<IsLastIterCond>) {
  937. // orig_var1 = private_orig_var1;
  938. // ...
  939. // orig_varn = private_orig_varn;
  940. // }
  941. llvm::BasicBlock *ThenBB = nullptr;
  942. llvm::BasicBlock *DoneBB = nullptr;
  943. if (IsLastIterCond) {
  944. ThenBB = createBasicBlock(".omp.lastprivate.then");
  945. DoneBB = createBasicBlock(".omp.lastprivate.done");
  946. Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB);
  947. EmitBlock(ThenBB);
  948. }
  949. llvm::DenseSet<const VarDecl *> AlreadyEmittedVars;
  950. llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates;
  951. if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) {
  952. auto IC = LoopDirective->counters().begin();
  953. for (const Expr *F : LoopDirective->finals()) {
  954. const auto *D =
  955. cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl();
  956. if (NoFinals)
  957. AlreadyEmittedVars.insert(D);
  958. else
  959. LoopCountersAndUpdates[D] = F;
  960. ++IC;
  961. }
  962. }
  963. for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
  964. auto IRef = C->varlist_begin();
  965. auto ISrcRef = C->source_exprs().begin();
  966. auto IDestRef = C->destination_exprs().begin();
  967. for (const Expr *AssignOp : C->assignment_ops()) {
  968. const auto *PrivateVD =
  969. cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  970. QualType Type = PrivateVD->getType();
  971. const auto *CanonicalVD = PrivateVD->getCanonicalDecl();
  972. if (AlreadyEmittedVars.insert(CanonicalVD).second) {
  973. // If lastprivate variable is a loop control variable for loop-based
  974. // directive, update its value before copyin back to original
  975. // variable.
  976. if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD))
  977. EmitIgnoredExpr(FinalExpr);
  978. const auto *SrcVD =
  979. cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl());
  980. const auto *DestVD =
  981. cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl());
  982. // Get the address of the original variable.
  983. Address OriginalAddr = GetAddrOfLocalVar(DestVD);
  984. // Get the address of the private variable.
  985. Address PrivateAddr = GetAddrOfLocalVar(PrivateVD);
  986. if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>())
  987. PrivateAddr =
  988. Address(Builder.CreateLoad(PrivateAddr),
  989. getNaturalTypeAlignment(RefTy->getPointeeType()));
  990. EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp);
  991. }
  992. ++IRef;
  993. ++ISrcRef;
  994. ++IDestRef;
  995. }
  996. if (const Expr *PostUpdate = C->getPostUpdateExpr())
  997. EmitIgnoredExpr(PostUpdate);
  998. }
  999. if (IsLastIterCond)
  1000. EmitBlock(DoneBB, /*IsFinished=*/true);
  1001. }
  1002. void CodeGenFunction::EmitOMPReductionClauseInit(
  1003. const OMPExecutableDirective &D,
  1004. CodeGenFunction::OMPPrivateScope &PrivateScope) {
  1005. if (!HaveInsertPoint())
  1006. return;
  1007. SmallVector<const Expr *, 4> Shareds;
  1008. SmallVector<const Expr *, 4> Privates;
  1009. SmallVector<const Expr *, 4> ReductionOps;
  1010. SmallVector<const Expr *, 4> LHSs;
  1011. SmallVector<const Expr *, 4> RHSs;
  1012. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1013. auto IPriv = C->privates().begin();
  1014. auto IRed = C->reduction_ops().begin();
  1015. auto ILHS = C->lhs_exprs().begin();
  1016. auto IRHS = C->rhs_exprs().begin();
  1017. for (const Expr *Ref : C->varlists()) {
  1018. Shareds.emplace_back(Ref);
  1019. Privates.emplace_back(*IPriv);
  1020. ReductionOps.emplace_back(*IRed);
  1021. LHSs.emplace_back(*ILHS);
  1022. RHSs.emplace_back(*IRHS);
  1023. std::advance(IPriv, 1);
  1024. std::advance(IRed, 1);
  1025. std::advance(ILHS, 1);
  1026. std::advance(IRHS, 1);
  1027. }
  1028. }
  1029. ReductionCodeGen RedCG(Shareds, Privates, ReductionOps);
  1030. unsigned Count = 0;
  1031. auto ILHS = LHSs.begin();
  1032. auto IRHS = RHSs.begin();
  1033. auto IPriv = Privates.begin();
  1034. for (const Expr *IRef : Shareds) {
  1035. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl());
  1036. // Emit private VarDecl with reduction init.
  1037. RedCG.emitSharedLValue(*this, Count);
  1038. RedCG.emitAggregateType(*this, Count);
  1039. AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD);
  1040. RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(),
  1041. RedCG.getSharedLValue(Count),
  1042. [&Emission](CodeGenFunction &CGF) {
  1043. CGF.EmitAutoVarInit(Emission);
  1044. return true;
  1045. });
  1046. EmitAutoVarCleanups(Emission);
  1047. Address BaseAddr = RedCG.adjustPrivateAddress(
  1048. *this, Count, Emission.getAllocatedAddress());
  1049. bool IsRegistered = PrivateScope.addPrivate(
  1050. RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; });
  1051. assert(IsRegistered && "private var already registered as private");
  1052. // Silence the warning about unused variable.
  1053. (void)IsRegistered;
  1054. const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
  1055. const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
  1056. QualType Type = PrivateVD->getType();
  1057. bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef);
  1058. if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) {
  1059. // Store the address of the original variable associated with the LHS
  1060. // implicit variable.
  1061. PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
  1062. return RedCG.getSharedLValue(Count).getAddress();
  1063. });
  1064. PrivateScope.addPrivate(
  1065. RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); });
  1066. } else if ((isaOMPArraySectionExpr && Type->isScalarType()) ||
  1067. isa<ArraySubscriptExpr>(IRef)) {
  1068. // Store the address of the original variable associated with the LHS
  1069. // implicit variable.
  1070. PrivateScope.addPrivate(LHSVD, [&RedCG, Count]() {
  1071. return RedCG.getSharedLValue(Count).getAddress();
  1072. });
  1073. PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() {
  1074. return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD),
  1075. ConvertTypeForMem(RHSVD->getType()),
  1076. "rhs.begin");
  1077. });
  1078. } else {
  1079. QualType Type = PrivateVD->getType();
  1080. bool IsArray = getContext().getAsArrayType(Type) != nullptr;
  1081. Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress();
  1082. // Store the address of the original variable associated with the LHS
  1083. // implicit variable.
  1084. if (IsArray) {
  1085. OriginalAddr = Builder.CreateElementBitCast(
  1086. OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin");
  1087. }
  1088. PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; });
  1089. PrivateScope.addPrivate(
  1090. RHSVD, [this, PrivateVD, RHSVD, IsArray]() {
  1091. return IsArray
  1092. ? Builder.CreateElementBitCast(
  1093. GetAddrOfLocalVar(PrivateVD),
  1094. ConvertTypeForMem(RHSVD->getType()), "rhs.begin")
  1095. : GetAddrOfLocalVar(PrivateVD);
  1096. });
  1097. }
  1098. ++ILHS;
  1099. ++IRHS;
  1100. ++IPriv;
  1101. ++Count;
  1102. }
  1103. }
  1104. void CodeGenFunction::EmitOMPReductionClauseFinal(
  1105. const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) {
  1106. if (!HaveInsertPoint())
  1107. return;
  1108. llvm::SmallVector<const Expr *, 8> Privates;
  1109. llvm::SmallVector<const Expr *, 8> LHSExprs;
  1110. llvm::SmallVector<const Expr *, 8> RHSExprs;
  1111. llvm::SmallVector<const Expr *, 8> ReductionOps;
  1112. bool HasAtLeastOneReduction = false;
  1113. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1114. HasAtLeastOneReduction = true;
  1115. Privates.append(C->privates().begin(), C->privates().end());
  1116. LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end());
  1117. RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end());
  1118. ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end());
  1119. }
  1120. if (HasAtLeastOneReduction) {
  1121. bool WithNowait = D.getSingleClause<OMPNowaitClause>() ||
  1122. isOpenMPParallelDirective(D.getDirectiveKind()) ||
  1123. ReductionKind == OMPD_simd;
  1124. bool SimpleReduction = ReductionKind == OMPD_simd;
  1125. // Emit nowait reduction if nowait clause is present or directive is a
  1126. // parallel directive (it always has implicit barrier).
  1127. CGM.getOpenMPRuntime().emitReduction(
  1128. *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps,
  1129. {WithNowait, SimpleReduction, ReductionKind});
  1130. }
  1131. }
  1132. static void emitPostUpdateForReductionClause(
  1133. CodeGenFunction &CGF, const OMPExecutableDirective &D,
  1134. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  1135. if (!CGF.HaveInsertPoint())
  1136. return;
  1137. llvm::BasicBlock *DoneBB = nullptr;
  1138. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  1139. if (const Expr *PostUpdate = C->getPostUpdateExpr()) {
  1140. if (!DoneBB) {
  1141. if (llvm::Value *Cond = CondGen(CGF)) {
  1142. // If the first post-update expression is found, emit conditional
  1143. // block if it was requested.
  1144. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu");
  1145. DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done");
  1146. CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1147. CGF.EmitBlock(ThenBB);
  1148. }
  1149. }
  1150. CGF.EmitIgnoredExpr(PostUpdate);
  1151. }
  1152. }
  1153. if (DoneBB)
  1154. CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
  1155. }
  1156. namespace {
  1157. /// Codegen lambda for appending distribute lower and upper bounds to outlined
  1158. /// parallel function. This is necessary for combined constructs such as
  1159. /// 'distribute parallel for'
  1160. typedef llvm::function_ref<void(CodeGenFunction &,
  1161. const OMPExecutableDirective &,
  1162. llvm::SmallVectorImpl<llvm::Value *> &)>
  1163. CodeGenBoundParametersTy;
  1164. } // anonymous namespace
  1165. static void emitCommonOMPParallelDirective(
  1166. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  1167. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
  1168. const CodeGenBoundParametersTy &CodeGenBoundParameters) {
  1169. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  1170. llvm::Value *OutlinedFn =
  1171. CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction(
  1172. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  1173. if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) {
  1174. CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
  1175. llvm::Value *NumThreads =
  1176. CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
  1177. /*IgnoreResultAssign=*/true);
  1178. CGF.CGM.getOpenMPRuntime().emitNumThreadsClause(
  1179. CGF, NumThreads, NumThreadsClause->getBeginLoc());
  1180. }
  1181. if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) {
  1182. CodeGenFunction::RunCleanupsScope ProcBindScope(CGF);
  1183. CGF.CGM.getOpenMPRuntime().emitProcBindClause(
  1184. CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc());
  1185. }
  1186. const Expr *IfCond = nullptr;
  1187. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  1188. if (C->getNameModifier() == OMPD_unknown ||
  1189. C->getNameModifier() == OMPD_parallel) {
  1190. IfCond = C->getCondition();
  1191. break;
  1192. }
  1193. }
  1194. OMPParallelScope Scope(CGF, S);
  1195. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  1196. // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk
  1197. // lower and upper bounds with the pragma 'for' chunking mechanism.
  1198. // The following lambda takes care of appending the lower and upper bound
  1199. // parameters when necessary
  1200. CodeGenBoundParameters(CGF, S, CapturedVars);
  1201. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  1202. CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn,
  1203. CapturedVars, IfCond);
  1204. }
  1205. static void emitEmptyBoundParameters(CodeGenFunction &,
  1206. const OMPExecutableDirective &,
  1207. llvm::SmallVectorImpl<llvm::Value *> &) {}
  1208. void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) {
  1209. // Emit parallel region as a standalone region.
  1210. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  1211. Action.Enter(CGF);
  1212. OMPPrivateScope PrivateScope(CGF);
  1213. bool Copyins = CGF.EmitOMPCopyinClause(S);
  1214. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  1215. if (Copyins) {
  1216. // Emit implicit barrier to synchronize threads and avoid data races on
  1217. // propagation master's thread values of threadprivate variables to local
  1218. // instances of that variables of all other implicit threads.
  1219. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  1220. CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  1221. /*ForceSimpleCall=*/true);
  1222. }
  1223. CGF.EmitOMPPrivateClause(S, PrivateScope);
  1224. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  1225. (void)PrivateScope.Privatize();
  1226. CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt());
  1227. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  1228. };
  1229. emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen,
  1230. emitEmptyBoundParameters);
  1231. emitPostUpdateForReductionClause(*this, S,
  1232. [](CodeGenFunction &) { return nullptr; });
  1233. }
  1234. void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D,
  1235. JumpDest LoopExit) {
  1236. RunCleanupsScope BodyScope(*this);
  1237. // Update counters values on current iteration.
  1238. for (const Expr *UE : D.updates())
  1239. EmitIgnoredExpr(UE);
  1240. // Update the linear variables.
  1241. // In distribute directives only loop counters may be marked as linear, no
  1242. // need to generate the code for them.
  1243. if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
  1244. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1245. for (const Expr *UE : C->updates())
  1246. EmitIgnoredExpr(UE);
  1247. }
  1248. }
  1249. // On a continue in the body, jump to the end.
  1250. JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue");
  1251. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1252. // Emit loop body.
  1253. EmitStmt(D.getBody());
  1254. // The end (updates/cleanups).
  1255. EmitBlock(Continue.getBlock());
  1256. BreakContinueStack.pop_back();
  1257. }
  1258. void CodeGenFunction::EmitOMPInnerLoop(
  1259. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  1260. const Expr *IncExpr,
  1261. const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
  1262. const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) {
  1263. auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end");
  1264. // Start the loop with a block that tests the condition.
  1265. auto CondBlock = createBasicBlock("omp.inner.for.cond");
  1266. EmitBlock(CondBlock);
  1267. const SourceRange R = S.getSourceRange();
  1268. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  1269. SourceLocToDebugLoc(R.getEnd()));
  1270. // If there are any cleanups between here and the loop-exit scope,
  1271. // create a block to stage a loop exit along.
  1272. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  1273. if (RequiresCleanup)
  1274. ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup");
  1275. llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body");
  1276. // Emit condition.
  1277. EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S));
  1278. if (ExitBlock != LoopExit.getBlock()) {
  1279. EmitBlock(ExitBlock);
  1280. EmitBranchThroughCleanup(LoopExit);
  1281. }
  1282. EmitBlock(LoopBody);
  1283. incrementProfileCounter(&S);
  1284. // Create a block for the increment.
  1285. JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc");
  1286. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1287. BodyGen(*this);
  1288. // Emit "IV = IV + 1" and a back-edge to the condition block.
  1289. EmitBlock(Continue.getBlock());
  1290. EmitIgnoredExpr(IncExpr);
  1291. PostIncGen(*this);
  1292. BreakContinueStack.pop_back();
  1293. EmitBranch(CondBlock);
  1294. LoopStack.pop();
  1295. // Emit the fall-through block.
  1296. EmitBlock(LoopExit.getBlock());
  1297. }
  1298. bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) {
  1299. if (!HaveInsertPoint())
  1300. return false;
  1301. // Emit inits for the linear variables.
  1302. bool HasLinears = false;
  1303. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1304. for (const Expr *Init : C->inits()) {
  1305. HasLinears = true;
  1306. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl());
  1307. if (const auto *Ref =
  1308. dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) {
  1309. AutoVarEmission Emission = EmitAutoVarAlloca(*VD);
  1310. const auto *OrigVD = cast<VarDecl>(Ref->getDecl());
  1311. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1312. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1313. VD->getInit()->getType(), VK_LValue,
  1314. VD->getInit()->getExprLoc());
  1315. EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(),
  1316. VD->getType()),
  1317. /*capturedByInit=*/false);
  1318. EmitAutoVarCleanups(Emission);
  1319. } else {
  1320. EmitVarDecl(*VD);
  1321. }
  1322. }
  1323. // Emit the linear steps for the linear clauses.
  1324. // If a step is not constant, it is pre-calculated before the loop.
  1325. if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep()))
  1326. if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) {
  1327. EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl()));
  1328. // Emit calculation of the linear step.
  1329. EmitIgnoredExpr(CS);
  1330. }
  1331. }
  1332. return HasLinears;
  1333. }
  1334. void CodeGenFunction::EmitOMPLinearClauseFinal(
  1335. const OMPLoopDirective &D,
  1336. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  1337. if (!HaveInsertPoint())
  1338. return;
  1339. llvm::BasicBlock *DoneBB = nullptr;
  1340. // Emit the final values of the linear variables.
  1341. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1342. auto IC = C->varlist_begin();
  1343. for (const Expr *F : C->finals()) {
  1344. if (!DoneBB) {
  1345. if (llvm::Value *Cond = CondGen(*this)) {
  1346. // If the first post-update expression is found, emit conditional
  1347. // block if it was requested.
  1348. llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu");
  1349. DoneBB = createBasicBlock(".omp.linear.pu.done");
  1350. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1351. EmitBlock(ThenBB);
  1352. }
  1353. }
  1354. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl());
  1355. DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
  1356. CapturedStmtInfo->lookup(OrigVD) != nullptr,
  1357. (*IC)->getType(), VK_LValue, (*IC)->getExprLoc());
  1358. Address OrigAddr = EmitLValue(&DRE).getAddress();
  1359. CodeGenFunction::OMPPrivateScope VarScope(*this);
  1360. VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
  1361. (void)VarScope.Privatize();
  1362. EmitIgnoredExpr(F);
  1363. ++IC;
  1364. }
  1365. if (const Expr *PostUpdate = C->getPostUpdateExpr())
  1366. EmitIgnoredExpr(PostUpdate);
  1367. }
  1368. if (DoneBB)
  1369. EmitBlock(DoneBB, /*IsFinished=*/true);
  1370. }
  1371. static void emitAlignedClause(CodeGenFunction &CGF,
  1372. const OMPExecutableDirective &D) {
  1373. if (!CGF.HaveInsertPoint())
  1374. return;
  1375. for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) {
  1376. unsigned ClauseAlignment = 0;
  1377. if (const Expr *AlignmentExpr = Clause->getAlignment()) {
  1378. auto *AlignmentCI =
  1379. cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr));
  1380. ClauseAlignment = static_cast<unsigned>(AlignmentCI->getZExtValue());
  1381. }
  1382. for (const Expr *E : Clause->varlists()) {
  1383. unsigned Alignment = ClauseAlignment;
  1384. if (Alignment == 0) {
  1385. // OpenMP [2.8.1, Description]
  1386. // If no optional parameter is specified, implementation-defined default
  1387. // alignments for SIMD instructions on the target platforms are assumed.
  1388. Alignment =
  1389. CGF.getContext()
  1390. .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
  1391. E->getType()->getPointeeType()))
  1392. .getQuantity();
  1393. }
  1394. assert((Alignment == 0 || llvm::isPowerOf2_32(Alignment)) &&
  1395. "alignment is not power of 2");
  1396. if (Alignment != 0) {
  1397. llvm::Value *PtrValue = CGF.EmitScalarExpr(E);
  1398. CGF.EmitAlignmentAssumption(PtrValue, Alignment);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. void CodeGenFunction::EmitOMPPrivateLoopCounters(
  1404. const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) {
  1405. if (!HaveInsertPoint())
  1406. return;
  1407. auto I = S.private_counters().begin();
  1408. for (const Expr *E : S.counters()) {
  1409. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1410. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl());
  1411. // Emit var without initialization.
  1412. AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD);
  1413. EmitAutoVarCleanups(VarEmission);
  1414. LocalDeclMap.erase(PrivateVD);
  1415. (void)LoopScope.addPrivate(VD, [&VarEmission]() {
  1416. return VarEmission.getAllocatedAddress();
  1417. });
  1418. if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) ||
  1419. VD->hasGlobalStorage()) {
  1420. (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() {
  1421. DeclRefExpr DRE(const_cast<VarDecl *>(VD),
  1422. LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD),
  1423. E->getType(), VK_LValue, E->getExprLoc());
  1424. return EmitLValue(&DRE).getAddress();
  1425. });
  1426. } else {
  1427. (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() {
  1428. return VarEmission.getAllocatedAddress();
  1429. });
  1430. }
  1431. ++I;
  1432. }
  1433. // Privatize extra loop counters used in loops for ordered(n) clauses.
  1434. for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) {
  1435. if (!C->getNumForLoops())
  1436. continue;
  1437. for (unsigned I = S.getCollapsedNumber(),
  1438. E = C->getLoopNumIterations().size();
  1439. I < E; ++I) {
  1440. const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I));
  1441. const auto *VD = cast<VarDecl>(DRE->getDecl());
  1442. // Override only those variables that are really emitted already.
  1443. if (LocalDeclMap.count(VD)) {
  1444. (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
  1445. return CreateMemTemp(DRE->getType(), VD->getName());
  1446. });
  1447. }
  1448. }
  1449. }
  1450. }
  1451. static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S,
  1452. const Expr *Cond, llvm::BasicBlock *TrueBlock,
  1453. llvm::BasicBlock *FalseBlock, uint64_t TrueCount) {
  1454. if (!CGF.HaveInsertPoint())
  1455. return;
  1456. {
  1457. CodeGenFunction::OMPPrivateScope PreCondScope(CGF);
  1458. CGF.EmitOMPPrivateLoopCounters(S, PreCondScope);
  1459. (void)PreCondScope.Privatize();
  1460. // Get initial values of real counters.
  1461. for (const Expr *I : S.inits()) {
  1462. CGF.EmitIgnoredExpr(I);
  1463. }
  1464. }
  1465. // Check that loop is executed at least one time.
  1466. CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount);
  1467. }
  1468. void CodeGenFunction::EmitOMPLinearClause(
  1469. const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) {
  1470. if (!HaveInsertPoint())
  1471. return;
  1472. llvm::DenseSet<const VarDecl *> SIMDLCVs;
  1473. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  1474. const auto *LoopDirective = cast<OMPLoopDirective>(&D);
  1475. for (const Expr *C : LoopDirective->counters()) {
  1476. SIMDLCVs.insert(
  1477. cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl());
  1478. }
  1479. }
  1480. for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) {
  1481. auto CurPrivate = C->privates().begin();
  1482. for (const Expr *E : C->varlists()) {
  1483. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  1484. const auto *PrivateVD =
  1485. cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl());
  1486. if (!SIMDLCVs.count(VD->getCanonicalDecl())) {
  1487. bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() {
  1488. // Emit private VarDecl with copy init.
  1489. EmitVarDecl(*PrivateVD);
  1490. return GetAddrOfLocalVar(PrivateVD);
  1491. });
  1492. assert(IsRegistered && "linear var already registered as private");
  1493. // Silence the warning about unused variable.
  1494. (void)IsRegistered;
  1495. } else {
  1496. EmitVarDecl(*PrivateVD);
  1497. }
  1498. ++CurPrivate;
  1499. }
  1500. }
  1501. }
  1502. static void emitSimdlenSafelenClause(CodeGenFunction &CGF,
  1503. const OMPExecutableDirective &D,
  1504. bool IsMonotonic) {
  1505. if (!CGF.HaveInsertPoint())
  1506. return;
  1507. if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) {
  1508. RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(),
  1509. /*ignoreResult=*/true);
  1510. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  1511. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  1512. // In presence of finite 'safelen', it may be unsafe to mark all
  1513. // the memory instructions parallel, because loop-carried
  1514. // dependences of 'safelen' iterations are possible.
  1515. if (!IsMonotonic)
  1516. CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>());
  1517. } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) {
  1518. RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(),
  1519. /*ignoreResult=*/true);
  1520. auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal());
  1521. CGF.LoopStack.setVectorizeWidth(Val->getZExtValue());
  1522. // In presence of finite 'safelen', it may be unsafe to mark all
  1523. // the memory instructions parallel, because loop-carried
  1524. // dependences of 'safelen' iterations are possible.
  1525. CGF.LoopStack.setParallel(/*Enable=*/false);
  1526. }
  1527. }
  1528. void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D,
  1529. bool IsMonotonic) {
  1530. // Walk clauses and process safelen/lastprivate.
  1531. LoopStack.setParallel(!IsMonotonic);
  1532. LoopStack.setVectorizeEnable();
  1533. emitSimdlenSafelenClause(*this, D, IsMonotonic);
  1534. }
  1535. void CodeGenFunction::EmitOMPSimdFinal(
  1536. const OMPLoopDirective &D,
  1537. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) {
  1538. if (!HaveInsertPoint())
  1539. return;
  1540. llvm::BasicBlock *DoneBB = nullptr;
  1541. auto IC = D.counters().begin();
  1542. auto IPC = D.private_counters().begin();
  1543. for (const Expr *F : D.finals()) {
  1544. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl());
  1545. const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl());
  1546. const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD);
  1547. if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) ||
  1548. OrigVD->hasGlobalStorage() || CED) {
  1549. if (!DoneBB) {
  1550. if (llvm::Value *Cond = CondGen(*this)) {
  1551. // If the first post-update expression is found, emit conditional
  1552. // block if it was requested.
  1553. llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then");
  1554. DoneBB = createBasicBlock(".omp.final.done");
  1555. Builder.CreateCondBr(Cond, ThenBB, DoneBB);
  1556. EmitBlock(ThenBB);
  1557. }
  1558. }
  1559. Address OrigAddr = Address::invalid();
  1560. if (CED) {
  1561. OrigAddr = EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress();
  1562. } else {
  1563. DeclRefExpr DRE(const_cast<VarDecl *>(PrivateVD),
  1564. /*RefersToEnclosingVariableOrCapture=*/false,
  1565. (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc());
  1566. OrigAddr = EmitLValue(&DRE).getAddress();
  1567. }
  1568. OMPPrivateScope VarScope(*this);
  1569. VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; });
  1570. (void)VarScope.Privatize();
  1571. EmitIgnoredExpr(F);
  1572. }
  1573. ++IC;
  1574. ++IPC;
  1575. }
  1576. if (DoneBB)
  1577. EmitBlock(DoneBB, /*IsFinished=*/true);
  1578. }
  1579. static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF,
  1580. const OMPLoopDirective &S,
  1581. CodeGenFunction::JumpDest LoopExit) {
  1582. CGF.EmitOMPLoopBody(S, LoopExit);
  1583. CGF.EmitStopPoint(&S);
  1584. }
  1585. /// Emit a helper variable and return corresponding lvalue.
  1586. static LValue EmitOMPHelperVar(CodeGenFunction &CGF,
  1587. const DeclRefExpr *Helper) {
  1588. auto VDecl = cast<VarDecl>(Helper->getDecl());
  1589. CGF.EmitVarDecl(*VDecl);
  1590. return CGF.EmitLValue(Helper);
  1591. }
  1592. static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S,
  1593. PrePostActionTy &Action) {
  1594. Action.Enter(CGF);
  1595. assert(isOpenMPSimdDirective(S.getDirectiveKind()) &&
  1596. "Expected simd directive");
  1597. OMPLoopScope PreInitScope(CGF, S);
  1598. // if (PreCond) {
  1599. // for (IV in 0..LastIteration) BODY;
  1600. // <Final counter/linear vars updates>;
  1601. // }
  1602. //
  1603. if (isOpenMPDistributeDirective(S.getDirectiveKind()) ||
  1604. isOpenMPWorksharingDirective(S.getDirectiveKind()) ||
  1605. isOpenMPTaskLoopDirective(S.getDirectiveKind())) {
  1606. (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()));
  1607. (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()));
  1608. }
  1609. // Emit: if (PreCond) - begin.
  1610. // If the condition constant folds and can be elided, avoid emitting the
  1611. // whole loop.
  1612. bool CondConstant;
  1613. llvm::BasicBlock *ContBlock = nullptr;
  1614. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  1615. if (!CondConstant)
  1616. return;
  1617. } else {
  1618. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then");
  1619. ContBlock = CGF.createBasicBlock("simd.if.end");
  1620. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  1621. CGF.getProfileCount(&S));
  1622. CGF.EmitBlock(ThenBlock);
  1623. CGF.incrementProfileCounter(&S);
  1624. }
  1625. // Emit the loop iteration variable.
  1626. const Expr *IVExpr = S.getIterationVariable();
  1627. const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  1628. CGF.EmitVarDecl(*IVDecl);
  1629. CGF.EmitIgnoredExpr(S.getInit());
  1630. // Emit the iterations count variable.
  1631. // If it is not a variable, Sema decided to calculate iterations count on
  1632. // each iteration (e.g., it is foldable into a constant).
  1633. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  1634. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  1635. // Emit calculation of the iterations count.
  1636. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  1637. }
  1638. CGF.EmitOMPSimdInit(S);
  1639. emitAlignedClause(CGF, S);
  1640. (void)CGF.EmitOMPLinearClauseInit(S);
  1641. {
  1642. CodeGenFunction::OMPPrivateScope LoopScope(CGF);
  1643. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  1644. CGF.EmitOMPLinearClause(S, LoopScope);
  1645. CGF.EmitOMPPrivateClause(S, LoopScope);
  1646. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  1647. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  1648. (void)LoopScope.Privatize();
  1649. CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  1650. S.getInc(),
  1651. [&S](CodeGenFunction &CGF) {
  1652. CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest());
  1653. CGF.EmitStopPoint(&S);
  1654. },
  1655. [](CodeGenFunction &) {});
  1656. CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; });
  1657. // Emit final copy of the lastprivate variables at the end of loops.
  1658. if (HasLastprivateClause)
  1659. CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true);
  1660. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd);
  1661. emitPostUpdateForReductionClause(CGF, S,
  1662. [](CodeGenFunction &) { return nullptr; });
  1663. }
  1664. CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; });
  1665. // Emit: if (PreCond) - end.
  1666. if (ContBlock) {
  1667. CGF.EmitBranch(ContBlock);
  1668. CGF.EmitBlock(ContBlock, true);
  1669. }
  1670. }
  1671. void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) {
  1672. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  1673. emitOMPSimdRegion(CGF, S, Action);
  1674. };
  1675. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  1676. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  1677. }
  1678. void CodeGenFunction::EmitOMPOuterLoop(
  1679. bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S,
  1680. CodeGenFunction::OMPPrivateScope &LoopScope,
  1681. const CodeGenFunction::OMPLoopArguments &LoopArgs,
  1682. const CodeGenFunction::CodeGenLoopTy &CodeGenLoop,
  1683. const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) {
  1684. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  1685. const Expr *IVExpr = S.getIterationVariable();
  1686. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1687. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1688. JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end");
  1689. // Start the loop with a block that tests the condition.
  1690. llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond");
  1691. EmitBlock(CondBlock);
  1692. const SourceRange R = S.getSourceRange();
  1693. LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
  1694. SourceLocToDebugLoc(R.getEnd()));
  1695. llvm::Value *BoolCondVal = nullptr;
  1696. if (!DynamicOrOrdered) {
  1697. // UB = min(UB, GlobalUB) or
  1698. // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g.
  1699. // 'distribute parallel for')
  1700. EmitIgnoredExpr(LoopArgs.EUB);
  1701. // IV = LB
  1702. EmitIgnoredExpr(LoopArgs.Init);
  1703. // IV < UB
  1704. BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond);
  1705. } else {
  1706. BoolCondVal =
  1707. RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL,
  1708. LoopArgs.LB, LoopArgs.UB, LoopArgs.ST);
  1709. }
  1710. // If there are any cleanups between here and the loop-exit scope,
  1711. // create a block to stage a loop exit along.
  1712. llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
  1713. if (LoopScope.requiresCleanups())
  1714. ExitBlock = createBasicBlock("omp.dispatch.cleanup");
  1715. llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body");
  1716. Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
  1717. if (ExitBlock != LoopExit.getBlock()) {
  1718. EmitBlock(ExitBlock);
  1719. EmitBranchThroughCleanup(LoopExit);
  1720. }
  1721. EmitBlock(LoopBody);
  1722. // Emit "IV = LB" (in case of static schedule, we have already calculated new
  1723. // LB for loop condition and emitted it above).
  1724. if (DynamicOrOrdered)
  1725. EmitIgnoredExpr(LoopArgs.Init);
  1726. // Create a block for the increment.
  1727. JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc");
  1728. BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
  1729. // Generate !llvm.loop.parallel metadata for loads and stores for loops
  1730. // with dynamic/guided scheduling and without ordered clause.
  1731. if (!isOpenMPSimdDirective(S.getDirectiveKind()))
  1732. LoopStack.setParallel(!IsMonotonic);
  1733. else
  1734. EmitOMPSimdInit(S, IsMonotonic);
  1735. SourceLocation Loc = S.getBeginLoc();
  1736. // when 'distribute' is not combined with a 'for':
  1737. // while (idx <= UB) { BODY; ++idx; }
  1738. // when 'distribute' is combined with a 'for'
  1739. // (e.g. 'distribute parallel for')
  1740. // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
  1741. EmitOMPInnerLoop(
  1742. S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr,
  1743. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  1744. CodeGenLoop(CGF, S, LoopExit);
  1745. },
  1746. [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) {
  1747. CodeGenOrdered(CGF, Loc, IVSize, IVSigned);
  1748. });
  1749. EmitBlock(Continue.getBlock());
  1750. BreakContinueStack.pop_back();
  1751. if (!DynamicOrOrdered) {
  1752. // Emit "LB = LB + Stride", "UB = UB + Stride".
  1753. EmitIgnoredExpr(LoopArgs.NextLB);
  1754. EmitIgnoredExpr(LoopArgs.NextUB);
  1755. }
  1756. EmitBranch(CondBlock);
  1757. LoopStack.pop();
  1758. // Emit the fall-through block.
  1759. EmitBlock(LoopExit.getBlock());
  1760. // Tell the runtime we are done.
  1761. auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) {
  1762. if (!DynamicOrOrdered)
  1763. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  1764. S.getDirectiveKind());
  1765. };
  1766. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  1767. }
  1768. void CodeGenFunction::EmitOMPForOuterLoop(
  1769. const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic,
  1770. const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
  1771. const OMPLoopArguments &LoopArgs,
  1772. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  1773. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  1774. // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime).
  1775. const bool DynamicOrOrdered =
  1776. Ordered || RT.isDynamic(ScheduleKind.Schedule);
  1777. assert((Ordered ||
  1778. !RT.isStaticNonchunked(ScheduleKind.Schedule,
  1779. LoopArgs.Chunk != nullptr)) &&
  1780. "static non-chunked schedule does not need outer loop");
  1781. // Emit outer loop.
  1782. //
  1783. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  1784. // When schedule(dynamic,chunk_size) is specified, the iterations are
  1785. // distributed to threads in the team in chunks as the threads request them.
  1786. // Each thread executes a chunk of iterations, then requests another chunk,
  1787. // until no chunks remain to be distributed. Each chunk contains chunk_size
  1788. // iterations, except for the last chunk to be distributed, which may have
  1789. // fewer iterations. When no chunk_size is specified, it defaults to 1.
  1790. //
  1791. // When schedule(guided,chunk_size) is specified, the iterations are assigned
  1792. // to threads in the team in chunks as the executing threads request them.
  1793. // Each thread executes a chunk of iterations, then requests another chunk,
  1794. // until no chunks remain to be assigned. For a chunk_size of 1, the size of
  1795. // each chunk is proportional to the number of unassigned iterations divided
  1796. // by the number of threads in the team, decreasing to 1. For a chunk_size
  1797. // with value k (greater than 1), the size of each chunk is determined in the
  1798. // same way, with the restriction that the chunks do not contain fewer than k
  1799. // iterations (except for the last chunk to be assigned, which may have fewer
  1800. // than k iterations).
  1801. //
  1802. // When schedule(auto) is specified, the decision regarding scheduling is
  1803. // delegated to the compiler and/or runtime system. The programmer gives the
  1804. // implementation the freedom to choose any possible mapping of iterations to
  1805. // threads in the team.
  1806. //
  1807. // When schedule(runtime) is specified, the decision regarding scheduling is
  1808. // deferred until run time, and the schedule and chunk size are taken from the
  1809. // run-sched-var ICV. If the ICV is set to auto, the schedule is
  1810. // implementation defined
  1811. //
  1812. // while(__kmpc_dispatch_next(&LB, &UB)) {
  1813. // idx = LB;
  1814. // while (idx <= UB) { BODY; ++idx;
  1815. // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only.
  1816. // } // inner loop
  1817. // }
  1818. //
  1819. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  1820. // When schedule(static, chunk_size) is specified, iterations are divided into
  1821. // chunks of size chunk_size, and the chunks are assigned to the threads in
  1822. // the team in a round-robin fashion in the order of the thread number.
  1823. //
  1824. // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) {
  1825. // while (idx <= UB) { BODY; ++idx; } // inner loop
  1826. // LB = LB + ST;
  1827. // UB = UB + ST;
  1828. // }
  1829. //
  1830. const Expr *IVExpr = S.getIterationVariable();
  1831. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1832. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1833. if (DynamicOrOrdered) {
  1834. const std::pair<llvm::Value *, llvm::Value *> DispatchBounds =
  1835. CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB);
  1836. llvm::Value *LBVal = DispatchBounds.first;
  1837. llvm::Value *UBVal = DispatchBounds.second;
  1838. CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal,
  1839. LoopArgs.Chunk};
  1840. RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize,
  1841. IVSigned, Ordered, DipatchRTInputValues);
  1842. } else {
  1843. CGOpenMPRuntime::StaticRTInput StaticInit(
  1844. IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB,
  1845. LoopArgs.ST, LoopArgs.Chunk);
  1846. RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
  1847. ScheduleKind, StaticInit);
  1848. }
  1849. auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc,
  1850. const unsigned IVSize,
  1851. const bool IVSigned) {
  1852. if (Ordered) {
  1853. CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize,
  1854. IVSigned);
  1855. }
  1856. };
  1857. OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST,
  1858. LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB);
  1859. OuterLoopArgs.IncExpr = S.getInc();
  1860. OuterLoopArgs.Init = S.getInit();
  1861. OuterLoopArgs.Cond = S.getCond();
  1862. OuterLoopArgs.NextLB = S.getNextLowerBound();
  1863. OuterLoopArgs.NextUB = S.getNextUpperBound();
  1864. EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs,
  1865. emitOMPLoopBodyWithStopPoint, CodeGenOrdered);
  1866. }
  1867. static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc,
  1868. const unsigned IVSize, const bool IVSigned) {}
  1869. void CodeGenFunction::EmitOMPDistributeOuterLoop(
  1870. OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S,
  1871. OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs,
  1872. const CodeGenLoopTy &CodeGenLoopContent) {
  1873. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  1874. // Emit outer loop.
  1875. // Same behavior as a OMPForOuterLoop, except that schedule cannot be
  1876. // dynamic
  1877. //
  1878. const Expr *IVExpr = S.getIterationVariable();
  1879. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  1880. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  1881. CGOpenMPRuntime::StaticRTInput StaticInit(
  1882. IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB,
  1883. LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk);
  1884. RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
  1885. // for combined 'distribute' and 'for' the increment expression of distribute
  1886. // is store in DistInc. For 'distribute' alone, it is in Inc.
  1887. Expr *IncExpr;
  1888. if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
  1889. IncExpr = S.getDistInc();
  1890. else
  1891. IncExpr = S.getInc();
  1892. // this routine is shared by 'omp distribute parallel for' and
  1893. // 'omp distribute': select the right EUB expression depending on the
  1894. // directive
  1895. OMPLoopArguments OuterLoopArgs;
  1896. OuterLoopArgs.LB = LoopArgs.LB;
  1897. OuterLoopArgs.UB = LoopArgs.UB;
  1898. OuterLoopArgs.ST = LoopArgs.ST;
  1899. OuterLoopArgs.IL = LoopArgs.IL;
  1900. OuterLoopArgs.Chunk = LoopArgs.Chunk;
  1901. OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1902. ? S.getCombinedEnsureUpperBound()
  1903. : S.getEnsureUpperBound();
  1904. OuterLoopArgs.IncExpr = IncExpr;
  1905. OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1906. ? S.getCombinedInit()
  1907. : S.getInit();
  1908. OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1909. ? S.getCombinedCond()
  1910. : S.getCond();
  1911. OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1912. ? S.getCombinedNextLowerBound()
  1913. : S.getNextLowerBound();
  1914. OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  1915. ? S.getCombinedNextUpperBound()
  1916. : S.getNextUpperBound();
  1917. EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S,
  1918. LoopScope, OuterLoopArgs, CodeGenLoopContent,
  1919. emitEmptyOrdered);
  1920. }
  1921. static std::pair<LValue, LValue>
  1922. emitDistributeParallelForInnerBounds(CodeGenFunction &CGF,
  1923. const OMPExecutableDirective &S) {
  1924. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  1925. LValue LB =
  1926. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  1927. LValue UB =
  1928. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  1929. // When composing 'distribute' with 'for' (e.g. as in 'distribute
  1930. // parallel for') we need to use the 'distribute'
  1931. // chunk lower and upper bounds rather than the whole loop iteration
  1932. // space. These are parameters to the outlined function for 'parallel'
  1933. // and we copy the bounds of the previous schedule into the
  1934. // the current ones.
  1935. LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable());
  1936. LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable());
  1937. llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar(
  1938. PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc());
  1939. PrevLBVal = CGF.EmitScalarConversion(
  1940. PrevLBVal, LS.getPrevLowerBoundVariable()->getType(),
  1941. LS.getIterationVariable()->getType(),
  1942. LS.getPrevLowerBoundVariable()->getExprLoc());
  1943. llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar(
  1944. PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc());
  1945. PrevUBVal = CGF.EmitScalarConversion(
  1946. PrevUBVal, LS.getPrevUpperBoundVariable()->getType(),
  1947. LS.getIterationVariable()->getType(),
  1948. LS.getPrevUpperBoundVariable()->getExprLoc());
  1949. CGF.EmitStoreOfScalar(PrevLBVal, LB);
  1950. CGF.EmitStoreOfScalar(PrevUBVal, UB);
  1951. return {LB, UB};
  1952. }
  1953. /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then
  1954. /// we need to use the LB and UB expressions generated by the worksharing
  1955. /// code generation support, whereas in non combined situations we would
  1956. /// just emit 0 and the LastIteration expression
  1957. /// This function is necessary due to the difference of the LB and UB
  1958. /// types for the RT emission routines for 'for_static_init' and
  1959. /// 'for_dispatch_init'
  1960. static std::pair<llvm::Value *, llvm::Value *>
  1961. emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF,
  1962. const OMPExecutableDirective &S,
  1963. Address LB, Address UB) {
  1964. const OMPLoopDirective &LS = cast<OMPLoopDirective>(S);
  1965. const Expr *IVExpr = LS.getIterationVariable();
  1966. // when implementing a dynamic schedule for a 'for' combined with a
  1967. // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop
  1968. // is not normalized as each team only executes its own assigned
  1969. // distribute chunk
  1970. QualType IteratorTy = IVExpr->getType();
  1971. llvm::Value *LBVal =
  1972. CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
  1973. llvm::Value *UBVal =
  1974. CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc());
  1975. return {LBVal, UBVal};
  1976. }
  1977. static void emitDistributeParallelForDistributeInnerBoundParams(
  1978. CodeGenFunction &CGF, const OMPExecutableDirective &S,
  1979. llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) {
  1980. const auto &Dir = cast<OMPLoopDirective>(S);
  1981. LValue LB =
  1982. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable()));
  1983. llvm::Value *LBCast = CGF.Builder.CreateIntCast(
  1984. CGF.Builder.CreateLoad(LB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
  1985. CapturedVars.push_back(LBCast);
  1986. LValue UB =
  1987. CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable()));
  1988. llvm::Value *UBCast = CGF.Builder.CreateIntCast(
  1989. CGF.Builder.CreateLoad(UB.getAddress()), CGF.SizeTy, /*isSigned=*/false);
  1990. CapturedVars.push_back(UBCast);
  1991. }
  1992. static void
  1993. emitInnerParallelForWhenCombined(CodeGenFunction &CGF,
  1994. const OMPLoopDirective &S,
  1995. CodeGenFunction::JumpDest LoopExit) {
  1996. auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF,
  1997. PrePostActionTy &Action) {
  1998. Action.Enter(CGF);
  1999. bool HasCancel = false;
  2000. if (!isOpenMPSimdDirective(S.getDirectiveKind())) {
  2001. if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S))
  2002. HasCancel = D->hasCancel();
  2003. else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S))
  2004. HasCancel = D->hasCancel();
  2005. else if (const auto *D =
  2006. dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S))
  2007. HasCancel = D->hasCancel();
  2008. }
  2009. CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(),
  2010. HasCancel);
  2011. CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(),
  2012. emitDistributeParallelForInnerBounds,
  2013. emitDistributeParallelForDispatchBounds);
  2014. };
  2015. emitCommonOMPParallelDirective(
  2016. CGF, S,
  2017. isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for,
  2018. CGInlinedWorksharingLoop,
  2019. emitDistributeParallelForDistributeInnerBoundParams);
  2020. }
  2021. void CodeGenFunction::EmitOMPDistributeParallelForDirective(
  2022. const OMPDistributeParallelForDirective &S) {
  2023. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2024. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  2025. S.getDistInc());
  2026. };
  2027. OMPLexicalScope Scope(*this, S, OMPD_parallel);
  2028. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  2029. }
  2030. void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective(
  2031. const OMPDistributeParallelForSimdDirective &S) {
  2032. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2033. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  2034. S.getDistInc());
  2035. };
  2036. OMPLexicalScope Scope(*this, S, OMPD_parallel);
  2037. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  2038. }
  2039. void CodeGenFunction::EmitOMPDistributeSimdDirective(
  2040. const OMPDistributeSimdDirective &S) {
  2041. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2042. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  2043. };
  2044. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2045. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  2046. }
  2047. void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
  2048. CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
  2049. // Emit SPMD target parallel for region as a standalone region.
  2050. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2051. emitOMPSimdRegion(CGF, S, Action);
  2052. };
  2053. llvm::Function *Fn;
  2054. llvm::Constant *Addr;
  2055. // Emit target region as a standalone region.
  2056. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  2057. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  2058. assert(Fn && Addr && "Target device function emission failed.");
  2059. }
  2060. void CodeGenFunction::EmitOMPTargetSimdDirective(
  2061. const OMPTargetSimdDirective &S) {
  2062. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2063. emitOMPSimdRegion(CGF, S, Action);
  2064. };
  2065. emitCommonOMPTargetDirective(*this, S, CodeGen);
  2066. }
  2067. namespace {
  2068. struct ScheduleKindModifiersTy {
  2069. OpenMPScheduleClauseKind Kind;
  2070. OpenMPScheduleClauseModifier M1;
  2071. OpenMPScheduleClauseModifier M2;
  2072. ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind,
  2073. OpenMPScheduleClauseModifier M1,
  2074. OpenMPScheduleClauseModifier M2)
  2075. : Kind(Kind), M1(M1), M2(M2) {}
  2076. };
  2077. } // namespace
  2078. bool CodeGenFunction::EmitOMPWorksharingLoop(
  2079. const OMPLoopDirective &S, Expr *EUB,
  2080. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  2081. const CodeGenDispatchBoundsTy &CGDispatchBounds) {
  2082. // Emit the loop iteration variable.
  2083. const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  2084. const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
  2085. EmitVarDecl(*IVDecl);
  2086. // Emit the iterations count variable.
  2087. // If it is not a variable, Sema decided to calculate iterations count on each
  2088. // iteration (e.g., it is foldable into a constant).
  2089. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  2090. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  2091. // Emit calculation of the iterations count.
  2092. EmitIgnoredExpr(S.getCalcLastIteration());
  2093. }
  2094. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  2095. bool HasLastprivateClause;
  2096. // Check pre-condition.
  2097. {
  2098. OMPLoopScope PreInitScope(*this, S);
  2099. // Skip the entire loop if we don't meet the precondition.
  2100. // If the condition constant folds and can be elided, avoid emitting the
  2101. // whole loop.
  2102. bool CondConstant;
  2103. llvm::BasicBlock *ContBlock = nullptr;
  2104. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  2105. if (!CondConstant)
  2106. return false;
  2107. } else {
  2108. llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
  2109. ContBlock = createBasicBlock("omp.precond.end");
  2110. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  2111. getProfileCount(&S));
  2112. EmitBlock(ThenBlock);
  2113. incrementProfileCounter(&S);
  2114. }
  2115. RunCleanupsScope DoacrossCleanupScope(*this);
  2116. bool Ordered = false;
  2117. if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) {
  2118. if (OrderedClause->getNumForLoops())
  2119. RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations());
  2120. else
  2121. Ordered = true;
  2122. }
  2123. llvm::DenseSet<const Expr *> EmittedFinals;
  2124. emitAlignedClause(*this, S);
  2125. bool HasLinears = EmitOMPLinearClauseInit(S);
  2126. // Emit helper vars inits.
  2127. std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S);
  2128. LValue LB = Bounds.first;
  2129. LValue UB = Bounds.second;
  2130. LValue ST =
  2131. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  2132. LValue IL =
  2133. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  2134. // Emit 'then' code.
  2135. {
  2136. OMPPrivateScope LoopScope(*this);
  2137. if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) {
  2138. // Emit implicit barrier to synchronize threads and avoid data races on
  2139. // initialization of firstprivate variables and post-update of
  2140. // lastprivate variables.
  2141. CGM.getOpenMPRuntime().emitBarrierCall(
  2142. *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  2143. /*ForceSimpleCall=*/true);
  2144. }
  2145. EmitOMPPrivateClause(S, LoopScope);
  2146. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  2147. EmitOMPReductionClauseInit(S, LoopScope);
  2148. EmitOMPPrivateLoopCounters(S, LoopScope);
  2149. EmitOMPLinearClause(S, LoopScope);
  2150. (void)LoopScope.Privatize();
  2151. // Detect the loop schedule kind and chunk.
  2152. llvm::Value *Chunk = nullptr;
  2153. OpenMPScheduleTy ScheduleKind;
  2154. if (const auto *C = S.getSingleClause<OMPScheduleClause>()) {
  2155. ScheduleKind.Schedule = C->getScheduleKind();
  2156. ScheduleKind.M1 = C->getFirstScheduleModifier();
  2157. ScheduleKind.M2 = C->getSecondScheduleModifier();
  2158. if (const Expr *Ch = C->getChunkSize()) {
  2159. Chunk = EmitScalarExpr(Ch);
  2160. Chunk = EmitScalarConversion(Chunk, Ch->getType(),
  2161. S.getIterationVariable()->getType(),
  2162. S.getBeginLoc());
  2163. }
  2164. } else {
  2165. // Default behaviour for schedule clause.
  2166. CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
  2167. *this, S, ScheduleKind.Schedule, Chunk);
  2168. }
  2169. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  2170. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  2171. // OpenMP 4.5, 2.7.1 Loop Construct, Description.
  2172. // If the static schedule kind is specified or if the ordered clause is
  2173. // specified, and if no monotonic modifier is specified, the effect will
  2174. // be as if the monotonic modifier was specified.
  2175. if (RT.isStaticNonchunked(ScheduleKind.Schedule,
  2176. /* Chunked */ Chunk != nullptr) &&
  2177. !Ordered) {
  2178. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  2179. EmitOMPSimdInit(S, /*IsMonotonic=*/true);
  2180. // OpenMP [2.7.1, Loop Construct, Description, table 2-1]
  2181. // When no chunk_size is specified, the iteration space is divided into
  2182. // chunks that are approximately equal in size, and at most one chunk is
  2183. // distributed to each thread. Note that the size of the chunks is
  2184. // unspecified in this case.
  2185. CGOpenMPRuntime::StaticRTInput StaticInit(
  2186. IVSize, IVSigned, Ordered, IL.getAddress(), LB.getAddress(),
  2187. UB.getAddress(), ST.getAddress());
  2188. RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(),
  2189. ScheduleKind, StaticInit);
  2190. JumpDest LoopExit =
  2191. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  2192. // UB = min(UB, GlobalUB);
  2193. EmitIgnoredExpr(S.getEnsureUpperBound());
  2194. // IV = LB;
  2195. EmitIgnoredExpr(S.getInit());
  2196. // while (idx <= UB) { BODY; ++idx; }
  2197. EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  2198. S.getInc(),
  2199. [&S, LoopExit](CodeGenFunction &CGF) {
  2200. CGF.EmitOMPLoopBody(S, LoopExit);
  2201. CGF.EmitStopPoint(&S);
  2202. },
  2203. [](CodeGenFunction &) {});
  2204. EmitBlock(LoopExit.getBlock());
  2205. // Tell the runtime we are done.
  2206. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  2207. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  2208. S.getDirectiveKind());
  2209. };
  2210. OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen);
  2211. } else {
  2212. const bool IsMonotonic =
  2213. Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static ||
  2214. ScheduleKind.Schedule == OMPC_SCHEDULE_unknown ||
  2215. ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic ||
  2216. ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic;
  2217. // Emit the outer loop, which requests its work chunk [LB..UB] from
  2218. // runtime and runs the inner loop to process it.
  2219. const OMPLoopArguments LoopArguments(LB.getAddress(), UB.getAddress(),
  2220. ST.getAddress(), IL.getAddress(),
  2221. Chunk, EUB);
  2222. EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered,
  2223. LoopArguments, CGDispatchBounds);
  2224. }
  2225. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  2226. EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
  2227. return CGF.Builder.CreateIsNotNull(
  2228. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  2229. });
  2230. }
  2231. EmitOMPReductionClauseFinal(
  2232. S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind())
  2233. ? /*Parallel and Simd*/ OMPD_parallel_for_simd
  2234. : /*Parallel only*/ OMPD_parallel);
  2235. // Emit post-update of the reduction variables if IsLastIter != 0.
  2236. emitPostUpdateForReductionClause(
  2237. *this, S, [IL, &S](CodeGenFunction &CGF) {
  2238. return CGF.Builder.CreateIsNotNull(
  2239. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  2240. });
  2241. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  2242. if (HasLastprivateClause)
  2243. EmitOMPLastprivateClauseFinal(
  2244. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  2245. Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
  2246. }
  2247. EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) {
  2248. return CGF.Builder.CreateIsNotNull(
  2249. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  2250. });
  2251. DoacrossCleanupScope.ForceCleanup();
  2252. // We're now done with the loop, so jump to the continuation block.
  2253. if (ContBlock) {
  2254. EmitBranch(ContBlock);
  2255. EmitBlock(ContBlock, /*IsFinished=*/true);
  2256. }
  2257. }
  2258. return HasLastprivateClause;
  2259. }
  2260. /// The following two functions generate expressions for the loop lower
  2261. /// and upper bounds in case of static and dynamic (dispatch) schedule
  2262. /// of the associated 'for' or 'distribute' loop.
  2263. static std::pair<LValue, LValue>
  2264. emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) {
  2265. const auto &LS = cast<OMPLoopDirective>(S);
  2266. LValue LB =
  2267. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable()));
  2268. LValue UB =
  2269. EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable()));
  2270. return {LB, UB};
  2271. }
  2272. /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not
  2273. /// consider the lower and upper bound expressions generated by the
  2274. /// worksharing loop support, but we use 0 and the iteration space size as
  2275. /// constants
  2276. static std::pair<llvm::Value *, llvm::Value *>
  2277. emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S,
  2278. Address LB, Address UB) {
  2279. const auto &LS = cast<OMPLoopDirective>(S);
  2280. const Expr *IVExpr = LS.getIterationVariable();
  2281. const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType());
  2282. llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0);
  2283. llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration());
  2284. return {LBVal, UBVal};
  2285. }
  2286. void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) {
  2287. bool HasLastprivates = false;
  2288. auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
  2289. PrePostActionTy &) {
  2290. OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel());
  2291. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  2292. emitForLoopBounds,
  2293. emitDispatchForLoopBounds);
  2294. };
  2295. {
  2296. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2297. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen,
  2298. S.hasCancel());
  2299. }
  2300. // Emit an implicit barrier at the end.
  2301. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
  2302. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
  2303. }
  2304. void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) {
  2305. bool HasLastprivates = false;
  2306. auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF,
  2307. PrePostActionTy &) {
  2308. HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(),
  2309. emitForLoopBounds,
  2310. emitDispatchForLoopBounds);
  2311. };
  2312. {
  2313. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2314. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen);
  2315. }
  2316. // Emit an implicit barrier at the end.
  2317. if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates)
  2318. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for);
  2319. }
  2320. static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty,
  2321. const Twine &Name,
  2322. llvm::Value *Init = nullptr) {
  2323. LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty);
  2324. if (Init)
  2325. CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true);
  2326. return LVal;
  2327. }
  2328. void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) {
  2329. const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
  2330. const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt);
  2331. bool HasLastprivates = false;
  2332. auto &&CodeGen = [&S, CapturedStmt, CS,
  2333. &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) {
  2334. ASTContext &C = CGF.getContext();
  2335. QualType KmpInt32Ty =
  2336. C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
  2337. // Emit helper vars inits.
  2338. LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.",
  2339. CGF.Builder.getInt32(0));
  2340. llvm::ConstantInt *GlobalUBVal = CS != nullptr
  2341. ? CGF.Builder.getInt32(CS->size() - 1)
  2342. : CGF.Builder.getInt32(0);
  2343. LValue UB =
  2344. createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal);
  2345. LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.",
  2346. CGF.Builder.getInt32(1));
  2347. LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.",
  2348. CGF.Builder.getInt32(0));
  2349. // Loop counter.
  2350. LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv.");
  2351. OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
  2352. CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV);
  2353. OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue);
  2354. CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB);
  2355. // Generate condition for loop.
  2356. BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue,
  2357. OK_Ordinary, S.getBeginLoc(), FPOptions());
  2358. // Increment for loop counter.
  2359. UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary,
  2360. S.getBeginLoc(), true);
  2361. auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) {
  2362. // Iterate through all sections and emit a switch construct:
  2363. // switch (IV) {
  2364. // case 0:
  2365. // <SectionStmt[0]>;
  2366. // break;
  2367. // ...
  2368. // case <NumSection> - 1:
  2369. // <SectionStmt[<NumSection> - 1]>;
  2370. // break;
  2371. // }
  2372. // .omp.sections.exit:
  2373. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit");
  2374. llvm::SwitchInst *SwitchStmt =
  2375. CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()),
  2376. ExitBB, CS == nullptr ? 1 : CS->size());
  2377. if (CS) {
  2378. unsigned CaseNumber = 0;
  2379. for (const Stmt *SubStmt : CS->children()) {
  2380. auto CaseBB = CGF.createBasicBlock(".omp.sections.case");
  2381. CGF.EmitBlock(CaseBB);
  2382. SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB);
  2383. CGF.EmitStmt(SubStmt);
  2384. CGF.EmitBranch(ExitBB);
  2385. ++CaseNumber;
  2386. }
  2387. } else {
  2388. llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case");
  2389. CGF.EmitBlock(CaseBB);
  2390. SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB);
  2391. CGF.EmitStmt(CapturedStmt);
  2392. CGF.EmitBranch(ExitBB);
  2393. }
  2394. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  2395. };
  2396. CodeGenFunction::OMPPrivateScope LoopScope(CGF);
  2397. if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) {
  2398. // Emit implicit barrier to synchronize threads and avoid data races on
  2399. // initialization of firstprivate variables and post-update of lastprivate
  2400. // variables.
  2401. CGF.CGM.getOpenMPRuntime().emitBarrierCall(
  2402. CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  2403. /*ForceSimpleCall=*/true);
  2404. }
  2405. CGF.EmitOMPPrivateClause(S, LoopScope);
  2406. HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  2407. CGF.EmitOMPReductionClauseInit(S, LoopScope);
  2408. (void)LoopScope.Privatize();
  2409. // Emit static non-chunked loop.
  2410. OpenMPScheduleTy ScheduleKind;
  2411. ScheduleKind.Schedule = OMPC_SCHEDULE_static;
  2412. CGOpenMPRuntime::StaticRTInput StaticInit(
  2413. /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(),
  2414. LB.getAddress(), UB.getAddress(), ST.getAddress());
  2415. CGF.CGM.getOpenMPRuntime().emitForStaticInit(
  2416. CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit);
  2417. // UB = min(UB, GlobalUB);
  2418. llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc());
  2419. llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect(
  2420. CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal);
  2421. CGF.EmitStoreOfScalar(MinUBGlobalUB, UB);
  2422. // IV = LB;
  2423. CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV);
  2424. // while (idx <= UB) { BODY; ++idx; }
  2425. CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen,
  2426. [](CodeGenFunction &) {});
  2427. // Tell the runtime we are done.
  2428. auto &&CodeGen = [&S](CodeGenFunction &CGF) {
  2429. CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(),
  2430. S.getDirectiveKind());
  2431. };
  2432. CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen);
  2433. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  2434. // Emit post-update of the reduction variables if IsLastIter != 0.
  2435. emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) {
  2436. return CGF.Builder.CreateIsNotNull(
  2437. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  2438. });
  2439. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  2440. if (HasLastprivates)
  2441. CGF.EmitOMPLastprivateClauseFinal(
  2442. S, /*NoFinals=*/false,
  2443. CGF.Builder.CreateIsNotNull(
  2444. CGF.EmitLoadOfScalar(IL, S.getBeginLoc())));
  2445. };
  2446. bool HasCancel = false;
  2447. if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S))
  2448. HasCancel = OSD->hasCancel();
  2449. else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S))
  2450. HasCancel = OPSD->hasCancel();
  2451. OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel);
  2452. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen,
  2453. HasCancel);
  2454. // Emit barrier for lastprivates only if 'sections' directive has 'nowait'
  2455. // clause. Otherwise the barrier will be generated by the codegen for the
  2456. // directive.
  2457. if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) {
  2458. // Emit implicit barrier to synchronize threads and avoid data races on
  2459. // initialization of firstprivate variables.
  2460. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
  2461. OMPD_unknown);
  2462. }
  2463. }
  2464. void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
  2465. {
  2466. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2467. EmitSections(S);
  2468. }
  2469. // Emit an implicit barrier at the end.
  2470. if (!S.getSingleClause<OMPNowaitClause>()) {
  2471. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(),
  2472. OMPD_sections);
  2473. }
  2474. }
  2475. void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) {
  2476. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  2477. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  2478. };
  2479. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2480. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen,
  2481. S.hasCancel());
  2482. }
  2483. void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) {
  2484. llvm::SmallVector<const Expr *, 8> CopyprivateVars;
  2485. llvm::SmallVector<const Expr *, 8> DestExprs;
  2486. llvm::SmallVector<const Expr *, 8> SrcExprs;
  2487. llvm::SmallVector<const Expr *, 8> AssignmentOps;
  2488. // Check if there are any 'copyprivate' clauses associated with this
  2489. // 'single' construct.
  2490. // Build a list of copyprivate variables along with helper expressions
  2491. // (<source>, <destination>, <destination>=<source> expressions)
  2492. for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) {
  2493. CopyprivateVars.append(C->varlists().begin(), C->varlists().end());
  2494. DestExprs.append(C->destination_exprs().begin(),
  2495. C->destination_exprs().end());
  2496. SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end());
  2497. AssignmentOps.append(C->assignment_ops().begin(),
  2498. C->assignment_ops().end());
  2499. }
  2500. // Emit code for 'single' region along with 'copyprivate' clauses
  2501. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2502. Action.Enter(CGF);
  2503. OMPPrivateScope SingleScope(CGF);
  2504. (void)CGF.EmitOMPFirstprivateClause(S, SingleScope);
  2505. CGF.EmitOMPPrivateClause(S, SingleScope);
  2506. (void)SingleScope.Privatize();
  2507. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  2508. };
  2509. {
  2510. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2511. CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(),
  2512. CopyprivateVars, DestExprs,
  2513. SrcExprs, AssignmentOps);
  2514. }
  2515. // Emit an implicit barrier at the end (to avoid data race on firstprivate
  2516. // init or if no 'nowait' clause was specified and no 'copyprivate' clause).
  2517. if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) {
  2518. CGM.getOpenMPRuntime().emitBarrierCall(
  2519. *this, S.getBeginLoc(),
  2520. S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single);
  2521. }
  2522. }
  2523. void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) {
  2524. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2525. Action.Enter(CGF);
  2526. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  2527. };
  2528. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2529. CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc());
  2530. }
  2531. void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) {
  2532. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2533. Action.Enter(CGF);
  2534. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  2535. };
  2536. const Expr *Hint = nullptr;
  2537. if (const auto *HintClause = S.getSingleClause<OMPHintClause>())
  2538. Hint = HintClause->getHint();
  2539. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  2540. CGM.getOpenMPRuntime().emitCriticalRegion(*this,
  2541. S.getDirectiveName().getAsString(),
  2542. CodeGen, S.getBeginLoc(), Hint);
  2543. }
  2544. void CodeGenFunction::EmitOMPParallelForDirective(
  2545. const OMPParallelForDirective &S) {
  2546. // Emit directive as a combined directive that consists of two implicit
  2547. // directives: 'parallel' with 'for' directive.
  2548. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2549. Action.Enter(CGF);
  2550. OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel());
  2551. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  2552. emitDispatchForLoopBounds);
  2553. };
  2554. emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen,
  2555. emitEmptyBoundParameters);
  2556. }
  2557. void CodeGenFunction::EmitOMPParallelForSimdDirective(
  2558. const OMPParallelForSimdDirective &S) {
  2559. // Emit directive as a combined directive that consists of two implicit
  2560. // directives: 'parallel' with 'for' directive.
  2561. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2562. Action.Enter(CGF);
  2563. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  2564. emitDispatchForLoopBounds);
  2565. };
  2566. emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen,
  2567. emitEmptyBoundParameters);
  2568. }
  2569. void CodeGenFunction::EmitOMPParallelSectionsDirective(
  2570. const OMPParallelSectionsDirective &S) {
  2571. // Emit directive as a combined directive that consists of two implicit
  2572. // directives: 'parallel' with 'sections' directive.
  2573. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2574. Action.Enter(CGF);
  2575. CGF.EmitSections(S);
  2576. };
  2577. emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen,
  2578. emitEmptyBoundParameters);
  2579. }
  2580. void CodeGenFunction::EmitOMPTaskBasedDirective(
  2581. const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion,
  2582. const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen,
  2583. OMPTaskDataTy &Data) {
  2584. // Emit outlined function for task construct.
  2585. const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion);
  2586. auto I = CS->getCapturedDecl()->param_begin();
  2587. auto PartId = std::next(I);
  2588. auto TaskT = std::next(I, 4);
  2589. // Check if the task is final
  2590. if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) {
  2591. // If the condition constant folds and can be elided, try to avoid emitting
  2592. // the condition and the dead arm of the if/else.
  2593. const Expr *Cond = Clause->getCondition();
  2594. bool CondConstant;
  2595. if (ConstantFoldsToSimpleInteger(Cond, CondConstant))
  2596. Data.Final.setInt(CondConstant);
  2597. else
  2598. Data.Final.setPointer(EvaluateExprAsBool(Cond));
  2599. } else {
  2600. // By default the task is not final.
  2601. Data.Final.setInt(/*IntVal=*/false);
  2602. }
  2603. // Check if the task has 'priority' clause.
  2604. if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) {
  2605. const Expr *Prio = Clause->getPriority();
  2606. Data.Priority.setInt(/*IntVal=*/true);
  2607. Data.Priority.setPointer(EmitScalarConversion(
  2608. EmitScalarExpr(Prio), Prio->getType(),
  2609. getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
  2610. Prio->getExprLoc()));
  2611. }
  2612. // The first function argument for tasks is a thread id, the second one is a
  2613. // part id (0 for tied tasks, >=0 for untied task).
  2614. llvm::DenseSet<const VarDecl *> EmittedAsPrivate;
  2615. // Get list of private variables.
  2616. for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) {
  2617. auto IRef = C->varlist_begin();
  2618. for (const Expr *IInit : C->private_copies()) {
  2619. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2620. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2621. Data.PrivateVars.push_back(*IRef);
  2622. Data.PrivateCopies.push_back(IInit);
  2623. }
  2624. ++IRef;
  2625. }
  2626. }
  2627. EmittedAsPrivate.clear();
  2628. // Get list of firstprivate variables.
  2629. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  2630. auto IRef = C->varlist_begin();
  2631. auto IElemInitRef = C->inits().begin();
  2632. for (const Expr *IInit : C->private_copies()) {
  2633. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2634. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2635. Data.FirstprivateVars.push_back(*IRef);
  2636. Data.FirstprivateCopies.push_back(IInit);
  2637. Data.FirstprivateInits.push_back(*IElemInitRef);
  2638. }
  2639. ++IRef;
  2640. ++IElemInitRef;
  2641. }
  2642. }
  2643. // Get list of lastprivate variables (for taskloops).
  2644. llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs;
  2645. for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) {
  2646. auto IRef = C->varlist_begin();
  2647. auto ID = C->destination_exprs().begin();
  2648. for (const Expr *IInit : C->private_copies()) {
  2649. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl());
  2650. if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) {
  2651. Data.LastprivateVars.push_back(*IRef);
  2652. Data.LastprivateCopies.push_back(IInit);
  2653. }
  2654. LastprivateDstsOrigs.insert(
  2655. {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()),
  2656. cast<DeclRefExpr>(*IRef)});
  2657. ++IRef;
  2658. ++ID;
  2659. }
  2660. }
  2661. SmallVector<const Expr *, 4> LHSs;
  2662. SmallVector<const Expr *, 4> RHSs;
  2663. for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) {
  2664. auto IPriv = C->privates().begin();
  2665. auto IRed = C->reduction_ops().begin();
  2666. auto ILHS = C->lhs_exprs().begin();
  2667. auto IRHS = C->rhs_exprs().begin();
  2668. for (const Expr *Ref : C->varlists()) {
  2669. Data.ReductionVars.emplace_back(Ref);
  2670. Data.ReductionCopies.emplace_back(*IPriv);
  2671. Data.ReductionOps.emplace_back(*IRed);
  2672. LHSs.emplace_back(*ILHS);
  2673. RHSs.emplace_back(*IRHS);
  2674. std::advance(IPriv, 1);
  2675. std::advance(IRed, 1);
  2676. std::advance(ILHS, 1);
  2677. std::advance(IRHS, 1);
  2678. }
  2679. }
  2680. Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit(
  2681. *this, S.getBeginLoc(), LHSs, RHSs, Data);
  2682. // Build list of dependences.
  2683. for (const auto *C : S.getClausesOfKind<OMPDependClause>())
  2684. for (const Expr *IRef : C->varlists())
  2685. Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
  2686. auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs,
  2687. CapturedRegion](CodeGenFunction &CGF,
  2688. PrePostActionTy &Action) {
  2689. // Set proper addresses for generated private copies.
  2690. OMPPrivateScope Scope(CGF);
  2691. if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() ||
  2692. !Data.LastprivateVars.empty()) {
  2693. enum { PrivatesParam = 2, CopyFnParam = 3 };
  2694. llvm::Value *CopyFn = CGF.Builder.CreateLoad(
  2695. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
  2696. llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
  2697. CS->getCapturedDecl()->getParam(PrivatesParam)));
  2698. // Map privates.
  2699. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
  2700. llvm::SmallVector<llvm::Value *, 16> CallArgs;
  2701. CallArgs.push_back(PrivatesPtr);
  2702. for (const Expr *E : Data.PrivateVars) {
  2703. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2704. Address PrivatePtr = CGF.CreateMemTemp(
  2705. CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr");
  2706. PrivatePtrs.emplace_back(VD, PrivatePtr);
  2707. CallArgs.push_back(PrivatePtr.getPointer());
  2708. }
  2709. for (const Expr *E : Data.FirstprivateVars) {
  2710. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2711. Address PrivatePtr =
  2712. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  2713. ".firstpriv.ptr.addr");
  2714. PrivatePtrs.emplace_back(VD, PrivatePtr);
  2715. CallArgs.push_back(PrivatePtr.getPointer());
  2716. }
  2717. for (const Expr *E : Data.LastprivateVars) {
  2718. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2719. Address PrivatePtr =
  2720. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  2721. ".lastpriv.ptr.addr");
  2722. PrivatePtrs.emplace_back(VD, PrivatePtr);
  2723. CallArgs.push_back(PrivatePtr.getPointer());
  2724. }
  2725. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
  2726. CopyFn, CallArgs);
  2727. for (const auto &Pair : LastprivateDstsOrigs) {
  2728. const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl());
  2729. DeclRefExpr DRE(
  2730. const_cast<VarDecl *>(OrigVD),
  2731. /*RefersToEnclosingVariableOrCapture=*/CGF.CapturedStmtInfo->lookup(
  2732. OrigVD) != nullptr,
  2733. Pair.second->getType(), VK_LValue, Pair.second->getExprLoc());
  2734. Scope.addPrivate(Pair.first, [&CGF, &DRE]() {
  2735. return CGF.EmitLValue(&DRE).getAddress();
  2736. });
  2737. }
  2738. for (const auto &Pair : PrivatePtrs) {
  2739. Address Replacement(CGF.Builder.CreateLoad(Pair.second),
  2740. CGF.getContext().getDeclAlign(Pair.first));
  2741. Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
  2742. }
  2743. }
  2744. if (Data.Reductions) {
  2745. OMPLexicalScope LexScope(CGF, S, CapturedRegion);
  2746. ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies,
  2747. Data.ReductionOps);
  2748. llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad(
  2749. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9)));
  2750. for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) {
  2751. RedCG.emitSharedLValue(CGF, Cnt);
  2752. RedCG.emitAggregateType(CGF, Cnt);
  2753. // FIXME: This must removed once the runtime library is fixed.
  2754. // Emit required threadprivate variables for
  2755. // initilizer/combiner/finalizer.
  2756. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  2757. RedCG, Cnt);
  2758. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  2759. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  2760. Replacement =
  2761. Address(CGF.EmitScalarConversion(
  2762. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  2763. CGF.getContext().getPointerType(
  2764. Data.ReductionCopies[Cnt]->getType()),
  2765. Data.ReductionCopies[Cnt]->getExprLoc()),
  2766. Replacement.getAlignment());
  2767. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  2768. Scope.addPrivate(RedCG.getBaseDecl(Cnt),
  2769. [Replacement]() { return Replacement; });
  2770. }
  2771. }
  2772. // Privatize all private variables except for in_reduction items.
  2773. (void)Scope.Privatize();
  2774. SmallVector<const Expr *, 4> InRedVars;
  2775. SmallVector<const Expr *, 4> InRedPrivs;
  2776. SmallVector<const Expr *, 4> InRedOps;
  2777. SmallVector<const Expr *, 4> TaskgroupDescriptors;
  2778. for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) {
  2779. auto IPriv = C->privates().begin();
  2780. auto IRed = C->reduction_ops().begin();
  2781. auto ITD = C->taskgroup_descriptors().begin();
  2782. for (const Expr *Ref : C->varlists()) {
  2783. InRedVars.emplace_back(Ref);
  2784. InRedPrivs.emplace_back(*IPriv);
  2785. InRedOps.emplace_back(*IRed);
  2786. TaskgroupDescriptors.emplace_back(*ITD);
  2787. std::advance(IPriv, 1);
  2788. std::advance(IRed, 1);
  2789. std::advance(ITD, 1);
  2790. }
  2791. }
  2792. // Privatize in_reduction items here, because taskgroup descriptors must be
  2793. // privatized earlier.
  2794. OMPPrivateScope InRedScope(CGF);
  2795. if (!InRedVars.empty()) {
  2796. ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps);
  2797. for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) {
  2798. RedCG.emitSharedLValue(CGF, Cnt);
  2799. RedCG.emitAggregateType(CGF, Cnt);
  2800. // The taskgroup descriptor variable is always implicit firstprivate and
  2801. // privatized already during procoessing of the firstprivates.
  2802. // FIXME: This must removed once the runtime library is fixed.
  2803. // Emit required threadprivate variables for
  2804. // initilizer/combiner/finalizer.
  2805. CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(),
  2806. RedCG, Cnt);
  2807. llvm::Value *ReductionsPtr =
  2808. CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]),
  2809. TaskgroupDescriptors[Cnt]->getExprLoc());
  2810. Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem(
  2811. CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt));
  2812. Replacement = Address(
  2813. CGF.EmitScalarConversion(
  2814. Replacement.getPointer(), CGF.getContext().VoidPtrTy,
  2815. CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()),
  2816. InRedPrivs[Cnt]->getExprLoc()),
  2817. Replacement.getAlignment());
  2818. Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement);
  2819. InRedScope.addPrivate(RedCG.getBaseDecl(Cnt),
  2820. [Replacement]() { return Replacement; });
  2821. }
  2822. }
  2823. (void)InRedScope.Privatize();
  2824. Action.Enter(CGF);
  2825. BodyGen(CGF);
  2826. };
  2827. llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
  2828. S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied,
  2829. Data.NumberOfParts);
  2830. OMPLexicalScope Scope(*this, S);
  2831. TaskGen(*this, OutlinedFn, Data);
  2832. }
  2833. static ImplicitParamDecl *
  2834. createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data,
  2835. QualType Ty, CapturedDecl *CD,
  2836. SourceLocation Loc) {
  2837. auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
  2838. ImplicitParamDecl::Other);
  2839. auto *OrigRef = DeclRefExpr::Create(
  2840. C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD,
  2841. /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
  2842. auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty,
  2843. ImplicitParamDecl::Other);
  2844. auto *PrivateRef = DeclRefExpr::Create(
  2845. C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD,
  2846. /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue);
  2847. QualType ElemType = C.getBaseElementType(Ty);
  2848. auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType,
  2849. ImplicitParamDecl::Other);
  2850. auto *InitRef = DeclRefExpr::Create(
  2851. C, NestedNameSpecifierLoc(), SourceLocation(), InitVD,
  2852. /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue);
  2853. PrivateVD->setInitStyle(VarDecl::CInit);
  2854. PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue,
  2855. InitRef, /*BasePath=*/nullptr,
  2856. VK_RValue));
  2857. Data.FirstprivateVars.emplace_back(OrigRef);
  2858. Data.FirstprivateCopies.emplace_back(PrivateRef);
  2859. Data.FirstprivateInits.emplace_back(InitRef);
  2860. return OrigVD;
  2861. }
  2862. void CodeGenFunction::EmitOMPTargetTaskBasedDirective(
  2863. const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen,
  2864. OMPTargetDataInfo &InputInfo) {
  2865. // Emit outlined function for task construct.
  2866. const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
  2867. Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
  2868. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  2869. auto I = CS->getCapturedDecl()->param_begin();
  2870. auto PartId = std::next(I);
  2871. auto TaskT = std::next(I, 4);
  2872. OMPTaskDataTy Data;
  2873. // The task is not final.
  2874. Data.Final.setInt(/*IntVal=*/false);
  2875. // Get list of firstprivate variables.
  2876. for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) {
  2877. auto IRef = C->varlist_begin();
  2878. auto IElemInitRef = C->inits().begin();
  2879. for (auto *IInit : C->private_copies()) {
  2880. Data.FirstprivateVars.push_back(*IRef);
  2881. Data.FirstprivateCopies.push_back(IInit);
  2882. Data.FirstprivateInits.push_back(*IElemInitRef);
  2883. ++IRef;
  2884. ++IElemInitRef;
  2885. }
  2886. }
  2887. OMPPrivateScope TargetScope(*this);
  2888. VarDecl *BPVD = nullptr;
  2889. VarDecl *PVD = nullptr;
  2890. VarDecl *SVD = nullptr;
  2891. if (InputInfo.NumberOfTargetItems > 0) {
  2892. auto *CD = CapturedDecl::Create(
  2893. getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0);
  2894. llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems);
  2895. QualType BaseAndPointersType = getContext().getConstantArrayType(
  2896. getContext().VoidPtrTy, ArrSize, ArrayType::Normal,
  2897. /*IndexTypeQuals=*/0);
  2898. BPVD = createImplicitFirstprivateForType(
  2899. getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
  2900. PVD = createImplicitFirstprivateForType(
  2901. getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc());
  2902. QualType SizesType = getContext().getConstantArrayType(
  2903. getContext().getSizeType(), ArrSize, ArrayType::Normal,
  2904. /*IndexTypeQuals=*/0);
  2905. SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
  2906. S.getBeginLoc());
  2907. TargetScope.addPrivate(
  2908. BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; });
  2909. TargetScope.addPrivate(PVD,
  2910. [&InputInfo]() { return InputInfo.PointersArray; });
  2911. TargetScope.addPrivate(SVD,
  2912. [&InputInfo]() { return InputInfo.SizesArray; });
  2913. }
  2914. (void)TargetScope.Privatize();
  2915. // Build list of dependences.
  2916. for (const auto *C : S.getClausesOfKind<OMPDependClause>())
  2917. for (const Expr *IRef : C->varlists())
  2918. Data.Dependences.emplace_back(C->getDependencyKind(), IRef);
  2919. auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD,
  2920. &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2921. // Set proper addresses for generated private copies.
  2922. OMPPrivateScope Scope(CGF);
  2923. if (!Data.FirstprivateVars.empty()) {
  2924. enum { PrivatesParam = 2, CopyFnParam = 3 };
  2925. llvm::Value *CopyFn = CGF.Builder.CreateLoad(
  2926. CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam)));
  2927. llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(
  2928. CS->getCapturedDecl()->getParam(PrivatesParam)));
  2929. // Map privates.
  2930. llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs;
  2931. llvm::SmallVector<llvm::Value *, 16> CallArgs;
  2932. CallArgs.push_back(PrivatesPtr);
  2933. for (const Expr *E : Data.FirstprivateVars) {
  2934. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  2935. Address PrivatePtr =
  2936. CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()),
  2937. ".firstpriv.ptr.addr");
  2938. PrivatePtrs.emplace_back(VD, PrivatePtr);
  2939. CallArgs.push_back(PrivatePtr.getPointer());
  2940. }
  2941. CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
  2942. CopyFn, CallArgs);
  2943. for (const auto &Pair : PrivatePtrs) {
  2944. Address Replacement(CGF.Builder.CreateLoad(Pair.second),
  2945. CGF.getContext().getDeclAlign(Pair.first));
  2946. Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; });
  2947. }
  2948. }
  2949. // Privatize all private variables except for in_reduction items.
  2950. (void)Scope.Privatize();
  2951. if (InputInfo.NumberOfTargetItems > 0) {
  2952. InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP(
  2953. CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0, CGF.getPointerSize());
  2954. InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP(
  2955. CGF.GetAddrOfLocalVar(PVD), /*Index=*/0, CGF.getPointerSize());
  2956. InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
  2957. CGF.GetAddrOfLocalVar(SVD), /*Index=*/0, CGF.getSizeSize());
  2958. }
  2959. Action.Enter(CGF);
  2960. OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false);
  2961. BodyGen(CGF);
  2962. };
  2963. llvm::Value *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction(
  2964. S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true,
  2965. Data.NumberOfParts);
  2966. llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0);
  2967. IntegerLiteral IfCond(getContext(), TrueOrFalse,
  2968. getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  2969. SourceLocation());
  2970. CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn,
  2971. SharedsTy, CapturedStruct, &IfCond, Data);
  2972. }
  2973. void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) {
  2974. // Emit outlined function for task construct.
  2975. const CapturedStmt *CS = S.getCapturedStmt(OMPD_task);
  2976. Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
  2977. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  2978. const Expr *IfCond = nullptr;
  2979. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  2980. if (C->getNameModifier() == OMPD_unknown ||
  2981. C->getNameModifier() == OMPD_task) {
  2982. IfCond = C->getCondition();
  2983. break;
  2984. }
  2985. }
  2986. OMPTaskDataTy Data;
  2987. // Check if we should emit tied or untied task.
  2988. Data.Tied = !S.getSingleClause<OMPUntiedClause>();
  2989. auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
  2990. CGF.EmitStmt(CS->getCapturedStmt());
  2991. };
  2992. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  2993. IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
  2994. const OMPTaskDataTy &Data) {
  2995. CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn,
  2996. SharedsTy, CapturedStruct, IfCond,
  2997. Data);
  2998. };
  2999. EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data);
  3000. }
  3001. void CodeGenFunction::EmitOMPTaskyieldDirective(
  3002. const OMPTaskyieldDirective &S) {
  3003. CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc());
  3004. }
  3005. void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) {
  3006. CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier);
  3007. }
  3008. void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) {
  3009. CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc());
  3010. }
  3011. void CodeGenFunction::EmitOMPTaskgroupDirective(
  3012. const OMPTaskgroupDirective &S) {
  3013. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3014. Action.Enter(CGF);
  3015. if (const Expr *E = S.getReductionRef()) {
  3016. SmallVector<const Expr *, 4> LHSs;
  3017. SmallVector<const Expr *, 4> RHSs;
  3018. OMPTaskDataTy Data;
  3019. for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) {
  3020. auto IPriv = C->privates().begin();
  3021. auto IRed = C->reduction_ops().begin();
  3022. auto ILHS = C->lhs_exprs().begin();
  3023. auto IRHS = C->rhs_exprs().begin();
  3024. for (const Expr *Ref : C->varlists()) {
  3025. Data.ReductionVars.emplace_back(Ref);
  3026. Data.ReductionCopies.emplace_back(*IPriv);
  3027. Data.ReductionOps.emplace_back(*IRed);
  3028. LHSs.emplace_back(*ILHS);
  3029. RHSs.emplace_back(*IRHS);
  3030. std::advance(IPriv, 1);
  3031. std::advance(IRed, 1);
  3032. std::advance(ILHS, 1);
  3033. std::advance(IRHS, 1);
  3034. }
  3035. }
  3036. llvm::Value *ReductionDesc =
  3037. CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(),
  3038. LHSs, RHSs, Data);
  3039. const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
  3040. CGF.EmitVarDecl(*VD);
  3041. CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD),
  3042. /*Volatile=*/false, E->getType());
  3043. }
  3044. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  3045. };
  3046. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3047. CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc());
  3048. }
  3049. void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) {
  3050. CGM.getOpenMPRuntime().emitFlush(
  3051. *this,
  3052. [&S]() -> ArrayRef<const Expr *> {
  3053. if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>())
  3054. return llvm::makeArrayRef(FlushClause->varlist_begin(),
  3055. FlushClause->varlist_end());
  3056. return llvm::None;
  3057. }(),
  3058. S.getBeginLoc());
  3059. }
  3060. void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S,
  3061. const CodeGenLoopTy &CodeGenLoop,
  3062. Expr *IncExpr) {
  3063. // Emit the loop iteration variable.
  3064. const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable());
  3065. const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl());
  3066. EmitVarDecl(*IVDecl);
  3067. // Emit the iterations count variable.
  3068. // If it is not a variable, Sema decided to calculate iterations count on each
  3069. // iteration (e.g., it is foldable into a constant).
  3070. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  3071. EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  3072. // Emit calculation of the iterations count.
  3073. EmitIgnoredExpr(S.getCalcLastIteration());
  3074. }
  3075. CGOpenMPRuntime &RT = CGM.getOpenMPRuntime();
  3076. bool HasLastprivateClause = false;
  3077. // Check pre-condition.
  3078. {
  3079. OMPLoopScope PreInitScope(*this, S);
  3080. // Skip the entire loop if we don't meet the precondition.
  3081. // If the condition constant folds and can be elided, avoid emitting the
  3082. // whole loop.
  3083. bool CondConstant;
  3084. llvm::BasicBlock *ContBlock = nullptr;
  3085. if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  3086. if (!CondConstant)
  3087. return;
  3088. } else {
  3089. llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then");
  3090. ContBlock = createBasicBlock("omp.precond.end");
  3091. emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock,
  3092. getProfileCount(&S));
  3093. EmitBlock(ThenBlock);
  3094. incrementProfileCounter(&S);
  3095. }
  3096. emitAlignedClause(*this, S);
  3097. // Emit 'then' code.
  3098. {
  3099. // Emit helper vars inits.
  3100. LValue LB = EmitOMPHelperVar(
  3101. *this, cast<DeclRefExpr>(
  3102. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  3103. ? S.getCombinedLowerBoundVariable()
  3104. : S.getLowerBoundVariable())));
  3105. LValue UB = EmitOMPHelperVar(
  3106. *this, cast<DeclRefExpr>(
  3107. (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  3108. ? S.getCombinedUpperBoundVariable()
  3109. : S.getUpperBoundVariable())));
  3110. LValue ST =
  3111. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable()));
  3112. LValue IL =
  3113. EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable()));
  3114. OMPPrivateScope LoopScope(*this);
  3115. if (EmitOMPFirstprivateClause(S, LoopScope)) {
  3116. // Emit implicit barrier to synchronize threads and avoid data races
  3117. // on initialization of firstprivate variables and post-update of
  3118. // lastprivate variables.
  3119. CGM.getOpenMPRuntime().emitBarrierCall(
  3120. *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
  3121. /*ForceSimpleCall=*/true);
  3122. }
  3123. EmitOMPPrivateClause(S, LoopScope);
  3124. if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
  3125. !isOpenMPParallelDirective(S.getDirectiveKind()) &&
  3126. !isOpenMPTeamsDirective(S.getDirectiveKind()))
  3127. EmitOMPReductionClauseInit(S, LoopScope);
  3128. HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope);
  3129. EmitOMPPrivateLoopCounters(S, LoopScope);
  3130. (void)LoopScope.Privatize();
  3131. // Detect the distribute schedule kind and chunk.
  3132. llvm::Value *Chunk = nullptr;
  3133. OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown;
  3134. if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) {
  3135. ScheduleKind = C->getDistScheduleKind();
  3136. if (const Expr *Ch = C->getChunkSize()) {
  3137. Chunk = EmitScalarExpr(Ch);
  3138. Chunk = EmitScalarConversion(Chunk, Ch->getType(),
  3139. S.getIterationVariable()->getType(),
  3140. S.getBeginLoc());
  3141. }
  3142. } else {
  3143. // Default behaviour for dist_schedule clause.
  3144. CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk(
  3145. *this, S, ScheduleKind, Chunk);
  3146. }
  3147. const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());
  3148. const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation();
  3149. // OpenMP [2.10.8, distribute Construct, Description]
  3150. // If dist_schedule is specified, kind must be static. If specified,
  3151. // iterations are divided into chunks of size chunk_size, chunks are
  3152. // assigned to the teams of the league in a round-robin fashion in the
  3153. // order of the team number. When no chunk_size is specified, the
  3154. // iteration space is divided into chunks that are approximately equal
  3155. // in size, and at most one chunk is distributed to each team of the
  3156. // league. The size of the chunks is unspecified in this case.
  3157. if (RT.isStaticNonchunked(ScheduleKind,
  3158. /* Chunked */ Chunk != nullptr)) {
  3159. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  3160. EmitOMPSimdInit(S, /*IsMonotonic=*/true);
  3161. CGOpenMPRuntime::StaticRTInput StaticInit(
  3162. IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(),
  3163. LB.getAddress(), UB.getAddress(), ST.getAddress());
  3164. RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind,
  3165. StaticInit);
  3166. JumpDest LoopExit =
  3167. getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit"));
  3168. // UB = min(UB, GlobalUB);
  3169. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  3170. ? S.getCombinedEnsureUpperBound()
  3171. : S.getEnsureUpperBound());
  3172. // IV = LB;
  3173. EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  3174. ? S.getCombinedInit()
  3175. : S.getInit());
  3176. const Expr *Cond =
  3177. isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())
  3178. ? S.getCombinedCond()
  3179. : S.getCond();
  3180. // for distribute alone, codegen
  3181. // while (idx <= UB) { BODY; ++idx; }
  3182. // when combined with 'for' (e.g. as in 'distribute parallel for')
  3183. // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; }
  3184. EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), Cond, IncExpr,
  3185. [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) {
  3186. CodeGenLoop(CGF, S, LoopExit);
  3187. },
  3188. [](CodeGenFunction &) {});
  3189. EmitBlock(LoopExit.getBlock());
  3190. // Tell the runtime we are done.
  3191. RT.emitForStaticFinish(*this, S.getBeginLoc(), S.getDirectiveKind());
  3192. } else {
  3193. // Emit the outer loop, which requests its work chunk [LB..UB] from
  3194. // runtime and runs the inner loop to process it.
  3195. const OMPLoopArguments LoopArguments = {
  3196. LB.getAddress(), UB.getAddress(), ST.getAddress(), IL.getAddress(),
  3197. Chunk};
  3198. EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments,
  3199. CodeGenLoop);
  3200. }
  3201. if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  3202. EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) {
  3203. return CGF.Builder.CreateIsNotNull(
  3204. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3205. });
  3206. }
  3207. if (isOpenMPSimdDirective(S.getDirectiveKind()) &&
  3208. !isOpenMPParallelDirective(S.getDirectiveKind()) &&
  3209. !isOpenMPTeamsDirective(S.getDirectiveKind())) {
  3210. OpenMPDirectiveKind ReductionKind = OMPD_unknown;
  3211. if (isOpenMPParallelDirective(S.getDirectiveKind()) &&
  3212. isOpenMPSimdDirective(S.getDirectiveKind())) {
  3213. ReductionKind = OMPD_parallel_for_simd;
  3214. } else if (isOpenMPParallelDirective(S.getDirectiveKind())) {
  3215. ReductionKind = OMPD_parallel_for;
  3216. } else if (isOpenMPSimdDirective(S.getDirectiveKind())) {
  3217. ReductionKind = OMPD_simd;
  3218. } else if (!isOpenMPTeamsDirective(S.getDirectiveKind()) &&
  3219. S.hasClausesOfKind<OMPReductionClause>()) {
  3220. llvm_unreachable(
  3221. "No reduction clauses is allowed in distribute directive.");
  3222. }
  3223. EmitOMPReductionClauseFinal(S, ReductionKind);
  3224. // Emit post-update of the reduction variables if IsLastIter != 0.
  3225. emitPostUpdateForReductionClause(
  3226. *this, S, [IL, &S](CodeGenFunction &CGF) {
  3227. return CGF.Builder.CreateIsNotNull(
  3228. CGF.EmitLoadOfScalar(IL, S.getBeginLoc()));
  3229. });
  3230. }
  3231. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  3232. if (HasLastprivateClause) {
  3233. EmitOMPLastprivateClauseFinal(
  3234. S, /*NoFinals=*/false,
  3235. Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc())));
  3236. }
  3237. }
  3238. // We're now done with the loop, so jump to the continuation block.
  3239. if (ContBlock) {
  3240. EmitBranch(ContBlock);
  3241. EmitBlock(ContBlock, true);
  3242. }
  3243. }
  3244. }
  3245. void CodeGenFunction::EmitOMPDistributeDirective(
  3246. const OMPDistributeDirective &S) {
  3247. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3248. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  3249. };
  3250. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3251. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen);
  3252. }
  3253. static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM,
  3254. const CapturedStmt *S) {
  3255. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  3256. CodeGenFunction::CGCapturedStmtInfo CapStmtInfo;
  3257. CGF.CapturedStmtInfo = &CapStmtInfo;
  3258. llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S);
  3259. Fn->setDoesNotRecurse();
  3260. return Fn;
  3261. }
  3262. void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) {
  3263. if (S.hasClausesOfKind<OMPDependClause>()) {
  3264. assert(!S.getAssociatedStmt() &&
  3265. "No associated statement must be in ordered depend construct.");
  3266. for (const auto *DC : S.getClausesOfKind<OMPDependClause>())
  3267. CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC);
  3268. return;
  3269. }
  3270. const auto *C = S.getSingleClause<OMPSIMDClause>();
  3271. auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF,
  3272. PrePostActionTy &Action) {
  3273. const CapturedStmt *CS = S.getInnermostCapturedStmt();
  3274. if (C) {
  3275. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3276. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  3277. llvm::Function *OutlinedFn = emitOutlinedOrderedFunction(CGM, CS);
  3278. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(),
  3279. OutlinedFn, CapturedVars);
  3280. } else {
  3281. Action.Enter(CGF);
  3282. CGF.EmitStmt(CS->getCapturedStmt());
  3283. }
  3284. };
  3285. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3286. CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C);
  3287. }
  3288. static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val,
  3289. QualType SrcType, QualType DestType,
  3290. SourceLocation Loc) {
  3291. assert(CGF.hasScalarEvaluationKind(DestType) &&
  3292. "DestType must have scalar evaluation kind.");
  3293. assert(!Val.isAggregate() && "Must be a scalar or complex.");
  3294. return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType,
  3295. DestType, Loc)
  3296. : CGF.EmitComplexToScalarConversion(
  3297. Val.getComplexVal(), SrcType, DestType, Loc);
  3298. }
  3299. static CodeGenFunction::ComplexPairTy
  3300. convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType,
  3301. QualType DestType, SourceLocation Loc) {
  3302. assert(CGF.getEvaluationKind(DestType) == TEK_Complex &&
  3303. "DestType must have complex evaluation kind.");
  3304. CodeGenFunction::ComplexPairTy ComplexVal;
  3305. if (Val.isScalar()) {
  3306. // Convert the input element to the element type of the complex.
  3307. QualType DestElementType =
  3308. DestType->castAs<ComplexType>()->getElementType();
  3309. llvm::Value *ScalarVal = CGF.EmitScalarConversion(
  3310. Val.getScalarVal(), SrcType, DestElementType, Loc);
  3311. ComplexVal = CodeGenFunction::ComplexPairTy(
  3312. ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType()));
  3313. } else {
  3314. assert(Val.isComplex() && "Must be a scalar or complex.");
  3315. QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType();
  3316. QualType DestElementType =
  3317. DestType->castAs<ComplexType>()->getElementType();
  3318. ComplexVal.first = CGF.EmitScalarConversion(
  3319. Val.getComplexVal().first, SrcElementType, DestElementType, Loc);
  3320. ComplexVal.second = CGF.EmitScalarConversion(
  3321. Val.getComplexVal().second, SrcElementType, DestElementType, Loc);
  3322. }
  3323. return ComplexVal;
  3324. }
  3325. static void emitSimpleAtomicStore(CodeGenFunction &CGF, bool IsSeqCst,
  3326. LValue LVal, RValue RVal) {
  3327. if (LVal.isGlobalReg()) {
  3328. CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal);
  3329. } else {
  3330. CGF.EmitAtomicStore(RVal, LVal,
  3331. IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3332. : llvm::AtomicOrdering::Monotonic,
  3333. LVal.isVolatile(), /*IsInit=*/false);
  3334. }
  3335. }
  3336. void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal,
  3337. QualType RValTy, SourceLocation Loc) {
  3338. switch (getEvaluationKind(LVal.getType())) {
  3339. case TEK_Scalar:
  3340. EmitStoreThroughLValue(RValue::get(convertToScalarValue(
  3341. *this, RVal, RValTy, LVal.getType(), Loc)),
  3342. LVal);
  3343. break;
  3344. case TEK_Complex:
  3345. EmitStoreOfComplex(
  3346. convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal,
  3347. /*isInit=*/false);
  3348. break;
  3349. case TEK_Aggregate:
  3350. llvm_unreachable("Must be a scalar or complex.");
  3351. }
  3352. }
  3353. static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3354. const Expr *X, const Expr *V,
  3355. SourceLocation Loc) {
  3356. // v = x;
  3357. assert(V->isLValue() && "V of 'omp atomic read' is not lvalue");
  3358. assert(X->isLValue() && "X of 'omp atomic read' is not lvalue");
  3359. LValue XLValue = CGF.EmitLValue(X);
  3360. LValue VLValue = CGF.EmitLValue(V);
  3361. RValue Res = XLValue.isGlobalReg()
  3362. ? CGF.EmitLoadOfLValue(XLValue, Loc)
  3363. : CGF.EmitAtomicLoad(
  3364. XLValue, Loc,
  3365. IsSeqCst ? llvm::AtomicOrdering::SequentiallyConsistent
  3366. : llvm::AtomicOrdering::Monotonic,
  3367. XLValue.isVolatile());
  3368. // OpenMP, 2.12.6, atomic Construct
  3369. // Any atomic construct with a seq_cst clause forces the atomically
  3370. // performed operation to include an implicit flush operation without a
  3371. // list.
  3372. if (IsSeqCst)
  3373. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3374. CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc);
  3375. }
  3376. static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3377. const Expr *X, const Expr *E,
  3378. SourceLocation Loc) {
  3379. // x = expr;
  3380. assert(X->isLValue() && "X of 'omp atomic write' is not lvalue");
  3381. emitSimpleAtomicStore(CGF, IsSeqCst, CGF.EmitLValue(X), CGF.EmitAnyExpr(E));
  3382. // OpenMP, 2.12.6, atomic Construct
  3383. // Any atomic construct with a seq_cst clause forces the atomically
  3384. // performed operation to include an implicit flush operation without a
  3385. // list.
  3386. if (IsSeqCst)
  3387. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3388. }
  3389. static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X,
  3390. RValue Update,
  3391. BinaryOperatorKind BO,
  3392. llvm::AtomicOrdering AO,
  3393. bool IsXLHSInRHSPart) {
  3394. ASTContext &Context = CGF.getContext();
  3395. // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x'
  3396. // expression is simple and atomic is allowed for the given type for the
  3397. // target platform.
  3398. if (BO == BO_Comma || !Update.isScalar() ||
  3399. !Update.getScalarVal()->getType()->isIntegerTy() ||
  3400. !X.isSimple() || (!isa<llvm::ConstantInt>(Update.getScalarVal()) &&
  3401. (Update.getScalarVal()->getType() !=
  3402. X.getAddress().getElementType())) ||
  3403. !X.getAddress().getElementType()->isIntegerTy() ||
  3404. !Context.getTargetInfo().hasBuiltinAtomic(
  3405. Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment())))
  3406. return std::make_pair(false, RValue::get(nullptr));
  3407. llvm::AtomicRMWInst::BinOp RMWOp;
  3408. switch (BO) {
  3409. case BO_Add:
  3410. RMWOp = llvm::AtomicRMWInst::Add;
  3411. break;
  3412. case BO_Sub:
  3413. if (!IsXLHSInRHSPart)
  3414. return std::make_pair(false, RValue::get(nullptr));
  3415. RMWOp = llvm::AtomicRMWInst::Sub;
  3416. break;
  3417. case BO_And:
  3418. RMWOp = llvm::AtomicRMWInst::And;
  3419. break;
  3420. case BO_Or:
  3421. RMWOp = llvm::AtomicRMWInst::Or;
  3422. break;
  3423. case BO_Xor:
  3424. RMWOp = llvm::AtomicRMWInst::Xor;
  3425. break;
  3426. case BO_LT:
  3427. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  3428. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min
  3429. : llvm::AtomicRMWInst::Max)
  3430. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin
  3431. : llvm::AtomicRMWInst::UMax);
  3432. break;
  3433. case BO_GT:
  3434. RMWOp = X.getType()->hasSignedIntegerRepresentation()
  3435. ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max
  3436. : llvm::AtomicRMWInst::Min)
  3437. : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax
  3438. : llvm::AtomicRMWInst::UMin);
  3439. break;
  3440. case BO_Assign:
  3441. RMWOp = llvm::AtomicRMWInst::Xchg;
  3442. break;
  3443. case BO_Mul:
  3444. case BO_Div:
  3445. case BO_Rem:
  3446. case BO_Shl:
  3447. case BO_Shr:
  3448. case BO_LAnd:
  3449. case BO_LOr:
  3450. return std::make_pair(false, RValue::get(nullptr));
  3451. case BO_PtrMemD:
  3452. case BO_PtrMemI:
  3453. case BO_LE:
  3454. case BO_GE:
  3455. case BO_EQ:
  3456. case BO_NE:
  3457. case BO_Cmp:
  3458. case BO_AddAssign:
  3459. case BO_SubAssign:
  3460. case BO_AndAssign:
  3461. case BO_OrAssign:
  3462. case BO_XorAssign:
  3463. case BO_MulAssign:
  3464. case BO_DivAssign:
  3465. case BO_RemAssign:
  3466. case BO_ShlAssign:
  3467. case BO_ShrAssign:
  3468. case BO_Comma:
  3469. llvm_unreachable("Unsupported atomic update operation");
  3470. }
  3471. llvm::Value *UpdateVal = Update.getScalarVal();
  3472. if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) {
  3473. UpdateVal = CGF.Builder.CreateIntCast(
  3474. IC, X.getAddress().getElementType(),
  3475. X.getType()->hasSignedIntegerRepresentation());
  3476. }
  3477. llvm::Value *Res =
  3478. CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(), UpdateVal, AO);
  3479. return std::make_pair(true, RValue::get(Res));
  3480. }
  3481. std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr(
  3482. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  3483. llvm::AtomicOrdering AO, SourceLocation Loc,
  3484. const llvm::function_ref<RValue(RValue)> CommonGen) {
  3485. // Update expressions are allowed to have the following forms:
  3486. // x binop= expr; -> xrval + expr;
  3487. // x++, ++x -> xrval + 1;
  3488. // x--, --x -> xrval - 1;
  3489. // x = x binop expr; -> xrval binop expr
  3490. // x = expr Op x; - > expr binop xrval;
  3491. auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart);
  3492. if (!Res.first) {
  3493. if (X.isGlobalReg()) {
  3494. // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop
  3495. // 'xrval'.
  3496. EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X);
  3497. } else {
  3498. // Perform compare-and-swap procedure.
  3499. EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified());
  3500. }
  3501. }
  3502. return Res;
  3503. }
  3504. static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3505. const Expr *X, const Expr *E,
  3506. const Expr *UE, bool IsXLHSInRHSPart,
  3507. SourceLocation Loc) {
  3508. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  3509. "Update expr in 'atomic update' must be a binary operator.");
  3510. const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  3511. // Update expressions are allowed to have the following forms:
  3512. // x binop= expr; -> xrval + expr;
  3513. // x++, ++x -> xrval + 1;
  3514. // x--, --x -> xrval - 1;
  3515. // x = x binop expr; -> xrval binop expr
  3516. // x = expr Op x; - > expr binop xrval;
  3517. assert(X->isLValue() && "X of 'omp atomic update' is not lvalue");
  3518. LValue XLValue = CGF.EmitLValue(X);
  3519. RValue ExprRValue = CGF.EmitAnyExpr(E);
  3520. llvm::AtomicOrdering AO = IsSeqCst
  3521. ? llvm::AtomicOrdering::SequentiallyConsistent
  3522. : llvm::AtomicOrdering::Monotonic;
  3523. const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  3524. const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  3525. const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  3526. const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  3527. auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) {
  3528. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3529. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  3530. return CGF.EmitAnyExpr(UE);
  3531. };
  3532. (void)CGF.EmitOMPAtomicSimpleUpdateExpr(
  3533. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  3534. // OpenMP, 2.12.6, atomic Construct
  3535. // Any atomic construct with a seq_cst clause forces the atomically
  3536. // performed operation to include an implicit flush operation without a
  3537. // list.
  3538. if (IsSeqCst)
  3539. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3540. }
  3541. static RValue convertToType(CodeGenFunction &CGF, RValue Value,
  3542. QualType SourceType, QualType ResType,
  3543. SourceLocation Loc) {
  3544. switch (CGF.getEvaluationKind(ResType)) {
  3545. case TEK_Scalar:
  3546. return RValue::get(
  3547. convertToScalarValue(CGF, Value, SourceType, ResType, Loc));
  3548. case TEK_Complex: {
  3549. auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc);
  3550. return RValue::getComplex(Res.first, Res.second);
  3551. }
  3552. case TEK_Aggregate:
  3553. break;
  3554. }
  3555. llvm_unreachable("Must be a scalar or complex.");
  3556. }
  3557. static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, bool IsSeqCst,
  3558. bool IsPostfixUpdate, const Expr *V,
  3559. const Expr *X, const Expr *E,
  3560. const Expr *UE, bool IsXLHSInRHSPart,
  3561. SourceLocation Loc) {
  3562. assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue");
  3563. assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue");
  3564. RValue NewVVal;
  3565. LValue VLValue = CGF.EmitLValue(V);
  3566. LValue XLValue = CGF.EmitLValue(X);
  3567. RValue ExprRValue = CGF.EmitAnyExpr(E);
  3568. llvm::AtomicOrdering AO = IsSeqCst
  3569. ? llvm::AtomicOrdering::SequentiallyConsistent
  3570. : llvm::AtomicOrdering::Monotonic;
  3571. QualType NewVValType;
  3572. if (UE) {
  3573. // 'x' is updated with some additional value.
  3574. assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) &&
  3575. "Update expr in 'atomic capture' must be a binary operator.");
  3576. const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts());
  3577. // Update expressions are allowed to have the following forms:
  3578. // x binop= expr; -> xrval + expr;
  3579. // x++, ++x -> xrval + 1;
  3580. // x--, --x -> xrval - 1;
  3581. // x = x binop expr; -> xrval binop expr
  3582. // x = expr Op x; - > expr binop xrval;
  3583. const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts());
  3584. const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts());
  3585. const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS;
  3586. NewVValType = XRValExpr->getType();
  3587. const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS;
  3588. auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr,
  3589. IsPostfixUpdate](RValue XRValue) {
  3590. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3591. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue);
  3592. RValue Res = CGF.EmitAnyExpr(UE);
  3593. NewVVal = IsPostfixUpdate ? XRValue : Res;
  3594. return Res;
  3595. };
  3596. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  3597. XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen);
  3598. if (Res.first) {
  3599. // 'atomicrmw' instruction was generated.
  3600. if (IsPostfixUpdate) {
  3601. // Use old value from 'atomicrmw'.
  3602. NewVVal = Res.second;
  3603. } else {
  3604. // 'atomicrmw' does not provide new value, so evaluate it using old
  3605. // value of 'x'.
  3606. CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue);
  3607. CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second);
  3608. NewVVal = CGF.EmitAnyExpr(UE);
  3609. }
  3610. }
  3611. } else {
  3612. // 'x' is simply rewritten with some 'expr'.
  3613. NewVValType = X->getType().getNonReferenceType();
  3614. ExprRValue = convertToType(CGF, ExprRValue, E->getType(),
  3615. X->getType().getNonReferenceType(), Loc);
  3616. auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) {
  3617. NewVVal = XRValue;
  3618. return ExprRValue;
  3619. };
  3620. // Try to perform atomicrmw xchg, otherwise simple exchange.
  3621. auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr(
  3622. XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO,
  3623. Loc, Gen);
  3624. if (Res.first) {
  3625. // 'atomicrmw' instruction was generated.
  3626. NewVVal = IsPostfixUpdate ? Res.second : ExprRValue;
  3627. }
  3628. }
  3629. // Emit post-update store to 'v' of old/new 'x' value.
  3630. CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc);
  3631. // OpenMP, 2.12.6, atomic Construct
  3632. // Any atomic construct with a seq_cst clause forces the atomically
  3633. // performed operation to include an implicit flush operation without a
  3634. // list.
  3635. if (IsSeqCst)
  3636. CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc);
  3637. }
  3638. static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind,
  3639. bool IsSeqCst, bool IsPostfixUpdate,
  3640. const Expr *X, const Expr *V, const Expr *E,
  3641. const Expr *UE, bool IsXLHSInRHSPart,
  3642. SourceLocation Loc) {
  3643. switch (Kind) {
  3644. case OMPC_read:
  3645. emitOMPAtomicReadExpr(CGF, IsSeqCst, X, V, Loc);
  3646. break;
  3647. case OMPC_write:
  3648. emitOMPAtomicWriteExpr(CGF, IsSeqCst, X, E, Loc);
  3649. break;
  3650. case OMPC_unknown:
  3651. case OMPC_update:
  3652. emitOMPAtomicUpdateExpr(CGF, IsSeqCst, X, E, UE, IsXLHSInRHSPart, Loc);
  3653. break;
  3654. case OMPC_capture:
  3655. emitOMPAtomicCaptureExpr(CGF, IsSeqCst, IsPostfixUpdate, V, X, E, UE,
  3656. IsXLHSInRHSPart, Loc);
  3657. break;
  3658. case OMPC_if:
  3659. case OMPC_final:
  3660. case OMPC_num_threads:
  3661. case OMPC_private:
  3662. case OMPC_firstprivate:
  3663. case OMPC_lastprivate:
  3664. case OMPC_reduction:
  3665. case OMPC_task_reduction:
  3666. case OMPC_in_reduction:
  3667. case OMPC_safelen:
  3668. case OMPC_simdlen:
  3669. case OMPC_collapse:
  3670. case OMPC_default:
  3671. case OMPC_seq_cst:
  3672. case OMPC_shared:
  3673. case OMPC_linear:
  3674. case OMPC_aligned:
  3675. case OMPC_copyin:
  3676. case OMPC_copyprivate:
  3677. case OMPC_flush:
  3678. case OMPC_proc_bind:
  3679. case OMPC_schedule:
  3680. case OMPC_ordered:
  3681. case OMPC_nowait:
  3682. case OMPC_untied:
  3683. case OMPC_threadprivate:
  3684. case OMPC_depend:
  3685. case OMPC_mergeable:
  3686. case OMPC_device:
  3687. case OMPC_threads:
  3688. case OMPC_simd:
  3689. case OMPC_map:
  3690. case OMPC_num_teams:
  3691. case OMPC_thread_limit:
  3692. case OMPC_priority:
  3693. case OMPC_grainsize:
  3694. case OMPC_nogroup:
  3695. case OMPC_num_tasks:
  3696. case OMPC_hint:
  3697. case OMPC_dist_schedule:
  3698. case OMPC_defaultmap:
  3699. case OMPC_uniform:
  3700. case OMPC_to:
  3701. case OMPC_from:
  3702. case OMPC_use_device_ptr:
  3703. case OMPC_is_device_ptr:
  3704. case OMPC_unified_address:
  3705. case OMP_unified_shared_memory:
  3706. llvm_unreachable("Clause is not allowed in 'omp atomic'.");
  3707. }
  3708. }
  3709. void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
  3710. bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
  3711. OpenMPClauseKind Kind = OMPC_unknown;
  3712. for (const OMPClause *C : S.clauses()) {
  3713. // Find first clause (skip seq_cst clause, if it is first).
  3714. if (C->getClauseKind() != OMPC_seq_cst) {
  3715. Kind = C->getClauseKind();
  3716. break;
  3717. }
  3718. }
  3719. const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers();
  3720. if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS))
  3721. enterFullExpression(EWC);
  3722. // Processing for statements under 'atomic capture'.
  3723. if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
  3724. for (const Stmt *C : Compound->body()) {
  3725. if (const auto *EWC = dyn_cast<ExprWithCleanups>(C))
  3726. enterFullExpression(EWC);
  3727. }
  3728. }
  3729. auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
  3730. PrePostActionTy &) {
  3731. CGF.EmitStopPoint(CS);
  3732. emitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
  3733. S.getV(), S.getExpr(), S.getUpdateExpr(),
  3734. S.isXLHSInRHSPart(), S.getBeginLoc());
  3735. };
  3736. OMPLexicalScope Scope(*this, S, OMPD_unknown);
  3737. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
  3738. }
  3739. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  3740. const OMPExecutableDirective &S,
  3741. const RegionCodeGenTy &CodeGen) {
  3742. assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
  3743. CodeGenModule &CGM = CGF.CGM;
  3744. // On device emit this construct as inlined code.
  3745. if (CGM.getLangOpts().OpenMPIsDevice) {
  3746. OMPLexicalScope Scope(CGF, S, OMPD_target);
  3747. CGM.getOpenMPRuntime().emitInlinedDirective(
  3748. CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3749. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  3750. });
  3751. return;
  3752. }
  3753. llvm::Function *Fn = nullptr;
  3754. llvm::Constant *FnID = nullptr;
  3755. const Expr *IfCond = nullptr;
  3756. // Check for the at most one if clause associated with the target region.
  3757. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3758. if (C->getNameModifier() == OMPD_unknown ||
  3759. C->getNameModifier() == OMPD_target) {
  3760. IfCond = C->getCondition();
  3761. break;
  3762. }
  3763. }
  3764. // Check if we have any device clause associated with the directive.
  3765. const Expr *Device = nullptr;
  3766. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3767. Device = C->getDevice();
  3768. // Check if we have an if clause whose conditional always evaluates to false
  3769. // or if we do not have any targets specified. If so the target region is not
  3770. // an offload entry point.
  3771. bool IsOffloadEntry = true;
  3772. if (IfCond) {
  3773. bool Val;
  3774. if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
  3775. IsOffloadEntry = false;
  3776. }
  3777. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3778. IsOffloadEntry = false;
  3779. assert(CGF.CurFuncDecl && "No parent declaration for target region!");
  3780. StringRef ParentName;
  3781. // In case we have Ctors/Dtors we use the complete type variant to produce
  3782. // the mangling of the device outlined kernel.
  3783. if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
  3784. ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
  3785. else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
  3786. ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
  3787. else
  3788. ParentName =
  3789. CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
  3790. // Emit target region as a standalone region.
  3791. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
  3792. IsOffloadEntry, CodeGen);
  3793. OMPLexicalScope Scope(CGF, S, OMPD_task);
  3794. CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device);
  3795. }
  3796. static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
  3797. PrePostActionTy &Action) {
  3798. Action.Enter(CGF);
  3799. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3800. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3801. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3802. (void)PrivateScope.Privatize();
  3803. CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt());
  3804. }
  3805. void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  3806. StringRef ParentName,
  3807. const OMPTargetDirective &S) {
  3808. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3809. emitTargetRegion(CGF, S, Action);
  3810. };
  3811. llvm::Function *Fn;
  3812. llvm::Constant *Addr;
  3813. // Emit target region as a standalone region.
  3814. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3815. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3816. assert(Fn && Addr && "Target device function emission failed.");
  3817. }
  3818. void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
  3819. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3820. emitTargetRegion(CGF, S, Action);
  3821. };
  3822. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3823. }
  3824. static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
  3825. const OMPExecutableDirective &S,
  3826. OpenMPDirectiveKind InnermostKind,
  3827. const RegionCodeGenTy &CodeGen) {
  3828. const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
  3829. llvm::Value *OutlinedFn =
  3830. CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
  3831. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  3832. const auto *NT = S.getSingleClause<OMPNumTeamsClause>();
  3833. const auto *TL = S.getSingleClause<OMPThreadLimitClause>();
  3834. if (NT || TL) {
  3835. const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr;
  3836. const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr;
  3837. CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
  3838. S.getBeginLoc());
  3839. }
  3840. OMPTeamsScope Scope(CGF, S);
  3841. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3842. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  3843. CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn,
  3844. CapturedVars);
  3845. }
  3846. void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
  3847. // Emit teams region as a standalone region.
  3848. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3849. Action.Enter(CGF);
  3850. OMPPrivateScope PrivateScope(CGF);
  3851. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3852. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3853. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3854. (void)PrivateScope.Privatize();
  3855. CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt());
  3856. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3857. };
  3858. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
  3859. emitPostUpdateForReductionClause(*this, S,
  3860. [](CodeGenFunction &) { return nullptr; });
  3861. }
  3862. static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  3863. const OMPTargetTeamsDirective &S) {
  3864. auto *CS = S.getCapturedStmt(OMPD_teams);
  3865. Action.Enter(CGF);
  3866. // Emit teams region as a standalone region.
  3867. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3868. Action.Enter(CGF);
  3869. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3870. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3871. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3872. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3873. (void)PrivateScope.Privatize();
  3874. CGF.EmitStmt(CS->getCapturedStmt());
  3875. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3876. };
  3877. emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
  3878. emitPostUpdateForReductionClause(CGF, S,
  3879. [](CodeGenFunction &) { return nullptr; });
  3880. }
  3881. void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  3882. CodeGenModule &CGM, StringRef ParentName,
  3883. const OMPTargetTeamsDirective &S) {
  3884. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3885. emitTargetTeamsRegion(CGF, Action, S);
  3886. };
  3887. llvm::Function *Fn;
  3888. llvm::Constant *Addr;
  3889. // Emit target region as a standalone region.
  3890. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3891. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3892. assert(Fn && Addr && "Target device function emission failed.");
  3893. }
  3894. void CodeGenFunction::EmitOMPTargetTeamsDirective(
  3895. const OMPTargetTeamsDirective &S) {
  3896. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3897. emitTargetTeamsRegion(CGF, Action, S);
  3898. };
  3899. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3900. }
  3901. static void
  3902. emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  3903. const OMPTargetTeamsDistributeDirective &S) {
  3904. Action.Enter(CGF);
  3905. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3906. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  3907. };
  3908. // Emit teams region as a standalone region.
  3909. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  3910. PrePostActionTy &Action) {
  3911. Action.Enter(CGF);
  3912. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3913. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3914. (void)PrivateScope.Privatize();
  3915. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  3916. CodeGenDistribute);
  3917. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3918. };
  3919. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen);
  3920. emitPostUpdateForReductionClause(CGF, S,
  3921. [](CodeGenFunction &) { return nullptr; });
  3922. }
  3923. void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
  3924. CodeGenModule &CGM, StringRef ParentName,
  3925. const OMPTargetTeamsDistributeDirective &S) {
  3926. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3927. emitTargetTeamsDistributeRegion(CGF, Action, S);
  3928. };
  3929. llvm::Function *Fn;
  3930. llvm::Constant *Addr;
  3931. // Emit target region as a standalone region.
  3932. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3933. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3934. assert(Fn && Addr && "Target device function emission failed.");
  3935. }
  3936. void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective(
  3937. const OMPTargetTeamsDistributeDirective &S) {
  3938. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3939. emitTargetTeamsDistributeRegion(CGF, Action, S);
  3940. };
  3941. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3942. }
  3943. static void emitTargetTeamsDistributeSimdRegion(
  3944. CodeGenFunction &CGF, PrePostActionTy &Action,
  3945. const OMPTargetTeamsDistributeSimdDirective &S) {
  3946. Action.Enter(CGF);
  3947. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3948. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  3949. };
  3950. // Emit teams region as a standalone region.
  3951. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  3952. PrePostActionTy &Action) {
  3953. Action.Enter(CGF);
  3954. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3955. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3956. (void)PrivateScope.Privatize();
  3957. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  3958. CodeGenDistribute);
  3959. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3960. };
  3961. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen);
  3962. emitPostUpdateForReductionClause(CGF, S,
  3963. [](CodeGenFunction &) { return nullptr; });
  3964. }
  3965. void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  3966. CodeGenModule &CGM, StringRef ParentName,
  3967. const OMPTargetTeamsDistributeSimdDirective &S) {
  3968. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3969. emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
  3970. };
  3971. llvm::Function *Fn;
  3972. llvm::Constant *Addr;
  3973. // Emit target region as a standalone region.
  3974. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3975. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3976. assert(Fn && Addr && "Target device function emission failed.");
  3977. }
  3978. void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective(
  3979. const OMPTargetTeamsDistributeSimdDirective &S) {
  3980. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3981. emitTargetTeamsDistributeSimdRegion(CGF, Action, S);
  3982. };
  3983. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3984. }
  3985. void CodeGenFunction::EmitOMPTeamsDistributeDirective(
  3986. const OMPTeamsDistributeDirective &S) {
  3987. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3988. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  3989. };
  3990. // Emit teams region as a standalone region.
  3991. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  3992. PrePostActionTy &Action) {
  3993. Action.Enter(CGF);
  3994. OMPPrivateScope PrivateScope(CGF);
  3995. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3996. (void)PrivateScope.Privatize();
  3997. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  3998. CodeGenDistribute);
  3999. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4000. };
  4001. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen);
  4002. emitPostUpdateForReductionClause(*this, S,
  4003. [](CodeGenFunction &) { return nullptr; });
  4004. }
  4005. void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective(
  4006. const OMPTeamsDistributeSimdDirective &S) {
  4007. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4008. CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc());
  4009. };
  4010. // Emit teams region as a standalone region.
  4011. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  4012. PrePostActionTy &Action) {
  4013. Action.Enter(CGF);
  4014. OMPPrivateScope PrivateScope(CGF);
  4015. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4016. (void)PrivateScope.Privatize();
  4017. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd,
  4018. CodeGenDistribute);
  4019. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4020. };
  4021. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen);
  4022. emitPostUpdateForReductionClause(*this, S,
  4023. [](CodeGenFunction &) { return nullptr; });
  4024. }
  4025. void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective(
  4026. const OMPTeamsDistributeParallelForDirective &S) {
  4027. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4028. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  4029. S.getDistInc());
  4030. };
  4031. // Emit teams region as a standalone region.
  4032. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  4033. PrePostActionTy &Action) {
  4034. Action.Enter(CGF);
  4035. OMPPrivateScope PrivateScope(CGF);
  4036. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4037. (void)PrivateScope.Privatize();
  4038. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute,
  4039. CodeGenDistribute);
  4040. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4041. };
  4042. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
  4043. emitPostUpdateForReductionClause(*this, S,
  4044. [](CodeGenFunction &) { return nullptr; });
  4045. }
  4046. void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective(
  4047. const OMPTeamsDistributeParallelForSimdDirective &S) {
  4048. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4049. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  4050. S.getDistInc());
  4051. };
  4052. // Emit teams region as a standalone region.
  4053. auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  4054. PrePostActionTy &Action) {
  4055. Action.Enter(CGF);
  4056. OMPPrivateScope PrivateScope(CGF);
  4057. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4058. (void)PrivateScope.Privatize();
  4059. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  4060. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  4061. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4062. };
  4063. emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen);
  4064. emitPostUpdateForReductionClause(*this, S,
  4065. [](CodeGenFunction &) { return nullptr; });
  4066. }
  4067. static void emitTargetTeamsDistributeParallelForRegion(
  4068. CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S,
  4069. PrePostActionTy &Action) {
  4070. Action.Enter(CGF);
  4071. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4072. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  4073. S.getDistInc());
  4074. };
  4075. // Emit teams region as a standalone region.
  4076. auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  4077. PrePostActionTy &Action) {
  4078. Action.Enter(CGF);
  4079. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  4080. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4081. (void)PrivateScope.Privatize();
  4082. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  4083. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  4084. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4085. };
  4086. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for,
  4087. CodeGenTeams);
  4088. emitPostUpdateForReductionClause(CGF, S,
  4089. [](CodeGenFunction &) { return nullptr; });
  4090. }
  4091. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
  4092. CodeGenModule &CGM, StringRef ParentName,
  4093. const OMPTargetTeamsDistributeParallelForDirective &S) {
  4094. // Emit SPMD target teams distribute parallel for region as a standalone
  4095. // region.
  4096. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4097. emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
  4098. };
  4099. llvm::Function *Fn;
  4100. llvm::Constant *Addr;
  4101. // Emit target region as a standalone region.
  4102. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  4103. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  4104. assert(Fn && Addr && "Target device function emission failed.");
  4105. }
  4106. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective(
  4107. const OMPTargetTeamsDistributeParallelForDirective &S) {
  4108. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4109. emitTargetTeamsDistributeParallelForRegion(CGF, S, Action);
  4110. };
  4111. emitCommonOMPTargetDirective(*this, S, CodeGen);
  4112. }
  4113. static void emitTargetTeamsDistributeParallelForSimdRegion(
  4114. CodeGenFunction &CGF,
  4115. const OMPTargetTeamsDistributeParallelForSimdDirective &S,
  4116. PrePostActionTy &Action) {
  4117. Action.Enter(CGF);
  4118. auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4119. CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined,
  4120. S.getDistInc());
  4121. };
  4122. // Emit teams region as a standalone region.
  4123. auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF,
  4124. PrePostActionTy &Action) {
  4125. Action.Enter(CGF);
  4126. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  4127. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4128. (void)PrivateScope.Privatize();
  4129. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(
  4130. CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false);
  4131. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  4132. };
  4133. emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd,
  4134. CodeGenTeams);
  4135. emitPostUpdateForReductionClause(CGF, S,
  4136. [](CodeGenFunction &) { return nullptr; });
  4137. }
  4138. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
  4139. CodeGenModule &CGM, StringRef ParentName,
  4140. const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
  4141. // Emit SPMD target teams distribute parallel for simd region as a standalone
  4142. // region.
  4143. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4144. emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
  4145. };
  4146. llvm::Function *Fn;
  4147. llvm::Constant *Addr;
  4148. // Emit target region as a standalone region.
  4149. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  4150. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  4151. assert(Fn && Addr && "Target device function emission failed.");
  4152. }
  4153. void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  4154. const OMPTargetTeamsDistributeParallelForSimdDirective &S) {
  4155. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4156. emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action);
  4157. };
  4158. emitCommonOMPTargetDirective(*this, S, CodeGen);
  4159. }
  4160. void CodeGenFunction::EmitOMPCancellationPointDirective(
  4161. const OMPCancellationPointDirective &S) {
  4162. CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(),
  4163. S.getCancelRegion());
  4164. }
  4165. void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
  4166. const Expr *IfCond = nullptr;
  4167. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  4168. if (C->getNameModifier() == OMPD_unknown ||
  4169. C->getNameModifier() == OMPD_cancel) {
  4170. IfCond = C->getCondition();
  4171. break;
  4172. }
  4173. }
  4174. CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond,
  4175. S.getCancelRegion());
  4176. }
  4177. CodeGenFunction::JumpDest
  4178. CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
  4179. if (Kind == OMPD_parallel || Kind == OMPD_task ||
  4180. Kind == OMPD_target_parallel)
  4181. return ReturnBlock;
  4182. assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
  4183. Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
  4184. Kind == OMPD_distribute_parallel_for ||
  4185. Kind == OMPD_target_parallel_for ||
  4186. Kind == OMPD_teams_distribute_parallel_for ||
  4187. Kind == OMPD_target_teams_distribute_parallel_for);
  4188. return OMPCancelStack.getExitBlock();
  4189. }
  4190. void CodeGenFunction::EmitOMPUseDevicePtrClause(
  4191. const OMPClause &NC, OMPPrivateScope &PrivateScope,
  4192. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
  4193. const auto &C = cast<OMPUseDevicePtrClause>(NC);
  4194. auto OrigVarIt = C.varlist_begin();
  4195. auto InitIt = C.inits().begin();
  4196. for (const Expr *PvtVarIt : C.private_copies()) {
  4197. const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
  4198. const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
  4199. const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
  4200. // In order to identify the right initializer we need to match the
  4201. // declaration used by the mapping logic. In some cases we may get
  4202. // OMPCapturedExprDecl that refers to the original declaration.
  4203. const ValueDecl *MatchingVD = OrigVD;
  4204. if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
  4205. // OMPCapturedExprDecl are used to privative fields of the current
  4206. // structure.
  4207. const auto *ME = cast<MemberExpr>(OED->getInit());
  4208. assert(isa<CXXThisExpr>(ME->getBase()) &&
  4209. "Base should be the current struct!");
  4210. MatchingVD = ME->getMemberDecl();
  4211. }
  4212. // If we don't have information about the current list item, move on to
  4213. // the next one.
  4214. auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
  4215. if (InitAddrIt == CaptureDeviceAddrMap.end())
  4216. continue;
  4217. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD,
  4218. InitAddrIt, InitVD,
  4219. PvtVD]() {
  4220. // Initialize the temporary initialization variable with the address we
  4221. // get from the runtime library. We have to cast the source address
  4222. // because it is always a void *. References are materialized in the
  4223. // privatization scope, so the initialization here disregards the fact
  4224. // the original variable is a reference.
  4225. QualType AddrQTy =
  4226. getContext().getPointerType(OrigVD->getType().getNonReferenceType());
  4227. llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
  4228. Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
  4229. setAddrOfLocalVar(InitVD, InitAddr);
  4230. // Emit private declaration, it will be initialized by the value we
  4231. // declaration we just added to the local declarations map.
  4232. EmitDecl(*PvtVD);
  4233. // The initialization variables reached its purpose in the emission
  4234. // of the previous declaration, so we don't need it anymore.
  4235. LocalDeclMap.erase(InitVD);
  4236. // Return the address of the private variable.
  4237. return GetAddrOfLocalVar(PvtVD);
  4238. });
  4239. assert(IsRegistered && "firstprivate var already registered as private");
  4240. // Silence the warning about unused variable.
  4241. (void)IsRegistered;
  4242. ++OrigVarIt;
  4243. ++InitIt;
  4244. }
  4245. }
  4246. // Generate the instructions for '#pragma omp target data' directive.
  4247. void CodeGenFunction::EmitOMPTargetDataDirective(
  4248. const OMPTargetDataDirective &S) {
  4249. CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
  4250. // Create a pre/post action to signal the privatization of the device pointer.
  4251. // This action can be replaced by the OpenMP runtime code generation to
  4252. // deactivate privatization.
  4253. bool PrivatizeDevicePointers = false;
  4254. class DevicePointerPrivActionTy : public PrePostActionTy {
  4255. bool &PrivatizeDevicePointers;
  4256. public:
  4257. explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
  4258. : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
  4259. void Enter(CodeGenFunction &CGF) override {
  4260. PrivatizeDevicePointers = true;
  4261. }
  4262. };
  4263. DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
  4264. auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
  4265. CodeGenFunction &CGF, PrePostActionTy &Action) {
  4266. auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  4267. CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt());
  4268. };
  4269. // Codegen that selects whether to generate the privatization code or not.
  4270. auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
  4271. &InnermostCodeGen](CodeGenFunction &CGF,
  4272. PrePostActionTy &Action) {
  4273. RegionCodeGenTy RCG(InnermostCodeGen);
  4274. PrivatizeDevicePointers = false;
  4275. // Call the pre-action to change the status of PrivatizeDevicePointers if
  4276. // needed.
  4277. Action.Enter(CGF);
  4278. if (PrivatizeDevicePointers) {
  4279. OMPPrivateScope PrivateScope(CGF);
  4280. // Emit all instances of the use_device_ptr clause.
  4281. for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
  4282. CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
  4283. Info.CaptureDeviceAddrMap);
  4284. (void)PrivateScope.Privatize();
  4285. RCG(CGF);
  4286. } else {
  4287. RCG(CGF);
  4288. }
  4289. };
  4290. // Forward the provided action to the privatization codegen.
  4291. RegionCodeGenTy PrivRCG(PrivCodeGen);
  4292. PrivRCG.setAction(Action);
  4293. // Notwithstanding the body of the region is emitted as inlined directive,
  4294. // we don't use an inline scope as changes in the references inside the
  4295. // region are expected to be visible outside, so we do not privative them.
  4296. OMPLexicalScope Scope(CGF, S);
  4297. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
  4298. PrivRCG);
  4299. };
  4300. RegionCodeGenTy RCG(CodeGen);
  4301. // If we don't have target devices, don't bother emitting the data mapping
  4302. // code.
  4303. if (CGM.getLangOpts().OMPTargetTriples.empty()) {
  4304. RCG(*this);
  4305. return;
  4306. }
  4307. // Check if we have any if clause associated with the directive.
  4308. const Expr *IfCond = nullptr;
  4309. if (const auto *C = S.getSingleClause<OMPIfClause>())
  4310. IfCond = C->getCondition();
  4311. // Check if we have any device clause associated with the directive.
  4312. const Expr *Device = nullptr;
  4313. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  4314. Device = C->getDevice();
  4315. // Set the action to signal privatization of device pointers.
  4316. RCG.setAction(PrivAction);
  4317. // Emit region code.
  4318. CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
  4319. Info);
  4320. }
  4321. void CodeGenFunction::EmitOMPTargetEnterDataDirective(
  4322. const OMPTargetEnterDataDirective &S) {
  4323. // If we don't have target devices, don't bother emitting the data mapping
  4324. // code.
  4325. if (CGM.getLangOpts().OMPTargetTriples.empty())
  4326. return;
  4327. // Check if we have any if clause associated with the directive.
  4328. const Expr *IfCond = nullptr;
  4329. if (const auto *C = S.getSingleClause<OMPIfClause>())
  4330. IfCond = C->getCondition();
  4331. // Check if we have any device clause associated with the directive.
  4332. const Expr *Device = nullptr;
  4333. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  4334. Device = C->getDevice();
  4335. OMPLexicalScope Scope(*this, S, OMPD_task);
  4336. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  4337. }
  4338. void CodeGenFunction::EmitOMPTargetExitDataDirective(
  4339. const OMPTargetExitDataDirective &S) {
  4340. // If we don't have target devices, don't bother emitting the data mapping
  4341. // code.
  4342. if (CGM.getLangOpts().OMPTargetTriples.empty())
  4343. return;
  4344. // Check if we have any if clause associated with the directive.
  4345. const Expr *IfCond = nullptr;
  4346. if (const auto *C = S.getSingleClause<OMPIfClause>())
  4347. IfCond = C->getCondition();
  4348. // Check if we have any device clause associated with the directive.
  4349. const Expr *Device = nullptr;
  4350. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  4351. Device = C->getDevice();
  4352. OMPLexicalScope Scope(*this, S, OMPD_task);
  4353. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  4354. }
  4355. static void emitTargetParallelRegion(CodeGenFunction &CGF,
  4356. const OMPTargetParallelDirective &S,
  4357. PrePostActionTy &Action) {
  4358. // Get the captured statement associated with the 'parallel' region.
  4359. const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel);
  4360. Action.Enter(CGF);
  4361. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4362. Action.Enter(CGF);
  4363. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  4364. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  4365. CGF.EmitOMPPrivateClause(S, PrivateScope);
  4366. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  4367. (void)PrivateScope.Privatize();
  4368. // TODO: Add support for clauses.
  4369. CGF.EmitStmt(CS->getCapturedStmt());
  4370. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  4371. };
  4372. emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
  4373. emitEmptyBoundParameters);
  4374. emitPostUpdateForReductionClause(CGF, S,
  4375. [](CodeGenFunction &) { return nullptr; });
  4376. }
  4377. void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  4378. CodeGenModule &CGM, StringRef ParentName,
  4379. const OMPTargetParallelDirective &S) {
  4380. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4381. emitTargetParallelRegion(CGF, S, Action);
  4382. };
  4383. llvm::Function *Fn;
  4384. llvm::Constant *Addr;
  4385. // Emit target region as a standalone region.
  4386. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  4387. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  4388. assert(Fn && Addr && "Target device function emission failed.");
  4389. }
  4390. void CodeGenFunction::EmitOMPTargetParallelDirective(
  4391. const OMPTargetParallelDirective &S) {
  4392. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4393. emitTargetParallelRegion(CGF, S, Action);
  4394. };
  4395. emitCommonOMPTargetDirective(*this, S, CodeGen);
  4396. }
  4397. static void emitTargetParallelForRegion(CodeGenFunction &CGF,
  4398. const OMPTargetParallelForDirective &S,
  4399. PrePostActionTy &Action) {
  4400. Action.Enter(CGF);
  4401. // Emit directive as a combined directive that consists of two implicit
  4402. // directives: 'parallel' with 'for' directive.
  4403. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4404. Action.Enter(CGF);
  4405. CodeGenFunction::OMPCancelStackRAII CancelRegion(
  4406. CGF, OMPD_target_parallel_for, S.hasCancel());
  4407. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  4408. emitDispatchForLoopBounds);
  4409. };
  4410. emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen,
  4411. emitEmptyBoundParameters);
  4412. }
  4413. void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
  4414. CodeGenModule &CGM, StringRef ParentName,
  4415. const OMPTargetParallelForDirective &S) {
  4416. // Emit SPMD target parallel for region as a standalone region.
  4417. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4418. emitTargetParallelForRegion(CGF, S, Action);
  4419. };
  4420. llvm::Function *Fn;
  4421. llvm::Constant *Addr;
  4422. // Emit target region as a standalone region.
  4423. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  4424. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  4425. assert(Fn && Addr && "Target device function emission failed.");
  4426. }
  4427. void CodeGenFunction::EmitOMPTargetParallelForDirective(
  4428. const OMPTargetParallelForDirective &S) {
  4429. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4430. emitTargetParallelForRegion(CGF, S, Action);
  4431. };
  4432. emitCommonOMPTargetDirective(*this, S, CodeGen);
  4433. }
  4434. static void
  4435. emitTargetParallelForSimdRegion(CodeGenFunction &CGF,
  4436. const OMPTargetParallelForSimdDirective &S,
  4437. PrePostActionTy &Action) {
  4438. Action.Enter(CGF);
  4439. // Emit directive as a combined directive that consists of two implicit
  4440. // directives: 'parallel' with 'for' directive.
  4441. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4442. Action.Enter(CGF);
  4443. CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds,
  4444. emitDispatchForLoopBounds);
  4445. };
  4446. emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen,
  4447. emitEmptyBoundParameters);
  4448. }
  4449. void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
  4450. CodeGenModule &CGM, StringRef ParentName,
  4451. const OMPTargetParallelForSimdDirective &S) {
  4452. // Emit SPMD target parallel for region as a standalone region.
  4453. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4454. emitTargetParallelForSimdRegion(CGF, S, Action);
  4455. };
  4456. llvm::Function *Fn;
  4457. llvm::Constant *Addr;
  4458. // Emit target region as a standalone region.
  4459. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  4460. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  4461. assert(Fn && Addr && "Target device function emission failed.");
  4462. }
  4463. void CodeGenFunction::EmitOMPTargetParallelForSimdDirective(
  4464. const OMPTargetParallelForSimdDirective &S) {
  4465. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4466. emitTargetParallelForSimdRegion(CGF, S, Action);
  4467. };
  4468. emitCommonOMPTargetDirective(*this, S, CodeGen);
  4469. }
  4470. /// Emit a helper variable and return corresponding lvalue.
  4471. static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
  4472. const ImplicitParamDecl *PVD,
  4473. CodeGenFunction::OMPPrivateScope &Privates) {
  4474. const auto *VDecl = cast<VarDecl>(Helper->getDecl());
  4475. Privates.addPrivate(VDecl,
  4476. [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); });
  4477. }
  4478. void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
  4479. assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
  4480. // Emit outlined function for task construct.
  4481. const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop);
  4482. Address CapturedStruct = GenerateCapturedStmtArgument(*CS);
  4483. QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  4484. const Expr *IfCond = nullptr;
  4485. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  4486. if (C->getNameModifier() == OMPD_unknown ||
  4487. C->getNameModifier() == OMPD_taskloop) {
  4488. IfCond = C->getCondition();
  4489. break;
  4490. }
  4491. }
  4492. OMPTaskDataTy Data;
  4493. // Check if taskloop must be emitted without taskgroup.
  4494. Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
  4495. // TODO: Check if we should emit tied or untied task.
  4496. Data.Tied = true;
  4497. // Set scheduling for taskloop
  4498. if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
  4499. // grainsize clause
  4500. Data.Schedule.setInt(/*IntVal=*/false);
  4501. Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
  4502. } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
  4503. // num_tasks clause
  4504. Data.Schedule.setInt(/*IntVal=*/true);
  4505. Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
  4506. }
  4507. auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
  4508. // if (PreCond) {
  4509. // for (IV in 0..LastIteration) BODY;
  4510. // <Final counter/linear vars updates>;
  4511. // }
  4512. //
  4513. // Emit: if (PreCond) - begin.
  4514. // If the condition constant folds and can be elided, avoid emitting the
  4515. // whole loop.
  4516. bool CondConstant;
  4517. llvm::BasicBlock *ContBlock = nullptr;
  4518. OMPLoopScope PreInitScope(CGF, S);
  4519. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  4520. if (!CondConstant)
  4521. return;
  4522. } else {
  4523. llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
  4524. ContBlock = CGF.createBasicBlock("taskloop.if.end");
  4525. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  4526. CGF.getProfileCount(&S));
  4527. CGF.EmitBlock(ThenBlock);
  4528. CGF.incrementProfileCounter(&S);
  4529. }
  4530. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  4531. CGF.EmitOMPSimdInit(S);
  4532. OMPPrivateScope LoopScope(CGF);
  4533. // Emit helper vars inits.
  4534. enum { LowerBound = 5, UpperBound, Stride, LastIter };
  4535. auto *I = CS->getCapturedDecl()->param_begin();
  4536. auto *LBP = std::next(I, LowerBound);
  4537. auto *UBP = std::next(I, UpperBound);
  4538. auto *STP = std::next(I, Stride);
  4539. auto *LIP = std::next(I, LastIter);
  4540. mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
  4541. LoopScope);
  4542. mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
  4543. LoopScope);
  4544. mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
  4545. mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
  4546. LoopScope);
  4547. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  4548. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  4549. (void)LoopScope.Privatize();
  4550. // Emit the loop iteration variable.
  4551. const Expr *IVExpr = S.getIterationVariable();
  4552. const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  4553. CGF.EmitVarDecl(*IVDecl);
  4554. CGF.EmitIgnoredExpr(S.getInit());
  4555. // Emit the iterations count variable.
  4556. // If it is not a variable, Sema decided to calculate iterations count on
  4557. // each iteration (e.g., it is foldable into a constant).
  4558. if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  4559. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  4560. // Emit calculation of the iterations count.
  4561. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  4562. }
  4563. CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  4564. S.getInc(),
  4565. [&S](CodeGenFunction &CGF) {
  4566. CGF.EmitOMPLoopBody(S, JumpDest());
  4567. CGF.EmitStopPoint(&S);
  4568. },
  4569. [](CodeGenFunction &) {});
  4570. // Emit: if (PreCond) - end.
  4571. if (ContBlock) {
  4572. CGF.EmitBranch(ContBlock);
  4573. CGF.EmitBlock(ContBlock, true);
  4574. }
  4575. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  4576. if (HasLastprivateClause) {
  4577. CGF.EmitOMPLastprivateClauseFinal(
  4578. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  4579. CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
  4580. CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
  4581. (*LIP)->getType(), S.getBeginLoc())));
  4582. }
  4583. };
  4584. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  4585. IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
  4586. const OMPTaskDataTy &Data) {
  4587. auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond,
  4588. &Data](CodeGenFunction &CGF, PrePostActionTy &) {
  4589. OMPLoopScope PreInitScope(CGF, S);
  4590. CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S,
  4591. OutlinedFn, SharedsTy,
  4592. CapturedStruct, IfCond, Data);
  4593. };
  4594. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
  4595. CodeGen);
  4596. };
  4597. if (Data.Nogroup) {
  4598. EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data);
  4599. } else {
  4600. CGM.getOpenMPRuntime().emitTaskgroupRegion(
  4601. *this,
  4602. [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
  4603. PrePostActionTy &Action) {
  4604. Action.Enter(CGF);
  4605. CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen,
  4606. Data);
  4607. },
  4608. S.getBeginLoc());
  4609. }
  4610. }
  4611. void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
  4612. EmitOMPTaskLoopBasedDirective(S);
  4613. }
  4614. void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
  4615. const OMPTaskLoopSimdDirective &S) {
  4616. EmitOMPTaskLoopBasedDirective(S);
  4617. }
  4618. // Generate the instructions for '#pragma omp target update' directive.
  4619. void CodeGenFunction::EmitOMPTargetUpdateDirective(
  4620. const OMPTargetUpdateDirective &S) {
  4621. // If we don't have target devices, don't bother emitting the data mapping
  4622. // code.
  4623. if (CGM.getLangOpts().OMPTargetTriples.empty())
  4624. return;
  4625. // Check if we have any if clause associated with the directive.
  4626. const Expr *IfCond = nullptr;
  4627. if (const auto *C = S.getSingleClause<OMPIfClause>())
  4628. IfCond = C->getCondition();
  4629. // Check if we have any device clause associated with the directive.
  4630. const Expr *Device = nullptr;
  4631. if (const auto *C = S.getSingleClause<OMPDeviceClause>())
  4632. Device = C->getDevice();
  4633. OMPLexicalScope Scope(*this, S, OMPD_task);
  4634. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  4635. }
  4636. void CodeGenFunction::EmitSimpleOMPExecutableDirective(
  4637. const OMPExecutableDirective &D) {
  4638. if (!D.hasAssociatedStmt() || !D.getAssociatedStmt())
  4639. return;
  4640. auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) {
  4641. if (isOpenMPSimdDirective(D.getDirectiveKind())) {
  4642. emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action);
  4643. } else {
  4644. if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) {
  4645. for (const Expr *E : LD->counters()) {
  4646. if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
  4647. cast<DeclRefExpr>(E)->getDecl())) {
  4648. // Emit only those that were not explicitly referenced in clauses.
  4649. if (!CGF.LocalDeclMap.count(VD))
  4650. CGF.EmitVarDecl(*VD);
  4651. }
  4652. }
  4653. for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) {
  4654. if (!C->getNumForLoops())
  4655. continue;
  4656. for (unsigned I = LD->getCollapsedNumber(),
  4657. E = C->getLoopNumIterations().size();
  4658. I < E; ++I) {
  4659. if (const auto *VD = dyn_cast<OMPCapturedExprDecl>(
  4660. cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) {
  4661. // Emit only those that were not explicitly referenced in clauses.
  4662. if (!CGF.LocalDeclMap.count(VD))
  4663. CGF.EmitVarDecl(*VD);
  4664. }
  4665. }
  4666. }
  4667. }
  4668. CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
  4669. }
  4670. };
  4671. OMPSimdLexicalScope Scope(*this, D);
  4672. CGM.getOpenMPRuntime().emitInlinedDirective(
  4673. *this,
  4674. isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd
  4675. : D.getDirectiveKind(),
  4676. CodeGen);
  4677. }