CGStmtOpenMP.cpp 215 KB

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