CGOpenMPRuntimeGPU.cpp 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671
  1. //===---- CGOpenMPRuntimeGPU.cpp - Interface to OpenMP GPU Runtimes ----===//
  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 provides a generalized class for OpenMP runtime code generation
  10. // specialized by GPU targets NVPTX and AMDGCN.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGOpenMPRuntimeGPU.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/DeclOpenMP.h"
  17. #include "clang/AST/OpenMPClause.h"
  18. #include "clang/AST/StmtOpenMP.h"
  19. #include "clang/AST/StmtVisitor.h"
  20. #include "clang/Basic/Cuda.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/Frontend/OpenMP/OMPGridValues.h"
  23. #include "llvm/Support/MathExtras.h"
  24. using namespace clang;
  25. using namespace CodeGen;
  26. using namespace llvm::omp;
  27. namespace {
  28. /// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
  29. class NVPTXActionTy final : public PrePostActionTy {
  30. llvm::FunctionCallee EnterCallee = nullptr;
  31. ArrayRef<llvm::Value *> EnterArgs;
  32. llvm::FunctionCallee ExitCallee = nullptr;
  33. ArrayRef<llvm::Value *> ExitArgs;
  34. bool Conditional = false;
  35. llvm::BasicBlock *ContBlock = nullptr;
  36. public:
  37. NVPTXActionTy(llvm::FunctionCallee EnterCallee,
  38. ArrayRef<llvm::Value *> EnterArgs,
  39. llvm::FunctionCallee ExitCallee,
  40. ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
  41. : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
  42. ExitArgs(ExitArgs), Conditional(Conditional) {}
  43. void Enter(CodeGenFunction &CGF) override {
  44. llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
  45. if (Conditional) {
  46. llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
  47. auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
  48. ContBlock = CGF.createBasicBlock("omp_if.end");
  49. // Generate the branch (If-stmt)
  50. CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
  51. CGF.EmitBlock(ThenBlock);
  52. }
  53. }
  54. void Done(CodeGenFunction &CGF) {
  55. // Emit the rest of blocks/branches
  56. CGF.EmitBranch(ContBlock);
  57. CGF.EmitBlock(ContBlock, true);
  58. }
  59. void Exit(CodeGenFunction &CGF) override {
  60. CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
  61. }
  62. };
  63. /// A class to track the execution mode when codegening directives within
  64. /// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
  65. /// to the target region and used by containing directives such as 'parallel'
  66. /// to emit optimized code.
  67. class ExecutionRuntimeModesRAII {
  68. private:
  69. CGOpenMPRuntimeGPU::ExecutionMode SavedExecMode =
  70. CGOpenMPRuntimeGPU::EM_Unknown;
  71. CGOpenMPRuntimeGPU::ExecutionMode &ExecMode;
  72. public:
  73. ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode,
  74. CGOpenMPRuntimeGPU::ExecutionMode EntryMode)
  75. : ExecMode(ExecMode) {
  76. SavedExecMode = ExecMode;
  77. ExecMode = EntryMode;
  78. }
  79. ~ExecutionRuntimeModesRAII() { ExecMode = SavedExecMode; }
  80. };
  81. /// GPU Configuration: This information can be derived from cuda registers,
  82. /// however, providing compile time constants helps generate more efficient
  83. /// code. For all practical purposes this is fine because the configuration
  84. /// is the same for all known NVPTX architectures.
  85. enum MachineConfiguration : unsigned {
  86. /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
  87. /// specific Grid Values like GV_Warp_Size, GV_Slot_Size
  88. /// Global memory alignment for performance.
  89. GlobalMemoryAlignment = 128,
  90. };
  91. static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
  92. RefExpr = RefExpr->IgnoreParens();
  93. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
  94. const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  95. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  96. Base = TempASE->getBase()->IgnoreParenImpCasts();
  97. RefExpr = Base;
  98. } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
  99. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  100. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  101. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  102. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  103. Base = TempASE->getBase()->IgnoreParenImpCasts();
  104. RefExpr = Base;
  105. }
  106. RefExpr = RefExpr->IgnoreParenImpCasts();
  107. if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
  108. return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
  109. const auto *ME = cast<MemberExpr>(RefExpr);
  110. return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
  111. }
  112. static RecordDecl *buildRecordForGlobalizedVars(
  113. ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
  114. ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
  115. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  116. &MappedDeclsFields, int BufSize) {
  117. using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
  118. if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
  119. return nullptr;
  120. SmallVector<VarsDataTy, 4> GlobalizedVars;
  121. for (const ValueDecl *D : EscapedDecls)
  122. GlobalizedVars.emplace_back(
  123. CharUnits::fromQuantity(std::max(
  124. C.getDeclAlign(D).getQuantity(),
  125. static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
  126. D);
  127. for (const ValueDecl *D : EscapedDeclsForTeams)
  128. GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
  129. llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
  130. return L.first > R.first;
  131. });
  132. // Build struct _globalized_locals_ty {
  133. // /* globalized vars */[WarSize] align (max(decl_align,
  134. // GlobalMemoryAlignment))
  135. // /* globalized vars */ for EscapedDeclsForTeams
  136. // };
  137. RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
  138. GlobalizedRD->startDefinition();
  139. llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
  140. EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
  141. for (const auto &Pair : GlobalizedVars) {
  142. const ValueDecl *VD = Pair.second;
  143. QualType Type = VD->getType();
  144. if (Type->isLValueReferenceType())
  145. Type = C.getPointerType(Type.getNonReferenceType());
  146. else
  147. Type = Type.getNonReferenceType();
  148. SourceLocation Loc = VD->getLocation();
  149. FieldDecl *Field;
  150. if (SingleEscaped.count(VD)) {
  151. Field = FieldDecl::Create(
  152. C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
  153. C.getTrivialTypeSourceInfo(Type, SourceLocation()),
  154. /*BW=*/nullptr, /*Mutable=*/false,
  155. /*InitStyle=*/ICIS_NoInit);
  156. Field->setAccess(AS_public);
  157. if (VD->hasAttrs()) {
  158. for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
  159. E(VD->getAttrs().end());
  160. I != E; ++I)
  161. Field->addAttr(*I);
  162. }
  163. } else {
  164. llvm::APInt ArraySize(32, BufSize);
  165. Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
  166. 0);
  167. Field = FieldDecl::Create(
  168. C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
  169. C.getTrivialTypeSourceInfo(Type, SourceLocation()),
  170. /*BW=*/nullptr, /*Mutable=*/false,
  171. /*InitStyle=*/ICIS_NoInit);
  172. Field->setAccess(AS_public);
  173. llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
  174. static_cast<CharUnits::QuantityType>(
  175. GlobalMemoryAlignment)));
  176. Field->addAttr(AlignedAttr::CreateImplicit(
  177. C, /*IsAlignmentExpr=*/true,
  178. IntegerLiteral::Create(C, Align,
  179. C.getIntTypeForBitwidth(32, /*Signed=*/0),
  180. SourceLocation()),
  181. {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
  182. }
  183. GlobalizedRD->addDecl(Field);
  184. MappedDeclsFields.try_emplace(VD, Field);
  185. }
  186. GlobalizedRD->completeDefinition();
  187. return GlobalizedRD;
  188. }
  189. /// Get the list of variables that can escape their declaration context.
  190. class CheckVarsEscapingDeclContext final
  191. : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
  192. CodeGenFunction &CGF;
  193. llvm::SetVector<const ValueDecl *> EscapedDecls;
  194. llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
  195. llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
  196. RecordDecl *GlobalizedRD = nullptr;
  197. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
  198. bool AllEscaped = false;
  199. bool IsForCombinedParallelRegion = false;
  200. void markAsEscaped(const ValueDecl *VD) {
  201. // Do not globalize declare target variables.
  202. if (!isa<VarDecl>(VD) ||
  203. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  204. return;
  205. VD = cast<ValueDecl>(VD->getCanonicalDecl());
  206. // Use user-specified allocation.
  207. if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
  208. return;
  209. // Variables captured by value must be globalized.
  210. if (auto *CSI = CGF.CapturedStmtInfo) {
  211. if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
  212. // Check if need to capture the variable that was already captured by
  213. // value in the outer region.
  214. if (!IsForCombinedParallelRegion) {
  215. if (!FD->hasAttrs())
  216. return;
  217. const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
  218. if (!Attr)
  219. return;
  220. if (((Attr->getCaptureKind() != OMPC_map) &&
  221. !isOpenMPPrivate(Attr->getCaptureKind())) ||
  222. ((Attr->getCaptureKind() == OMPC_map) &&
  223. !FD->getType()->isAnyPointerType()))
  224. return;
  225. }
  226. if (!FD->getType()->isReferenceType()) {
  227. assert(!VD->getType()->isVariablyModifiedType() &&
  228. "Parameter captured by value with variably modified type");
  229. EscapedParameters.insert(VD);
  230. } else if (!IsForCombinedParallelRegion) {
  231. return;
  232. }
  233. }
  234. }
  235. if ((!CGF.CapturedStmtInfo ||
  236. (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
  237. VD->getType()->isReferenceType())
  238. // Do not globalize variables with reference type.
  239. return;
  240. if (VD->getType()->isVariablyModifiedType())
  241. EscapedVariableLengthDecls.insert(VD);
  242. else
  243. EscapedDecls.insert(VD);
  244. }
  245. void VisitValueDecl(const ValueDecl *VD) {
  246. if (VD->getType()->isLValueReferenceType())
  247. markAsEscaped(VD);
  248. if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
  249. if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
  250. const bool SavedAllEscaped = AllEscaped;
  251. AllEscaped = VD->getType()->isLValueReferenceType();
  252. Visit(VarD->getInit());
  253. AllEscaped = SavedAllEscaped;
  254. }
  255. }
  256. }
  257. void VisitOpenMPCapturedStmt(const CapturedStmt *S,
  258. ArrayRef<OMPClause *> Clauses,
  259. bool IsCombinedParallelRegion) {
  260. if (!S)
  261. return;
  262. for (const CapturedStmt::Capture &C : S->captures()) {
  263. if (C.capturesVariable() && !C.capturesVariableByCopy()) {
  264. const ValueDecl *VD = C.getCapturedVar();
  265. bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
  266. if (IsCombinedParallelRegion) {
  267. // Check if the variable is privatized in the combined construct and
  268. // those private copies must be shared in the inner parallel
  269. // directive.
  270. IsForCombinedParallelRegion = false;
  271. for (const OMPClause *C : Clauses) {
  272. if (!isOpenMPPrivate(C->getClauseKind()) ||
  273. C->getClauseKind() == OMPC_reduction ||
  274. C->getClauseKind() == OMPC_linear ||
  275. C->getClauseKind() == OMPC_private)
  276. continue;
  277. ArrayRef<const Expr *> Vars;
  278. if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
  279. Vars = PC->getVarRefs();
  280. else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
  281. Vars = PC->getVarRefs();
  282. else
  283. llvm_unreachable("Unexpected clause.");
  284. for (const auto *E : Vars) {
  285. const Decl *D =
  286. cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
  287. if (D == VD->getCanonicalDecl()) {
  288. IsForCombinedParallelRegion = true;
  289. break;
  290. }
  291. }
  292. if (IsForCombinedParallelRegion)
  293. break;
  294. }
  295. }
  296. markAsEscaped(VD);
  297. if (isa<OMPCapturedExprDecl>(VD))
  298. VisitValueDecl(VD);
  299. IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
  300. }
  301. }
  302. }
  303. void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
  304. assert(!GlobalizedRD &&
  305. "Record for globalized variables is built already.");
  306. ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
  307. unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
  308. if (IsInTTDRegion)
  309. EscapedDeclsForTeams = EscapedDecls.getArrayRef();
  310. else
  311. EscapedDeclsForParallel = EscapedDecls.getArrayRef();
  312. GlobalizedRD = ::buildRecordForGlobalizedVars(
  313. CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
  314. MappedDeclsFields, WarpSize);
  315. }
  316. public:
  317. CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
  318. ArrayRef<const ValueDecl *> TeamsReductions)
  319. : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
  320. }
  321. virtual ~CheckVarsEscapingDeclContext() = default;
  322. void VisitDeclStmt(const DeclStmt *S) {
  323. if (!S)
  324. return;
  325. for (const Decl *D : S->decls())
  326. if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
  327. VisitValueDecl(VD);
  328. }
  329. void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
  330. if (!D)
  331. return;
  332. if (!D->hasAssociatedStmt())
  333. return;
  334. if (const auto *S =
  335. dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
  336. // Do not analyze directives that do not actually require capturing,
  337. // like `omp for` or `omp simd` directives.
  338. llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  339. getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
  340. if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
  341. VisitStmt(S->getCapturedStmt());
  342. return;
  343. }
  344. VisitOpenMPCapturedStmt(
  345. S, D->clauses(),
  346. CaptureRegions.back() == OMPD_parallel &&
  347. isOpenMPDistributeDirective(D->getDirectiveKind()));
  348. }
  349. }
  350. void VisitCapturedStmt(const CapturedStmt *S) {
  351. if (!S)
  352. return;
  353. for (const CapturedStmt::Capture &C : S->captures()) {
  354. if (C.capturesVariable() && !C.capturesVariableByCopy()) {
  355. const ValueDecl *VD = C.getCapturedVar();
  356. markAsEscaped(VD);
  357. if (isa<OMPCapturedExprDecl>(VD))
  358. VisitValueDecl(VD);
  359. }
  360. }
  361. }
  362. void VisitLambdaExpr(const LambdaExpr *E) {
  363. if (!E)
  364. return;
  365. for (const LambdaCapture &C : E->captures()) {
  366. if (C.capturesVariable()) {
  367. if (C.getCaptureKind() == LCK_ByRef) {
  368. const ValueDecl *VD = C.getCapturedVar();
  369. markAsEscaped(VD);
  370. if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
  371. VisitValueDecl(VD);
  372. }
  373. }
  374. }
  375. }
  376. void VisitBlockExpr(const BlockExpr *E) {
  377. if (!E)
  378. return;
  379. for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
  380. if (C.isByRef()) {
  381. const VarDecl *VD = C.getVariable();
  382. markAsEscaped(VD);
  383. if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
  384. VisitValueDecl(VD);
  385. }
  386. }
  387. }
  388. void VisitCallExpr(const CallExpr *E) {
  389. if (!E)
  390. return;
  391. for (const Expr *Arg : E->arguments()) {
  392. if (!Arg)
  393. continue;
  394. if (Arg->isLValue()) {
  395. const bool SavedAllEscaped = AllEscaped;
  396. AllEscaped = true;
  397. Visit(Arg);
  398. AllEscaped = SavedAllEscaped;
  399. } else {
  400. Visit(Arg);
  401. }
  402. }
  403. Visit(E->getCallee());
  404. }
  405. void VisitDeclRefExpr(const DeclRefExpr *E) {
  406. if (!E)
  407. return;
  408. const ValueDecl *VD = E->getDecl();
  409. if (AllEscaped)
  410. markAsEscaped(VD);
  411. if (isa<OMPCapturedExprDecl>(VD))
  412. VisitValueDecl(VD);
  413. else if (VD->isInitCapture())
  414. VisitValueDecl(VD);
  415. }
  416. void VisitUnaryOperator(const UnaryOperator *E) {
  417. if (!E)
  418. return;
  419. if (E->getOpcode() == UO_AddrOf) {
  420. const bool SavedAllEscaped = AllEscaped;
  421. AllEscaped = true;
  422. Visit(E->getSubExpr());
  423. AllEscaped = SavedAllEscaped;
  424. } else {
  425. Visit(E->getSubExpr());
  426. }
  427. }
  428. void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
  429. if (!E)
  430. return;
  431. if (E->getCastKind() == CK_ArrayToPointerDecay) {
  432. const bool SavedAllEscaped = AllEscaped;
  433. AllEscaped = true;
  434. Visit(E->getSubExpr());
  435. AllEscaped = SavedAllEscaped;
  436. } else {
  437. Visit(E->getSubExpr());
  438. }
  439. }
  440. void VisitExpr(const Expr *E) {
  441. if (!E)
  442. return;
  443. bool SavedAllEscaped = AllEscaped;
  444. if (!E->isLValue())
  445. AllEscaped = false;
  446. for (const Stmt *Child : E->children())
  447. if (Child)
  448. Visit(Child);
  449. AllEscaped = SavedAllEscaped;
  450. }
  451. void VisitStmt(const Stmt *S) {
  452. if (!S)
  453. return;
  454. for (const Stmt *Child : S->children())
  455. if (Child)
  456. Visit(Child);
  457. }
  458. /// Returns the record that handles all the escaped local variables and used
  459. /// instead of their original storage.
  460. const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
  461. if (!GlobalizedRD)
  462. buildRecordForGlobalizedVars(IsInTTDRegion);
  463. return GlobalizedRD;
  464. }
  465. /// Returns the field in the globalized record for the escaped variable.
  466. const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
  467. assert(GlobalizedRD &&
  468. "Record for globalized variables must be generated already.");
  469. auto I = MappedDeclsFields.find(VD);
  470. if (I == MappedDeclsFields.end())
  471. return nullptr;
  472. return I->getSecond();
  473. }
  474. /// Returns the list of the escaped local variables/parameters.
  475. ArrayRef<const ValueDecl *> getEscapedDecls() const {
  476. return EscapedDecls.getArrayRef();
  477. }
  478. /// Checks if the escaped local variable is actually a parameter passed by
  479. /// value.
  480. const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
  481. return EscapedParameters;
  482. }
  483. /// Returns the list of the escaped variables with the variably modified
  484. /// types.
  485. ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
  486. return EscapedVariableLengthDecls.getArrayRef();
  487. }
  488. };
  489. } // anonymous namespace
  490. /// Get the id of the warp in the block.
  491. /// We assume that the warp size is 32, which is always the case
  492. /// on the NVPTX device, to generate more efficient code.
  493. static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
  494. CGBuilderTy &Bld = CGF.Builder;
  495. unsigned LaneIDBits =
  496. llvm::Log2_32(CGF.getTarget().getGridValue().GV_Warp_Size);
  497. auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  498. return Bld.CreateAShr(RT.getGPUThreadID(CGF), LaneIDBits, "nvptx_warp_id");
  499. }
  500. /// Get the id of the current lane in the Warp.
  501. /// We assume that the warp size is 32, which is always the case
  502. /// on the NVPTX device, to generate more efficient code.
  503. static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
  504. CGBuilderTy &Bld = CGF.Builder;
  505. unsigned LaneIDBits =
  506. llvm::Log2_32(CGF.getTarget().getGridValue().GV_Warp_Size);
  507. unsigned LaneIDMask = ~0u >> (32u - LaneIDBits);
  508. auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  509. return Bld.CreateAnd(RT.getGPUThreadID(CGF), Bld.getInt32(LaneIDMask),
  510. "nvptx_lane_id");
  511. }
  512. CGOpenMPRuntimeGPU::ExecutionMode
  513. CGOpenMPRuntimeGPU::getExecutionMode() const {
  514. return CurrentExecutionMode;
  515. }
  516. static CGOpenMPRuntimeGPU::DataSharingMode
  517. getDataSharingMode(CodeGenModule &CGM) {
  518. return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeGPU::CUDA
  519. : CGOpenMPRuntimeGPU::Generic;
  520. }
  521. /// Check for inner (nested) SPMD construct, if any
  522. static bool hasNestedSPMDDirective(ASTContext &Ctx,
  523. const OMPExecutableDirective &D) {
  524. const auto *CS = D.getInnermostCapturedStmt();
  525. const auto *Body =
  526. CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
  527. const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  528. if (const auto *NestedDir =
  529. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  530. OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
  531. switch (D.getDirectiveKind()) {
  532. case OMPD_target:
  533. if (isOpenMPParallelDirective(DKind))
  534. return true;
  535. if (DKind == OMPD_teams) {
  536. Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
  537. /*IgnoreCaptured=*/true);
  538. if (!Body)
  539. return false;
  540. ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
  541. if (const auto *NND =
  542. dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
  543. DKind = NND->getDirectiveKind();
  544. if (isOpenMPParallelDirective(DKind))
  545. return true;
  546. }
  547. }
  548. return false;
  549. case OMPD_target_teams:
  550. return isOpenMPParallelDirective(DKind);
  551. case OMPD_target_simd:
  552. case OMPD_target_parallel:
  553. case OMPD_target_parallel_for:
  554. case OMPD_target_parallel_for_simd:
  555. case OMPD_target_teams_distribute:
  556. case OMPD_target_teams_distribute_simd:
  557. case OMPD_target_teams_distribute_parallel_for:
  558. case OMPD_target_teams_distribute_parallel_for_simd:
  559. case OMPD_parallel:
  560. case OMPD_for:
  561. case OMPD_parallel_for:
  562. case OMPD_parallel_master:
  563. case OMPD_parallel_sections:
  564. case OMPD_for_simd:
  565. case OMPD_parallel_for_simd:
  566. case OMPD_cancel:
  567. case OMPD_cancellation_point:
  568. case OMPD_ordered:
  569. case OMPD_threadprivate:
  570. case OMPD_allocate:
  571. case OMPD_task:
  572. case OMPD_simd:
  573. case OMPD_sections:
  574. case OMPD_section:
  575. case OMPD_single:
  576. case OMPD_master:
  577. case OMPD_critical:
  578. case OMPD_taskyield:
  579. case OMPD_barrier:
  580. case OMPD_taskwait:
  581. case OMPD_taskgroup:
  582. case OMPD_atomic:
  583. case OMPD_flush:
  584. case OMPD_depobj:
  585. case OMPD_scan:
  586. case OMPD_teams:
  587. case OMPD_target_data:
  588. case OMPD_target_exit_data:
  589. case OMPD_target_enter_data:
  590. case OMPD_distribute:
  591. case OMPD_distribute_simd:
  592. case OMPD_distribute_parallel_for:
  593. case OMPD_distribute_parallel_for_simd:
  594. case OMPD_teams_distribute:
  595. case OMPD_teams_distribute_simd:
  596. case OMPD_teams_distribute_parallel_for:
  597. case OMPD_teams_distribute_parallel_for_simd:
  598. case OMPD_target_update:
  599. case OMPD_declare_simd:
  600. case OMPD_declare_variant:
  601. case OMPD_begin_declare_variant:
  602. case OMPD_end_declare_variant:
  603. case OMPD_declare_target:
  604. case OMPD_end_declare_target:
  605. case OMPD_declare_reduction:
  606. case OMPD_declare_mapper:
  607. case OMPD_taskloop:
  608. case OMPD_taskloop_simd:
  609. case OMPD_master_taskloop:
  610. case OMPD_master_taskloop_simd:
  611. case OMPD_parallel_master_taskloop:
  612. case OMPD_parallel_master_taskloop_simd:
  613. case OMPD_requires:
  614. case OMPD_unknown:
  615. default:
  616. llvm_unreachable("Unexpected directive.");
  617. }
  618. }
  619. return false;
  620. }
  621. static bool supportsSPMDExecutionMode(ASTContext &Ctx,
  622. const OMPExecutableDirective &D) {
  623. OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
  624. switch (DirectiveKind) {
  625. case OMPD_target:
  626. case OMPD_target_teams:
  627. return hasNestedSPMDDirective(Ctx, D);
  628. case OMPD_target_parallel:
  629. case OMPD_target_parallel_for:
  630. case OMPD_target_parallel_for_simd:
  631. case OMPD_target_teams_distribute_parallel_for:
  632. case OMPD_target_teams_distribute_parallel_for_simd:
  633. case OMPD_target_simd:
  634. case OMPD_target_teams_distribute_simd:
  635. return true;
  636. case OMPD_target_teams_distribute:
  637. return false;
  638. case OMPD_parallel:
  639. case OMPD_for:
  640. case OMPD_parallel_for:
  641. case OMPD_parallel_master:
  642. case OMPD_parallel_sections:
  643. case OMPD_for_simd:
  644. case OMPD_parallel_for_simd:
  645. case OMPD_cancel:
  646. case OMPD_cancellation_point:
  647. case OMPD_ordered:
  648. case OMPD_threadprivate:
  649. case OMPD_allocate:
  650. case OMPD_task:
  651. case OMPD_simd:
  652. case OMPD_sections:
  653. case OMPD_section:
  654. case OMPD_single:
  655. case OMPD_master:
  656. case OMPD_critical:
  657. case OMPD_taskyield:
  658. case OMPD_barrier:
  659. case OMPD_taskwait:
  660. case OMPD_taskgroup:
  661. case OMPD_atomic:
  662. case OMPD_flush:
  663. case OMPD_depobj:
  664. case OMPD_scan:
  665. case OMPD_teams:
  666. case OMPD_target_data:
  667. case OMPD_target_exit_data:
  668. case OMPD_target_enter_data:
  669. case OMPD_distribute:
  670. case OMPD_distribute_simd:
  671. case OMPD_distribute_parallel_for:
  672. case OMPD_distribute_parallel_for_simd:
  673. case OMPD_teams_distribute:
  674. case OMPD_teams_distribute_simd:
  675. case OMPD_teams_distribute_parallel_for:
  676. case OMPD_teams_distribute_parallel_for_simd:
  677. case OMPD_target_update:
  678. case OMPD_declare_simd:
  679. case OMPD_declare_variant:
  680. case OMPD_begin_declare_variant:
  681. case OMPD_end_declare_variant:
  682. case OMPD_declare_target:
  683. case OMPD_end_declare_target:
  684. case OMPD_declare_reduction:
  685. case OMPD_declare_mapper:
  686. case OMPD_taskloop:
  687. case OMPD_taskloop_simd:
  688. case OMPD_master_taskloop:
  689. case OMPD_master_taskloop_simd:
  690. case OMPD_parallel_master_taskloop:
  691. case OMPD_parallel_master_taskloop_simd:
  692. case OMPD_requires:
  693. case OMPD_unknown:
  694. default:
  695. break;
  696. }
  697. llvm_unreachable(
  698. "Unknown programming model for OpenMP directive on NVPTX target.");
  699. }
  700. void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
  701. StringRef ParentName,
  702. llvm::Function *&OutlinedFn,
  703. llvm::Constant *&OutlinedFnID,
  704. bool IsOffloadEntry,
  705. const RegionCodeGenTy &CodeGen) {
  706. ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_NonSPMD);
  707. EntryFunctionState EST;
  708. WrapperFunctionsMap.clear();
  709. // Emit target region as a standalone region.
  710. class NVPTXPrePostActionTy : public PrePostActionTy {
  711. CGOpenMPRuntimeGPU::EntryFunctionState &EST;
  712. public:
  713. NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST)
  714. : EST(EST) {}
  715. void Enter(CodeGenFunction &CGF) override {
  716. auto &RT =
  717. static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  718. RT.emitKernelInit(CGF, EST, /* IsSPMD */ false);
  719. // Skip target region initialization.
  720. RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
  721. }
  722. void Exit(CodeGenFunction &CGF) override {
  723. auto &RT =
  724. static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  725. RT.clearLocThreadIdInsertPt(CGF);
  726. RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ false);
  727. }
  728. } Action(EST);
  729. CodeGen.setAction(Action);
  730. IsInTTDRegion = true;
  731. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  732. IsOffloadEntry, CodeGen);
  733. IsInTTDRegion = false;
  734. }
  735. void CGOpenMPRuntimeGPU::emitKernelInit(CodeGenFunction &CGF,
  736. EntryFunctionState &EST, bool IsSPMD) {
  737. CGBuilderTy &Bld = CGF.Builder;
  738. Bld.restoreIP(OMPBuilder.createTargetInit(Bld, IsSPMD));
  739. if (!IsSPMD)
  740. emitGenericVarsProlog(CGF, EST.Loc);
  741. }
  742. void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction &CGF,
  743. EntryFunctionState &EST,
  744. bool IsSPMD) {
  745. if (!IsSPMD)
  746. emitGenericVarsEpilog(CGF);
  747. CGBuilderTy &Bld = CGF.Builder;
  748. OMPBuilder.createTargetDeinit(Bld, IsSPMD);
  749. }
  750. void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
  751. StringRef ParentName,
  752. llvm::Function *&OutlinedFn,
  753. llvm::Constant *&OutlinedFnID,
  754. bool IsOffloadEntry,
  755. const RegionCodeGenTy &CodeGen) {
  756. ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode, EM_SPMD);
  757. EntryFunctionState EST;
  758. // Emit target region as a standalone region.
  759. class NVPTXPrePostActionTy : public PrePostActionTy {
  760. CGOpenMPRuntimeGPU &RT;
  761. CGOpenMPRuntimeGPU::EntryFunctionState &EST;
  762. public:
  763. NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
  764. CGOpenMPRuntimeGPU::EntryFunctionState &EST)
  765. : RT(RT), EST(EST) {}
  766. void Enter(CodeGenFunction &CGF) override {
  767. RT.emitKernelInit(CGF, EST, /* IsSPMD */ true);
  768. // Skip target region initialization.
  769. RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
  770. }
  771. void Exit(CodeGenFunction &CGF) override {
  772. RT.clearLocThreadIdInsertPt(CGF);
  773. RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ true);
  774. }
  775. } Action(*this, EST);
  776. CodeGen.setAction(Action);
  777. IsInTTDRegion = true;
  778. emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
  779. IsOffloadEntry, CodeGen);
  780. IsInTTDRegion = false;
  781. }
  782. // Create a unique global variable to indicate the execution mode of this target
  783. // region. The execution mode is either 'generic', or 'spmd' depending on the
  784. // target directive. This variable is picked up by the offload library to setup
  785. // the device appropriately before kernel launch. If the execution mode is
  786. // 'generic', the runtime reserves one warp for the master, otherwise, all
  787. // warps participate in parallel work.
  788. static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
  789. bool Mode) {
  790. auto *GVMode = new llvm::GlobalVariable(
  791. CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
  792. llvm::GlobalValue::WeakAnyLinkage,
  793. llvm::ConstantInt::get(CGM.Int8Ty, Mode ? OMP_TGT_EXEC_MODE_SPMD
  794. : OMP_TGT_EXEC_MODE_GENERIC),
  795. Twine(Name, "_exec_mode"));
  796. GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
  797. CGM.addCompilerUsedGlobal(GVMode);
  798. }
  799. void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
  800. const OMPExecutableDirective &D, StringRef ParentName,
  801. llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
  802. bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
  803. if (!IsOffloadEntry) // Nothing to do.
  804. return;
  805. assert(!ParentName.empty() && "Invalid target region parent name!");
  806. bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
  807. if (Mode)
  808. emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
  809. CodeGen);
  810. else
  811. emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
  812. CodeGen);
  813. setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
  814. }
  815. CGOpenMPRuntimeGPU::CGOpenMPRuntimeGPU(CodeGenModule &CGM)
  816. : CGOpenMPRuntime(CGM) {
  817. llvm::OpenMPIRBuilderConfig Config(CGM.getLangOpts().OpenMPIsDevice, true,
  818. hasRequiresUnifiedSharedMemory(),
  819. CGM.getLangOpts().OpenMPOffloadMandatory);
  820. OMPBuilder.setConfig(Config);
  821. OffloadEntriesInfoManager.setConfig(Config);
  822. if (!CGM.getLangOpts().OpenMPIsDevice)
  823. llvm_unreachable("OpenMP can only handle device code.");
  824. llvm::OpenMPIRBuilder &OMPBuilder = getOMPBuilder();
  825. if (CGM.getLangOpts().NoGPULib || CGM.getLangOpts().OMPHostIRFile.empty())
  826. return;
  827. OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTargetDebug,
  828. "__omp_rtl_debug_kind");
  829. OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPTeamSubscription,
  830. "__omp_rtl_assume_teams_oversubscription");
  831. OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPThreadSubscription,
  832. "__omp_rtl_assume_threads_oversubscription");
  833. OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoThreadState,
  834. "__omp_rtl_assume_no_thread_state");
  835. OMPBuilder.createGlobalFlag(CGM.getLangOpts().OpenMPNoNestedParallelism,
  836. "__omp_rtl_assume_no_nested_parallelism");
  837. }
  838. void CGOpenMPRuntimeGPU::emitProcBindClause(CodeGenFunction &CGF,
  839. ProcBindKind ProcBind,
  840. SourceLocation Loc) {
  841. // Do nothing in case of SPMD mode and L0 parallel.
  842. if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
  843. return;
  844. CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
  845. }
  846. void CGOpenMPRuntimeGPU::emitNumThreadsClause(CodeGenFunction &CGF,
  847. llvm::Value *NumThreads,
  848. SourceLocation Loc) {
  849. // Nothing to do.
  850. }
  851. void CGOpenMPRuntimeGPU::emitNumTeamsClause(CodeGenFunction &CGF,
  852. const Expr *NumTeams,
  853. const Expr *ThreadLimit,
  854. SourceLocation Loc) {}
  855. llvm::Function *CGOpenMPRuntimeGPU::emitParallelOutlinedFunction(
  856. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  857. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  858. // Emit target region as a standalone region.
  859. bool PrevIsInTTDRegion = IsInTTDRegion;
  860. IsInTTDRegion = false;
  861. auto *OutlinedFun =
  862. cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
  863. D, ThreadIDVar, InnermostKind, CodeGen));
  864. IsInTTDRegion = PrevIsInTTDRegion;
  865. if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD) {
  866. llvm::Function *WrapperFun =
  867. createParallelDataSharingWrapper(OutlinedFun, D);
  868. WrapperFunctionsMap[OutlinedFun] = WrapperFun;
  869. }
  870. return OutlinedFun;
  871. }
  872. /// Get list of lastprivate variables from the teams distribute ... or
  873. /// teams {distribute ...} directives.
  874. static void
  875. getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
  876. llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
  877. assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
  878. "expected teams directive.");
  879. const OMPExecutableDirective *Dir = &D;
  880. if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
  881. if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
  882. Ctx,
  883. D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
  884. /*IgnoreCaptured=*/true))) {
  885. Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
  886. if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
  887. Dir = nullptr;
  888. }
  889. }
  890. if (!Dir)
  891. return;
  892. for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
  893. for (const Expr *E : C->getVarRefs())
  894. Vars.push_back(getPrivateItem(E));
  895. }
  896. }
  897. /// Get list of reduction variables from the teams ... directives.
  898. static void
  899. getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
  900. llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
  901. assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
  902. "expected teams directive.");
  903. for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
  904. for (const Expr *E : C->privates())
  905. Vars.push_back(getPrivateItem(E));
  906. }
  907. }
  908. llvm::Function *CGOpenMPRuntimeGPU::emitTeamsOutlinedFunction(
  909. const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
  910. OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
  911. SourceLocation Loc = D.getBeginLoc();
  912. const RecordDecl *GlobalizedRD = nullptr;
  913. llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
  914. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
  915. unsigned WarpSize = CGM.getTarget().getGridValue().GV_Warp_Size;
  916. // Globalize team reductions variable unconditionally in all modes.
  917. if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
  918. getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
  919. if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
  920. getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
  921. if (!LastPrivatesReductions.empty()) {
  922. GlobalizedRD = ::buildRecordForGlobalizedVars(
  923. CGM.getContext(), std::nullopt, LastPrivatesReductions,
  924. MappedDeclsFields, WarpSize);
  925. }
  926. } else if (!LastPrivatesReductions.empty()) {
  927. assert(!TeamAndReductions.first &&
  928. "Previous team declaration is not expected.");
  929. TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
  930. std::swap(TeamAndReductions.second, LastPrivatesReductions);
  931. }
  932. // Emit target region as a standalone region.
  933. class NVPTXPrePostActionTy : public PrePostActionTy {
  934. SourceLocation &Loc;
  935. const RecordDecl *GlobalizedRD;
  936. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  937. &MappedDeclsFields;
  938. public:
  939. NVPTXPrePostActionTy(
  940. SourceLocation &Loc, const RecordDecl *GlobalizedRD,
  941. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  942. &MappedDeclsFields)
  943. : Loc(Loc), GlobalizedRD(GlobalizedRD),
  944. MappedDeclsFields(MappedDeclsFields) {}
  945. void Enter(CodeGenFunction &CGF) override {
  946. auto &Rt =
  947. static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  948. if (GlobalizedRD) {
  949. auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
  950. I->getSecond().MappedParams =
  951. std::make_unique<CodeGenFunction::OMPMapVars>();
  952. DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
  953. for (const auto &Pair : MappedDeclsFields) {
  954. assert(Pair.getFirst()->isCanonicalDecl() &&
  955. "Expected canonical declaration");
  956. Data.insert(std::make_pair(Pair.getFirst(), MappedVarData()));
  957. }
  958. }
  959. Rt.emitGenericVarsProlog(CGF, Loc);
  960. }
  961. void Exit(CodeGenFunction &CGF) override {
  962. static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
  963. .emitGenericVarsEpilog(CGF);
  964. }
  965. } Action(Loc, GlobalizedRD, MappedDeclsFields);
  966. CodeGen.setAction(Action);
  967. llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
  968. D, ThreadIDVar, InnermostKind, CodeGen);
  969. return OutlinedFun;
  970. }
  971. void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
  972. SourceLocation Loc,
  973. bool WithSPMDCheck) {
  974. if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
  975. getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
  976. return;
  977. CGBuilderTy &Bld = CGF.Builder;
  978. const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  979. if (I == FunctionGlobalizedDecls.end())
  980. return;
  981. for (auto &Rec : I->getSecond().LocalVarData) {
  982. const auto *VD = cast<VarDecl>(Rec.first);
  983. bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
  984. QualType VarTy = VD->getType();
  985. // Get the local allocation of a firstprivate variable before sharing
  986. llvm::Value *ParValue;
  987. if (EscapedParam) {
  988. LValue ParLVal =
  989. CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
  990. ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
  991. }
  992. // Allocate space for the variable to be globalized
  993. llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
  994. llvm::CallBase *VoidPtr =
  995. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  996. CGM.getModule(), OMPRTL___kmpc_alloc_shared),
  997. AllocArgs, VD->getName());
  998. // FIXME: We should use the variables actual alignment as an argument.
  999. VoidPtr->addRetAttr(llvm::Attribute::get(
  1000. CGM.getLLVMContext(), llvm::Attribute::Alignment,
  1001. CGM.getContext().getTargetInfo().getNewAlign() / 8));
  1002. // Cast the void pointer and get the address of the globalized variable.
  1003. llvm::PointerType *VarPtrTy = CGF.ConvertTypeForMem(VarTy)->getPointerTo();
  1004. llvm::Value *CastedVoidPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  1005. VoidPtr, VarPtrTy, VD->getName() + "_on_stack");
  1006. LValue VarAddr = CGF.MakeNaturalAlignAddrLValue(CastedVoidPtr, VarTy);
  1007. Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
  1008. Rec.second.GlobalizedVal = VoidPtr;
  1009. // Assign the local allocation to the newly globalized location.
  1010. if (EscapedParam) {
  1011. CGF.EmitStoreOfScalar(ParValue, VarAddr);
  1012. I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress(CGF));
  1013. }
  1014. if (auto *DI = CGF.getDebugInfo())
  1015. VoidPtr->setDebugLoc(DI->SourceLocToDebugLoc(VD->getLocation()));
  1016. }
  1017. for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
  1018. // Use actual memory size of the VLA object including the padding
  1019. // for alignment purposes.
  1020. llvm::Value *Size = CGF.getTypeSize(VD->getType());
  1021. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  1022. Size = Bld.CreateNUWAdd(
  1023. Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
  1024. llvm::Value *AlignVal =
  1025. llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
  1026. Size = Bld.CreateUDiv(Size, AlignVal);
  1027. Size = Bld.CreateNUWMul(Size, AlignVal);
  1028. // Allocate space for this VLA object to be globalized.
  1029. llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
  1030. llvm::CallBase *VoidPtr =
  1031. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1032. CGM.getModule(), OMPRTL___kmpc_alloc_shared),
  1033. AllocArgs, VD->getName());
  1034. VoidPtr->addRetAttr(
  1035. llvm::Attribute::get(CGM.getLLVMContext(), llvm::Attribute::Alignment,
  1036. CGM.getContext().getTargetInfo().getNewAlign()));
  1037. I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(
  1038. std::pair<llvm::Value *, llvm::Value *>(
  1039. {VoidPtr, CGF.getTypeSize(VD->getType())}));
  1040. LValue Base = CGF.MakeAddrLValue(VoidPtr, VD->getType(),
  1041. CGM.getContext().getDeclAlign(VD),
  1042. AlignmentSource::Decl);
  1043. I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
  1044. Base.getAddress(CGF));
  1045. }
  1046. I->getSecond().MappedParams->apply(CGF);
  1047. }
  1048. void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF,
  1049. bool WithSPMDCheck) {
  1050. if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
  1051. getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
  1052. return;
  1053. const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  1054. if (I != FunctionGlobalizedDecls.end()) {
  1055. // Deallocate the memory for each globalized VLA object
  1056. for (auto AddrSizePair :
  1057. llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
  1058. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1059. CGM.getModule(), OMPRTL___kmpc_free_shared),
  1060. {AddrSizePair.first, AddrSizePair.second});
  1061. }
  1062. // Deallocate the memory for each globalized value
  1063. for (auto &Rec : llvm::reverse(I->getSecond().LocalVarData)) {
  1064. const auto *VD = cast<VarDecl>(Rec.first);
  1065. I->getSecond().MappedParams->restore(CGF);
  1066. llvm::Value *FreeArgs[] = {Rec.second.GlobalizedVal,
  1067. CGF.getTypeSize(VD->getType())};
  1068. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1069. CGM.getModule(), OMPRTL___kmpc_free_shared),
  1070. FreeArgs);
  1071. }
  1072. }
  1073. }
  1074. void CGOpenMPRuntimeGPU::emitTeamsCall(CodeGenFunction &CGF,
  1075. const OMPExecutableDirective &D,
  1076. SourceLocation Loc,
  1077. llvm::Function *OutlinedFn,
  1078. ArrayRef<llvm::Value *> CapturedVars) {
  1079. if (!CGF.HaveInsertPoint())
  1080. return;
  1081. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  1082. /*Name=*/".zero.addr");
  1083. CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
  1084. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
  1085. OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
  1086. OutlinedFnArgs.push_back(ZeroAddr.getPointer());
  1087. OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
  1088. emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
  1089. }
  1090. void CGOpenMPRuntimeGPU::emitParallelCall(CodeGenFunction &CGF,
  1091. SourceLocation Loc,
  1092. llvm::Function *OutlinedFn,
  1093. ArrayRef<llvm::Value *> CapturedVars,
  1094. const Expr *IfCond,
  1095. llvm::Value *NumThreads) {
  1096. if (!CGF.HaveInsertPoint())
  1097. return;
  1098. auto &&ParallelGen = [this, Loc, OutlinedFn, CapturedVars, IfCond,
  1099. NumThreads](CodeGenFunction &CGF,
  1100. PrePostActionTy &Action) {
  1101. CGBuilderTy &Bld = CGF.Builder;
  1102. llvm::Value *NumThreadsVal = NumThreads;
  1103. llvm::Function *WFn = WrapperFunctionsMap[OutlinedFn];
  1104. llvm::Value *ID = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
  1105. if (WFn)
  1106. ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
  1107. llvm::Value *FnPtr = Bld.CreateBitOrPointerCast(OutlinedFn, CGM.Int8PtrTy);
  1108. // Create a private scope that will globalize the arguments
  1109. // passed from the outside of the target region.
  1110. // TODO: Is that needed?
  1111. CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
  1112. Address CapturedVarsAddrs = CGF.CreateDefaultAlignTempAlloca(
  1113. llvm::ArrayType::get(CGM.VoidPtrTy, CapturedVars.size()),
  1114. "captured_vars_addrs");
  1115. // There's something to share.
  1116. if (!CapturedVars.empty()) {
  1117. // Prepare for parallel region. Indicate the outlined function.
  1118. ASTContext &Ctx = CGF.getContext();
  1119. unsigned Idx = 0;
  1120. for (llvm::Value *V : CapturedVars) {
  1121. Address Dst = Bld.CreateConstArrayGEP(CapturedVarsAddrs, Idx);
  1122. llvm::Value *PtrV;
  1123. if (V->getType()->isIntegerTy())
  1124. PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
  1125. else
  1126. PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
  1127. CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
  1128. Ctx.getPointerType(Ctx.VoidPtrTy));
  1129. ++Idx;
  1130. }
  1131. }
  1132. llvm::Value *IfCondVal = nullptr;
  1133. if (IfCond)
  1134. IfCondVal = Bld.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.Int32Ty,
  1135. /* isSigned */ false);
  1136. else
  1137. IfCondVal = llvm::ConstantInt::get(CGF.Int32Ty, 1);
  1138. if (!NumThreadsVal)
  1139. NumThreadsVal = llvm::ConstantInt::get(CGF.Int32Ty, -1);
  1140. else
  1141. NumThreadsVal = Bld.CreateZExtOrTrunc(NumThreadsVal, CGF.Int32Ty),
  1142. assert(IfCondVal && "Expected a value");
  1143. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  1144. llvm::Value *Args[] = {
  1145. RTLoc,
  1146. getThreadID(CGF, Loc),
  1147. IfCondVal,
  1148. NumThreadsVal,
  1149. llvm::ConstantInt::get(CGF.Int32Ty, -1),
  1150. FnPtr,
  1151. ID,
  1152. Bld.CreateBitOrPointerCast(CapturedVarsAddrs.getPointer(),
  1153. CGF.VoidPtrPtrTy),
  1154. llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
  1155. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1156. CGM.getModule(), OMPRTL___kmpc_parallel_51),
  1157. Args);
  1158. };
  1159. RegionCodeGenTy RCG(ParallelGen);
  1160. RCG(CGF);
  1161. }
  1162. void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
  1163. // Always emit simple barriers!
  1164. if (!CGF.HaveInsertPoint())
  1165. return;
  1166. // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
  1167. // This function does not use parameters, so we can emit just default values.
  1168. llvm::Value *Args[] = {
  1169. llvm::ConstantPointerNull::get(
  1170. cast<llvm::PointerType>(getIdentTyPointerTy())),
  1171. llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
  1172. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1173. CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
  1174. Args);
  1175. }
  1176. void CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
  1177. SourceLocation Loc,
  1178. OpenMPDirectiveKind Kind, bool,
  1179. bool) {
  1180. // Always emit simple barriers!
  1181. if (!CGF.HaveInsertPoint())
  1182. return;
  1183. // Build call __kmpc_cancel_barrier(loc, thread_id);
  1184. unsigned Flags = getDefaultFlagsForBarriers(Kind);
  1185. llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
  1186. getThreadID(CGF, Loc)};
  1187. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1188. CGM.getModule(), OMPRTL___kmpc_barrier),
  1189. Args);
  1190. }
  1191. void CGOpenMPRuntimeGPU::emitCriticalRegion(
  1192. CodeGenFunction &CGF, StringRef CriticalName,
  1193. const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
  1194. const Expr *Hint) {
  1195. llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
  1196. llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
  1197. llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
  1198. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
  1199. llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
  1200. auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  1201. // Get the mask of active threads in the warp.
  1202. llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1203. CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
  1204. // Fetch team-local id of the thread.
  1205. llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
  1206. // Get the width of the team.
  1207. llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
  1208. // Initialize the counter variable for the loop.
  1209. QualType Int32Ty =
  1210. CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
  1211. Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
  1212. LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
  1213. CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
  1214. /*isInit=*/true);
  1215. // Block checks if loop counter exceeds upper bound.
  1216. CGF.EmitBlock(LoopBB);
  1217. llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
  1218. llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
  1219. CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
  1220. // Block tests which single thread should execute region, and which threads
  1221. // should go straight to synchronisation point.
  1222. CGF.EmitBlock(TestBB);
  1223. CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
  1224. llvm::Value *CmpThreadToCounter =
  1225. CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
  1226. CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
  1227. // Block emits the body of the critical region.
  1228. CGF.EmitBlock(BodyBB);
  1229. // Output the critical statement.
  1230. CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
  1231. Hint);
  1232. // After the body surrounded by the critical region, the single executing
  1233. // thread will jump to the synchronisation point.
  1234. // Block waits for all threads in current team to finish then increments the
  1235. // counter variable and returns to the loop.
  1236. CGF.EmitBlock(SyncBB);
  1237. // Reconverge active threads in the warp.
  1238. (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  1239. CGM.getModule(), OMPRTL___kmpc_syncwarp),
  1240. Mask);
  1241. llvm::Value *IncCounterVal =
  1242. CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
  1243. CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
  1244. CGF.EmitBranch(LoopBB);
  1245. // Block that is reached when all threads in the team complete the region.
  1246. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  1247. }
  1248. /// Cast value to the specified type.
  1249. static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
  1250. QualType ValTy, QualType CastTy,
  1251. SourceLocation Loc) {
  1252. assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
  1253. "Cast type must sized.");
  1254. assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
  1255. "Val type must sized.");
  1256. llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
  1257. if (ValTy == CastTy)
  1258. return Val;
  1259. if (CGF.getContext().getTypeSizeInChars(ValTy) ==
  1260. CGF.getContext().getTypeSizeInChars(CastTy))
  1261. return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
  1262. if (CastTy->isIntegerType() && ValTy->isIntegerType())
  1263. return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
  1264. CastTy->hasSignedIntegerRepresentation());
  1265. Address CastItem = CGF.CreateMemTemp(CastTy);
  1266. Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  1267. CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()),
  1268. Val->getType());
  1269. CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
  1270. LValueBaseInfo(AlignmentSource::Type),
  1271. TBAAAccessInfo());
  1272. return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
  1273. LValueBaseInfo(AlignmentSource::Type),
  1274. TBAAAccessInfo());
  1275. }
  1276. /// This function creates calls to one of two shuffle functions to copy
  1277. /// variables between lanes in a warp.
  1278. static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
  1279. llvm::Value *Elem,
  1280. QualType ElemType,
  1281. llvm::Value *Offset,
  1282. SourceLocation Loc) {
  1283. CodeGenModule &CGM = CGF.CGM;
  1284. CGBuilderTy &Bld = CGF.Builder;
  1285. CGOpenMPRuntimeGPU &RT =
  1286. *(static_cast<CGOpenMPRuntimeGPU *>(&CGM.getOpenMPRuntime()));
  1287. llvm::OpenMPIRBuilder &OMPBuilder = RT.getOMPBuilder();
  1288. CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
  1289. assert(Size.getQuantity() <= 8 &&
  1290. "Unsupported bitwidth in shuffle instruction.");
  1291. RuntimeFunction ShuffleFn = Size.getQuantity() <= 4
  1292. ? OMPRTL___kmpc_shuffle_int32
  1293. : OMPRTL___kmpc_shuffle_int64;
  1294. // Cast all types to 32- or 64-bit values before calling shuffle routines.
  1295. QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
  1296. Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
  1297. llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
  1298. llvm::Value *WarpSize =
  1299. Bld.CreateIntCast(RT.getGPUWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
  1300. llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
  1301. OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), ShuffleFn),
  1302. {ElemCast, Offset, WarpSize});
  1303. return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
  1304. }
  1305. static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
  1306. Address DestAddr, QualType ElemType,
  1307. llvm::Value *Offset, SourceLocation Loc) {
  1308. CGBuilderTy &Bld = CGF.Builder;
  1309. CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
  1310. // Create the loop over the big sized data.
  1311. // ptr = (void*)Elem;
  1312. // ptrEnd = (void*) Elem + 1;
  1313. // Step = 8;
  1314. // while (ptr + Step < ptrEnd)
  1315. // shuffle((int64_t)*ptr);
  1316. // Step = 4;
  1317. // while (ptr + Step < ptrEnd)
  1318. // shuffle((int32_t)*ptr);
  1319. // ...
  1320. Address ElemPtr = DestAddr;
  1321. Address Ptr = SrcAddr;
  1322. Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
  1323. Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy, CGF.Int8Ty);
  1324. for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
  1325. if (Size < CharUnits::fromQuantity(IntSize))
  1326. continue;
  1327. QualType IntType = CGF.getContext().getIntTypeForBitwidth(
  1328. CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
  1329. /*Signed=*/1);
  1330. llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
  1331. Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo(),
  1332. IntTy);
  1333. ElemPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  1334. ElemPtr, IntTy->getPointerTo(), IntTy);
  1335. if (Size.getQuantity() / IntSize > 1) {
  1336. llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
  1337. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
  1338. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
  1339. llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
  1340. CGF.EmitBlock(PreCondBB);
  1341. llvm::PHINode *PhiSrc =
  1342. Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
  1343. PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
  1344. llvm::PHINode *PhiDest =
  1345. Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
  1346. PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
  1347. Ptr = Address(PhiSrc, Ptr.getElementType(), Ptr.getAlignment());
  1348. ElemPtr =
  1349. Address(PhiDest, ElemPtr.getElementType(), ElemPtr.getAlignment());
  1350. llvm::Value *PtrDiff = Bld.CreatePtrDiff(
  1351. CGF.Int8Ty, PtrEnd.getPointer(),
  1352. Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr.getPointer(),
  1353. CGF.VoidPtrTy));
  1354. Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
  1355. ThenBB, ExitBB);
  1356. CGF.EmitBlock(ThenBB);
  1357. llvm::Value *Res = createRuntimeShuffleFunction(
  1358. CGF,
  1359. CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
  1360. LValueBaseInfo(AlignmentSource::Type),
  1361. TBAAAccessInfo()),
  1362. IntType, Offset, Loc);
  1363. CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
  1364. LValueBaseInfo(AlignmentSource::Type),
  1365. TBAAAccessInfo());
  1366. Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
  1367. Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
  1368. PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
  1369. PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
  1370. CGF.EmitBranch(PreCondBB);
  1371. CGF.EmitBlock(ExitBB);
  1372. } else {
  1373. llvm::Value *Res = createRuntimeShuffleFunction(
  1374. CGF,
  1375. CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
  1376. LValueBaseInfo(AlignmentSource::Type),
  1377. TBAAAccessInfo()),
  1378. IntType, Offset, Loc);
  1379. CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
  1380. LValueBaseInfo(AlignmentSource::Type),
  1381. TBAAAccessInfo());
  1382. Ptr = Bld.CreateConstGEP(Ptr, 1);
  1383. ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
  1384. }
  1385. Size = Size % IntSize;
  1386. }
  1387. }
  1388. namespace {
  1389. enum CopyAction : unsigned {
  1390. // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
  1391. // the warp using shuffle instructions.
  1392. RemoteLaneToThread,
  1393. // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
  1394. ThreadCopy,
  1395. // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
  1396. ThreadToScratchpad,
  1397. // ScratchpadToThread: Copy from a scratchpad array in global memory
  1398. // containing team-reduced data to a thread's stack.
  1399. ScratchpadToThread,
  1400. };
  1401. } // namespace
  1402. struct CopyOptionsTy {
  1403. llvm::Value *RemoteLaneOffset;
  1404. llvm::Value *ScratchpadIndex;
  1405. llvm::Value *ScratchpadWidth;
  1406. };
  1407. /// Emit instructions to copy a Reduce list, which contains partially
  1408. /// aggregated values, in the specified direction.
  1409. static void emitReductionListCopy(
  1410. CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
  1411. ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
  1412. CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
  1413. CodeGenModule &CGM = CGF.CGM;
  1414. ASTContext &C = CGM.getContext();
  1415. CGBuilderTy &Bld = CGF.Builder;
  1416. llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
  1417. llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
  1418. llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
  1419. // Iterates, element-by-element, through the source Reduce list and
  1420. // make a copy.
  1421. unsigned Idx = 0;
  1422. unsigned Size = Privates.size();
  1423. for (const Expr *Private : Privates) {
  1424. Address SrcElementAddr = Address::invalid();
  1425. Address DestElementAddr = Address::invalid();
  1426. Address DestElementPtrAddr = Address::invalid();
  1427. // Should we shuffle in an element from a remote lane?
  1428. bool ShuffleInElement = false;
  1429. // Set to true to update the pointer in the dest Reduce list to a
  1430. // newly created element.
  1431. bool UpdateDestListPtr = false;
  1432. // Increment the src or dest pointer to the scratchpad, for each
  1433. // new element.
  1434. bool IncrScratchpadSrc = false;
  1435. bool IncrScratchpadDest = false;
  1436. QualType PrivatePtrType = C.getPointerType(Private->getType());
  1437. llvm::Type *PrivateLlvmPtrType = CGF.ConvertType(PrivatePtrType);
  1438. switch (Action) {
  1439. case RemoteLaneToThread: {
  1440. // Step 1.1: Get the address for the src element in the Reduce list.
  1441. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  1442. SrcElementAddr =
  1443. CGF.EmitLoadOfPointer(CGF.Builder.CreateElementBitCast(
  1444. SrcElementPtrAddr, PrivateLlvmPtrType),
  1445. PrivatePtrType->castAs<PointerType>());
  1446. // Step 1.2: Create a temporary to store the element in the destination
  1447. // Reduce list.
  1448. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  1449. DestElementAddr =
  1450. CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
  1451. ShuffleInElement = true;
  1452. UpdateDestListPtr = true;
  1453. break;
  1454. }
  1455. case ThreadCopy: {
  1456. // Step 1.1: Get the address for the src element in the Reduce list.
  1457. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  1458. SrcElementAddr =
  1459. CGF.EmitLoadOfPointer(CGF.Builder.CreateElementBitCast(
  1460. SrcElementPtrAddr, PrivateLlvmPtrType),
  1461. PrivatePtrType->castAs<PointerType>());
  1462. // Step 1.2: Get the address for dest element. The destination
  1463. // element has already been created on the thread's stack.
  1464. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  1465. DestElementAddr =
  1466. CGF.EmitLoadOfPointer(CGF.Builder.CreateElementBitCast(
  1467. DestElementPtrAddr, PrivateLlvmPtrType),
  1468. PrivatePtrType->castAs<PointerType>());
  1469. break;
  1470. }
  1471. case ThreadToScratchpad: {
  1472. // Step 1.1: Get the address for the src element in the Reduce list.
  1473. Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
  1474. SrcElementAddr =
  1475. CGF.EmitLoadOfPointer(CGF.Builder.CreateElementBitCast(
  1476. SrcElementPtrAddr, PrivateLlvmPtrType),
  1477. PrivatePtrType->castAs<PointerType>());
  1478. // Step 1.2: Get the address for dest element:
  1479. // address = base + index * ElementSizeInChars.
  1480. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  1481. llvm::Value *CurrentOffset =
  1482. Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
  1483. llvm::Value *ScratchPadElemAbsolutePtrVal =
  1484. Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
  1485. ScratchPadElemAbsolutePtrVal =
  1486. Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
  1487. DestElementAddr = Address(ScratchPadElemAbsolutePtrVal, CGF.Int8Ty,
  1488. C.getTypeAlignInChars(Private->getType()));
  1489. IncrScratchpadDest = true;
  1490. break;
  1491. }
  1492. case ScratchpadToThread: {
  1493. // Step 1.1: Get the address for the src element in the scratchpad.
  1494. // address = base + index * ElementSizeInChars.
  1495. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  1496. llvm::Value *CurrentOffset =
  1497. Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
  1498. llvm::Value *ScratchPadElemAbsolutePtrVal =
  1499. Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
  1500. ScratchPadElemAbsolutePtrVal =
  1501. Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
  1502. SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal, CGF.Int8Ty,
  1503. C.getTypeAlignInChars(Private->getType()));
  1504. IncrScratchpadSrc = true;
  1505. // Step 1.2: Create a temporary to store the element in the destination
  1506. // Reduce list.
  1507. DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
  1508. DestElementAddr =
  1509. CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
  1510. UpdateDestListPtr = true;
  1511. break;
  1512. }
  1513. }
  1514. // Regardless of src and dest of copy, we emit the load of src
  1515. // element as this is required in all directions
  1516. SrcElementAddr = Bld.CreateElementBitCast(
  1517. SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
  1518. DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
  1519. SrcElementAddr.getElementType());
  1520. // Now that all active lanes have read the element in the
  1521. // Reduce list, shuffle over the value from the remote lane.
  1522. if (ShuffleInElement) {
  1523. shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
  1524. RemoteLaneOffset, Private->getExprLoc());
  1525. } else {
  1526. switch (CGF.getEvaluationKind(Private->getType())) {
  1527. case TEK_Scalar: {
  1528. llvm::Value *Elem = CGF.EmitLoadOfScalar(
  1529. SrcElementAddr, /*Volatile=*/false, Private->getType(),
  1530. Private->getExprLoc(), LValueBaseInfo(AlignmentSource::Type),
  1531. TBAAAccessInfo());
  1532. // Store the source element value to the dest element address.
  1533. CGF.EmitStoreOfScalar(
  1534. Elem, DestElementAddr, /*Volatile=*/false, Private->getType(),
  1535. LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
  1536. break;
  1537. }
  1538. case TEK_Complex: {
  1539. CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
  1540. CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
  1541. Private->getExprLoc());
  1542. CGF.EmitStoreOfComplex(
  1543. Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
  1544. /*isInit=*/false);
  1545. break;
  1546. }
  1547. case TEK_Aggregate:
  1548. CGF.EmitAggregateCopy(
  1549. CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
  1550. CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
  1551. Private->getType(), AggValueSlot::DoesNotOverlap);
  1552. break;
  1553. }
  1554. }
  1555. // Step 3.1: Modify reference in dest Reduce list as needed.
  1556. // Modifying the reference in Reduce list to point to the newly
  1557. // created element. The element is live in the current function
  1558. // scope and that of functions it invokes (i.e., reduce_function).
  1559. // RemoteReduceData[i] = (void*)&RemoteElem
  1560. if (UpdateDestListPtr) {
  1561. CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
  1562. DestElementAddr.getPointer(), CGF.VoidPtrTy),
  1563. DestElementPtrAddr, /*Volatile=*/false,
  1564. C.VoidPtrTy);
  1565. }
  1566. // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
  1567. // address of the next element in scratchpad memory, unless we're currently
  1568. // processing the last one. Memory alignment is also taken care of here.
  1569. if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
  1570. // FIXME: This code doesn't make any sense, it's trying to perform
  1571. // integer arithmetic on pointers.
  1572. llvm::Value *ScratchpadBasePtr =
  1573. IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
  1574. llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
  1575. ScratchpadBasePtr = Bld.CreateNUWAdd(
  1576. ScratchpadBasePtr,
  1577. Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
  1578. // Take care of global memory alignment for performance
  1579. ScratchpadBasePtr = Bld.CreateNUWSub(
  1580. ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
  1581. ScratchpadBasePtr = Bld.CreateUDiv(
  1582. ScratchpadBasePtr,
  1583. llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
  1584. ScratchpadBasePtr = Bld.CreateNUWAdd(
  1585. ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
  1586. ScratchpadBasePtr = Bld.CreateNUWMul(
  1587. ScratchpadBasePtr,
  1588. llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
  1589. if (IncrScratchpadDest)
  1590. DestBase =
  1591. Address(ScratchpadBasePtr, CGF.VoidPtrTy, CGF.getPointerAlign());
  1592. else /* IncrScratchpadSrc = true */
  1593. SrcBase =
  1594. Address(ScratchpadBasePtr, CGF.VoidPtrTy, CGF.getPointerAlign());
  1595. }
  1596. ++Idx;
  1597. }
  1598. }
  1599. /// This function emits a helper that gathers Reduce lists from the first
  1600. /// lane of every active warp to lanes in the first warp.
  1601. ///
  1602. /// void inter_warp_copy_func(void* reduce_data, num_warps)
  1603. /// shared smem[warp_size];
  1604. /// For all data entries D in reduce_data:
  1605. /// sync
  1606. /// If (I am the first lane in each warp)
  1607. /// Copy my local D to smem[warp_id]
  1608. /// sync
  1609. /// if (I am the first warp)
  1610. /// Copy smem[thread_id] to my local D
  1611. static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
  1612. ArrayRef<const Expr *> Privates,
  1613. QualType ReductionArrayTy,
  1614. SourceLocation Loc) {
  1615. ASTContext &C = CGM.getContext();
  1616. llvm::Module &M = CGM.getModule();
  1617. // ReduceList: thread local Reduce list.
  1618. // At the stage of the computation when this function is called, partially
  1619. // aggregated values reside in the first lane of every active warp.
  1620. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1621. C.VoidPtrTy, ImplicitParamDecl::Other);
  1622. // NumWarps: number of warps active in the parallel region. This could
  1623. // be smaller than 32 (max warps in a CTA) for partial block reduction.
  1624. ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1625. C.getIntTypeForBitwidth(32, /* Signed */ true),
  1626. ImplicitParamDecl::Other);
  1627. FunctionArgList Args;
  1628. Args.push_back(&ReduceListArg);
  1629. Args.push_back(&NumWarpsArg);
  1630. const CGFunctionInfo &CGFI =
  1631. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  1632. auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
  1633. llvm::GlobalValue::InternalLinkage,
  1634. "_omp_reduction_inter_warp_copy_func", &M);
  1635. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  1636. Fn->setDoesNotRecurse();
  1637. CodeGenFunction CGF(CGM);
  1638. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  1639. CGBuilderTy &Bld = CGF.Builder;
  1640. // This array is used as a medium to transfer, one reduce element at a time,
  1641. // the data from the first lane of every warp to lanes in the first warp
  1642. // in order to perform the final step of a reduction in a parallel region
  1643. // (reduction across warps). The array is placed in NVPTX __shared__ memory
  1644. // for reduced latency, as well as to have a distinct copy for concurrently
  1645. // executing target regions. The array is declared with common linkage so
  1646. // as to be shared across compilation units.
  1647. StringRef TransferMediumName =
  1648. "__openmp_nvptx_data_transfer_temporary_storage";
  1649. llvm::GlobalVariable *TransferMedium =
  1650. M.getGlobalVariable(TransferMediumName);
  1651. unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
  1652. if (!TransferMedium) {
  1653. auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
  1654. unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
  1655. TransferMedium = new llvm::GlobalVariable(
  1656. M, Ty, /*isConstant=*/false, llvm::GlobalVariable::WeakAnyLinkage,
  1657. llvm::UndefValue::get(Ty), TransferMediumName,
  1658. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  1659. SharedAddressSpace);
  1660. CGM.addCompilerUsedGlobal(TransferMedium);
  1661. }
  1662. auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  1663. // Get the CUDA thread id of the current OpenMP thread on the GPU.
  1664. llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
  1665. // nvptx_lane_id = nvptx_id % warpsize
  1666. llvm::Value *LaneID = getNVPTXLaneID(CGF);
  1667. // nvptx_warp_id = nvptx_id / warpsize
  1668. llvm::Value *WarpID = getNVPTXWarpID(CGF);
  1669. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  1670. llvm::Type *ElemTy = CGF.ConvertTypeForMem(ReductionArrayTy);
  1671. Address LocalReduceList(
  1672. Bld.CreatePointerBitCastOrAddrSpaceCast(
  1673. CGF.EmitLoadOfScalar(
  1674. AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc,
  1675. LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo()),
  1676. ElemTy->getPointerTo()),
  1677. ElemTy, CGF.getPointerAlign());
  1678. unsigned Idx = 0;
  1679. for (const Expr *Private : Privates) {
  1680. //
  1681. // Warp master copies reduce element to transfer medium in __shared__
  1682. // memory.
  1683. //
  1684. unsigned RealTySize =
  1685. C.getTypeSizeInChars(Private->getType())
  1686. .alignTo(C.getTypeAlignInChars(Private->getType()))
  1687. .getQuantity();
  1688. for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
  1689. unsigned NumIters = RealTySize / TySize;
  1690. if (NumIters == 0)
  1691. continue;
  1692. QualType CType = C.getIntTypeForBitwidth(
  1693. C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
  1694. llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
  1695. CharUnits Align = CharUnits::fromQuantity(TySize);
  1696. llvm::Value *Cnt = nullptr;
  1697. Address CntAddr = Address::invalid();
  1698. llvm::BasicBlock *PrecondBB = nullptr;
  1699. llvm::BasicBlock *ExitBB = nullptr;
  1700. if (NumIters > 1) {
  1701. CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
  1702. CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
  1703. /*Volatile=*/false, C.IntTy);
  1704. PrecondBB = CGF.createBasicBlock("precond");
  1705. ExitBB = CGF.createBasicBlock("exit");
  1706. llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
  1707. // There is no need to emit line number for unconditional branch.
  1708. (void)ApplyDebugLocation::CreateEmpty(CGF);
  1709. CGF.EmitBlock(PrecondBB);
  1710. Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
  1711. llvm::Value *Cmp =
  1712. Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
  1713. Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
  1714. CGF.EmitBlock(BodyBB);
  1715. }
  1716. // kmpc_barrier.
  1717. CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
  1718. /*EmitChecks=*/false,
  1719. /*ForceSimpleCall=*/true);
  1720. llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
  1721. llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
  1722. llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
  1723. // if (lane_id == 0)
  1724. llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
  1725. Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
  1726. CGF.EmitBlock(ThenBB);
  1727. // Reduce element = LocalReduceList[i]
  1728. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  1729. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  1730. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  1731. // elemptr = ((CopyType*)(elemptrptr)) + I
  1732. Address ElemPtr(ElemPtrPtr, CGF.Int8Ty, Align);
  1733. ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
  1734. if (NumIters > 1)
  1735. ElemPtr = Bld.CreateGEP(ElemPtr, Cnt);
  1736. // Get pointer to location in transfer medium.
  1737. // MediumPtr = &medium[warp_id]
  1738. llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
  1739. TransferMedium->getValueType(), TransferMedium,
  1740. {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
  1741. // Casting to actual data type.
  1742. // MediumPtr = (CopyType*)MediumPtrAddr;
  1743. Address MediumPtr(
  1744. Bld.CreateBitCast(
  1745. MediumPtrVal,
  1746. CopyType->getPointerTo(
  1747. MediumPtrVal->getType()->getPointerAddressSpace())),
  1748. CopyType, Align);
  1749. // elem = *elemptr
  1750. //*MediumPtr = elem
  1751. llvm::Value *Elem = CGF.EmitLoadOfScalar(
  1752. ElemPtr, /*Volatile=*/false, CType, Loc,
  1753. LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
  1754. // Store the source element value to the dest element address.
  1755. CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType,
  1756. LValueBaseInfo(AlignmentSource::Type),
  1757. TBAAAccessInfo());
  1758. Bld.CreateBr(MergeBB);
  1759. CGF.EmitBlock(ElseBB);
  1760. Bld.CreateBr(MergeBB);
  1761. CGF.EmitBlock(MergeBB);
  1762. // kmpc_barrier.
  1763. CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
  1764. /*EmitChecks=*/false,
  1765. /*ForceSimpleCall=*/true);
  1766. //
  1767. // Warp 0 copies reduce element from transfer medium.
  1768. //
  1769. llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
  1770. llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
  1771. llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
  1772. Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
  1773. llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
  1774. AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
  1775. // Up to 32 threads in warp 0 are active.
  1776. llvm::Value *IsActiveThread =
  1777. Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
  1778. Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
  1779. CGF.EmitBlock(W0ThenBB);
  1780. // SrcMediumPtr = &medium[tid]
  1781. llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
  1782. TransferMedium->getValueType(), TransferMedium,
  1783. {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
  1784. // SrcMediumVal = *SrcMediumPtr;
  1785. Address SrcMediumPtr(
  1786. Bld.CreateBitCast(
  1787. SrcMediumPtrVal,
  1788. CopyType->getPointerTo(
  1789. SrcMediumPtrVal->getType()->getPointerAddressSpace())),
  1790. CopyType, Align);
  1791. // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
  1792. Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  1793. llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
  1794. TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
  1795. Address TargetElemPtr(TargetElemPtrVal, CGF.Int8Ty, Align);
  1796. TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
  1797. if (NumIters > 1)
  1798. TargetElemPtr = Bld.CreateGEP(TargetElemPtr, Cnt);
  1799. // *TargetElemPtr = SrcMediumVal;
  1800. llvm::Value *SrcMediumValue =
  1801. CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
  1802. CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
  1803. CType);
  1804. Bld.CreateBr(W0MergeBB);
  1805. CGF.EmitBlock(W0ElseBB);
  1806. Bld.CreateBr(W0MergeBB);
  1807. CGF.EmitBlock(W0MergeBB);
  1808. if (NumIters > 1) {
  1809. Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
  1810. CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
  1811. CGF.EmitBranch(PrecondBB);
  1812. (void)ApplyDebugLocation::CreateEmpty(CGF);
  1813. CGF.EmitBlock(ExitBB);
  1814. }
  1815. RealTySize %= TySize;
  1816. }
  1817. ++Idx;
  1818. }
  1819. CGF.FinishFunction();
  1820. return Fn;
  1821. }
  1822. /// Emit a helper that reduces data across two OpenMP threads (lanes)
  1823. /// in the same warp. It uses shuffle instructions to copy over data from
  1824. /// a remote lane's stack. The reduction algorithm performed is specified
  1825. /// by the fourth parameter.
  1826. ///
  1827. /// Algorithm Versions.
  1828. /// Full Warp Reduce (argument value 0):
  1829. /// This algorithm assumes that all 32 lanes are active and gathers
  1830. /// data from these 32 lanes, producing a single resultant value.
  1831. /// Contiguous Partial Warp Reduce (argument value 1):
  1832. /// This algorithm assumes that only a *contiguous* subset of lanes
  1833. /// are active. This happens for the last warp in a parallel region
  1834. /// when the user specified num_threads is not an integer multiple of
  1835. /// 32. This contiguous subset always starts with the zeroth lane.
  1836. /// Partial Warp Reduce (argument value 2):
  1837. /// This algorithm gathers data from any number of lanes at any position.
  1838. /// All reduced values are stored in the lowest possible lane. The set
  1839. /// of problems every algorithm addresses is a super set of those
  1840. /// addressable by algorithms with a lower version number. Overhead
  1841. /// increases as algorithm version increases.
  1842. ///
  1843. /// Terminology
  1844. /// Reduce element:
  1845. /// Reduce element refers to the individual data field with primitive
  1846. /// data types to be combined and reduced across threads.
  1847. /// Reduce list:
  1848. /// Reduce list refers to a collection of local, thread-private
  1849. /// reduce elements.
  1850. /// Remote Reduce list:
  1851. /// Remote Reduce list refers to a collection of remote (relative to
  1852. /// the current thread) reduce elements.
  1853. ///
  1854. /// We distinguish between three states of threads that are important to
  1855. /// the implementation of this function.
  1856. /// Alive threads:
  1857. /// Threads in a warp executing the SIMT instruction, as distinguished from
  1858. /// threads that are inactive due to divergent control flow.
  1859. /// Active threads:
  1860. /// The minimal set of threads that has to be alive upon entry to this
  1861. /// function. The computation is correct iff active threads are alive.
  1862. /// Some threads are alive but they are not active because they do not
  1863. /// contribute to the computation in any useful manner. Turning them off
  1864. /// may introduce control flow overheads without any tangible benefits.
  1865. /// Effective threads:
  1866. /// In order to comply with the argument requirements of the shuffle
  1867. /// function, we must keep all lanes holding data alive. But at most
  1868. /// half of them perform value aggregation; we refer to this half of
  1869. /// threads as effective. The other half is simply handing off their
  1870. /// data.
  1871. ///
  1872. /// Procedure
  1873. /// Value shuffle:
  1874. /// In this step active threads transfer data from higher lane positions
  1875. /// in the warp to lower lane positions, creating Remote Reduce list.
  1876. /// Value aggregation:
  1877. /// In this step, effective threads combine their thread local Reduce list
  1878. /// with Remote Reduce list and store the result in the thread local
  1879. /// Reduce list.
  1880. /// Value copy:
  1881. /// In this step, we deal with the assumption made by algorithm 2
  1882. /// (i.e. contiguity assumption). When we have an odd number of lanes
  1883. /// active, say 2k+1, only k threads will be effective and therefore k
  1884. /// new values will be produced. However, the Reduce list owned by the
  1885. /// (2k+1)th thread is ignored in the value aggregation. Therefore
  1886. /// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
  1887. /// that the contiguity assumption still holds.
  1888. static llvm::Function *emitShuffleAndReduceFunction(
  1889. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  1890. QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
  1891. ASTContext &C = CGM.getContext();
  1892. // Thread local Reduce list used to host the values of data to be reduced.
  1893. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1894. C.VoidPtrTy, ImplicitParamDecl::Other);
  1895. // Current lane id; could be logical.
  1896. ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
  1897. ImplicitParamDecl::Other);
  1898. // Offset of the remote source lane relative to the current lane.
  1899. ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1900. C.ShortTy, ImplicitParamDecl::Other);
  1901. // Algorithm version. This is expected to be known at compile time.
  1902. ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  1903. C.ShortTy, ImplicitParamDecl::Other);
  1904. FunctionArgList Args;
  1905. Args.push_back(&ReduceListArg);
  1906. Args.push_back(&LaneIDArg);
  1907. Args.push_back(&RemoteLaneOffsetArg);
  1908. Args.push_back(&AlgoVerArg);
  1909. const CGFunctionInfo &CGFI =
  1910. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  1911. auto *Fn = llvm::Function::Create(
  1912. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  1913. "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
  1914. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  1915. Fn->setDoesNotRecurse();
  1916. CodeGenFunction CGF(CGM);
  1917. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  1918. CGBuilderTy &Bld = CGF.Builder;
  1919. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  1920. llvm::Type *ElemTy = CGF.ConvertTypeForMem(ReductionArrayTy);
  1921. Address LocalReduceList(
  1922. Bld.CreatePointerBitCastOrAddrSpaceCast(
  1923. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  1924. C.VoidPtrTy, SourceLocation()),
  1925. ElemTy->getPointerTo()),
  1926. ElemTy, CGF.getPointerAlign());
  1927. Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
  1928. llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
  1929. AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  1930. Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
  1931. llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
  1932. AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  1933. Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
  1934. llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
  1935. AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
  1936. // Create a local thread-private variable to host the Reduce list
  1937. // from a remote lane.
  1938. Address RemoteReduceList =
  1939. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
  1940. // This loop iterates through the list of reduce elements and copies,
  1941. // element by element, from a remote lane in the warp to RemoteReduceList,
  1942. // hosted on the thread's stack.
  1943. emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
  1944. LocalReduceList, RemoteReduceList,
  1945. {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
  1946. /*ScratchpadIndex=*/nullptr,
  1947. /*ScratchpadWidth=*/nullptr});
  1948. // The actions to be performed on the Remote Reduce list is dependent
  1949. // on the algorithm version.
  1950. //
  1951. // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
  1952. // LaneId % 2 == 0 && Offset > 0):
  1953. // do the reduction value aggregation
  1954. //
  1955. // The thread local variable Reduce list is mutated in place to host the
  1956. // reduced data, which is the aggregated value produced from local and
  1957. // remote lanes.
  1958. //
  1959. // Note that AlgoVer is expected to be a constant integer known at compile
  1960. // time.
  1961. // When AlgoVer==0, the first conjunction evaluates to true, making
  1962. // the entire predicate true during compile time.
  1963. // When AlgoVer==1, the second conjunction has only the second part to be
  1964. // evaluated during runtime. Other conjunctions evaluates to false
  1965. // during compile time.
  1966. // When AlgoVer==2, the third conjunction has only the second part to be
  1967. // evaluated during runtime. Other conjunctions evaluates to false
  1968. // during compile time.
  1969. llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
  1970. llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
  1971. llvm::Value *CondAlgo1 = Bld.CreateAnd(
  1972. Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
  1973. llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
  1974. llvm::Value *CondAlgo2 = Bld.CreateAnd(
  1975. Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
  1976. CondAlgo2 = Bld.CreateAnd(
  1977. CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
  1978. llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
  1979. CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
  1980. llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
  1981. llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
  1982. llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
  1983. Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
  1984. CGF.EmitBlock(ThenBB);
  1985. // reduce_function(LocalReduceList, RemoteReduceList)
  1986. llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  1987. LocalReduceList.getPointer(), CGF.VoidPtrTy);
  1988. llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  1989. RemoteReduceList.getPointer(), CGF.VoidPtrTy);
  1990. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  1991. CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
  1992. Bld.CreateBr(MergeBB);
  1993. CGF.EmitBlock(ElseBB);
  1994. Bld.CreateBr(MergeBB);
  1995. CGF.EmitBlock(MergeBB);
  1996. // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
  1997. // Reduce list.
  1998. Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
  1999. llvm::Value *CondCopy = Bld.CreateAnd(
  2000. Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
  2001. llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
  2002. llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
  2003. llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
  2004. Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
  2005. CGF.EmitBlock(CpyThenBB);
  2006. emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
  2007. RemoteReduceList, LocalReduceList);
  2008. Bld.CreateBr(CpyMergeBB);
  2009. CGF.EmitBlock(CpyElseBB);
  2010. Bld.CreateBr(CpyMergeBB);
  2011. CGF.EmitBlock(CpyMergeBB);
  2012. CGF.FinishFunction();
  2013. return Fn;
  2014. }
  2015. /// This function emits a helper that copies all the reduction variables from
  2016. /// the team into the provided global buffer for the reduction variables.
  2017. ///
  2018. /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
  2019. /// For all data entries D in reduce_data:
  2020. /// Copy local D to buffer.D[Idx]
  2021. static llvm::Value *emitListToGlobalCopyFunction(
  2022. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  2023. QualType ReductionArrayTy, SourceLocation Loc,
  2024. const RecordDecl *TeamReductionRec,
  2025. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  2026. &VarFieldMap) {
  2027. ASTContext &C = CGM.getContext();
  2028. // Buffer: global reduction buffer.
  2029. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2030. C.VoidPtrTy, ImplicitParamDecl::Other);
  2031. // Idx: index of the buffer.
  2032. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  2033. ImplicitParamDecl::Other);
  2034. // ReduceList: thread local Reduce list.
  2035. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2036. C.VoidPtrTy, ImplicitParamDecl::Other);
  2037. FunctionArgList Args;
  2038. Args.push_back(&BufferArg);
  2039. Args.push_back(&IdxArg);
  2040. Args.push_back(&ReduceListArg);
  2041. const CGFunctionInfo &CGFI =
  2042. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2043. auto *Fn = llvm::Function::Create(
  2044. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2045. "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
  2046. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2047. Fn->setDoesNotRecurse();
  2048. CodeGenFunction CGF(CGM);
  2049. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2050. CGBuilderTy &Bld = CGF.Builder;
  2051. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  2052. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  2053. llvm::Type *ElemTy = CGF.ConvertTypeForMem(ReductionArrayTy);
  2054. Address LocalReduceList(
  2055. Bld.CreatePointerBitCastOrAddrSpaceCast(
  2056. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  2057. C.VoidPtrTy, Loc),
  2058. ElemTy->getPointerTo()),
  2059. ElemTy, CGF.getPointerAlign());
  2060. QualType StaticTy = C.getRecordType(TeamReductionRec);
  2061. llvm::Type *LLVMReductionsBufferTy =
  2062. CGM.getTypes().ConvertTypeForMem(StaticTy);
  2063. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2064. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  2065. LLVMReductionsBufferTy->getPointerTo());
  2066. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  2067. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  2068. /*Volatile=*/false, C.IntTy,
  2069. Loc)};
  2070. unsigned Idx = 0;
  2071. for (const Expr *Private : Privates) {
  2072. // Reduce element = LocalReduceList[i]
  2073. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  2074. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  2075. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  2076. // elemptr = ((CopyType*)(elemptrptr)) + I
  2077. ElemTy = CGF.ConvertTypeForMem(Private->getType());
  2078. ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2079. ElemPtrPtr, ElemTy->getPointerTo());
  2080. Address ElemPtr =
  2081. Address(ElemPtrPtr, ElemTy, C.getTypeAlignInChars(Private->getType()));
  2082. const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
  2083. // Global = Buffer.VD[Idx];
  2084. const FieldDecl *FD = VarFieldMap.lookup(VD);
  2085. LValue GlobLVal = CGF.EmitLValueForField(
  2086. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  2087. Address GlobAddr = GlobLVal.getAddress(CGF);
  2088. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobAddr.getElementType(),
  2089. GlobAddr.getPointer(), Idxs);
  2090. GlobLVal.setAddress(Address(BufferPtr,
  2091. CGF.ConvertTypeForMem(Private->getType()),
  2092. GlobAddr.getAlignment()));
  2093. switch (CGF.getEvaluationKind(Private->getType())) {
  2094. case TEK_Scalar: {
  2095. llvm::Value *V = CGF.EmitLoadOfScalar(
  2096. ElemPtr, /*Volatile=*/false, Private->getType(), Loc,
  2097. LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
  2098. CGF.EmitStoreOfScalar(V, GlobLVal);
  2099. break;
  2100. }
  2101. case TEK_Complex: {
  2102. CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
  2103. CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
  2104. CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
  2105. break;
  2106. }
  2107. case TEK_Aggregate:
  2108. CGF.EmitAggregateCopy(GlobLVal,
  2109. CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  2110. Private->getType(), AggValueSlot::DoesNotOverlap);
  2111. break;
  2112. }
  2113. ++Idx;
  2114. }
  2115. CGF.FinishFunction();
  2116. return Fn;
  2117. }
  2118. /// This function emits a helper that reduces all the reduction variables from
  2119. /// the team into the provided global buffer for the reduction variables.
  2120. ///
  2121. /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
  2122. /// void *GlobPtrs[];
  2123. /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
  2124. /// ...
  2125. /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
  2126. /// reduce_function(GlobPtrs, reduce_data);
  2127. static llvm::Value *emitListToGlobalReduceFunction(
  2128. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  2129. QualType ReductionArrayTy, SourceLocation Loc,
  2130. const RecordDecl *TeamReductionRec,
  2131. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  2132. &VarFieldMap,
  2133. llvm::Function *ReduceFn) {
  2134. ASTContext &C = CGM.getContext();
  2135. // Buffer: global reduction buffer.
  2136. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2137. C.VoidPtrTy, ImplicitParamDecl::Other);
  2138. // Idx: index of the buffer.
  2139. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  2140. ImplicitParamDecl::Other);
  2141. // ReduceList: thread local Reduce list.
  2142. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2143. C.VoidPtrTy, ImplicitParamDecl::Other);
  2144. FunctionArgList Args;
  2145. Args.push_back(&BufferArg);
  2146. Args.push_back(&IdxArg);
  2147. Args.push_back(&ReduceListArg);
  2148. const CGFunctionInfo &CGFI =
  2149. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2150. auto *Fn = llvm::Function::Create(
  2151. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2152. "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
  2153. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2154. Fn->setDoesNotRecurse();
  2155. CodeGenFunction CGF(CGM);
  2156. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2157. CGBuilderTy &Bld = CGF.Builder;
  2158. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  2159. QualType StaticTy = C.getRecordType(TeamReductionRec);
  2160. llvm::Type *LLVMReductionsBufferTy =
  2161. CGM.getTypes().ConvertTypeForMem(StaticTy);
  2162. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2163. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  2164. LLVMReductionsBufferTy->getPointerTo());
  2165. // 1. Build a list of reduction variables.
  2166. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  2167. Address ReductionList =
  2168. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  2169. auto IPriv = Privates.begin();
  2170. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  2171. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  2172. /*Volatile=*/false, C.IntTy,
  2173. Loc)};
  2174. unsigned Idx = 0;
  2175. for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
  2176. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2177. // Global = Buffer.VD[Idx];
  2178. const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
  2179. const FieldDecl *FD = VarFieldMap.lookup(VD);
  2180. LValue GlobLVal = CGF.EmitLValueForField(
  2181. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  2182. Address GlobAddr = GlobLVal.getAddress(CGF);
  2183. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
  2184. GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
  2185. llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
  2186. CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
  2187. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  2188. // Store array size.
  2189. ++Idx;
  2190. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2191. llvm::Value *Size = CGF.Builder.CreateIntCast(
  2192. CGF.getVLASize(
  2193. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  2194. .NumElts,
  2195. CGF.SizeTy, /*isSigned=*/false);
  2196. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  2197. Elem);
  2198. }
  2199. }
  2200. // Call reduce_function(GlobalReduceList, ReduceList)
  2201. llvm::Value *GlobalReduceList =
  2202. CGF.EmitCastToVoidPtr(ReductionList.getPointer());
  2203. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  2204. llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
  2205. AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
  2206. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  2207. CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
  2208. CGF.FinishFunction();
  2209. return Fn;
  2210. }
  2211. /// This function emits a helper that copies all the reduction variables from
  2212. /// the team into the provided global buffer for the reduction variables.
  2213. ///
  2214. /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
  2215. /// For all data entries D in reduce_data:
  2216. /// Copy buffer.D[Idx] to local D;
  2217. static llvm::Value *emitGlobalToListCopyFunction(
  2218. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  2219. QualType ReductionArrayTy, SourceLocation Loc,
  2220. const RecordDecl *TeamReductionRec,
  2221. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  2222. &VarFieldMap) {
  2223. ASTContext &C = CGM.getContext();
  2224. // Buffer: global reduction buffer.
  2225. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2226. C.VoidPtrTy, ImplicitParamDecl::Other);
  2227. // Idx: index of the buffer.
  2228. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  2229. ImplicitParamDecl::Other);
  2230. // ReduceList: thread local Reduce list.
  2231. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2232. C.VoidPtrTy, ImplicitParamDecl::Other);
  2233. FunctionArgList Args;
  2234. Args.push_back(&BufferArg);
  2235. Args.push_back(&IdxArg);
  2236. Args.push_back(&ReduceListArg);
  2237. const CGFunctionInfo &CGFI =
  2238. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2239. auto *Fn = llvm::Function::Create(
  2240. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2241. "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
  2242. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2243. Fn->setDoesNotRecurse();
  2244. CodeGenFunction CGF(CGM);
  2245. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2246. CGBuilderTy &Bld = CGF.Builder;
  2247. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  2248. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  2249. llvm::Type *ElemTy = CGF.ConvertTypeForMem(ReductionArrayTy);
  2250. Address LocalReduceList(
  2251. Bld.CreatePointerBitCastOrAddrSpaceCast(
  2252. CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
  2253. C.VoidPtrTy, Loc),
  2254. ElemTy->getPointerTo()),
  2255. ElemTy, CGF.getPointerAlign());
  2256. QualType StaticTy = C.getRecordType(TeamReductionRec);
  2257. llvm::Type *LLVMReductionsBufferTy =
  2258. CGM.getTypes().ConvertTypeForMem(StaticTy);
  2259. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2260. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  2261. LLVMReductionsBufferTy->getPointerTo());
  2262. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  2263. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  2264. /*Volatile=*/false, C.IntTy,
  2265. Loc)};
  2266. unsigned Idx = 0;
  2267. for (const Expr *Private : Privates) {
  2268. // Reduce element = LocalReduceList[i]
  2269. Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
  2270. llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
  2271. ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
  2272. // elemptr = ((CopyType*)(elemptrptr)) + I
  2273. ElemTy = CGF.ConvertTypeForMem(Private->getType());
  2274. ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2275. ElemPtrPtr, ElemTy->getPointerTo());
  2276. Address ElemPtr =
  2277. Address(ElemPtrPtr, ElemTy, C.getTypeAlignInChars(Private->getType()));
  2278. const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
  2279. // Global = Buffer.VD[Idx];
  2280. const FieldDecl *FD = VarFieldMap.lookup(VD);
  2281. LValue GlobLVal = CGF.EmitLValueForField(
  2282. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  2283. Address GlobAddr = GlobLVal.getAddress(CGF);
  2284. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobAddr.getElementType(),
  2285. GlobAddr.getPointer(), Idxs);
  2286. GlobLVal.setAddress(Address(BufferPtr,
  2287. CGF.ConvertTypeForMem(Private->getType()),
  2288. GlobAddr.getAlignment()));
  2289. switch (CGF.getEvaluationKind(Private->getType())) {
  2290. case TEK_Scalar: {
  2291. llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
  2292. CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType(),
  2293. LValueBaseInfo(AlignmentSource::Type),
  2294. TBAAAccessInfo());
  2295. break;
  2296. }
  2297. case TEK_Complex: {
  2298. CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
  2299. CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  2300. /*isInit=*/false);
  2301. break;
  2302. }
  2303. case TEK_Aggregate:
  2304. CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
  2305. GlobLVal, Private->getType(),
  2306. AggValueSlot::DoesNotOverlap);
  2307. break;
  2308. }
  2309. ++Idx;
  2310. }
  2311. CGF.FinishFunction();
  2312. return Fn;
  2313. }
  2314. /// This function emits a helper that reduces all the reduction variables from
  2315. /// the team into the provided global buffer for the reduction variables.
  2316. ///
  2317. /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
  2318. /// void *GlobPtrs[];
  2319. /// GlobPtrs[0] = (void*)&buffer.D0[Idx];
  2320. /// ...
  2321. /// GlobPtrs[N] = (void*)&buffer.DN[Idx];
  2322. /// reduce_function(reduce_data, GlobPtrs);
  2323. static llvm::Value *emitGlobalToListReduceFunction(
  2324. CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
  2325. QualType ReductionArrayTy, SourceLocation Loc,
  2326. const RecordDecl *TeamReductionRec,
  2327. const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
  2328. &VarFieldMap,
  2329. llvm::Function *ReduceFn) {
  2330. ASTContext &C = CGM.getContext();
  2331. // Buffer: global reduction buffer.
  2332. ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2333. C.VoidPtrTy, ImplicitParamDecl::Other);
  2334. // Idx: index of the buffer.
  2335. ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
  2336. ImplicitParamDecl::Other);
  2337. // ReduceList: thread local Reduce list.
  2338. ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
  2339. C.VoidPtrTy, ImplicitParamDecl::Other);
  2340. FunctionArgList Args;
  2341. Args.push_back(&BufferArg);
  2342. Args.push_back(&IdxArg);
  2343. Args.push_back(&ReduceListArg);
  2344. const CGFunctionInfo &CGFI =
  2345. CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
  2346. auto *Fn = llvm::Function::Create(
  2347. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2348. "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
  2349. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2350. Fn->setDoesNotRecurse();
  2351. CodeGenFunction CGF(CGM);
  2352. CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
  2353. CGBuilderTy &Bld = CGF.Builder;
  2354. Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
  2355. QualType StaticTy = C.getRecordType(TeamReductionRec);
  2356. llvm::Type *LLVMReductionsBufferTy =
  2357. CGM.getTypes().ConvertTypeForMem(StaticTy);
  2358. llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2359. CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
  2360. LLVMReductionsBufferTy->getPointerTo());
  2361. // 1. Build a list of reduction variables.
  2362. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  2363. Address ReductionList =
  2364. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  2365. auto IPriv = Privates.begin();
  2366. llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
  2367. CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
  2368. /*Volatile=*/false, C.IntTy,
  2369. Loc)};
  2370. unsigned Idx = 0;
  2371. for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
  2372. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2373. // Global = Buffer.VD[Idx];
  2374. const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
  2375. const FieldDecl *FD = VarFieldMap.lookup(VD);
  2376. LValue GlobLVal = CGF.EmitLValueForField(
  2377. CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
  2378. Address GlobAddr = GlobLVal.getAddress(CGF);
  2379. llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
  2380. GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
  2381. llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
  2382. CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
  2383. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  2384. // Store array size.
  2385. ++Idx;
  2386. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2387. llvm::Value *Size = CGF.Builder.CreateIntCast(
  2388. CGF.getVLASize(
  2389. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  2390. .NumElts,
  2391. CGF.SizeTy, /*isSigned=*/false);
  2392. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  2393. Elem);
  2394. }
  2395. }
  2396. // Call reduce_function(ReduceList, GlobalReduceList)
  2397. llvm::Value *GlobalReduceList =
  2398. CGF.EmitCastToVoidPtr(ReductionList.getPointer());
  2399. Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
  2400. llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
  2401. AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
  2402. CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
  2403. CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
  2404. CGF.FinishFunction();
  2405. return Fn;
  2406. }
  2407. ///
  2408. /// Design of OpenMP reductions on the GPU
  2409. ///
  2410. /// Consider a typical OpenMP program with one or more reduction
  2411. /// clauses:
  2412. ///
  2413. /// float foo;
  2414. /// double bar;
  2415. /// #pragma omp target teams distribute parallel for \
  2416. /// reduction(+:foo) reduction(*:bar)
  2417. /// for (int i = 0; i < N; i++) {
  2418. /// foo += A[i]; bar *= B[i];
  2419. /// }
  2420. ///
  2421. /// where 'foo' and 'bar' are reduced across all OpenMP threads in
  2422. /// all teams. In our OpenMP implementation on the NVPTX device an
  2423. /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
  2424. /// within a team are mapped to CUDA threads within a threadblock.
  2425. /// Our goal is to efficiently aggregate values across all OpenMP
  2426. /// threads such that:
  2427. ///
  2428. /// - the compiler and runtime are logically concise, and
  2429. /// - the reduction is performed efficiently in a hierarchical
  2430. /// manner as follows: within OpenMP threads in the same warp,
  2431. /// across warps in a threadblock, and finally across teams on
  2432. /// the NVPTX device.
  2433. ///
  2434. /// Introduction to Decoupling
  2435. ///
  2436. /// We would like to decouple the compiler and the runtime so that the
  2437. /// latter is ignorant of the reduction variables (number, data types)
  2438. /// and the reduction operators. This allows a simpler interface
  2439. /// and implementation while still attaining good performance.
  2440. ///
  2441. /// Pseudocode for the aforementioned OpenMP program generated by the
  2442. /// compiler is as follows:
  2443. ///
  2444. /// 1. Create private copies of reduction variables on each OpenMP
  2445. /// thread: 'foo_private', 'bar_private'
  2446. /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
  2447. /// to it and writes the result in 'foo_private' and 'bar_private'
  2448. /// respectively.
  2449. /// 3. Call the OpenMP runtime on the GPU to reduce within a team
  2450. /// and store the result on the team master:
  2451. ///
  2452. /// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
  2453. /// reduceData, shuffleReduceFn, interWarpCpyFn)
  2454. ///
  2455. /// where:
  2456. /// struct ReduceData {
  2457. /// double *foo;
  2458. /// double *bar;
  2459. /// } reduceData
  2460. /// reduceData.foo = &foo_private
  2461. /// reduceData.bar = &bar_private
  2462. ///
  2463. /// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
  2464. /// auxiliary functions generated by the compiler that operate on
  2465. /// variables of type 'ReduceData'. They aid the runtime perform
  2466. /// algorithmic steps in a data agnostic manner.
  2467. ///
  2468. /// 'shuffleReduceFn' is a pointer to a function that reduces data
  2469. /// of type 'ReduceData' across two OpenMP threads (lanes) in the
  2470. /// same warp. It takes the following arguments as input:
  2471. ///
  2472. /// a. variable of type 'ReduceData' on the calling lane,
  2473. /// b. its lane_id,
  2474. /// c. an offset relative to the current lane_id to generate a
  2475. /// remote_lane_id. The remote lane contains the second
  2476. /// variable of type 'ReduceData' that is to be reduced.
  2477. /// d. an algorithm version parameter determining which reduction
  2478. /// algorithm to use.
  2479. ///
  2480. /// 'shuffleReduceFn' retrieves data from the remote lane using
  2481. /// efficient GPU shuffle intrinsics and reduces, using the
  2482. /// algorithm specified by the 4th parameter, the two operands
  2483. /// element-wise. The result is written to the first operand.
  2484. ///
  2485. /// Different reduction algorithms are implemented in different
  2486. /// runtime functions, all calling 'shuffleReduceFn' to perform
  2487. /// the essential reduction step. Therefore, based on the 4th
  2488. /// parameter, this function behaves slightly differently to
  2489. /// cooperate with the runtime to ensure correctness under
  2490. /// different circumstances.
  2491. ///
  2492. /// 'InterWarpCpyFn' is a pointer to a function that transfers
  2493. /// reduced variables across warps. It tunnels, through CUDA
  2494. /// shared memory, the thread-private data of type 'ReduceData'
  2495. /// from lane 0 of each warp to a lane in the first warp.
  2496. /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
  2497. /// The last team writes the global reduced value to memory.
  2498. ///
  2499. /// ret = __kmpc_nvptx_teams_reduce_nowait(...,
  2500. /// reduceData, shuffleReduceFn, interWarpCpyFn,
  2501. /// scratchpadCopyFn, loadAndReduceFn)
  2502. ///
  2503. /// 'scratchpadCopyFn' is a helper that stores reduced
  2504. /// data from the team master to a scratchpad array in
  2505. /// global memory.
  2506. ///
  2507. /// 'loadAndReduceFn' is a helper that loads data from
  2508. /// the scratchpad array and reduces it with the input
  2509. /// operand.
  2510. ///
  2511. /// These compiler generated functions hide address
  2512. /// calculation and alignment information from the runtime.
  2513. /// 5. if ret == 1:
  2514. /// The team master of the last team stores the reduced
  2515. /// result to the globals in memory.
  2516. /// foo += reduceData.foo; bar *= reduceData.bar
  2517. ///
  2518. ///
  2519. /// Warp Reduction Algorithms
  2520. ///
  2521. /// On the warp level, we have three algorithms implemented in the
  2522. /// OpenMP runtime depending on the number of active lanes:
  2523. ///
  2524. /// Full Warp Reduction
  2525. ///
  2526. /// The reduce algorithm within a warp where all lanes are active
  2527. /// is implemented in the runtime as follows:
  2528. ///
  2529. /// full_warp_reduce(void *reduce_data,
  2530. /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
  2531. /// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
  2532. /// ShuffleReduceFn(reduce_data, 0, offset, 0);
  2533. /// }
  2534. ///
  2535. /// The algorithm completes in log(2, WARPSIZE) steps.
  2536. ///
  2537. /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
  2538. /// not used therefore we save instructions by not retrieving lane_id
  2539. /// from the corresponding special registers. The 4th parameter, which
  2540. /// represents the version of the algorithm being used, is set to 0 to
  2541. /// signify full warp reduction.
  2542. ///
  2543. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  2544. ///
  2545. /// #reduce_elem refers to an element in the local lane's data structure
  2546. /// #remote_elem is retrieved from a remote lane
  2547. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  2548. /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
  2549. ///
  2550. /// Contiguous Partial Warp Reduction
  2551. ///
  2552. /// This reduce algorithm is used within a warp where only the first
  2553. /// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
  2554. /// number of OpenMP threads in a parallel region is not a multiple of
  2555. /// WARPSIZE. The algorithm is implemented in the runtime as follows:
  2556. ///
  2557. /// void
  2558. /// contiguous_partial_reduce(void *reduce_data,
  2559. /// kmp_ShuffleReductFctPtr ShuffleReduceFn,
  2560. /// int size, int lane_id) {
  2561. /// int curr_size;
  2562. /// int offset;
  2563. /// curr_size = size;
  2564. /// mask = curr_size/2;
  2565. /// while (offset>0) {
  2566. /// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
  2567. /// curr_size = (curr_size+1)/2;
  2568. /// offset = curr_size/2;
  2569. /// }
  2570. /// }
  2571. ///
  2572. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  2573. ///
  2574. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  2575. /// if (lane_id < offset)
  2576. /// reduce_elem = reduce_elem REDUCE_OP remote_elem
  2577. /// else
  2578. /// reduce_elem = remote_elem
  2579. ///
  2580. /// This algorithm assumes that the data to be reduced are located in a
  2581. /// contiguous subset of lanes starting from the first. When there is
  2582. /// an odd number of active lanes, the data in the last lane is not
  2583. /// aggregated with any other lane's dat but is instead copied over.
  2584. ///
  2585. /// Dispersed Partial Warp Reduction
  2586. ///
  2587. /// This algorithm is used within a warp when any discontiguous subset of
  2588. /// lanes are active. It is used to implement the reduction operation
  2589. /// across lanes in an OpenMP simd region or in a nested parallel region.
  2590. ///
  2591. /// void
  2592. /// dispersed_partial_reduce(void *reduce_data,
  2593. /// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
  2594. /// int size, remote_id;
  2595. /// int logical_lane_id = number_of_active_lanes_before_me() * 2;
  2596. /// do {
  2597. /// remote_id = next_active_lane_id_right_after_me();
  2598. /// # the above function returns 0 of no active lane
  2599. /// # is present right after the current lane.
  2600. /// size = number_of_active_lanes_in_this_warp();
  2601. /// logical_lane_id /= 2;
  2602. /// ShuffleReduceFn(reduce_data, logical_lane_id,
  2603. /// remote_id-1-threadIdx.x, 2);
  2604. /// } while (logical_lane_id % 2 == 0 && size > 1);
  2605. /// }
  2606. ///
  2607. /// There is no assumption made about the initial state of the reduction.
  2608. /// Any number of lanes (>=1) could be active at any position. The reduction
  2609. /// result is returned in the first active lane.
  2610. ///
  2611. /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
  2612. ///
  2613. /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
  2614. /// if (lane_id % 2 == 0 && offset > 0)
  2615. /// reduce_elem = reduce_elem REDUCE_OP remote_elem
  2616. /// else
  2617. /// reduce_elem = remote_elem
  2618. ///
  2619. ///
  2620. /// Intra-Team Reduction
  2621. ///
  2622. /// This function, as implemented in the runtime call
  2623. /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
  2624. /// threads in a team. It first reduces within a warp using the
  2625. /// aforementioned algorithms. We then proceed to gather all such
  2626. /// reduced values at the first warp.
  2627. ///
  2628. /// The runtime makes use of the function 'InterWarpCpyFn', which copies
  2629. /// data from each of the "warp master" (zeroth lane of each warp, where
  2630. /// warp-reduced data is held) to the zeroth warp. This step reduces (in
  2631. /// a mathematical sense) the problem of reduction across warp masters in
  2632. /// a block to the problem of warp reduction.
  2633. ///
  2634. ///
  2635. /// Inter-Team Reduction
  2636. ///
  2637. /// Once a team has reduced its data to a single value, it is stored in
  2638. /// a global scratchpad array. Since each team has a distinct slot, this
  2639. /// can be done without locking.
  2640. ///
  2641. /// The last team to write to the scratchpad array proceeds to reduce the
  2642. /// scratchpad array. One or more workers in the last team use the helper
  2643. /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
  2644. /// the k'th worker reduces every k'th element.
  2645. ///
  2646. /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
  2647. /// reduce across workers and compute a globally reduced value.
  2648. ///
  2649. void CGOpenMPRuntimeGPU::emitReduction(
  2650. CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
  2651. ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
  2652. ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
  2653. if (!CGF.HaveInsertPoint())
  2654. return;
  2655. bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
  2656. #ifndef NDEBUG
  2657. bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
  2658. #endif
  2659. if (Options.SimpleReduction) {
  2660. assert(!TeamsReduction && !ParallelReduction &&
  2661. "Invalid reduction selection in emitReduction.");
  2662. CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
  2663. ReductionOps, Options);
  2664. return;
  2665. }
  2666. assert((TeamsReduction || ParallelReduction) &&
  2667. "Invalid reduction selection in emitReduction.");
  2668. // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
  2669. // RedList, shuffle_reduce_func, interwarp_copy_func);
  2670. // or
  2671. // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
  2672. llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
  2673. llvm::Value *ThreadId = getThreadID(CGF, Loc);
  2674. llvm::Value *Res;
  2675. ASTContext &C = CGM.getContext();
  2676. // 1. Build a list of reduction variables.
  2677. // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
  2678. auto Size = RHSExprs.size();
  2679. for (const Expr *E : Privates) {
  2680. if (E->getType()->isVariablyModifiedType())
  2681. // Reserve place for array size.
  2682. ++Size;
  2683. }
  2684. llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
  2685. QualType ReductionArrayTy =
  2686. C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
  2687. /*IndexTypeQuals=*/0);
  2688. Address ReductionList =
  2689. CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
  2690. auto IPriv = Privates.begin();
  2691. unsigned Idx = 0;
  2692. for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
  2693. Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2694. CGF.Builder.CreateStore(
  2695. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2696. CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
  2697. Elem);
  2698. if ((*IPriv)->getType()->isVariablyModifiedType()) {
  2699. // Store array size.
  2700. ++Idx;
  2701. Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
  2702. llvm::Value *Size = CGF.Builder.CreateIntCast(
  2703. CGF.getVLASize(
  2704. CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
  2705. .NumElts,
  2706. CGF.SizeTy, /*isSigned=*/false);
  2707. CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
  2708. Elem);
  2709. }
  2710. }
  2711. llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2712. ReductionList.getPointer(), CGF.VoidPtrTy);
  2713. llvm::Function *ReductionFn =
  2714. emitReductionFunction(Loc, CGF.ConvertTypeForMem(ReductionArrayTy),
  2715. Privates, LHSExprs, RHSExprs, ReductionOps);
  2716. llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
  2717. llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
  2718. CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
  2719. llvm::Value *InterWarpCopyFn =
  2720. emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
  2721. if (ParallelReduction) {
  2722. llvm::Value *Args[] = {RTLoc,
  2723. ThreadId,
  2724. CGF.Builder.getInt32(RHSExprs.size()),
  2725. ReductionArrayTySize,
  2726. RL,
  2727. ShuffleAndReduceFn,
  2728. InterWarpCopyFn};
  2729. Res = CGF.EmitRuntimeCall(
  2730. OMPBuilder.getOrCreateRuntimeFunction(
  2731. CGM.getModule(), OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2),
  2732. Args);
  2733. } else {
  2734. assert(TeamsReduction && "expected teams reduction.");
  2735. llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
  2736. llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
  2737. int Cnt = 0;
  2738. for (const Expr *DRE : Privates) {
  2739. PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
  2740. ++Cnt;
  2741. }
  2742. const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
  2743. CGM.getContext(), PrivatesReductions, std::nullopt, VarFieldMap,
  2744. C.getLangOpts().OpenMPCUDAReductionBufNum);
  2745. TeamsReductions.push_back(TeamReductionRec);
  2746. if (!KernelTeamsReductionPtr) {
  2747. KernelTeamsReductionPtr = new llvm::GlobalVariable(
  2748. CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
  2749. llvm::GlobalValue::InternalLinkage, nullptr,
  2750. "_openmp_teams_reductions_buffer_$_$ptr");
  2751. }
  2752. llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
  2753. Address(KernelTeamsReductionPtr, CGF.VoidPtrTy, CGM.getPointerAlign()),
  2754. /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
  2755. llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
  2756. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
  2757. llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
  2758. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
  2759. ReductionFn);
  2760. llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
  2761. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
  2762. llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
  2763. CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
  2764. ReductionFn);
  2765. llvm::Value *Args[] = {
  2766. RTLoc,
  2767. ThreadId,
  2768. GlobalBufferPtr,
  2769. CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
  2770. RL,
  2771. ShuffleAndReduceFn,
  2772. InterWarpCopyFn,
  2773. GlobalToBufferCpyFn,
  2774. GlobalToBufferRedFn,
  2775. BufferToGlobalCpyFn,
  2776. BufferToGlobalRedFn};
  2777. Res = CGF.EmitRuntimeCall(
  2778. OMPBuilder.getOrCreateRuntimeFunction(
  2779. CGM.getModule(), OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2),
  2780. Args);
  2781. }
  2782. // 5. Build if (res == 1)
  2783. llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
  2784. llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
  2785. llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
  2786. Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
  2787. CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
  2788. // 6. Build then branch: where we have reduced values in the master
  2789. // thread in each team.
  2790. // __kmpc_end_reduce{_nowait}(<gtid>);
  2791. // break;
  2792. CGF.EmitBlock(ThenBB);
  2793. // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
  2794. auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
  2795. this](CodeGenFunction &CGF, PrePostActionTy &Action) {
  2796. auto IPriv = Privates.begin();
  2797. auto ILHS = LHSExprs.begin();
  2798. auto IRHS = RHSExprs.begin();
  2799. for (const Expr *E : ReductionOps) {
  2800. emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
  2801. cast<DeclRefExpr>(*IRHS));
  2802. ++IPriv;
  2803. ++ILHS;
  2804. ++IRHS;
  2805. }
  2806. };
  2807. llvm::Value *EndArgs[] = {ThreadId};
  2808. RegionCodeGenTy RCG(CodeGen);
  2809. NVPTXActionTy Action(
  2810. nullptr, std::nullopt,
  2811. OMPBuilder.getOrCreateRuntimeFunction(
  2812. CGM.getModule(), OMPRTL___kmpc_nvptx_end_reduce_nowait),
  2813. EndArgs);
  2814. RCG.setAction(Action);
  2815. RCG(CGF);
  2816. // There is no need to emit line number for unconditional branch.
  2817. (void)ApplyDebugLocation::CreateEmpty(CGF);
  2818. CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
  2819. }
  2820. const VarDecl *
  2821. CGOpenMPRuntimeGPU::translateParameter(const FieldDecl *FD,
  2822. const VarDecl *NativeParam) const {
  2823. if (!NativeParam->getType()->isReferenceType())
  2824. return NativeParam;
  2825. QualType ArgType = NativeParam->getType();
  2826. QualifierCollector QC;
  2827. const Type *NonQualTy = QC.strip(ArgType);
  2828. QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
  2829. if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
  2830. if (Attr->getCaptureKind() == OMPC_map) {
  2831. PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
  2832. LangAS::opencl_global);
  2833. }
  2834. }
  2835. ArgType = CGM.getContext().getPointerType(PointeeTy);
  2836. QC.addRestrict();
  2837. enum { NVPTX_local_addr = 5 };
  2838. QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
  2839. ArgType = QC.apply(CGM.getContext(), ArgType);
  2840. if (isa<ImplicitParamDecl>(NativeParam))
  2841. return ImplicitParamDecl::Create(
  2842. CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
  2843. NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
  2844. return ParmVarDecl::Create(
  2845. CGM.getContext(),
  2846. const_cast<DeclContext *>(NativeParam->getDeclContext()),
  2847. NativeParam->getBeginLoc(), NativeParam->getLocation(),
  2848. NativeParam->getIdentifier(), ArgType,
  2849. /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
  2850. }
  2851. Address
  2852. CGOpenMPRuntimeGPU::getParameterAddress(CodeGenFunction &CGF,
  2853. const VarDecl *NativeParam,
  2854. const VarDecl *TargetParam) const {
  2855. assert(NativeParam != TargetParam &&
  2856. NativeParam->getType()->isReferenceType() &&
  2857. "Native arg must not be the same as target arg.");
  2858. Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
  2859. QualType NativeParamType = NativeParam->getType();
  2860. QualifierCollector QC;
  2861. const Type *NonQualTy = QC.strip(NativeParamType);
  2862. QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
  2863. unsigned NativePointeeAddrSpace =
  2864. CGF.getTypes().getTargetAddressSpace(NativePointeeTy);
  2865. QualType TargetTy = TargetParam->getType();
  2866. llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
  2867. LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
  2868. // First cast to generic.
  2869. TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2870. TargetAddr, llvm::PointerType::getWithSamePointeeType(
  2871. cast<llvm::PointerType>(TargetAddr->getType()), /*AddrSpace=*/0));
  2872. // Cast from generic to native address space.
  2873. TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2874. TargetAddr, llvm::PointerType::getWithSamePointeeType(
  2875. cast<llvm::PointerType>(TargetAddr->getType()),
  2876. NativePointeeAddrSpace));
  2877. Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
  2878. CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
  2879. NativeParamType);
  2880. return NativeParamAddr;
  2881. }
  2882. void CGOpenMPRuntimeGPU::emitOutlinedFunctionCall(
  2883. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  2884. ArrayRef<llvm::Value *> Args) const {
  2885. SmallVector<llvm::Value *, 4> TargetArgs;
  2886. TargetArgs.reserve(Args.size());
  2887. auto *FnType = OutlinedFn.getFunctionType();
  2888. for (unsigned I = 0, E = Args.size(); I < E; ++I) {
  2889. if (FnType->isVarArg() && FnType->getNumParams() <= I) {
  2890. TargetArgs.append(std::next(Args.begin(), I), Args.end());
  2891. break;
  2892. }
  2893. llvm::Type *TargetType = FnType->getParamType(I);
  2894. llvm::Value *NativeArg = Args[I];
  2895. if (!TargetType->isPointerTy()) {
  2896. TargetArgs.emplace_back(NativeArg);
  2897. continue;
  2898. }
  2899. llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  2900. NativeArg, llvm::PointerType::getWithSamePointeeType(
  2901. cast<llvm::PointerType>(NativeArg->getType()), /*AddrSpace*/ 0));
  2902. TargetArgs.emplace_back(
  2903. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
  2904. }
  2905. CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
  2906. }
  2907. /// Emit function which wraps the outline parallel region
  2908. /// and controls the arguments which are passed to this function.
  2909. /// The wrapper ensures that the outlined function is called
  2910. /// with the correct arguments when data is shared.
  2911. llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
  2912. llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
  2913. ASTContext &Ctx = CGM.getContext();
  2914. const auto &CS = *D.getCapturedStmt(OMPD_parallel);
  2915. // Create a function that takes as argument the source thread.
  2916. FunctionArgList WrapperArgs;
  2917. QualType Int16QTy =
  2918. Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
  2919. QualType Int32QTy =
  2920. Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
  2921. ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
  2922. /*Id=*/nullptr, Int16QTy,
  2923. ImplicitParamDecl::Other);
  2924. ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
  2925. /*Id=*/nullptr, Int32QTy,
  2926. ImplicitParamDecl::Other);
  2927. WrapperArgs.emplace_back(&ParallelLevelArg);
  2928. WrapperArgs.emplace_back(&WrapperArg);
  2929. const CGFunctionInfo &CGFI =
  2930. CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
  2931. auto *Fn = llvm::Function::Create(
  2932. CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
  2933. Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
  2934. // Ensure we do not inline the function. This is trivially true for the ones
  2935. // passed to __kmpc_fork_call but the ones calles in serialized regions
  2936. // could be inlined. This is not a perfect but it is closer to the invariant
  2937. // we want, namely, every data environment starts with a new function.
  2938. // TODO: We should pass the if condition to the runtime function and do the
  2939. // handling there. Much cleaner code.
  2940. Fn->addFnAttr(llvm::Attribute::NoInline);
  2941. CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
  2942. Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
  2943. Fn->setDoesNotRecurse();
  2944. CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
  2945. CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
  2946. D.getBeginLoc(), D.getBeginLoc());
  2947. const auto *RD = CS.getCapturedRecordDecl();
  2948. auto CurField = RD->field_begin();
  2949. Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
  2950. /*Name=*/".zero.addr");
  2951. CGF.Builder.CreateStore(CGF.Builder.getInt32(/*C*/ 0), ZeroAddr);
  2952. // Get the array of arguments.
  2953. SmallVector<llvm::Value *, 8> Args;
  2954. Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
  2955. Args.emplace_back(ZeroAddr.getPointer());
  2956. CGBuilderTy &Bld = CGF.Builder;
  2957. auto CI = CS.capture_begin();
  2958. // Use global memory for data sharing.
  2959. // Handle passing of global args to workers.
  2960. Address GlobalArgs =
  2961. CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
  2962. llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
  2963. llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
  2964. CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  2965. CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
  2966. DataSharingArgs);
  2967. // Retrieve the shared variables from the list of references returned
  2968. // by the runtime. Pass the variables to the outlined function.
  2969. Address SharedArgListAddress = Address::invalid();
  2970. if (CS.capture_size() > 0 ||
  2971. isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
  2972. SharedArgListAddress = CGF.EmitLoadOfPointer(
  2973. GlobalArgs, CGF.getContext()
  2974. .getPointerType(CGF.getContext().VoidPtrTy)
  2975. .castAs<PointerType>());
  2976. }
  2977. unsigned Idx = 0;
  2978. if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
  2979. Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
  2980. Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2981. Src, CGF.SizeTy->getPointerTo(), CGF.SizeTy);
  2982. llvm::Value *LB = CGF.EmitLoadOfScalar(
  2983. TypedAddress,
  2984. /*Volatile=*/false,
  2985. CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
  2986. cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
  2987. Args.emplace_back(LB);
  2988. ++Idx;
  2989. Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
  2990. TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  2991. Src, CGF.SizeTy->getPointerTo(), CGF.SizeTy);
  2992. llvm::Value *UB = CGF.EmitLoadOfScalar(
  2993. TypedAddress,
  2994. /*Volatile=*/false,
  2995. CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
  2996. cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
  2997. Args.emplace_back(UB);
  2998. ++Idx;
  2999. }
  3000. if (CS.capture_size() > 0) {
  3001. ASTContext &CGFContext = CGF.getContext();
  3002. for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
  3003. QualType ElemTy = CurField->getType();
  3004. Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
  3005. Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
  3006. Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)),
  3007. CGF.ConvertTypeForMem(ElemTy));
  3008. llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
  3009. /*Volatile=*/false,
  3010. CGFContext.getPointerType(ElemTy),
  3011. CI->getLocation());
  3012. if (CI->capturesVariableByCopy() &&
  3013. !CI->getCapturedVar()->getType()->isAnyPointerType()) {
  3014. Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
  3015. CI->getLocation());
  3016. }
  3017. Args.emplace_back(Arg);
  3018. }
  3019. }
  3020. emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
  3021. CGF.FinishFunction();
  3022. return Fn;
  3023. }
  3024. void CGOpenMPRuntimeGPU::emitFunctionProlog(CodeGenFunction &CGF,
  3025. const Decl *D) {
  3026. if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
  3027. return;
  3028. assert(D && "Expected function or captured|block decl.");
  3029. assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
  3030. "Function is registered already.");
  3031. assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
  3032. "Team is set but not processed.");
  3033. const Stmt *Body = nullptr;
  3034. bool NeedToDelayGlobalization = false;
  3035. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  3036. Body = FD->getBody();
  3037. } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  3038. Body = BD->getBody();
  3039. } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
  3040. Body = CD->getBody();
  3041. NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
  3042. if (NeedToDelayGlobalization &&
  3043. getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
  3044. return;
  3045. }
  3046. if (!Body)
  3047. return;
  3048. CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
  3049. VarChecker.Visit(Body);
  3050. const RecordDecl *GlobalizedVarsRecord =
  3051. VarChecker.getGlobalizedRecord(IsInTTDRegion);
  3052. TeamAndReductions.first = nullptr;
  3053. TeamAndReductions.second.clear();
  3054. ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
  3055. VarChecker.getEscapedVariableLengthDecls();
  3056. if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
  3057. return;
  3058. auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
  3059. I->getSecond().MappedParams =
  3060. std::make_unique<CodeGenFunction::OMPMapVars>();
  3061. I->getSecond().EscapedParameters.insert(
  3062. VarChecker.getEscapedParameters().begin(),
  3063. VarChecker.getEscapedParameters().end());
  3064. I->getSecond().EscapedVariableLengthDecls.append(
  3065. EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
  3066. DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
  3067. for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
  3068. assert(VD->isCanonicalDecl() && "Expected canonical declaration");
  3069. Data.insert(std::make_pair(VD, MappedVarData()));
  3070. }
  3071. if (!NeedToDelayGlobalization) {
  3072. emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
  3073. struct GlobalizationScope final : EHScopeStack::Cleanup {
  3074. GlobalizationScope() = default;
  3075. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3076. static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
  3077. .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
  3078. }
  3079. };
  3080. CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
  3081. }
  3082. }
  3083. Address CGOpenMPRuntimeGPU::getAddressOfLocalVariable(CodeGenFunction &CGF,
  3084. const VarDecl *VD) {
  3085. if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
  3086. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  3087. auto AS = LangAS::Default;
  3088. switch (A->getAllocatorType()) {
  3089. // Use the default allocator here as by default local vars are
  3090. // threadlocal.
  3091. case OMPAllocateDeclAttr::OMPNullMemAlloc:
  3092. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  3093. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  3094. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  3095. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  3096. // Follow the user decision - use default allocation.
  3097. return Address::invalid();
  3098. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  3099. // TODO: implement aupport for user-defined allocators.
  3100. return Address::invalid();
  3101. case OMPAllocateDeclAttr::OMPConstMemAlloc:
  3102. AS = LangAS::cuda_constant;
  3103. break;
  3104. case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
  3105. AS = LangAS::cuda_shared;
  3106. break;
  3107. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  3108. case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
  3109. break;
  3110. }
  3111. llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
  3112. auto *GV = new llvm::GlobalVariable(
  3113. CGM.getModule(), VarTy, /*isConstant=*/false,
  3114. llvm::GlobalValue::InternalLinkage, llvm::Constant::getNullValue(VarTy),
  3115. VD->getName(),
  3116. /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
  3117. CGM.getContext().getTargetAddressSpace(AS));
  3118. CharUnits Align = CGM.getContext().getDeclAlign(VD);
  3119. GV->setAlignment(Align.getAsAlign());
  3120. return Address(
  3121. CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  3122. GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
  3123. VD->getType().getAddressSpace()))),
  3124. VarTy, Align);
  3125. }
  3126. if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
  3127. return Address::invalid();
  3128. VD = VD->getCanonicalDecl();
  3129. auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
  3130. if (I == FunctionGlobalizedDecls.end())
  3131. return Address::invalid();
  3132. auto VDI = I->getSecond().LocalVarData.find(VD);
  3133. if (VDI != I->getSecond().LocalVarData.end())
  3134. return VDI->second.PrivateAddr;
  3135. if (VD->hasAttrs()) {
  3136. for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
  3137. E(VD->attr_end());
  3138. IT != E; ++IT) {
  3139. auto VDI = I->getSecond().LocalVarData.find(
  3140. cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
  3141. ->getCanonicalDecl());
  3142. if (VDI != I->getSecond().LocalVarData.end())
  3143. return VDI->second.PrivateAddr;
  3144. }
  3145. }
  3146. return Address::invalid();
  3147. }
  3148. void CGOpenMPRuntimeGPU::functionFinished(CodeGenFunction &CGF) {
  3149. FunctionGlobalizedDecls.erase(CGF.CurFn);
  3150. CGOpenMPRuntime::functionFinished(CGF);
  3151. }
  3152. void CGOpenMPRuntimeGPU::getDefaultDistScheduleAndChunk(
  3153. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3154. OpenMPDistScheduleClauseKind &ScheduleKind,
  3155. llvm::Value *&Chunk) const {
  3156. auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
  3157. if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
  3158. ScheduleKind = OMPC_DIST_SCHEDULE_static;
  3159. Chunk = CGF.EmitScalarConversion(
  3160. RT.getGPUNumThreads(CGF),
  3161. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  3162. S.getIterationVariable()->getType(), S.getBeginLoc());
  3163. return;
  3164. }
  3165. CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
  3166. CGF, S, ScheduleKind, Chunk);
  3167. }
  3168. void CGOpenMPRuntimeGPU::getDefaultScheduleAndChunk(
  3169. CodeGenFunction &CGF, const OMPLoopDirective &S,
  3170. OpenMPScheduleClauseKind &ScheduleKind,
  3171. const Expr *&ChunkExpr) const {
  3172. ScheduleKind = OMPC_SCHEDULE_static;
  3173. // Chunk size is 1 in this case.
  3174. llvm::APInt ChunkSize(32, 1);
  3175. ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
  3176. CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
  3177. SourceLocation());
  3178. }
  3179. void CGOpenMPRuntimeGPU::adjustTargetSpecificDataForLambdas(
  3180. CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
  3181. assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
  3182. " Expected target-based directive.");
  3183. const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
  3184. for (const CapturedStmt::Capture &C : CS->captures()) {
  3185. // Capture variables captured by reference in lambdas for target-based
  3186. // directives.
  3187. if (!C.capturesVariable())
  3188. continue;
  3189. const VarDecl *VD = C.getCapturedVar();
  3190. const auto *RD = VD->getType()
  3191. .getCanonicalType()
  3192. .getNonReferenceType()
  3193. ->getAsCXXRecordDecl();
  3194. if (!RD || !RD->isLambda())
  3195. continue;
  3196. Address VDAddr = CGF.GetAddrOfLocalVar(VD);
  3197. LValue VDLVal;
  3198. if (VD->getType().getCanonicalType()->isReferenceType())
  3199. VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
  3200. else
  3201. VDLVal = CGF.MakeAddrLValue(
  3202. VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
  3203. llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
  3204. FieldDecl *ThisCapture = nullptr;
  3205. RD->getCaptureFields(Captures, ThisCapture);
  3206. if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
  3207. LValue ThisLVal =
  3208. CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
  3209. llvm::Value *CXXThis = CGF.LoadCXXThis();
  3210. CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
  3211. }
  3212. for (const LambdaCapture &LC : RD->captures()) {
  3213. if (LC.getCaptureKind() != LCK_ByRef)
  3214. continue;
  3215. const ValueDecl *VD = LC.getCapturedVar();
  3216. // FIXME: For now VD is always a VarDecl because OpenMP does not support
  3217. // capturing structured bindings in lambdas yet.
  3218. if (!CS->capturesVariable(cast<VarDecl>(VD)))
  3219. continue;
  3220. auto It = Captures.find(VD);
  3221. assert(It != Captures.end() && "Found lambda capture without field.");
  3222. LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
  3223. Address VDAddr = CGF.GetAddrOfLocalVar(cast<VarDecl>(VD));
  3224. if (VD->getType().getCanonicalType()->isReferenceType())
  3225. VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
  3226. VD->getType().getCanonicalType())
  3227. .getAddress(CGF);
  3228. CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
  3229. }
  3230. }
  3231. }
  3232. bool CGOpenMPRuntimeGPU::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
  3233. LangAS &AS) {
  3234. if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
  3235. return false;
  3236. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  3237. switch(A->getAllocatorType()) {
  3238. case OMPAllocateDeclAttr::OMPNullMemAlloc:
  3239. case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
  3240. // Not supported, fallback to the default mem space.
  3241. case OMPAllocateDeclAttr::OMPThreadMemAlloc:
  3242. case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
  3243. case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
  3244. case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
  3245. case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
  3246. AS = LangAS::Default;
  3247. return true;
  3248. case OMPAllocateDeclAttr::OMPConstMemAlloc:
  3249. AS = LangAS::cuda_constant;
  3250. return true;
  3251. case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
  3252. AS = LangAS::cuda_shared;
  3253. return true;
  3254. case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
  3255. llvm_unreachable("Expected predefined allocator for the variables with the "
  3256. "static storage.");
  3257. }
  3258. return false;
  3259. }
  3260. // Get current CudaArch and ignore any unknown values
  3261. static CudaArch getCudaArch(CodeGenModule &CGM) {
  3262. if (!CGM.getTarget().hasFeature("ptx"))
  3263. return CudaArch::UNKNOWN;
  3264. for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
  3265. if (Feature.getValue()) {
  3266. CudaArch Arch = StringToCudaArch(Feature.getKey());
  3267. if (Arch != CudaArch::UNKNOWN)
  3268. return Arch;
  3269. }
  3270. }
  3271. return CudaArch::UNKNOWN;
  3272. }
  3273. /// Check to see if target architecture supports unified addressing which is
  3274. /// a restriction for OpenMP requires clause "unified_shared_memory".
  3275. void CGOpenMPRuntimeGPU::processRequiresDirective(
  3276. const OMPRequiresDecl *D) {
  3277. for (const OMPClause *Clause : D->clauselists()) {
  3278. if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
  3279. CudaArch Arch = getCudaArch(CGM);
  3280. switch (Arch) {
  3281. case CudaArch::SM_20:
  3282. case CudaArch::SM_21:
  3283. case CudaArch::SM_30:
  3284. case CudaArch::SM_32:
  3285. case CudaArch::SM_35:
  3286. case CudaArch::SM_37:
  3287. case CudaArch::SM_50:
  3288. case CudaArch::SM_52:
  3289. case CudaArch::SM_53: {
  3290. SmallString<256> Buffer;
  3291. llvm::raw_svector_ostream Out(Buffer);
  3292. Out << "Target architecture " << CudaArchToString(Arch)
  3293. << " does not support unified addressing";
  3294. CGM.Error(Clause->getBeginLoc(), Out.str());
  3295. return;
  3296. }
  3297. case CudaArch::SM_60:
  3298. case CudaArch::SM_61:
  3299. case CudaArch::SM_62:
  3300. case CudaArch::SM_70:
  3301. case CudaArch::SM_72:
  3302. case CudaArch::SM_75:
  3303. case CudaArch::SM_80:
  3304. case CudaArch::SM_86:
  3305. case CudaArch::SM_87:
  3306. case CudaArch::SM_89:
  3307. case CudaArch::SM_90:
  3308. case CudaArch::GFX600:
  3309. case CudaArch::GFX601:
  3310. case CudaArch::GFX602:
  3311. case CudaArch::GFX700:
  3312. case CudaArch::GFX701:
  3313. case CudaArch::GFX702:
  3314. case CudaArch::GFX703:
  3315. case CudaArch::GFX704:
  3316. case CudaArch::GFX705:
  3317. case CudaArch::GFX801:
  3318. case CudaArch::GFX802:
  3319. case CudaArch::GFX803:
  3320. case CudaArch::GFX805:
  3321. case CudaArch::GFX810:
  3322. case CudaArch::GFX900:
  3323. case CudaArch::GFX902:
  3324. case CudaArch::GFX904:
  3325. case CudaArch::GFX906:
  3326. case CudaArch::GFX908:
  3327. case CudaArch::GFX909:
  3328. case CudaArch::GFX90a:
  3329. case CudaArch::GFX90c:
  3330. case CudaArch::GFX940:
  3331. case CudaArch::GFX1010:
  3332. case CudaArch::GFX1011:
  3333. case CudaArch::GFX1012:
  3334. case CudaArch::GFX1013:
  3335. case CudaArch::GFX1030:
  3336. case CudaArch::GFX1031:
  3337. case CudaArch::GFX1032:
  3338. case CudaArch::GFX1033:
  3339. case CudaArch::GFX1034:
  3340. case CudaArch::GFX1035:
  3341. case CudaArch::GFX1036:
  3342. case CudaArch::GFX1100:
  3343. case CudaArch::GFX1101:
  3344. case CudaArch::GFX1102:
  3345. case CudaArch::GFX1103:
  3346. case CudaArch::Generic:
  3347. case CudaArch::UNUSED:
  3348. case CudaArch::UNKNOWN:
  3349. break;
  3350. case CudaArch::LAST:
  3351. llvm_unreachable("Unexpected Cuda arch.");
  3352. }
  3353. }
  3354. }
  3355. CGOpenMPRuntime::processRequiresDirective(D);
  3356. }
  3357. void CGOpenMPRuntimeGPU::clear() {
  3358. if (!TeamsReductions.empty()) {
  3359. ASTContext &C = CGM.getContext();
  3360. RecordDecl *StaticRD = C.buildImplicitRecord(
  3361. "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
  3362. StaticRD->startDefinition();
  3363. for (const RecordDecl *TeamReductionRec : TeamsReductions) {
  3364. QualType RecTy = C.getRecordType(TeamReductionRec);
  3365. auto *Field = FieldDecl::Create(
  3366. C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
  3367. C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
  3368. /*BW=*/nullptr, /*Mutable=*/false,
  3369. /*InitStyle=*/ICIS_NoInit);
  3370. Field->setAccess(AS_public);
  3371. StaticRD->addDecl(Field);
  3372. }
  3373. StaticRD->completeDefinition();
  3374. QualType StaticTy = C.getRecordType(StaticRD);
  3375. llvm::Type *LLVMReductionsBufferTy =
  3376. CGM.getTypes().ConvertTypeForMem(StaticTy);
  3377. // FIXME: nvlink does not handle weak linkage correctly (object with the
  3378. // different size are reported as erroneous).
  3379. // Restore CommonLinkage as soon as nvlink is fixed.
  3380. auto *GV = new llvm::GlobalVariable(
  3381. CGM.getModule(), LLVMReductionsBufferTy,
  3382. /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
  3383. llvm::Constant::getNullValue(LLVMReductionsBufferTy),
  3384. "_openmp_teams_reductions_buffer_$_");
  3385. KernelTeamsReductionPtr->setInitializer(
  3386. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
  3387. CGM.VoidPtrTy));
  3388. }
  3389. CGOpenMPRuntime::clear();
  3390. }
  3391. llvm::Value *CGOpenMPRuntimeGPU::getGPUNumThreads(CodeGenFunction &CGF) {
  3392. CGBuilderTy &Bld = CGF.Builder;
  3393. llvm::Module *M = &CGF.CGM.getModule();
  3394. const char *LocSize = "__kmpc_get_hardware_num_threads_in_block";
  3395. llvm::Function *F = M->getFunction(LocSize);
  3396. if (!F) {
  3397. F = llvm::Function::Create(
  3398. llvm::FunctionType::get(CGF.Int32Ty, std::nullopt, false),
  3399. llvm::GlobalVariable::ExternalLinkage, LocSize, &CGF.CGM.getModule());
  3400. }
  3401. return Bld.CreateCall(F, std::nullopt, "nvptx_num_threads");
  3402. }
  3403. llvm::Value *CGOpenMPRuntimeGPU::getGPUThreadID(CodeGenFunction &CGF) {
  3404. ArrayRef<llvm::Value *> Args{};
  3405. return CGF.EmitRuntimeCall(
  3406. OMPBuilder.getOrCreateRuntimeFunction(
  3407. CGM.getModule(), OMPRTL___kmpc_get_hardware_thread_id_in_block),
  3408. Args);
  3409. }
  3410. llvm::Value *CGOpenMPRuntimeGPU::getGPUWarpSize(CodeGenFunction &CGF) {
  3411. ArrayRef<llvm::Value *> Args{};
  3412. return CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
  3413. CGM.getModule(), OMPRTL___kmpc_get_warp_size),
  3414. Args);
  3415. }