CGStmtOpenMP.cpp 170 KB

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