CGStmtOpenMP.cpp 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162
  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_in_reduction:
  3261. case OMPC_safelen:
  3262. case OMPC_simdlen:
  3263. case OMPC_collapse:
  3264. case OMPC_default:
  3265. case OMPC_seq_cst:
  3266. case OMPC_shared:
  3267. case OMPC_linear:
  3268. case OMPC_aligned:
  3269. case OMPC_copyin:
  3270. case OMPC_copyprivate:
  3271. case OMPC_flush:
  3272. case OMPC_proc_bind:
  3273. case OMPC_schedule:
  3274. case OMPC_ordered:
  3275. case OMPC_nowait:
  3276. case OMPC_untied:
  3277. case OMPC_threadprivate:
  3278. case OMPC_depend:
  3279. case OMPC_mergeable:
  3280. case OMPC_device:
  3281. case OMPC_threads:
  3282. case OMPC_simd:
  3283. case OMPC_map:
  3284. case OMPC_num_teams:
  3285. case OMPC_thread_limit:
  3286. case OMPC_priority:
  3287. case OMPC_grainsize:
  3288. case OMPC_nogroup:
  3289. case OMPC_num_tasks:
  3290. case OMPC_hint:
  3291. case OMPC_dist_schedule:
  3292. case OMPC_defaultmap:
  3293. case OMPC_uniform:
  3294. case OMPC_to:
  3295. case OMPC_from:
  3296. case OMPC_use_device_ptr:
  3297. case OMPC_is_device_ptr:
  3298. llvm_unreachable("Clause is not allowed in 'omp atomic'.");
  3299. }
  3300. }
  3301. void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) {
  3302. bool IsSeqCst = S.getSingleClause<OMPSeqCstClause>();
  3303. OpenMPClauseKind Kind = OMPC_unknown;
  3304. for (auto *C : S.clauses()) {
  3305. // Find first clause (skip seq_cst clause, if it is first).
  3306. if (C->getClauseKind() != OMPC_seq_cst) {
  3307. Kind = C->getClauseKind();
  3308. break;
  3309. }
  3310. }
  3311. const auto *CS =
  3312. S.getAssociatedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  3313. if (const auto *EWC = dyn_cast<ExprWithCleanups>(CS)) {
  3314. enterFullExpression(EWC);
  3315. }
  3316. // Processing for statements under 'atomic capture'.
  3317. if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) {
  3318. for (const auto *C : Compound->body()) {
  3319. if (const auto *EWC = dyn_cast<ExprWithCleanups>(C)) {
  3320. enterFullExpression(EWC);
  3321. }
  3322. }
  3323. }
  3324. auto &&CodeGen = [&S, Kind, IsSeqCst, CS](CodeGenFunction &CGF,
  3325. PrePostActionTy &) {
  3326. CGF.EmitStopPoint(CS);
  3327. EmitOMPAtomicExpr(CGF, Kind, IsSeqCst, S.isPostfixUpdate(), S.getX(),
  3328. S.getV(), S.getExpr(), S.getUpdateExpr(),
  3329. S.isXLHSInRHSPart(), S.getLocStart());
  3330. };
  3331. OMPLexicalScope Scope(*this, S, /*AsInlined=*/true);
  3332. CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen);
  3333. }
  3334. static void emitCommonOMPTargetDirective(CodeGenFunction &CGF,
  3335. const OMPExecutableDirective &S,
  3336. const RegionCodeGenTy &CodeGen) {
  3337. assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind()));
  3338. CodeGenModule &CGM = CGF.CGM;
  3339. const CapturedStmt &CS = *cast<CapturedStmt>(S.getAssociatedStmt());
  3340. llvm::Function *Fn = nullptr;
  3341. llvm::Constant *FnID = nullptr;
  3342. const Expr *IfCond = nullptr;
  3343. // Check for the at most one if clause associated with the target region.
  3344. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3345. if (C->getNameModifier() == OMPD_unknown ||
  3346. C->getNameModifier() == OMPD_target) {
  3347. IfCond = C->getCondition();
  3348. break;
  3349. }
  3350. }
  3351. // Check if we have any device clause associated with the directive.
  3352. const Expr *Device = nullptr;
  3353. if (auto *C = S.getSingleClause<OMPDeviceClause>()) {
  3354. Device = C->getDevice();
  3355. }
  3356. // Check if we have an if clause whose conditional always evaluates to false
  3357. // or if we do not have any targets specified. If so the target region is not
  3358. // an offload entry point.
  3359. bool IsOffloadEntry = true;
  3360. if (IfCond) {
  3361. bool Val;
  3362. if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val)
  3363. IsOffloadEntry = false;
  3364. }
  3365. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3366. IsOffloadEntry = false;
  3367. assert(CGF.CurFuncDecl && "No parent declaration for target region!");
  3368. StringRef ParentName;
  3369. // In case we have Ctors/Dtors we use the complete type variant to produce
  3370. // the mangling of the device outlined kernel.
  3371. if (auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl))
  3372. ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete));
  3373. else if (auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl))
  3374. ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete));
  3375. else
  3376. ParentName =
  3377. CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl)));
  3378. // Emit target region as a standalone region.
  3379. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID,
  3380. IsOffloadEntry, CodeGen);
  3381. OMPLexicalScope Scope(CGF, S);
  3382. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3383. CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
  3384. CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device,
  3385. CapturedVars);
  3386. }
  3387. static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S,
  3388. PrePostActionTy &Action) {
  3389. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3390. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3391. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3392. (void)PrivateScope.Privatize();
  3393. Action.Enter(CGF);
  3394. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3395. }
  3396. void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  3397. StringRef ParentName,
  3398. const OMPTargetDirective &S) {
  3399. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3400. emitTargetRegion(CGF, S, Action);
  3401. };
  3402. llvm::Function *Fn;
  3403. llvm::Constant *Addr;
  3404. // Emit target region as a standalone region.
  3405. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3406. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3407. assert(Fn && Addr && "Target device function emission failed.");
  3408. }
  3409. void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) {
  3410. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3411. emitTargetRegion(CGF, S, Action);
  3412. };
  3413. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3414. }
  3415. static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF,
  3416. const OMPExecutableDirective &S,
  3417. OpenMPDirectiveKind InnermostKind,
  3418. const RegionCodeGenTy &CodeGen) {
  3419. const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams);
  3420. auto OutlinedFn = CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction(
  3421. S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen);
  3422. const OMPNumTeamsClause *NT = S.getSingleClause<OMPNumTeamsClause>();
  3423. const OMPThreadLimitClause *TL = S.getSingleClause<OMPThreadLimitClause>();
  3424. if (NT || TL) {
  3425. Expr *NumTeams = (NT) ? NT->getNumTeams() : nullptr;
  3426. Expr *ThreadLimit = (TL) ? TL->getThreadLimit() : nullptr;
  3427. CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit,
  3428. S.getLocStart());
  3429. }
  3430. OMPTeamsScope Scope(CGF, S);
  3431. llvm::SmallVector<llvm::Value *, 16> CapturedVars;
  3432. CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars);
  3433. CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getLocStart(), OutlinedFn,
  3434. CapturedVars);
  3435. }
  3436. void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) {
  3437. // Emit teams region as a standalone region.
  3438. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3439. OMPPrivateScope PrivateScope(CGF);
  3440. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3441. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3442. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3443. (void)PrivateScope.Privatize();
  3444. CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3445. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams);
  3446. };
  3447. emitCommonOMPTeamsDirective(*this, S, OMPD_teams, CodeGen);
  3448. emitPostUpdateForReductionClause(
  3449. *this, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  3450. }
  3451. static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action,
  3452. const OMPTargetTeamsDirective &S) {
  3453. auto *CS = S.getCapturedStmt(OMPD_teams);
  3454. Action.Enter(CGF);
  3455. auto &&CodeGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) {
  3456. // TODO: Add support for clauses.
  3457. CGF.EmitStmt(CS->getCapturedStmt());
  3458. };
  3459. emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen);
  3460. }
  3461. void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
  3462. CodeGenModule &CGM, StringRef ParentName,
  3463. const OMPTargetTeamsDirective &S) {
  3464. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3465. emitTargetTeamsRegion(CGF, Action, S);
  3466. };
  3467. llvm::Function *Fn;
  3468. llvm::Constant *Addr;
  3469. // Emit target region as a standalone region.
  3470. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3471. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3472. assert(Fn && Addr && "Target device function emission failed.");
  3473. }
  3474. void CodeGenFunction::EmitOMPTargetTeamsDirective(
  3475. const OMPTargetTeamsDirective &S) {
  3476. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3477. emitTargetTeamsRegion(CGF, Action, S);
  3478. };
  3479. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3480. }
  3481. void CodeGenFunction::EmitOMPCancellationPointDirective(
  3482. const OMPCancellationPointDirective &S) {
  3483. CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getLocStart(),
  3484. S.getCancelRegion());
  3485. }
  3486. void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) {
  3487. const Expr *IfCond = nullptr;
  3488. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3489. if (C->getNameModifier() == OMPD_unknown ||
  3490. C->getNameModifier() == OMPD_cancel) {
  3491. IfCond = C->getCondition();
  3492. break;
  3493. }
  3494. }
  3495. CGM.getOpenMPRuntime().emitCancelCall(*this, S.getLocStart(), IfCond,
  3496. S.getCancelRegion());
  3497. }
  3498. CodeGenFunction::JumpDest
  3499. CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) {
  3500. if (Kind == OMPD_parallel || Kind == OMPD_task ||
  3501. Kind == OMPD_target_parallel)
  3502. return ReturnBlock;
  3503. assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections ||
  3504. Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for ||
  3505. Kind == OMPD_distribute_parallel_for ||
  3506. Kind == OMPD_target_parallel_for);
  3507. return OMPCancelStack.getExitBlock();
  3508. }
  3509. void CodeGenFunction::EmitOMPUseDevicePtrClause(
  3510. const OMPClause &NC, OMPPrivateScope &PrivateScope,
  3511. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) {
  3512. const auto &C = cast<OMPUseDevicePtrClause>(NC);
  3513. auto OrigVarIt = C.varlist_begin();
  3514. auto InitIt = C.inits().begin();
  3515. for (auto PvtVarIt : C.private_copies()) {
  3516. auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl());
  3517. auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl());
  3518. auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl());
  3519. // In order to identify the right initializer we need to match the
  3520. // declaration used by the mapping logic. In some cases we may get
  3521. // OMPCapturedExprDecl that refers to the original declaration.
  3522. const ValueDecl *MatchingVD = OrigVD;
  3523. if (auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) {
  3524. // OMPCapturedExprDecl are used to privative fields of the current
  3525. // structure.
  3526. auto *ME = cast<MemberExpr>(OED->getInit());
  3527. assert(isa<CXXThisExpr>(ME->getBase()) &&
  3528. "Base should be the current struct!");
  3529. MatchingVD = ME->getMemberDecl();
  3530. }
  3531. // If we don't have information about the current list item, move on to
  3532. // the next one.
  3533. auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD);
  3534. if (InitAddrIt == CaptureDeviceAddrMap.end())
  3535. continue;
  3536. bool IsRegistered = PrivateScope.addPrivate(OrigVD, [&]() -> Address {
  3537. // Initialize the temporary initialization variable with the address we
  3538. // get from the runtime library. We have to cast the source address
  3539. // because it is always a void *. References are materialized in the
  3540. // privatization scope, so the initialization here disregards the fact
  3541. // the original variable is a reference.
  3542. QualType AddrQTy =
  3543. getContext().getPointerType(OrigVD->getType().getNonReferenceType());
  3544. llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy);
  3545. Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy);
  3546. setAddrOfLocalVar(InitVD, InitAddr);
  3547. // Emit private declaration, it will be initialized by the value we
  3548. // declaration we just added to the local declarations map.
  3549. EmitDecl(*PvtVD);
  3550. // The initialization variables reached its purpose in the emission
  3551. // ofthe previous declaration, so we don't need it anymore.
  3552. LocalDeclMap.erase(InitVD);
  3553. // Return the address of the private variable.
  3554. return GetAddrOfLocalVar(PvtVD);
  3555. });
  3556. assert(IsRegistered && "firstprivate var already registered as private");
  3557. // Silence the warning about unused variable.
  3558. (void)IsRegistered;
  3559. ++OrigVarIt;
  3560. ++InitIt;
  3561. }
  3562. }
  3563. // Generate the instructions for '#pragma omp target data' directive.
  3564. void CodeGenFunction::EmitOMPTargetDataDirective(
  3565. const OMPTargetDataDirective &S) {
  3566. CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true);
  3567. // Create a pre/post action to signal the privatization of the device pointer.
  3568. // This action can be replaced by the OpenMP runtime code generation to
  3569. // deactivate privatization.
  3570. bool PrivatizeDevicePointers = false;
  3571. class DevicePointerPrivActionTy : public PrePostActionTy {
  3572. bool &PrivatizeDevicePointers;
  3573. public:
  3574. explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers)
  3575. : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {}
  3576. void Enter(CodeGenFunction &CGF) override {
  3577. PrivatizeDevicePointers = true;
  3578. }
  3579. };
  3580. DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers);
  3581. auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers](
  3582. CodeGenFunction &CGF, PrePostActionTy &Action) {
  3583. auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) {
  3584. CGF.EmitStmt(
  3585. cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt());
  3586. };
  3587. // Codegen that selects wheather to generate the privatization code or not.
  3588. auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers,
  3589. &InnermostCodeGen](CodeGenFunction &CGF,
  3590. PrePostActionTy &Action) {
  3591. RegionCodeGenTy RCG(InnermostCodeGen);
  3592. PrivatizeDevicePointers = false;
  3593. // Call the pre-action to change the status of PrivatizeDevicePointers if
  3594. // needed.
  3595. Action.Enter(CGF);
  3596. if (PrivatizeDevicePointers) {
  3597. OMPPrivateScope PrivateScope(CGF);
  3598. // Emit all instances of the use_device_ptr clause.
  3599. for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>())
  3600. CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope,
  3601. Info.CaptureDeviceAddrMap);
  3602. (void)PrivateScope.Privatize();
  3603. RCG(CGF);
  3604. } else
  3605. RCG(CGF);
  3606. };
  3607. // Forward the provided action to the privatization codegen.
  3608. RegionCodeGenTy PrivRCG(PrivCodeGen);
  3609. PrivRCG.setAction(Action);
  3610. // Notwithstanding the body of the region is emitted as inlined directive,
  3611. // we don't use an inline scope as changes in the references inside the
  3612. // region are expected to be visible outside, so we do not privative them.
  3613. OMPLexicalScope Scope(CGF, S);
  3614. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data,
  3615. PrivRCG);
  3616. };
  3617. RegionCodeGenTy RCG(CodeGen);
  3618. // If we don't have target devices, don't bother emitting the data mapping
  3619. // code.
  3620. if (CGM.getLangOpts().OMPTargetTriples.empty()) {
  3621. RCG(*this);
  3622. return;
  3623. }
  3624. // Check if we have any if clause associated with the directive.
  3625. const Expr *IfCond = nullptr;
  3626. if (auto *C = S.getSingleClause<OMPIfClause>())
  3627. IfCond = C->getCondition();
  3628. // Check if we have any device clause associated with the directive.
  3629. const Expr *Device = nullptr;
  3630. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3631. Device = C->getDevice();
  3632. // Set the action to signal privatization of device pointers.
  3633. RCG.setAction(PrivAction);
  3634. // Emit region code.
  3635. CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG,
  3636. Info);
  3637. }
  3638. void CodeGenFunction::EmitOMPTargetEnterDataDirective(
  3639. const OMPTargetEnterDataDirective &S) {
  3640. // If we don't have target devices, don't bother emitting the data mapping
  3641. // code.
  3642. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3643. return;
  3644. // Check if we have any if clause associated with the directive.
  3645. const Expr *IfCond = nullptr;
  3646. if (auto *C = S.getSingleClause<OMPIfClause>())
  3647. IfCond = C->getCondition();
  3648. // Check if we have any device clause associated with the directive.
  3649. const Expr *Device = nullptr;
  3650. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3651. Device = C->getDevice();
  3652. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3653. }
  3654. void CodeGenFunction::EmitOMPTargetExitDataDirective(
  3655. const OMPTargetExitDataDirective &S) {
  3656. // If we don't have target devices, don't bother emitting the data mapping
  3657. // code.
  3658. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3659. return;
  3660. // Check if we have any if clause associated with the directive.
  3661. const Expr *IfCond = nullptr;
  3662. if (auto *C = S.getSingleClause<OMPIfClause>())
  3663. IfCond = C->getCondition();
  3664. // Check if we have any device clause associated with the directive.
  3665. const Expr *Device = nullptr;
  3666. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3667. Device = C->getDevice();
  3668. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3669. }
  3670. static void emitTargetParallelRegion(CodeGenFunction &CGF,
  3671. const OMPTargetParallelDirective &S,
  3672. PrePostActionTy &Action) {
  3673. // Get the captured statement associated with the 'parallel' region.
  3674. auto *CS = S.getCapturedStmt(OMPD_parallel);
  3675. Action.Enter(CGF);
  3676. auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &) {
  3677. CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
  3678. (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
  3679. CGF.EmitOMPPrivateClause(S, PrivateScope);
  3680. CGF.EmitOMPReductionClauseInit(S, PrivateScope);
  3681. (void)PrivateScope.Privatize();
  3682. // TODO: Add support for clauses.
  3683. CGF.EmitStmt(CS->getCapturedStmt());
  3684. CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel);
  3685. };
  3686. emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen,
  3687. emitEmptyBoundParameters);
  3688. emitPostUpdateForReductionClause(
  3689. CGF, S, [](CodeGenFunction &) -> llvm::Value * { return nullptr; });
  3690. }
  3691. void CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
  3692. CodeGenModule &CGM, StringRef ParentName,
  3693. const OMPTargetParallelDirective &S) {
  3694. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3695. emitTargetParallelRegion(CGF, S, Action);
  3696. };
  3697. llvm::Function *Fn;
  3698. llvm::Constant *Addr;
  3699. // Emit target region as a standalone region.
  3700. CGM.getOpenMPRuntime().emitTargetOutlinedFunction(
  3701. S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen);
  3702. assert(Fn && Addr && "Target device function emission failed.");
  3703. }
  3704. void CodeGenFunction::EmitOMPTargetParallelDirective(
  3705. const OMPTargetParallelDirective &S) {
  3706. auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
  3707. emitTargetParallelRegion(CGF, S, Action);
  3708. };
  3709. emitCommonOMPTargetDirective(*this, S, CodeGen);
  3710. }
  3711. void CodeGenFunction::EmitOMPTargetParallelForDirective(
  3712. const OMPTargetParallelForDirective &S) {
  3713. // TODO: codegen for target parallel for.
  3714. }
  3715. /// Emit a helper variable and return corresponding lvalue.
  3716. static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper,
  3717. const ImplicitParamDecl *PVD,
  3718. CodeGenFunction::OMPPrivateScope &Privates) {
  3719. auto *VDecl = cast<VarDecl>(Helper->getDecl());
  3720. Privates.addPrivate(
  3721. VDecl, [&CGF, PVD]() -> Address { return CGF.GetAddrOfLocalVar(PVD); });
  3722. }
  3723. void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
  3724. assert(isOpenMPTaskLoopDirective(S.getDirectiveKind()));
  3725. // Emit outlined function for task construct.
  3726. auto CS = cast<CapturedStmt>(S.getAssociatedStmt());
  3727. auto CapturedStruct = GenerateCapturedStmtArgument(*CS);
  3728. auto SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl());
  3729. const Expr *IfCond = nullptr;
  3730. for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
  3731. if (C->getNameModifier() == OMPD_unknown ||
  3732. C->getNameModifier() == OMPD_taskloop) {
  3733. IfCond = C->getCondition();
  3734. break;
  3735. }
  3736. }
  3737. OMPTaskDataTy Data;
  3738. // Check if taskloop must be emitted without taskgroup.
  3739. Data.Nogroup = S.getSingleClause<OMPNogroupClause>();
  3740. // TODO: Check if we should emit tied or untied task.
  3741. Data.Tied = true;
  3742. // Set scheduling for taskloop
  3743. if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) {
  3744. // grainsize clause
  3745. Data.Schedule.setInt(/*IntVal=*/false);
  3746. Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
  3747. } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) {
  3748. // num_tasks clause
  3749. Data.Schedule.setInt(/*IntVal=*/true);
  3750. Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks()));
  3751. }
  3752. auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) {
  3753. // if (PreCond) {
  3754. // for (IV in 0..LastIteration) BODY;
  3755. // <Final counter/linear vars updates>;
  3756. // }
  3757. //
  3758. // Emit: if (PreCond) - begin.
  3759. // If the condition constant folds and can be elided, avoid emitting the
  3760. // whole loop.
  3761. bool CondConstant;
  3762. llvm::BasicBlock *ContBlock = nullptr;
  3763. OMPLoopScope PreInitScope(CGF, S);
  3764. if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) {
  3765. if (!CondConstant)
  3766. return;
  3767. } else {
  3768. auto *ThenBlock = CGF.createBasicBlock("taskloop.if.then");
  3769. ContBlock = CGF.createBasicBlock("taskloop.if.end");
  3770. emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock,
  3771. CGF.getProfileCount(&S));
  3772. CGF.EmitBlock(ThenBlock);
  3773. CGF.incrementProfileCounter(&S);
  3774. }
  3775. if (isOpenMPSimdDirective(S.getDirectiveKind()))
  3776. CGF.EmitOMPSimdInit(S);
  3777. OMPPrivateScope LoopScope(CGF);
  3778. // Emit helper vars inits.
  3779. enum { LowerBound = 5, UpperBound, Stride, LastIter };
  3780. auto *I = CS->getCapturedDecl()->param_begin();
  3781. auto *LBP = std::next(I, LowerBound);
  3782. auto *UBP = std::next(I, UpperBound);
  3783. auto *STP = std::next(I, Stride);
  3784. auto *LIP = std::next(I, LastIter);
  3785. mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP,
  3786. LoopScope);
  3787. mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP,
  3788. LoopScope);
  3789. mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope);
  3790. mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP,
  3791. LoopScope);
  3792. CGF.EmitOMPPrivateLoopCounters(S, LoopScope);
  3793. bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope);
  3794. (void)LoopScope.Privatize();
  3795. // Emit the loop iteration variable.
  3796. const Expr *IVExpr = S.getIterationVariable();
  3797. const VarDecl *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl());
  3798. CGF.EmitVarDecl(*IVDecl);
  3799. CGF.EmitIgnoredExpr(S.getInit());
  3800. // Emit the iterations count variable.
  3801. // If it is not a variable, Sema decided to calculate iterations count on
  3802. // each iteration (e.g., it is foldable into a constant).
  3803. if (auto LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) {
  3804. CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl()));
  3805. // Emit calculation of the iterations count.
  3806. CGF.EmitIgnoredExpr(S.getCalcLastIteration());
  3807. }
  3808. CGF.EmitOMPInnerLoop(S, LoopScope.requiresCleanups(), S.getCond(),
  3809. S.getInc(),
  3810. [&S](CodeGenFunction &CGF) {
  3811. CGF.EmitOMPLoopBody(S, JumpDest());
  3812. CGF.EmitStopPoint(&S);
  3813. },
  3814. [](CodeGenFunction &) {});
  3815. // Emit: if (PreCond) - end.
  3816. if (ContBlock) {
  3817. CGF.EmitBranch(ContBlock);
  3818. CGF.EmitBlock(ContBlock, true);
  3819. }
  3820. // Emit final copy of the lastprivate variables if IsLastIter != 0.
  3821. if (HasLastprivateClause) {
  3822. CGF.EmitOMPLastprivateClauseFinal(
  3823. S, isOpenMPSimdDirective(S.getDirectiveKind()),
  3824. CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar(
  3825. CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false,
  3826. (*LIP)->getType(), S.getLocStart())));
  3827. }
  3828. };
  3829. auto &&TaskGen = [&S, SharedsTy, CapturedStruct,
  3830. IfCond](CodeGenFunction &CGF, llvm::Value *OutlinedFn,
  3831. const OMPTaskDataTy &Data) {
  3832. auto &&CodeGen = [&](CodeGenFunction &CGF, PrePostActionTy &) {
  3833. OMPLoopScope PreInitScope(CGF, S);
  3834. CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getLocStart(), S,
  3835. OutlinedFn, SharedsTy,
  3836. CapturedStruct, IfCond, Data);
  3837. };
  3838. CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop,
  3839. CodeGen);
  3840. };
  3841. if (Data.Nogroup)
  3842. EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
  3843. else {
  3844. CGM.getOpenMPRuntime().emitTaskgroupRegion(
  3845. *this,
  3846. [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF,
  3847. PrePostActionTy &Action) {
  3848. Action.Enter(CGF);
  3849. CGF.EmitOMPTaskBasedDirective(S, BodyGen, TaskGen, Data);
  3850. },
  3851. S.getLocStart());
  3852. }
  3853. }
  3854. void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) {
  3855. EmitOMPTaskLoopBasedDirective(S);
  3856. }
  3857. void CodeGenFunction::EmitOMPTaskLoopSimdDirective(
  3858. const OMPTaskLoopSimdDirective &S) {
  3859. EmitOMPTaskLoopBasedDirective(S);
  3860. }
  3861. // Generate the instructions for '#pragma omp target update' directive.
  3862. void CodeGenFunction::EmitOMPTargetUpdateDirective(
  3863. const OMPTargetUpdateDirective &S) {
  3864. // If we don't have target devices, don't bother emitting the data mapping
  3865. // code.
  3866. if (CGM.getLangOpts().OMPTargetTriples.empty())
  3867. return;
  3868. // Check if we have any if clause associated with the directive.
  3869. const Expr *IfCond = nullptr;
  3870. if (auto *C = S.getSingleClause<OMPIfClause>())
  3871. IfCond = C->getCondition();
  3872. // Check if we have any device clause associated with the directive.
  3873. const Expr *Device = nullptr;
  3874. if (auto *C = S.getSingleClause<OMPDeviceClause>())
  3875. Device = C->getDevice();
  3876. CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device);
  3877. }