CGStmtOpenMP.cpp 203 KB

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