CGStmtOpenMP.cpp 217 KB

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