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 
14 #include "CGOpenMPRuntimeGPU.h"
15 #include "CGOpenMPRuntimeNVPTX.h"
16 #include "CodeGenFunction.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtOpenMP.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/Basic/Cuda.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
24 #include "llvm/IR/IntrinsicsNVPTX.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 using namespace llvm::omp;
29 
30 namespace {
31 /// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
32 class NVPTXActionTy final : public PrePostActionTy {
33   llvm::FunctionCallee EnterCallee = nullptr;
34   ArrayRef<llvm::Value *> EnterArgs;
35   llvm::FunctionCallee ExitCallee = nullptr;
36   ArrayRef<llvm::Value *> ExitArgs;
37   bool Conditional = false;
38   llvm::BasicBlock *ContBlock = nullptr;
39 
40 public:
41   NVPTXActionTy(llvm::FunctionCallee EnterCallee,
42                 ArrayRef<llvm::Value *> EnterArgs,
43                 llvm::FunctionCallee ExitCallee,
44                 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
45       : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
46         ExitArgs(ExitArgs), Conditional(Conditional) {}
47   void Enter(CodeGenFunction &CGF) override {
48     llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
49     if (Conditional) {
50       llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
51       auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
52       ContBlock = CGF.createBasicBlock("omp_if.end");
53       // Generate the branch (If-stmt)
54       CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
55       CGF.EmitBlock(ThenBlock);
56     }
57   }
58   void Done(CodeGenFunction &CGF) {
59     // Emit the rest of blocks/branches
60     CGF.EmitBranch(ContBlock);
61     CGF.EmitBlock(ContBlock, true);
62   }
63   void Exit(CodeGenFunction &CGF) override {
64     CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
65   }
66 };
67 
68 /// A class to track the execution mode when codegening directives within
69 /// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
70 /// to the target region and used by containing directives such as 'parallel'
71 /// to emit optimized code.
72 class ExecutionRuntimeModesRAII {
73 private:
74   CGOpenMPRuntimeGPU::ExecutionMode SavedExecMode =
75       CGOpenMPRuntimeGPU::EM_Unknown;
76   CGOpenMPRuntimeGPU::ExecutionMode &ExecMode;
77   bool SavedRuntimeMode = false;
78   bool *RuntimeMode = nullptr;
79 
80 public:
81   /// Constructor for Non-SPMD mode.
82   ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode)
83       : ExecMode(ExecMode) {
84     SavedExecMode = ExecMode;
85     ExecMode = CGOpenMPRuntimeGPU::EM_NonSPMD;
86   }
87   /// Constructor for SPMD mode.
88   ExecutionRuntimeModesRAII(CGOpenMPRuntimeGPU::ExecutionMode &ExecMode,
89                             bool &RuntimeMode, bool FullRuntimeMode)
90       : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
91     SavedExecMode = ExecMode;
92     SavedRuntimeMode = RuntimeMode;
93     ExecMode = CGOpenMPRuntimeGPU::EM_SPMD;
94     RuntimeMode = FullRuntimeMode;
95   }
96   ~ExecutionRuntimeModesRAII() {
97     ExecMode = SavedExecMode;
98     if (RuntimeMode)
99       *RuntimeMode = SavedRuntimeMode;
100   }
101 };
102 
103 /// GPU Configuration:  This information can be derived from cuda registers,
104 /// however, providing compile time constants helps generate more efficient
105 /// code.  For all practical purposes this is fine because the configuration
106 /// is the same for all known NVPTX architectures.
107 enum MachineConfiguration : unsigned {
108   /// See "llvm/Frontend/OpenMP/OMPGridValues.h" for various related target
109   /// specific Grid Values like GV_Warp_Size, GV_Warp_Size_Log2,
110   /// and GV_Warp_Size_Log2_Mask.
111 
112   /// Global memory alignment for performance.
113   GlobalMemoryAlignment = 128,
114 
115   /// Maximal size of the shared memory buffer.
116   SharedMemorySize = 128,
117 };
118 
119 static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
120   RefExpr = RefExpr->IgnoreParens();
121   if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
122     const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
123     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
124       Base = TempASE->getBase()->IgnoreParenImpCasts();
125     RefExpr = Base;
126   } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
127     const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
128     while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
129       Base = TempOASE->getBase()->IgnoreParenImpCasts();
130     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
131       Base = TempASE->getBase()->IgnoreParenImpCasts();
132     RefExpr = Base;
133   }
134   RefExpr = RefExpr->IgnoreParenImpCasts();
135   if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
136     return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
137   const auto *ME = cast<MemberExpr>(RefExpr);
138   return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
139 }
140 
141 
142 static RecordDecl *buildRecordForGlobalizedVars(
143     ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
144     ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
145     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
146         &MappedDeclsFields, int BufSize) {
147   using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
148   if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
149     return nullptr;
150   SmallVector<VarsDataTy, 4> GlobalizedVars;
151   for (const ValueDecl *D : EscapedDecls)
152     GlobalizedVars.emplace_back(
153         CharUnits::fromQuantity(std::max(
154             C.getDeclAlign(D).getQuantity(),
155             static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
156         D);
157   for (const ValueDecl *D : EscapedDeclsForTeams)
158     GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
159   llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
160     return L.first > R.first;
161   });
162 
163   // Build struct _globalized_locals_ty {
164   //         /*  globalized vars  */[WarSize] align (max(decl_align,
165   //         GlobalMemoryAlignment))
166   //         /*  globalized vars  */ for EscapedDeclsForTeams
167   //       };
168   RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
169   GlobalizedRD->startDefinition();
170   llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
171       EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
172   for (const auto &Pair : GlobalizedVars) {
173     const ValueDecl *VD = Pair.second;
174     QualType Type = VD->getType();
175     if (Type->isLValueReferenceType())
176       Type = C.getPointerType(Type.getNonReferenceType());
177     else
178       Type = Type.getNonReferenceType();
179     SourceLocation Loc = VD->getLocation();
180     FieldDecl *Field;
181     if (SingleEscaped.count(VD)) {
182       Field = FieldDecl::Create(
183           C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
184           C.getTrivialTypeSourceInfo(Type, SourceLocation()),
185           /*BW=*/nullptr, /*Mutable=*/false,
186           /*InitStyle=*/ICIS_NoInit);
187       Field->setAccess(AS_public);
188       if (VD->hasAttrs()) {
189         for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
190              E(VD->getAttrs().end());
191              I != E; ++I)
192           Field->addAttr(*I);
193       }
194     } else {
195       llvm::APInt ArraySize(32, BufSize);
196       Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
197                                     0);
198       Field = FieldDecl::Create(
199           C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
200           C.getTrivialTypeSourceInfo(Type, SourceLocation()),
201           /*BW=*/nullptr, /*Mutable=*/false,
202           /*InitStyle=*/ICIS_NoInit);
203       Field->setAccess(AS_public);
204       llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
205                                      static_cast<CharUnits::QuantityType>(
206                                          GlobalMemoryAlignment)));
207       Field->addAttr(AlignedAttr::CreateImplicit(
208           C, /*IsAlignmentExpr=*/true,
209           IntegerLiteral::Create(C, Align,
210                                  C.getIntTypeForBitwidth(32, /*Signed=*/0),
211                                  SourceLocation()),
212           {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
213     }
214     GlobalizedRD->addDecl(Field);
215     MappedDeclsFields.try_emplace(VD, Field);
216   }
217   GlobalizedRD->completeDefinition();
218   return GlobalizedRD;
219 }
220 
221 /// Get the list of variables that can escape their declaration context.
222 class CheckVarsEscapingDeclContext final
223     : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
224   CodeGenFunction &CGF;
225   llvm::SetVector<const ValueDecl *> EscapedDecls;
226   llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
227   llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
228   RecordDecl *GlobalizedRD = nullptr;
229   llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
230   bool AllEscaped = false;
231   bool IsForCombinedParallelRegion = false;
232 
233   void markAsEscaped(const ValueDecl *VD) {
234     // Do not globalize declare target variables.
235     if (!isa<VarDecl>(VD) ||
236         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
237       return;
238     VD = cast<ValueDecl>(VD->getCanonicalDecl());
239     // Use user-specified allocation.
240     if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
241       return;
242     // Variables captured by value must be globalized.
243     if (auto *CSI = CGF.CapturedStmtInfo) {
244       if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
245         // Check if need to capture the variable that was already captured by
246         // value in the outer region.
247         if (!IsForCombinedParallelRegion) {
248           if (!FD->hasAttrs())
249             return;
250           const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
251           if (!Attr)
252             return;
253           if (((Attr->getCaptureKind() != OMPC_map) &&
254                !isOpenMPPrivate(Attr->getCaptureKind())) ||
255               ((Attr->getCaptureKind() == OMPC_map) &&
256                !FD->getType()->isAnyPointerType()))
257             return;
258         }
259         if (!FD->getType()->isReferenceType()) {
260           assert(!VD->getType()->isVariablyModifiedType() &&
261                  "Parameter captured by value with variably modified type");
262           EscapedParameters.insert(VD);
263         } else if (!IsForCombinedParallelRegion) {
264           return;
265         }
266       }
267     }
268     if ((!CGF.CapturedStmtInfo ||
269          (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
270         VD->getType()->isReferenceType())
271       // Do not globalize variables with reference type.
272       return;
273     if (VD->getType()->isVariablyModifiedType())
274       EscapedVariableLengthDecls.insert(VD);
275     else
276       EscapedDecls.insert(VD);
277   }
278 
279   void VisitValueDecl(const ValueDecl *VD) {
280     if (VD->getType()->isLValueReferenceType())
281       markAsEscaped(VD);
282     if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
283       if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
284         const bool SavedAllEscaped = AllEscaped;
285         AllEscaped = VD->getType()->isLValueReferenceType();
286         Visit(VarD->getInit());
287         AllEscaped = SavedAllEscaped;
288       }
289     }
290   }
291   void VisitOpenMPCapturedStmt(const CapturedStmt *S,
292                                ArrayRef<OMPClause *> Clauses,
293                                bool IsCombinedParallelRegion) {
294     if (!S)
295       return;
296     for (const CapturedStmt::Capture &C : S->captures()) {
297       if (C.capturesVariable() && !C.capturesVariableByCopy()) {
298         const ValueDecl *VD = C.getCapturedVar();
299         bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
300         if (IsCombinedParallelRegion) {
301           // Check if the variable is privatized in the combined construct and
302           // those private copies must be shared in the inner parallel
303           // directive.
304           IsForCombinedParallelRegion = false;
305           for (const OMPClause *C : Clauses) {
306             if (!isOpenMPPrivate(C->getClauseKind()) ||
307                 C->getClauseKind() == OMPC_reduction ||
308                 C->getClauseKind() == OMPC_linear ||
309                 C->getClauseKind() == OMPC_private)
310               continue;
311             ArrayRef<const Expr *> Vars;
312             if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
313               Vars = PC->getVarRefs();
314             else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
315               Vars = PC->getVarRefs();
316             else
317               llvm_unreachable("Unexpected clause.");
318             for (const auto *E : Vars) {
319               const Decl *D =
320                   cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
321               if (D == VD->getCanonicalDecl()) {
322                 IsForCombinedParallelRegion = true;
323                 break;
324               }
325             }
326             if (IsForCombinedParallelRegion)
327               break;
328           }
329         }
330         markAsEscaped(VD);
331         if (isa<OMPCapturedExprDecl>(VD))
332           VisitValueDecl(VD);
333         IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
334       }
335     }
336   }
337 
338   void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
339     assert(!GlobalizedRD &&
340            "Record for globalized variables is built already.");
341     ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
342     unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
343     if (IsInTTDRegion)
344       EscapedDeclsForTeams = EscapedDecls.getArrayRef();
345     else
346       EscapedDeclsForParallel = EscapedDecls.getArrayRef();
347     GlobalizedRD = ::buildRecordForGlobalizedVars(
348         CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
349         MappedDeclsFields, WarpSize);
350   }
351 
352 public:
353   CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
354                                ArrayRef<const ValueDecl *> TeamsReductions)
355       : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
356   }
357   virtual ~CheckVarsEscapingDeclContext() = default;
358   void VisitDeclStmt(const DeclStmt *S) {
359     if (!S)
360       return;
361     for (const Decl *D : S->decls())
362       if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
363         VisitValueDecl(VD);
364   }
365   void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
366     if (!D)
367       return;
368     if (!D->hasAssociatedStmt())
369       return;
370     if (const auto *S =
371             dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
372       // Do not analyze directives that do not actually require capturing,
373       // like `omp for` or `omp simd` directives.
374       llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
375       getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
376       if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
377         VisitStmt(S->getCapturedStmt());
378         return;
379       }
380       VisitOpenMPCapturedStmt(
381           S, D->clauses(),
382           CaptureRegions.back() == OMPD_parallel &&
383               isOpenMPDistributeDirective(D->getDirectiveKind()));
384     }
385   }
386   void VisitCapturedStmt(const CapturedStmt *S) {
387     if (!S)
388       return;
389     for (const CapturedStmt::Capture &C : S->captures()) {
390       if (C.capturesVariable() && !C.capturesVariableByCopy()) {
391         const ValueDecl *VD = C.getCapturedVar();
392         markAsEscaped(VD);
393         if (isa<OMPCapturedExprDecl>(VD))
394           VisitValueDecl(VD);
395       }
396     }
397   }
398   void VisitLambdaExpr(const LambdaExpr *E) {
399     if (!E)
400       return;
401     for (const LambdaCapture &C : E->captures()) {
402       if (C.capturesVariable()) {
403         if (C.getCaptureKind() == LCK_ByRef) {
404           const ValueDecl *VD = C.getCapturedVar();
405           markAsEscaped(VD);
406           if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
407             VisitValueDecl(VD);
408         }
409       }
410     }
411   }
412   void VisitBlockExpr(const BlockExpr *E) {
413     if (!E)
414       return;
415     for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
416       if (C.isByRef()) {
417         const VarDecl *VD = C.getVariable();
418         markAsEscaped(VD);
419         if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
420           VisitValueDecl(VD);
421       }
422     }
423   }
424   void VisitCallExpr(const CallExpr *E) {
425     if (!E)
426       return;
427     for (const Expr *Arg : E->arguments()) {
428       if (!Arg)
429         continue;
430       if (Arg->isLValue()) {
431         const bool SavedAllEscaped = AllEscaped;
432         AllEscaped = true;
433         Visit(Arg);
434         AllEscaped = SavedAllEscaped;
435       } else {
436         Visit(Arg);
437       }
438     }
439     Visit(E->getCallee());
440   }
441   void VisitDeclRefExpr(const DeclRefExpr *E) {
442     if (!E)
443       return;
444     const ValueDecl *VD = E->getDecl();
445     if (AllEscaped)
446       markAsEscaped(VD);
447     if (isa<OMPCapturedExprDecl>(VD))
448       VisitValueDecl(VD);
449     else if (const auto *VarD = dyn_cast<VarDecl>(VD))
450       if (VarD->isInitCapture())
451         VisitValueDecl(VD);
452   }
453   void VisitUnaryOperator(const UnaryOperator *E) {
454     if (!E)
455       return;
456     if (E->getOpcode() == UO_AddrOf) {
457       const bool SavedAllEscaped = AllEscaped;
458       AllEscaped = true;
459       Visit(E->getSubExpr());
460       AllEscaped = SavedAllEscaped;
461     } else {
462       Visit(E->getSubExpr());
463     }
464   }
465   void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
466     if (!E)
467       return;
468     if (E->getCastKind() == CK_ArrayToPointerDecay) {
469       const bool SavedAllEscaped = AllEscaped;
470       AllEscaped = true;
471       Visit(E->getSubExpr());
472       AllEscaped = SavedAllEscaped;
473     } else {
474       Visit(E->getSubExpr());
475     }
476   }
477   void VisitExpr(const Expr *E) {
478     if (!E)
479       return;
480     bool SavedAllEscaped = AllEscaped;
481     if (!E->isLValue())
482       AllEscaped = false;
483     for (const Stmt *Child : E->children())
484       if (Child)
485         Visit(Child);
486     AllEscaped = SavedAllEscaped;
487   }
488   void VisitStmt(const Stmt *S) {
489     if (!S)
490       return;
491     for (const Stmt *Child : S->children())
492       if (Child)
493         Visit(Child);
494   }
495 
496   /// Returns the record that handles all the escaped local variables and used
497   /// instead of their original storage.
498   const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
499     if (!GlobalizedRD)
500       buildRecordForGlobalizedVars(IsInTTDRegion);
501     return GlobalizedRD;
502   }
503 
504   /// Returns the field in the globalized record for the escaped variable.
505   const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
506     assert(GlobalizedRD &&
507            "Record for globalized variables must be generated already.");
508     auto I = MappedDeclsFields.find(VD);
509     if (I == MappedDeclsFields.end())
510       return nullptr;
511     return I->getSecond();
512   }
513 
514   /// Returns the list of the escaped local variables/parameters.
515   ArrayRef<const ValueDecl *> getEscapedDecls() const {
516     return EscapedDecls.getArrayRef();
517   }
518 
519   /// Checks if the escaped local variable is actually a parameter passed by
520   /// value.
521   const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
522     return EscapedParameters;
523   }
524 
525   /// Returns the list of the escaped variables with the variably modified
526   /// types.
527   ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
528     return EscapedVariableLengthDecls.getArrayRef();
529   }
530 };
531 } // anonymous namespace
532 
533 /// Get the id of the warp in the block.
534 /// We assume that the warp size is 32, which is always the case
535 /// on the NVPTX device, to generate more efficient code.
536 static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
537   CGBuilderTy &Bld = CGF.Builder;
538   unsigned LaneIDBits =
539       CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size_Log2);
540   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
541   return Bld.CreateAShr(RT.getGPUThreadID(CGF), LaneIDBits, "nvptx_warp_id");
542 }
543 
544 /// Get the id of the current lane in the Warp.
545 /// We assume that the warp size is 32, which is always the case
546 /// on the NVPTX device, to generate more efficient code.
547 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
548   CGBuilderTy &Bld = CGF.Builder;
549   unsigned LaneIDMask = CGF.getContext().getTargetInfo().getGridValue(
550       llvm::omp::GV_Warp_Size_Log2_Mask);
551   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
552   return Bld.CreateAnd(RT.getGPUThreadID(CGF), Bld.getInt32(LaneIDMask),
553                        "nvptx_lane_id");
554 }
555 
556 /// Get the value of the thread_limit clause in the teams directive.
557 /// For the 'generic' execution mode, the runtime encodes thread_limit in
558 /// the launch parameters, always starting thread_limit+warpSize threads per
559 /// CTA. The threads in the last warp are reserved for master execution.
560 /// For the 'spmd' execution mode, all threads in a CTA are part of the team.
561 static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
562                                    bool IsInSPMDExecutionMode = false) {
563   CGBuilderTy &Bld = CGF.Builder;
564   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
565   return IsInSPMDExecutionMode
566              ? RT.getGPUNumThreads(CGF)
567              : Bld.CreateNUWSub(RT.getGPUNumThreads(CGF),
568                                 RT.getGPUWarpSize(CGF), "thread_limit");
569 }
570 
571 /// Get the thread id of the OMP master thread.
572 /// The master thread id is the first thread (lane) of the last warp in the
573 /// GPU block.  Warp size is assumed to be some power of 2.
574 /// Thread id is 0 indexed.
575 /// E.g: If NumThreads is 33, master id is 32.
576 ///      If NumThreads is 64, master id is 32.
577 ///      If NumThreads is 1024, master id is 992.
578 static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
579   CGBuilderTy &Bld = CGF.Builder;
580   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
581   llvm::Value *NumThreads = RT.getGPUNumThreads(CGF);
582   // We assume that the warp size is a power of 2.
583   llvm::Value *Mask = Bld.CreateNUWSub(RT.getGPUWarpSize(CGF), Bld.getInt32(1));
584 
585   return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
586                        Bld.CreateNot(Mask), "master_tid");
587 }
588 
589 CGOpenMPRuntimeGPU::WorkerFunctionState::WorkerFunctionState(
590     CodeGenModule &CGM, SourceLocation Loc)
591     : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
592       Loc(Loc) {
593   createWorkerFunction(CGM);
594 }
595 
596 void CGOpenMPRuntimeGPU::WorkerFunctionState::createWorkerFunction(
597     CodeGenModule &CGM) {
598   // Create an worker function with no arguments.
599 
600   WorkerFn = llvm::Function::Create(
601       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
602       /*placeholder=*/"_worker", &CGM.getModule());
603   CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
604   WorkerFn->setDoesNotRecurse();
605 }
606 
607 CGOpenMPRuntimeGPU::ExecutionMode
608 CGOpenMPRuntimeGPU::getExecutionMode() const {
609   return CurrentExecutionMode;
610 }
611 
612 static CGOpenMPRuntimeGPU::DataSharingMode
613 getDataSharingMode(CodeGenModule &CGM) {
614   return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeGPU::CUDA
615                                           : CGOpenMPRuntimeGPU::Generic;
616 }
617 
618 /// Check for inner (nested) SPMD construct, if any
619 static bool hasNestedSPMDDirective(ASTContext &Ctx,
620                                    const OMPExecutableDirective &D) {
621   const auto *CS = D.getInnermostCapturedStmt();
622   const auto *Body =
623       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
624   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
625 
626   if (const auto *NestedDir =
627           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
628     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
629     switch (D.getDirectiveKind()) {
630     case OMPD_target:
631       if (isOpenMPParallelDirective(DKind))
632         return true;
633       if (DKind == OMPD_teams) {
634         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
635             /*IgnoreCaptured=*/true);
636         if (!Body)
637           return false;
638         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
639         if (const auto *NND =
640                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
641           DKind = NND->getDirectiveKind();
642           if (isOpenMPParallelDirective(DKind))
643             return true;
644         }
645       }
646       return false;
647     case OMPD_target_teams:
648       return isOpenMPParallelDirective(DKind);
649     case OMPD_target_simd:
650     case OMPD_target_parallel:
651     case OMPD_target_parallel_for:
652     case OMPD_target_parallel_for_simd:
653     case OMPD_target_teams_distribute:
654     case OMPD_target_teams_distribute_simd:
655     case OMPD_target_teams_distribute_parallel_for:
656     case OMPD_target_teams_distribute_parallel_for_simd:
657     case OMPD_parallel:
658     case OMPD_for:
659     case OMPD_parallel_for:
660     case OMPD_parallel_master:
661     case OMPD_parallel_sections:
662     case OMPD_for_simd:
663     case OMPD_parallel_for_simd:
664     case OMPD_cancel:
665     case OMPD_cancellation_point:
666     case OMPD_ordered:
667     case OMPD_threadprivate:
668     case OMPD_allocate:
669     case OMPD_task:
670     case OMPD_simd:
671     case OMPD_sections:
672     case OMPD_section:
673     case OMPD_single:
674     case OMPD_master:
675     case OMPD_critical:
676     case OMPD_taskyield:
677     case OMPD_barrier:
678     case OMPD_taskwait:
679     case OMPD_taskgroup:
680     case OMPD_atomic:
681     case OMPD_flush:
682     case OMPD_depobj:
683     case OMPD_scan:
684     case OMPD_teams:
685     case OMPD_target_data:
686     case OMPD_target_exit_data:
687     case OMPD_target_enter_data:
688     case OMPD_distribute:
689     case OMPD_distribute_simd:
690     case OMPD_distribute_parallel_for:
691     case OMPD_distribute_parallel_for_simd:
692     case OMPD_teams_distribute:
693     case OMPD_teams_distribute_simd:
694     case OMPD_teams_distribute_parallel_for:
695     case OMPD_teams_distribute_parallel_for_simd:
696     case OMPD_target_update:
697     case OMPD_declare_simd:
698     case OMPD_declare_variant:
699     case OMPD_begin_declare_variant:
700     case OMPD_end_declare_variant:
701     case OMPD_declare_target:
702     case OMPD_end_declare_target:
703     case OMPD_declare_reduction:
704     case OMPD_declare_mapper:
705     case OMPD_taskloop:
706     case OMPD_taskloop_simd:
707     case OMPD_master_taskloop:
708     case OMPD_master_taskloop_simd:
709     case OMPD_parallel_master_taskloop:
710     case OMPD_parallel_master_taskloop_simd:
711     case OMPD_requires:
712     case OMPD_unknown:
713     default:
714       llvm_unreachable("Unexpected directive.");
715     }
716   }
717 
718   return false;
719 }
720 
721 static bool supportsSPMDExecutionMode(ASTContext &Ctx,
722                                       const OMPExecutableDirective &D) {
723   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
724   switch (DirectiveKind) {
725   case OMPD_target:
726   case OMPD_target_teams:
727     return hasNestedSPMDDirective(Ctx, D);
728   case OMPD_target_parallel:
729   case OMPD_target_parallel_for:
730   case OMPD_target_parallel_for_simd:
731   case OMPD_target_teams_distribute_parallel_for:
732   case OMPD_target_teams_distribute_parallel_for_simd:
733   case OMPD_target_simd:
734   case OMPD_target_teams_distribute_simd:
735     return true;
736   case OMPD_target_teams_distribute:
737     return false;
738   case OMPD_parallel:
739   case OMPD_for:
740   case OMPD_parallel_for:
741   case OMPD_parallel_master:
742   case OMPD_parallel_sections:
743   case OMPD_for_simd:
744   case OMPD_parallel_for_simd:
745   case OMPD_cancel:
746   case OMPD_cancellation_point:
747   case OMPD_ordered:
748   case OMPD_threadprivate:
749   case OMPD_allocate:
750   case OMPD_task:
751   case OMPD_simd:
752   case OMPD_sections:
753   case OMPD_section:
754   case OMPD_single:
755   case OMPD_master:
756   case OMPD_critical:
757   case OMPD_taskyield:
758   case OMPD_barrier:
759   case OMPD_taskwait:
760   case OMPD_taskgroup:
761   case OMPD_atomic:
762   case OMPD_flush:
763   case OMPD_depobj:
764   case OMPD_scan:
765   case OMPD_teams:
766   case OMPD_target_data:
767   case OMPD_target_exit_data:
768   case OMPD_target_enter_data:
769   case OMPD_distribute:
770   case OMPD_distribute_simd:
771   case OMPD_distribute_parallel_for:
772   case OMPD_distribute_parallel_for_simd:
773   case OMPD_teams_distribute:
774   case OMPD_teams_distribute_simd:
775   case OMPD_teams_distribute_parallel_for:
776   case OMPD_teams_distribute_parallel_for_simd:
777   case OMPD_target_update:
778   case OMPD_declare_simd:
779   case OMPD_declare_variant:
780   case OMPD_begin_declare_variant:
781   case OMPD_end_declare_variant:
782   case OMPD_declare_target:
783   case OMPD_end_declare_target:
784   case OMPD_declare_reduction:
785   case OMPD_declare_mapper:
786   case OMPD_taskloop:
787   case OMPD_taskloop_simd:
788   case OMPD_master_taskloop:
789   case OMPD_master_taskloop_simd:
790   case OMPD_parallel_master_taskloop:
791   case OMPD_parallel_master_taskloop_simd:
792   case OMPD_requires:
793   case OMPD_unknown:
794   default:
795     break;
796   }
797   llvm_unreachable(
798       "Unknown programming model for OpenMP directive on NVPTX target.");
799 }
800 
801 /// Check if the directive is loops based and has schedule clause at all or has
802 /// static scheduling.
803 static bool hasStaticScheduling(const OMPExecutableDirective &D) {
804   assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
805          isOpenMPLoopDirective(D.getDirectiveKind()) &&
806          "Expected loop-based directive.");
807   return !D.hasClausesOfKind<OMPOrderedClause>() &&
808          (!D.hasClausesOfKind<OMPScheduleClause>() ||
809           llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
810                        [](const OMPScheduleClause *C) {
811                          return C->getScheduleKind() == OMPC_SCHEDULE_static;
812                        }));
813 }
814 
815 /// Check for inner (nested) lightweight runtime construct, if any
816 static bool hasNestedLightweightDirective(ASTContext &Ctx,
817                                           const OMPExecutableDirective &D) {
818   assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
819   const auto *CS = D.getInnermostCapturedStmt();
820   const auto *Body =
821       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
822   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
823 
824   if (const auto *NestedDir =
825           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
826     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
827     switch (D.getDirectiveKind()) {
828     case OMPD_target:
829       if (isOpenMPParallelDirective(DKind) &&
830           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
831           hasStaticScheduling(*NestedDir))
832         return true;
833       if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
834         return true;
835       if (DKind == OMPD_parallel) {
836         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
837             /*IgnoreCaptured=*/true);
838         if (!Body)
839           return false;
840         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
841         if (const auto *NND =
842                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
843           DKind = NND->getDirectiveKind();
844           if (isOpenMPWorksharingDirective(DKind) &&
845               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
846             return true;
847         }
848       } else if (DKind == OMPD_teams) {
849         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
850             /*IgnoreCaptured=*/true);
851         if (!Body)
852           return false;
853         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
854         if (const auto *NND =
855                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
856           DKind = NND->getDirectiveKind();
857           if (isOpenMPParallelDirective(DKind) &&
858               isOpenMPWorksharingDirective(DKind) &&
859               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
860             return true;
861           if (DKind == OMPD_parallel) {
862             Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
863                 /*IgnoreCaptured=*/true);
864             if (!Body)
865               return false;
866             ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
867             if (const auto *NND =
868                     dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
869               DKind = NND->getDirectiveKind();
870               if (isOpenMPWorksharingDirective(DKind) &&
871                   isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
872                 return true;
873             }
874           }
875         }
876       }
877       return false;
878     case OMPD_target_teams:
879       if (isOpenMPParallelDirective(DKind) &&
880           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
881           hasStaticScheduling(*NestedDir))
882         return true;
883       if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
884         return true;
885       if (DKind == OMPD_parallel) {
886         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
887             /*IgnoreCaptured=*/true);
888         if (!Body)
889           return false;
890         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
891         if (const auto *NND =
892                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
893           DKind = NND->getDirectiveKind();
894           if (isOpenMPWorksharingDirective(DKind) &&
895               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
896             return true;
897         }
898       }
899       return false;
900     case OMPD_target_parallel:
901       if (DKind == OMPD_simd)
902         return true;
903       return isOpenMPWorksharingDirective(DKind) &&
904              isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
905     case OMPD_target_teams_distribute:
906     case OMPD_target_simd:
907     case OMPD_target_parallel_for:
908     case OMPD_target_parallel_for_simd:
909     case OMPD_target_teams_distribute_simd:
910     case OMPD_target_teams_distribute_parallel_for:
911     case OMPD_target_teams_distribute_parallel_for_simd:
912     case OMPD_parallel:
913     case OMPD_for:
914     case OMPD_parallel_for:
915     case OMPD_parallel_master:
916     case OMPD_parallel_sections:
917     case OMPD_for_simd:
918     case OMPD_parallel_for_simd:
919     case OMPD_cancel:
920     case OMPD_cancellation_point:
921     case OMPD_ordered:
922     case OMPD_threadprivate:
923     case OMPD_allocate:
924     case OMPD_task:
925     case OMPD_simd:
926     case OMPD_sections:
927     case OMPD_section:
928     case OMPD_single:
929     case OMPD_master:
930     case OMPD_critical:
931     case OMPD_taskyield:
932     case OMPD_barrier:
933     case OMPD_taskwait:
934     case OMPD_taskgroup:
935     case OMPD_atomic:
936     case OMPD_flush:
937     case OMPD_depobj:
938     case OMPD_scan:
939     case OMPD_teams:
940     case OMPD_target_data:
941     case OMPD_target_exit_data:
942     case OMPD_target_enter_data:
943     case OMPD_distribute:
944     case OMPD_distribute_simd:
945     case OMPD_distribute_parallel_for:
946     case OMPD_distribute_parallel_for_simd:
947     case OMPD_teams_distribute:
948     case OMPD_teams_distribute_simd:
949     case OMPD_teams_distribute_parallel_for:
950     case OMPD_teams_distribute_parallel_for_simd:
951     case OMPD_target_update:
952     case OMPD_declare_simd:
953     case OMPD_declare_variant:
954     case OMPD_begin_declare_variant:
955     case OMPD_end_declare_variant:
956     case OMPD_declare_target:
957     case OMPD_end_declare_target:
958     case OMPD_declare_reduction:
959     case OMPD_declare_mapper:
960     case OMPD_taskloop:
961     case OMPD_taskloop_simd:
962     case OMPD_master_taskloop:
963     case OMPD_master_taskloop_simd:
964     case OMPD_parallel_master_taskloop:
965     case OMPD_parallel_master_taskloop_simd:
966     case OMPD_requires:
967     case OMPD_unknown:
968     default:
969       llvm_unreachable("Unexpected directive.");
970     }
971   }
972 
973   return false;
974 }
975 
976 /// Checks if the construct supports lightweight runtime. It must be SPMD
977 /// construct + inner loop-based construct with static scheduling.
978 static bool supportsLightweightRuntime(ASTContext &Ctx,
979                                        const OMPExecutableDirective &D) {
980   if (!supportsSPMDExecutionMode(Ctx, D))
981     return false;
982   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
983   switch (DirectiveKind) {
984   case OMPD_target:
985   case OMPD_target_teams:
986   case OMPD_target_parallel:
987     return hasNestedLightweightDirective(Ctx, D);
988   case OMPD_target_parallel_for:
989   case OMPD_target_parallel_for_simd:
990   case OMPD_target_teams_distribute_parallel_for:
991   case OMPD_target_teams_distribute_parallel_for_simd:
992     // (Last|First)-privates must be shared in parallel region.
993     return hasStaticScheduling(D);
994   case OMPD_target_simd:
995   case OMPD_target_teams_distribute_simd:
996     return true;
997   case OMPD_target_teams_distribute:
998     return false;
999   case OMPD_parallel:
1000   case OMPD_for:
1001   case OMPD_parallel_for:
1002   case OMPD_parallel_master:
1003   case OMPD_parallel_sections:
1004   case OMPD_for_simd:
1005   case OMPD_parallel_for_simd:
1006   case OMPD_cancel:
1007   case OMPD_cancellation_point:
1008   case OMPD_ordered:
1009   case OMPD_threadprivate:
1010   case OMPD_allocate:
1011   case OMPD_task:
1012   case OMPD_simd:
1013   case OMPD_sections:
1014   case OMPD_section:
1015   case OMPD_single:
1016   case OMPD_master:
1017   case OMPD_critical:
1018   case OMPD_taskyield:
1019   case OMPD_barrier:
1020   case OMPD_taskwait:
1021   case OMPD_taskgroup:
1022   case OMPD_atomic:
1023   case OMPD_flush:
1024   case OMPD_depobj:
1025   case OMPD_scan:
1026   case OMPD_teams:
1027   case OMPD_target_data:
1028   case OMPD_target_exit_data:
1029   case OMPD_target_enter_data:
1030   case OMPD_distribute:
1031   case OMPD_distribute_simd:
1032   case OMPD_distribute_parallel_for:
1033   case OMPD_distribute_parallel_for_simd:
1034   case OMPD_teams_distribute:
1035   case OMPD_teams_distribute_simd:
1036   case OMPD_teams_distribute_parallel_for:
1037   case OMPD_teams_distribute_parallel_for_simd:
1038   case OMPD_target_update:
1039   case OMPD_declare_simd:
1040   case OMPD_declare_variant:
1041   case OMPD_begin_declare_variant:
1042   case OMPD_end_declare_variant:
1043   case OMPD_declare_target:
1044   case OMPD_end_declare_target:
1045   case OMPD_declare_reduction:
1046   case OMPD_declare_mapper:
1047   case OMPD_taskloop:
1048   case OMPD_taskloop_simd:
1049   case OMPD_master_taskloop:
1050   case OMPD_master_taskloop_simd:
1051   case OMPD_parallel_master_taskloop:
1052   case OMPD_parallel_master_taskloop_simd:
1053   case OMPD_requires:
1054   case OMPD_unknown:
1055   default:
1056     break;
1057   }
1058   llvm_unreachable(
1059       "Unknown programming model for OpenMP directive on NVPTX target.");
1060 }
1061 
1062 void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
1063                                              StringRef ParentName,
1064                                              llvm::Function *&OutlinedFn,
1065                                              llvm::Constant *&OutlinedFnID,
1066                                              bool IsOffloadEntry,
1067                                              const RegionCodeGenTy &CodeGen) {
1068   ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
1069   EntryFunctionState EST;
1070   WorkerFunctionState WST(CGM, D.getBeginLoc());
1071   Work.clear();
1072   WrapperFunctionsMap.clear();
1073 
1074   // Emit target region as a standalone region.
1075   class NVPTXPrePostActionTy : public PrePostActionTy {
1076     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1077     CGOpenMPRuntimeGPU::WorkerFunctionState &WST;
1078 
1079   public:
1080     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST,
1081                          CGOpenMPRuntimeGPU::WorkerFunctionState &WST)
1082         : EST(EST), WST(WST) {}
1083     void Enter(CodeGenFunction &CGF) override {
1084       auto &RT =
1085           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1086       RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1087       // Skip target region initialization.
1088       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1089     }
1090     void Exit(CodeGenFunction &CGF) override {
1091       auto &RT =
1092           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1093       RT.clearLocThreadIdInsertPt(CGF);
1094       RT.emitNonSPMDEntryFooter(CGF, EST);
1095     }
1096   } Action(EST, WST);
1097   CodeGen.setAction(Action);
1098   IsInTTDRegion = true;
1099   // Reserve place for the globalized memory.
1100   GlobalizedRecords.emplace_back();
1101   if (!KernelStaticGlobalized) {
1102     KernelStaticGlobalized = new llvm::GlobalVariable(
1103         CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1104         llvm::GlobalValue::InternalLinkage,
1105         llvm::UndefValue::get(CGM.VoidPtrTy),
1106         "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1107         llvm::GlobalValue::NotThreadLocal,
1108         CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1109   }
1110   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1111                                    IsOffloadEntry, CodeGen);
1112   IsInTTDRegion = false;
1113 
1114   // Now change the name of the worker function to correspond to this target
1115   // region's entry function.
1116   WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
1117 
1118   // Create the worker function
1119   emitWorkerFunction(WST);
1120 }
1121 
1122 // Setup NVPTX threads for master-worker OpenMP scheme.
1123 void CGOpenMPRuntimeGPU::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
1124                                                   EntryFunctionState &EST,
1125                                                   WorkerFunctionState &WST) {
1126   CGBuilderTy &Bld = CGF.Builder;
1127 
1128   llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1129   llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1130   llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1131   EST.ExitBB = CGF.createBasicBlock(".exit");
1132 
1133   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1134   llvm::Value *IsWorker =
1135       Bld.CreateICmpULT(RT.getGPUThreadID(CGF), getThreadLimit(CGF));
1136   Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1137 
1138   CGF.EmitBlock(WorkerBB);
1139   emitCall(CGF, WST.Loc, WST.WorkerFn);
1140   CGF.EmitBranch(EST.ExitBB);
1141 
1142   CGF.EmitBlock(MasterCheckBB);
1143   llvm::Value *IsMaster =
1144       Bld.CreateICmpEQ(RT.getGPUThreadID(CGF), getMasterThreadID(CGF));
1145   Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1146 
1147   CGF.EmitBlock(MasterBB);
1148   IsInTargetMasterThreadRegion = true;
1149   // SEQUENTIAL (MASTER) REGION START
1150   // First action in sequential region:
1151   // Initialize the state of the OpenMP runtime library on the GPU.
1152   // TODO: Optimize runtime initialization and pass in correct value.
1153   llvm::Value *Args[] = {getThreadLimit(CGF),
1154                          Bld.getInt16(/*RequiresOMPRuntime=*/1)};
1155   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1156                           CGM.getModule(), OMPRTL___kmpc_kernel_init),
1157                       Args);
1158 
1159   // For data sharing, we need to initialize the stack.
1160   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1161       CGM.getModule(), OMPRTL___kmpc_data_sharing_init_stack));
1162 
1163   emitGenericVarsProlog(CGF, WST.Loc);
1164 }
1165 
1166 void CGOpenMPRuntimeGPU::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
1167                                                   EntryFunctionState &EST) {
1168   IsInTargetMasterThreadRegion = false;
1169   if (!CGF.HaveInsertPoint())
1170     return;
1171 
1172   emitGenericVarsEpilog(CGF);
1173 
1174   if (!EST.ExitBB)
1175     EST.ExitBB = CGF.createBasicBlock(".exit");
1176 
1177   llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1178   CGF.EmitBranch(TerminateBB);
1179 
1180   CGF.EmitBlock(TerminateBB);
1181   // Signal termination condition.
1182   // TODO: Optimize runtime initialization and pass in correct value.
1183   llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
1184   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1185                           CGM.getModule(), OMPRTL___kmpc_kernel_deinit),
1186                       Args);
1187   // Barrier to terminate worker threads.
1188   syncCTAThreads(CGF);
1189   // Master thread jumps to exit point.
1190   CGF.EmitBranch(EST.ExitBB);
1191 
1192   CGF.EmitBlock(EST.ExitBB);
1193   EST.ExitBB = nullptr;
1194 }
1195 
1196 void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
1197                                           StringRef ParentName,
1198                                           llvm::Function *&OutlinedFn,
1199                                           llvm::Constant *&OutlinedFnID,
1200                                           bool IsOffloadEntry,
1201                                           const RegionCodeGenTy &CodeGen) {
1202   ExecutionRuntimeModesRAII ModeRAII(
1203       CurrentExecutionMode, RequiresFullRuntime,
1204       CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1205           !supportsLightweightRuntime(CGM.getContext(), D));
1206   EntryFunctionState EST;
1207 
1208   // Emit target region as a standalone region.
1209   class NVPTXPrePostActionTy : public PrePostActionTy {
1210     CGOpenMPRuntimeGPU &RT;
1211     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1212     const OMPExecutableDirective &D;
1213 
1214   public:
1215     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
1216                          CGOpenMPRuntimeGPU::EntryFunctionState &EST,
1217                          const OMPExecutableDirective &D)
1218         : RT(RT), EST(EST), D(D) {}
1219     void Enter(CodeGenFunction &CGF) override {
1220       RT.emitSPMDEntryHeader(CGF, EST, D);
1221       // Skip target region initialization.
1222       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1223     }
1224     void Exit(CodeGenFunction &CGF) override {
1225       RT.clearLocThreadIdInsertPt(CGF);
1226       RT.emitSPMDEntryFooter(CGF, EST);
1227     }
1228   } Action(*this, EST, D);
1229   CodeGen.setAction(Action);
1230   IsInTTDRegion = true;
1231   // Reserve place for the globalized memory.
1232   GlobalizedRecords.emplace_back();
1233   if (!KernelStaticGlobalized) {
1234     KernelStaticGlobalized = new llvm::GlobalVariable(
1235         CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1236         llvm::GlobalValue::InternalLinkage,
1237         llvm::UndefValue::get(CGM.VoidPtrTy),
1238         "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1239         llvm::GlobalValue::NotThreadLocal,
1240         CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1241   }
1242   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1243                                    IsOffloadEntry, CodeGen);
1244   IsInTTDRegion = false;
1245 }
1246 
1247 void CGOpenMPRuntimeGPU::emitSPMDEntryHeader(
1248     CodeGenFunction &CGF, EntryFunctionState &EST,
1249     const OMPExecutableDirective &D) {
1250   CGBuilderTy &Bld = CGF.Builder;
1251 
1252   // Setup BBs in entry function.
1253   llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1254   EST.ExitBB = CGF.createBasicBlock(".exit");
1255 
1256   llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1257                          /*RequiresOMPRuntime=*/
1258                          Bld.getInt16(RequiresFullRuntime ? 1 : 0)};
1259   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1260                           CGM.getModule(), OMPRTL___kmpc_spmd_kernel_init),
1261                       Args);
1262 
1263   if (RequiresFullRuntime) {
1264     // For data sharing, we need to initialize the stack.
1265     CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1266         CGM.getModule(), OMPRTL___kmpc_data_sharing_init_stack_spmd));
1267   }
1268 
1269   CGF.EmitBranch(ExecuteBB);
1270 
1271   CGF.EmitBlock(ExecuteBB);
1272 
1273   IsInTargetMasterThreadRegion = true;
1274 }
1275 
1276 void CGOpenMPRuntimeGPU::emitSPMDEntryFooter(CodeGenFunction &CGF,
1277                                                EntryFunctionState &EST) {
1278   IsInTargetMasterThreadRegion = false;
1279   if (!CGF.HaveInsertPoint())
1280     return;
1281 
1282   if (!EST.ExitBB)
1283     EST.ExitBB = CGF.createBasicBlock(".exit");
1284 
1285   llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1286   CGF.EmitBranch(OMPDeInitBB);
1287 
1288   CGF.EmitBlock(OMPDeInitBB);
1289   // DeInitialize the OMP state in the runtime; called by all active threads.
1290   llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1291                          CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
1292   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1293                           CGM.getModule(), OMPRTL___kmpc_spmd_kernel_deinit_v2),
1294                       Args);
1295   CGF.EmitBranch(EST.ExitBB);
1296 
1297   CGF.EmitBlock(EST.ExitBB);
1298   EST.ExitBB = nullptr;
1299 }
1300 
1301 // Create a unique global variable to indicate the execution mode of this target
1302 // region. The execution mode is either 'generic', or 'spmd' depending on the
1303 // target directive. This variable is picked up by the offload library to setup
1304 // the device appropriately before kernel launch. If the execution mode is
1305 // 'generic', the runtime reserves one warp for the master, otherwise, all
1306 // warps participate in parallel work.
1307 static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
1308                                      bool Mode) {
1309   auto *GVMode =
1310       new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1311                                llvm::GlobalValue::WeakAnyLinkage,
1312                                llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1313                                Twine(Name, "_exec_mode"));
1314   CGM.addCompilerUsedGlobal(GVMode);
1315 }
1316 
1317 void CGOpenMPRuntimeGPU::emitWorkerFunction(WorkerFunctionState &WST) {
1318   ASTContext &Ctx = CGM.getContext();
1319 
1320   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
1321   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
1322                     WST.Loc, WST.Loc);
1323   emitWorkerLoop(CGF, WST);
1324   CGF.FinishFunction();
1325 }
1326 
1327 void CGOpenMPRuntimeGPU::emitWorkerLoop(CodeGenFunction &CGF,
1328                                         WorkerFunctionState &WST) {
1329   //
1330   // The workers enter this loop and wait for parallel work from the master.
1331   // When the master encounters a parallel region it sets up the work + variable
1332   // arguments, and wakes up the workers.  The workers first check to see if
1333   // they are required for the parallel region, i.e., within the # of requested
1334   // parallel threads.  The activated workers load the variable arguments and
1335   // execute the parallel work.
1336   //
1337 
1338   CGBuilderTy &Bld = CGF.Builder;
1339 
1340   llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1341   llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1342   llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1343   llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1344   llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1345   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1346 
1347   CGF.EmitBranch(AwaitBB);
1348 
1349   // Workers wait for work from master.
1350   CGF.EmitBlock(AwaitBB);
1351   // Wait for parallel work
1352   syncCTAThreads(CGF);
1353 
1354   Address WorkFn =
1355       CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1356   Address ExecStatus =
1357       CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1358   CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1359   CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1360 
1361   // TODO: Optimize runtime initialization and pass in correct value.
1362   llvm::Value *Args[] = {WorkFn.getPointer()};
1363   llvm::Value *Ret =
1364       CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1365                               CGM.getModule(), OMPRTL___kmpc_kernel_parallel),
1366                           Args);
1367   Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
1368 
1369   // On termination condition (workid == 0), exit loop.
1370   llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1371   llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
1372   Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1373 
1374   // Activate requested workers.
1375   CGF.EmitBlock(SelectWorkersBB);
1376   llvm::Value *IsActive =
1377       Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1378   Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
1379 
1380   // Signal start of parallel region.
1381   CGF.EmitBlock(ExecuteBB);
1382   // Skip initialization.
1383   setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1384 
1385   // Process work items: outlined parallel functions.
1386   for (llvm::Function *W : Work) {
1387     // Try to match this outlined function.
1388     llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
1389 
1390     llvm::Value *WorkFnMatch =
1391         Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1392 
1393     llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1394     llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1395     Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1396 
1397     // Execute this outlined function.
1398     CGF.EmitBlock(ExecuteFNBB);
1399 
1400     // Insert call to work function via shared wrapper. The shared
1401     // wrapper takes two arguments:
1402     //   - the parallelism level;
1403     //   - the thread ID;
1404     emitCall(CGF, WST.Loc, W,
1405              {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1406 
1407     // Go to end of parallel region.
1408     CGF.EmitBranch(TerminateBB);
1409 
1410     CGF.EmitBlock(CheckNextBB);
1411   }
1412   // Default case: call to outlined function through pointer if the target
1413   // region makes a declare target call that may contain an orphaned parallel
1414   // directive.
1415   auto *ParallelFnTy =
1416       llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1417                               /*isVarArg=*/false);
1418   llvm::Value *WorkFnCast =
1419       Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
1420   // Insert call to work function via shared wrapper. The shared
1421   // wrapper takes two arguments:
1422   //   - the parallelism level;
1423   //   - the thread ID;
1424   emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
1425            {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1426   // Go to end of parallel region.
1427   CGF.EmitBranch(TerminateBB);
1428 
1429   // Signal end of parallel region.
1430   CGF.EmitBlock(TerminateBB);
1431   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1432                           CGM.getModule(), OMPRTL___kmpc_kernel_end_parallel),
1433                       llvm::None);
1434   CGF.EmitBranch(BarrierBB);
1435 
1436   // All active and inactive workers wait at a barrier after parallel region.
1437   CGF.EmitBlock(BarrierBB);
1438   // Barrier after parallel region.
1439   syncCTAThreads(CGF);
1440   CGF.EmitBranch(AwaitBB);
1441 
1442   // Exit target region.
1443   CGF.EmitBlock(ExitBB);
1444   // Skip initialization.
1445   clearLocThreadIdInsertPt(CGF);
1446 }
1447 
1448 void CGOpenMPRuntimeGPU::createOffloadEntry(llvm::Constant *ID,
1449                                               llvm::Constant *Addr,
1450                                               uint64_t Size, int32_t,
1451                                               llvm::GlobalValue::LinkageTypes) {
1452   // TODO: Add support for global variables on the device after declare target
1453   // support.
1454   if (!isa<llvm::Function>(Addr))
1455     return;
1456   llvm::Module &M = CGM.getModule();
1457   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1458 
1459   // Get "nvvm.annotations" metadata node
1460   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1461 
1462   llvm::Metadata *MDVals[] = {
1463       llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
1464       llvm::ConstantAsMetadata::get(
1465           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1466   // Append metadata to nvvm.annotations
1467   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1468 }
1469 
1470 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
1471     const OMPExecutableDirective &D, StringRef ParentName,
1472     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
1473     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
1474   if (!IsOffloadEntry) // Nothing to do.
1475     return;
1476 
1477   assert(!ParentName.empty() && "Invalid target region parent name!");
1478 
1479   bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
1480   if (Mode)
1481     emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1482                    CodeGen);
1483   else
1484     emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1485                       CodeGen);
1486 
1487   setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
1488 }
1489 
1490 namespace {
1491 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1492 /// Enum for accesseing the reserved_2 field of the ident_t struct.
1493 enum ModeFlagsTy : unsigned {
1494   /// Bit set to 1 when in SPMD mode.
1495   KMP_IDENT_SPMD_MODE = 0x01,
1496   /// Bit set to 1 when a simplified runtime is used.
1497   KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1498   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1499 };
1500 
1501 /// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1502 static const ModeFlagsTy UndefinedMode =
1503     (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1504 } // anonymous namespace
1505 
1506 unsigned CGOpenMPRuntimeGPU::getDefaultLocationReserved2Flags() const {
1507   switch (getExecutionMode()) {
1508   case EM_SPMD:
1509     if (requiresFullRuntime())
1510       return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1511     return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1512   case EM_NonSPMD:
1513     assert(requiresFullRuntime() && "Expected full runtime.");
1514     return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1515   case EM_Unknown:
1516     return UndefinedMode;
1517   }
1518   llvm_unreachable("Unknown flags are requested.");
1519 }
1520 
1521 CGOpenMPRuntimeGPU::CGOpenMPRuntimeGPU(CodeGenModule &CGM)
1522     : CGOpenMPRuntime(CGM, "_", "$") {
1523   if (!CGM.getLangOpts().OpenMPIsDevice)
1524     llvm_unreachable("OpenMP NVPTX can only handle device code.");
1525 }
1526 
1527 void CGOpenMPRuntimeGPU::emitProcBindClause(CodeGenFunction &CGF,
1528                                               ProcBindKind ProcBind,
1529                                               SourceLocation Loc) {
1530   // Do nothing in case of SPMD mode and L0 parallel.
1531   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1532     return;
1533 
1534   CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1535 }
1536 
1537 void CGOpenMPRuntimeGPU::emitNumThreadsClause(CodeGenFunction &CGF,
1538                                                 llvm::Value *NumThreads,
1539                                                 SourceLocation Loc) {
1540   // Do nothing in case of SPMD mode and L0 parallel.
1541   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1542     return;
1543 
1544   CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1545 }
1546 
1547 void CGOpenMPRuntimeGPU::emitNumTeamsClause(CodeGenFunction &CGF,
1548                                               const Expr *NumTeams,
1549                                               const Expr *ThreadLimit,
1550                                               SourceLocation Loc) {}
1551 
1552 llvm::Function *CGOpenMPRuntimeGPU::emitParallelOutlinedFunction(
1553     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1554     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1555   // Emit target region as a standalone region.
1556   class NVPTXPrePostActionTy : public PrePostActionTy {
1557     bool &IsInParallelRegion;
1558     bool PrevIsInParallelRegion;
1559 
1560   public:
1561     NVPTXPrePostActionTy(bool &IsInParallelRegion)
1562         : IsInParallelRegion(IsInParallelRegion) {}
1563     void Enter(CodeGenFunction &CGF) override {
1564       PrevIsInParallelRegion = IsInParallelRegion;
1565       IsInParallelRegion = true;
1566     }
1567     void Exit(CodeGenFunction &CGF) override {
1568       IsInParallelRegion = PrevIsInParallelRegion;
1569     }
1570   } Action(IsInParallelRegion);
1571   CodeGen.setAction(Action);
1572   bool PrevIsInTTDRegion = IsInTTDRegion;
1573   IsInTTDRegion = false;
1574   bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1575   IsInTargetMasterThreadRegion = false;
1576   auto *OutlinedFun =
1577       cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1578           D, ThreadIDVar, InnermostKind, CodeGen));
1579   IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
1580   IsInTTDRegion = PrevIsInTTDRegion;
1581   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD &&
1582       !IsInParallelRegion) {
1583     llvm::Function *WrapperFun =
1584         createParallelDataSharingWrapper(OutlinedFun, D);
1585     WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1586   }
1587 
1588   return OutlinedFun;
1589 }
1590 
1591 /// Get list of lastprivate variables from the teams distribute ... or
1592 /// teams {distribute ...} directives.
1593 static void
1594 getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1595                              llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1596   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1597          "expected teams directive.");
1598   const OMPExecutableDirective *Dir = &D;
1599   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1600     if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
1601             Ctx,
1602             D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1603                 /*IgnoreCaptured=*/true))) {
1604       Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
1605       if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1606         Dir = nullptr;
1607     }
1608   }
1609   if (!Dir)
1610     return;
1611   for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
1612     for (const Expr *E : C->getVarRefs())
1613       Vars.push_back(getPrivateItem(E));
1614   }
1615 }
1616 
1617 /// Get list of reduction variables from the teams ... directives.
1618 static void
1619 getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1620                       llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1621   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1622          "expected teams directive.");
1623   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1624     for (const Expr *E : C->privates())
1625       Vars.push_back(getPrivateItem(E));
1626   }
1627 }
1628 
1629 llvm::Function *CGOpenMPRuntimeGPU::emitTeamsOutlinedFunction(
1630     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1631     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1632   SourceLocation Loc = D.getBeginLoc();
1633 
1634   const RecordDecl *GlobalizedRD = nullptr;
1635   llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
1636   llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1637   unsigned WarpSize = CGM.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
1638   // Globalize team reductions variable unconditionally in all modes.
1639   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1640     getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
1641   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
1642     getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1643     if (!LastPrivatesReductions.empty()) {
1644       GlobalizedRD = ::buildRecordForGlobalizedVars(
1645           CGM.getContext(), llvm::None, LastPrivatesReductions,
1646           MappedDeclsFields, WarpSize);
1647     }
1648   } else if (!LastPrivatesReductions.empty()) {
1649     assert(!TeamAndReductions.first &&
1650            "Previous team declaration is not expected.");
1651     TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
1652     std::swap(TeamAndReductions.second, LastPrivatesReductions);
1653   }
1654 
1655   // Emit target region as a standalone region.
1656   class NVPTXPrePostActionTy : public PrePostActionTy {
1657     SourceLocation &Loc;
1658     const RecordDecl *GlobalizedRD;
1659     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1660         &MappedDeclsFields;
1661 
1662   public:
1663     NVPTXPrePostActionTy(
1664         SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1665         llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1666             &MappedDeclsFields)
1667         : Loc(Loc), GlobalizedRD(GlobalizedRD),
1668           MappedDeclsFields(MappedDeclsFields) {}
1669     void Enter(CodeGenFunction &CGF) override {
1670       auto &Rt =
1671           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1672       if (GlobalizedRD) {
1673         auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1674         I->getSecond().GlobalRecord = GlobalizedRD;
1675         I->getSecond().MappedParams =
1676             std::make_unique<CodeGenFunction::OMPMapVars>();
1677         DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1678         for (const auto &Pair : MappedDeclsFields) {
1679           assert(Pair.getFirst()->isCanonicalDecl() &&
1680                  "Expected canonical declaration");
1681           Data.insert(std::make_pair(Pair.getFirst(),
1682                                      MappedVarData(Pair.getSecond(),
1683                                                    /*IsOnePerTeam=*/true)));
1684         }
1685       }
1686       Rt.emitGenericVarsProlog(CGF, Loc);
1687     }
1688     void Exit(CodeGenFunction &CGF) override {
1689       static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
1690           .emitGenericVarsEpilog(CGF);
1691     }
1692   } Action(Loc, GlobalizedRD, MappedDeclsFields);
1693   CodeGen.setAction(Action);
1694   llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1695       D, ThreadIDVar, InnermostKind, CodeGen);
1696 
1697   return OutlinedFun;
1698 }
1699 
1700 void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
1701                                                  SourceLocation Loc,
1702                                                  bool WithSPMDCheck) {
1703   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
1704       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1705     return;
1706 
1707   CGBuilderTy &Bld = CGF.Builder;
1708 
1709   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1710   if (I == FunctionGlobalizedDecls.end())
1711     return;
1712   if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
1713     QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
1714     QualType SecGlobalRecTy;
1715 
1716     // Recover pointer to this function's global record. The runtime will
1717     // handle the specifics of the allocation of the memory.
1718     // Use actual memory size of the record including the padding
1719     // for alignment purposes.
1720     unsigned Alignment =
1721         CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
1722     unsigned GlobalRecordSize =
1723         CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
1724     GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
1725 
1726     llvm::PointerType *GlobalRecPtrTy =
1727         CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
1728     llvm::Value *GlobalRecCastAddr;
1729     llvm::Value *IsTTD = nullptr;
1730     if (!IsInTTDRegion &&
1731         (WithSPMDCheck ||
1732          getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
1733       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1734       llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
1735       llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
1736       if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
1737         llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1738         llvm::Value *ThreadID = getThreadID(CGF, Loc);
1739         llvm::Value *PL = CGF.EmitRuntimeCall(
1740             OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
1741                                                   OMPRTL___kmpc_parallel_level),
1742             {RTLoc, ThreadID});
1743         IsTTD = Bld.CreateIsNull(PL);
1744       }
1745       llvm::Value *IsSPMD = Bld.CreateIsNotNull(
1746           CGF.EmitNounwindRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1747               CGM.getModule(), OMPRTL___kmpc_is_spmd_exec_mode)));
1748       Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
1749       // There is no need to emit line number for unconditional branch.
1750       (void)ApplyDebugLocation::CreateEmpty(CGF);
1751       CGF.EmitBlock(SPMDBB);
1752       Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
1753                                CharUnits::fromQuantity(Alignment));
1754       CGF.EmitBranch(ExitBB);
1755       // There is no need to emit line number for unconditional branch.
1756       (void)ApplyDebugLocation::CreateEmpty(CGF);
1757       CGF.EmitBlock(NonSPMDBB);
1758       llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
1759       if (const RecordDecl *SecGlobalizedVarsRecord =
1760               I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
1761         SecGlobalRecTy =
1762             CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
1763 
1764         // Recover pointer to this function's global record. The runtime will
1765         // handle the specifics of the allocation of the memory.
1766         // Use actual memory size of the record including the padding
1767         // for alignment purposes.
1768         unsigned Alignment =
1769             CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
1770         unsigned GlobalRecordSize =
1771             CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
1772         GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
1773         Size = Bld.CreateSelect(
1774             IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
1775       }
1776       // TODO: allow the usage of shared memory to be controlled by
1777       // the user, for now, default to global.
1778       llvm::Value *GlobalRecordSizeArg[] = {
1779           Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1780       llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1781           OMPBuilder.getOrCreateRuntimeFunction(
1782               CGM.getModule(), OMPRTL___kmpc_data_sharing_coalesced_push_stack),
1783           GlobalRecordSizeArg);
1784       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1785           GlobalRecValue, GlobalRecPtrTy);
1786       CGF.EmitBlock(ExitBB);
1787       auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
1788                                 /*NumReservedValues=*/2, "_select_stack");
1789       Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
1790       Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
1791       GlobalRecCastAddr = Phi;
1792       I->getSecond().GlobalRecordAddr = Phi;
1793       I->getSecond().IsInSPMDModeFlag = IsSPMD;
1794     } else if (!CGM.getLangOpts().OpenMPCUDATargetParallel && IsInTTDRegion) {
1795       assert(GlobalizedRecords.back().Records.size() < 2 &&
1796              "Expected less than 2 globalized records: one for target and one "
1797              "for teams.");
1798       unsigned Offset = 0;
1799       for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
1800         QualType RDTy = CGM.getContext().getRecordType(RD);
1801         unsigned Alignment =
1802             CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
1803         unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
1804         Offset =
1805             llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
1806       }
1807       unsigned Alignment =
1808           CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
1809       Offset = llvm::alignTo(Offset, Alignment);
1810       GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
1811       ++GlobalizedRecords.back().RegionCounter;
1812       if (GlobalizedRecords.back().Records.size() == 1) {
1813         assert(KernelStaticGlobalized &&
1814                "Kernel static pointer must be initialized already.");
1815         auto *UseSharedMemory = new llvm::GlobalVariable(
1816             CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
1817             llvm::GlobalValue::InternalLinkage, nullptr,
1818             "_openmp_static_kernel$is_shared");
1819         UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1820         QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
1821             /*DestWidth=*/16, /*Signed=*/0);
1822         llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
1823             Address(UseSharedMemory,
1824                     CGM.getContext().getTypeAlignInChars(Int16Ty)),
1825             /*Volatile=*/false, Int16Ty, Loc);
1826         auto *StaticGlobalized = new llvm::GlobalVariable(
1827             CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
1828             llvm::GlobalValue::CommonLinkage, nullptr);
1829         auto *RecSize = new llvm::GlobalVariable(
1830             CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
1831             llvm::GlobalValue::InternalLinkage, nullptr,
1832             "_openmp_static_kernel$size");
1833         RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1834         llvm::Value *Ld = CGF.EmitLoadOfScalar(
1835             Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
1836             CGM.getContext().getSizeType(), Loc);
1837         llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1838             KernelStaticGlobalized, CGM.VoidPtrPtrTy);
1839         llvm::Value *GlobalRecordSizeArg[] = {
1840             llvm::ConstantInt::get(
1841                 CGM.Int16Ty,
1842                 getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD ? 1 : 0),
1843             StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
1844         CGF.EmitRuntimeCall(
1845             OMPBuilder.getOrCreateRuntimeFunction(
1846                 CGM.getModule(), OMPRTL___kmpc_get_team_static_memory),
1847             GlobalRecordSizeArg);
1848         GlobalizedRecords.back().Buffer = StaticGlobalized;
1849         GlobalizedRecords.back().RecSize = RecSize;
1850         GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
1851         GlobalizedRecords.back().Loc = Loc;
1852       }
1853       assert(KernelStaticGlobalized && "Global address must be set already.");
1854       Address FrameAddr = CGF.EmitLoadOfPointer(
1855           Address(KernelStaticGlobalized, CGM.getPointerAlign()),
1856           CGM.getContext()
1857               .getPointerType(CGM.getContext().VoidPtrTy)
1858               .castAs<PointerType>());
1859       llvm::Value *GlobalRecValue =
1860           Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
1861       I->getSecond().GlobalRecordAddr = GlobalRecValue;
1862       I->getSecond().IsInSPMDModeFlag = nullptr;
1863       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1864           GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
1865     } else {
1866       // TODO: allow the usage of shared memory to be controlled by
1867       // the user, for now, default to global.
1868       bool UseSharedMemory =
1869           IsInTTDRegion && GlobalRecordSize <= SharedMemorySize;
1870       llvm::Value *GlobalRecordSizeArg[] = {
1871           llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
1872           CGF.Builder.getInt16(UseSharedMemory ? 1 : 0)};
1873       llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1874           OMPBuilder.getOrCreateRuntimeFunction(
1875               CGM.getModule(),
1876               IsInTTDRegion ? OMPRTL___kmpc_data_sharing_push_stack
1877                             : OMPRTL___kmpc_data_sharing_coalesced_push_stack),
1878           GlobalRecordSizeArg);
1879       GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1880           GlobalRecValue, GlobalRecPtrTy);
1881       I->getSecond().GlobalRecordAddr = GlobalRecValue;
1882       I->getSecond().IsInSPMDModeFlag = nullptr;
1883     }
1884     LValue Base =
1885         CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
1886 
1887     // Emit the "global alloca" which is a GEP from the global declaration
1888     // record using the pointer returned by the runtime.
1889     LValue SecBase;
1890     decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
1891     if (IsTTD) {
1892       SecIt = I->getSecond().SecondaryLocalVarData->begin();
1893       llvm::PointerType *SecGlobalRecPtrTy =
1894           CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
1895       SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
1896           Bld.CreatePointerBitCastOrAddrSpaceCast(
1897               I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
1898           SecGlobalRecTy);
1899     }
1900     for (auto &Rec : I->getSecond().LocalVarData) {
1901       bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1902       llvm::Value *ParValue;
1903       if (EscapedParam) {
1904         const auto *VD = cast<VarDecl>(Rec.first);
1905         LValue ParLVal =
1906             CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1907         ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1908       }
1909       LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
1910       // Emit VarAddr basing on lane-id if required.
1911       QualType VarTy;
1912       if (Rec.second.IsOnePerTeam) {
1913         VarTy = Rec.second.FD->getType();
1914       } else {
1915         Address Addr = VarAddr.getAddress(CGF);
1916         llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
1917             Addr.getElementType(), Addr.getPointer(),
1918             {Bld.getInt32(0), getNVPTXLaneID(CGF)});
1919         VarTy =
1920             Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
1921         VarAddr = CGF.MakeAddrLValue(
1922             Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
1923             AlignmentSource::Decl);
1924       }
1925       Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
1926       if (!IsInTTDRegion &&
1927           (WithSPMDCheck ||
1928            getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
1929         assert(I->getSecond().IsInSPMDModeFlag &&
1930                "Expected unknown execution mode or required SPMD check.");
1931         if (IsTTD) {
1932           assert(SecIt->second.IsOnePerTeam &&
1933                  "Secondary glob data must be one per team.");
1934           LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
1935           VarAddr.setAddress(
1936               Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(CGF),
1937                                        VarAddr.getPointer(CGF)),
1938                       VarAddr.getAlignment()));
1939           Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
1940         }
1941         Address GlobalPtr = Rec.second.PrivateAddr;
1942         Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
1943         Rec.second.PrivateAddr = Address(
1944             Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
1945                              LocalAddr.getPointer(), GlobalPtr.getPointer()),
1946             LocalAddr.getAlignment());
1947       }
1948       if (EscapedParam) {
1949         const auto *VD = cast<VarDecl>(Rec.first);
1950         CGF.EmitStoreOfScalar(ParValue, VarAddr);
1951         I->getSecond().MappedParams->setVarAddr(CGF, VD,
1952                                                 VarAddr.getAddress(CGF));
1953       }
1954       if (IsTTD)
1955         ++SecIt;
1956     }
1957   }
1958   for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
1959     // Recover pointer to this function's global record. The runtime will
1960     // handle the specifics of the allocation of the memory.
1961     // Use actual memory size of the record including the padding
1962     // for alignment purposes.
1963     CGBuilderTy &Bld = CGF.Builder;
1964     llvm::Value *Size = CGF.getTypeSize(VD->getType());
1965     CharUnits Align = CGM.getContext().getDeclAlign(VD);
1966     Size = Bld.CreateNUWAdd(
1967         Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1968     llvm::Value *AlignVal =
1969         llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1970     Size = Bld.CreateUDiv(Size, AlignVal);
1971     Size = Bld.CreateNUWMul(Size, AlignVal);
1972     // TODO: allow the usage of shared memory to be controlled by
1973     // the user, for now, default to global.
1974     llvm::Value *GlobalRecordSizeArg[] = {
1975         Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
1976     llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
1977         OMPBuilder.getOrCreateRuntimeFunction(
1978             CGM.getModule(), OMPRTL___kmpc_data_sharing_coalesced_push_stack),
1979         GlobalRecordSizeArg);
1980     llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1981         GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
1982     LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
1983                                      CGM.getContext().getDeclAlign(VD),
1984                                      AlignmentSource::Decl);
1985     I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1986                                             Base.getAddress(CGF));
1987     I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
1988   }
1989   I->getSecond().MappedParams->apply(CGF);
1990 }
1991 
1992 void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF,
1993                                                  bool WithSPMDCheck) {
1994   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
1995       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1996     return;
1997 
1998   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1999   if (I != FunctionGlobalizedDecls.end()) {
2000     I->getSecond().MappedParams->restore(CGF);
2001     if (!CGF.HaveInsertPoint())
2002       return;
2003     for (llvm::Value *Addr :
2004          llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2005       CGF.EmitRuntimeCall(
2006           OMPBuilder.getOrCreateRuntimeFunction(
2007               CGM.getModule(), OMPRTL___kmpc_data_sharing_pop_stack),
2008           Addr);
2009     }
2010     if (I->getSecond().GlobalRecordAddr) {
2011       if (!IsInTTDRegion &&
2012           (WithSPMDCheck ||
2013            getExecutionMode() == CGOpenMPRuntimeGPU::EM_Unknown)) {
2014         CGBuilderTy &Bld = CGF.Builder;
2015         llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2016         llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2017         Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2018         // There is no need to emit line number for unconditional branch.
2019         (void)ApplyDebugLocation::CreateEmpty(CGF);
2020         CGF.EmitBlock(NonSPMDBB);
2021         CGF.EmitRuntimeCall(
2022             OMPBuilder.getOrCreateRuntimeFunction(
2023                 CGM.getModule(), OMPRTL___kmpc_data_sharing_pop_stack),
2024             CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2025         CGF.EmitBlock(ExitBB);
2026       } else if (!CGM.getLangOpts().OpenMPCUDATargetParallel && IsInTTDRegion) {
2027         assert(GlobalizedRecords.back().RegionCounter > 0 &&
2028                "region counter must be > 0.");
2029         --GlobalizedRecords.back().RegionCounter;
2030         // Emit the restore function only in the target region.
2031         if (GlobalizedRecords.back().RegionCounter == 0) {
2032           QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2033               /*DestWidth=*/16, /*Signed=*/0);
2034           llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2035               Address(GlobalizedRecords.back().UseSharedMemory,
2036                       CGM.getContext().getTypeAlignInChars(Int16Ty)),
2037               /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
2038           llvm::Value *Args[] = {
2039               llvm::ConstantInt::get(
2040                   CGM.Int16Ty,
2041                   getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD ? 1 : 0),
2042               IsInSharedMemory};
2043           CGF.EmitRuntimeCall(
2044               OMPBuilder.getOrCreateRuntimeFunction(
2045                   CGM.getModule(), OMPRTL___kmpc_restore_team_static_memory),
2046               Args);
2047         }
2048       } else {
2049         CGF.EmitRuntimeCall(
2050             OMPBuilder.getOrCreateRuntimeFunction(
2051                 CGM.getModule(), OMPRTL___kmpc_data_sharing_pop_stack),
2052             I->getSecond().GlobalRecordAddr);
2053       }
2054     }
2055   }
2056 }
2057 
2058 void CGOpenMPRuntimeGPU::emitTeamsCall(CodeGenFunction &CGF,
2059                                          const OMPExecutableDirective &D,
2060                                          SourceLocation Loc,
2061                                          llvm::Function *OutlinedFn,
2062                                          ArrayRef<llvm::Value *> CapturedVars) {
2063   if (!CGF.HaveInsertPoint())
2064     return;
2065 
2066   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2067                                                       /*Name=*/".zero.addr");
2068   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2069   llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2070   OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
2071   OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2072   OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2073   emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2074 }
2075 
2076 void CGOpenMPRuntimeGPU::emitParallelCall(
2077     CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2078     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2079   if (!CGF.HaveInsertPoint())
2080     return;
2081 
2082   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
2083     emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2084   else
2085     emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
2086 }
2087 
2088 void CGOpenMPRuntimeGPU::emitNonSPMDParallelCall(
2089     CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2090     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2091   llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
2092 
2093   // Force inline this outlined function at its call site.
2094   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2095 
2096   // Ensure we do not inline the function. This is trivially true for the ones
2097   // passed to __kmpc_fork_call but the ones calles in serialized regions
2098   // could be inlined. This is not a perfect but it is closer to the invariant
2099   // we want, namely, every data environment starts with a new function.
2100   // TODO: We should pass the if condition to the runtime function and do the
2101   //       handling there. Much cleaner code.
2102   cast<llvm::Function>(OutlinedFn)->addFnAttr(llvm::Attribute::NoInline);
2103 
2104   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2105                                                       /*Name=*/".zero.addr");
2106   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2107   // ThreadId for serialized parallels is 0.
2108   Address ThreadIDAddr = ZeroAddr;
2109   auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
2110                        CodeGenFunction &CGF, PrePostActionTy &Action) {
2111     Action.Enter(CGF);
2112 
2113     Address ZeroAddr =
2114         CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2115                                          /*Name=*/".bound.zero.addr");
2116     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2117     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2118     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2119     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2120     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2121     emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2122   };
2123   auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2124                                         PrePostActionTy &) {
2125 
2126     RegionCodeGenTy RCG(CodeGen);
2127     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2128     llvm::Value *ThreadID = getThreadID(CGF, Loc);
2129     llvm::Value *Args[] = {RTLoc, ThreadID};
2130 
2131     NVPTXActionTy Action(
2132         OMPBuilder.getOrCreateRuntimeFunction(
2133             CGM.getModule(), OMPRTL___kmpc_serialized_parallel),
2134         Args,
2135         OMPBuilder.getOrCreateRuntimeFunction(
2136             CGM.getModule(), OMPRTL___kmpc_end_serialized_parallel),
2137         Args);
2138     RCG.setAction(Action);
2139     RCG(CGF);
2140   };
2141 
2142   auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2143                                                   PrePostActionTy &Action) {
2144     CGBuilderTy &Bld = CGF.Builder;
2145     llvm::Function *WFn = WrapperFunctionsMap[Fn];
2146     assert(WFn && "Wrapper function does not exist!");
2147     llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2148 
2149     // Prepare for parallel region. Indicate the outlined function.
2150     llvm::Value *Args[] = {ID};
2151     CGF.EmitRuntimeCall(
2152         OMPBuilder.getOrCreateRuntimeFunction(
2153             CGM.getModule(), OMPRTL___kmpc_kernel_prepare_parallel),
2154         Args);
2155 
2156     // Create a private scope that will globalize the arguments
2157     // passed from the outside of the target region.
2158     CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2159 
2160     // There's something to share.
2161     if (!CapturedVars.empty()) {
2162       // Prepare for parallel region. Indicate the outlined function.
2163       Address SharedArgs =
2164           CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2165       llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2166 
2167       llvm::Value *DataSharingArgs[] = {
2168           SharedArgsPtr,
2169           llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2170       CGF.EmitRuntimeCall(
2171           OMPBuilder.getOrCreateRuntimeFunction(
2172               CGM.getModule(), OMPRTL___kmpc_begin_sharing_variables),
2173           DataSharingArgs);
2174 
2175       // Store variable address in a list of references to pass to workers.
2176       unsigned Idx = 0;
2177       ASTContext &Ctx = CGF.getContext();
2178       Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2179           SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2180                           .castAs<PointerType>());
2181       for (llvm::Value *V : CapturedVars) {
2182         Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
2183         llvm::Value *PtrV;
2184         if (V->getType()->isIntegerTy())
2185           PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2186         else
2187           PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
2188         CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2189                               Ctx.getPointerType(Ctx.VoidPtrTy));
2190         ++Idx;
2191       }
2192     }
2193 
2194     // Activate workers. This barrier is used by the master to signal
2195     // work for the workers.
2196     syncCTAThreads(CGF);
2197 
2198     // OpenMP [2.5, Parallel Construct, p.49]
2199     // There is an implied barrier at the end of a parallel region. After the
2200     // end of a parallel region, only the master thread of the team resumes
2201     // execution of the enclosing task region.
2202     //
2203     // The master waits at this barrier until all workers are done.
2204     syncCTAThreads(CGF);
2205 
2206     if (!CapturedVars.empty())
2207       CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2208           CGM.getModule(), OMPRTL___kmpc_end_sharing_variables));
2209 
2210     // Remember for post-processing in worker loop.
2211     Work.emplace_back(WFn);
2212   };
2213 
2214   auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2215                              CodeGenFunction &CGF, PrePostActionTy &Action) {
2216     if (IsInParallelRegion) {
2217       SeqGen(CGF, Action);
2218     } else if (IsInTargetMasterThreadRegion) {
2219       L0ParallelGen(CGF, Action);
2220     } else {
2221       // Check for master and then parallelism:
2222       // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
2223       //   Serialized execution.
2224       // } else {
2225       //   Worker call.
2226       // }
2227       CGBuilderTy &Bld = CGF.Builder;
2228       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2229       llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2230       llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
2231       llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
2232       llvm::Value *IsSPMD = Bld.CreateIsNotNull(
2233           CGF.EmitNounwindRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2234               CGM.getModule(), OMPRTL___kmpc_is_spmd_exec_mode)));
2235       Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
2236       // There is no need to emit line number for unconditional branch.
2237       (void)ApplyDebugLocation::CreateEmpty(CGF);
2238       CGF.EmitBlock(ParallelCheckBB);
2239       llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2240       llvm::Value *ThreadID = getThreadID(CGF, Loc);
2241       llvm::Value *PL = CGF.EmitRuntimeCall(
2242           OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2243                                                 OMPRTL___kmpc_parallel_level),
2244           {RTLoc, ThreadID});
2245       llvm::Value *Res = Bld.CreateIsNotNull(PL);
2246       Bld.CreateCondBr(Res, SeqBB, MasterBB);
2247       CGF.EmitBlock(SeqBB);
2248       SeqGen(CGF, Action);
2249       CGF.EmitBranch(ExitBB);
2250       // There is no need to emit line number for unconditional branch.
2251       (void)ApplyDebugLocation::CreateEmpty(CGF);
2252       CGF.EmitBlock(MasterBB);
2253       L0ParallelGen(CGF, Action);
2254       CGF.EmitBranch(ExitBB);
2255       // There is no need to emit line number for unconditional branch.
2256       (void)ApplyDebugLocation::CreateEmpty(CGF);
2257       // Emit the continuation block for code after the if.
2258       CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2259     }
2260   };
2261 
2262   if (IfCond) {
2263     emitIfClause(CGF, IfCond, LNParallelGen, SeqGen);
2264   } else {
2265     CodeGenFunction::RunCleanupsScope Scope(CGF);
2266     RegionCodeGenTy ThenRCG(LNParallelGen);
2267     ThenRCG(CGF);
2268   }
2269 }
2270 
2271 void CGOpenMPRuntimeGPU::emitSPMDParallelCall(
2272     CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
2273     ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2274   // Just call the outlined function to execute the parallel region.
2275   // OutlinedFn(&GTid, &zero, CapturedStruct);
2276   //
2277   llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2278 
2279   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2280                                                       /*Name=*/".zero.addr");
2281   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2282   // ThreadId for serialized parallels is 0.
2283   Address ThreadIDAddr = ZeroAddr;
2284   auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2285                        CodeGenFunction &CGF, PrePostActionTy &Action) {
2286     Action.Enter(CGF);
2287 
2288     Address ZeroAddr =
2289         CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2290                                          /*Name=*/".bound.zero.addr");
2291     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2292     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2293     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2294     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2295     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2296     emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2297   };
2298   auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2299                                         PrePostActionTy &) {
2300 
2301     RegionCodeGenTy RCG(CodeGen);
2302     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2303     llvm::Value *ThreadID = getThreadID(CGF, Loc);
2304     llvm::Value *Args[] = {RTLoc, ThreadID};
2305 
2306     NVPTXActionTy Action(
2307         OMPBuilder.getOrCreateRuntimeFunction(
2308             CGM.getModule(), OMPRTL___kmpc_serialized_parallel),
2309         Args,
2310         OMPBuilder.getOrCreateRuntimeFunction(
2311             CGM.getModule(), OMPRTL___kmpc_end_serialized_parallel),
2312         Args);
2313     RCG.setAction(Action);
2314     RCG(CGF);
2315   };
2316 
2317   if (IsInTargetMasterThreadRegion) {
2318     // In the worker need to use the real thread id.
2319     ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
2320     RegionCodeGenTy RCG(CodeGen);
2321     RCG(CGF);
2322   } else {
2323     // If we are not in the target region, it is definitely L2 parallelism or
2324     // more, because for SPMD mode we always has L1 parallel level, sowe don't
2325     // need to check for orphaned directives.
2326     RegionCodeGenTy RCG(SeqGen);
2327     RCG(CGF);
2328   }
2329 }
2330 
2331 void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
2332   // Always emit simple barriers!
2333   if (!CGF.HaveInsertPoint())
2334     return;
2335   // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2336   // This function does not use parameters, so we can emit just default values.
2337   llvm::Value *Args[] = {
2338       llvm::ConstantPointerNull::get(
2339           cast<llvm::PointerType>(getIdentTyPointerTy())),
2340       llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2341   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2342                           CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
2343                       Args);
2344 }
2345 
2346 void CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
2347                                            SourceLocation Loc,
2348                                            OpenMPDirectiveKind Kind, bool,
2349                                            bool) {
2350   // Always emit simple barriers!
2351   if (!CGF.HaveInsertPoint())
2352     return;
2353   // Build call __kmpc_cancel_barrier(loc, thread_id);
2354   unsigned Flags = getDefaultFlagsForBarriers(Kind);
2355   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2356                          getThreadID(CGF, Loc)};
2357 
2358   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2359                           CGM.getModule(), OMPRTL___kmpc_barrier),
2360                       Args);
2361 }
2362 
2363 void CGOpenMPRuntimeGPU::emitCriticalRegion(
2364     CodeGenFunction &CGF, StringRef CriticalName,
2365     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2366     const Expr *Hint) {
2367   llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2368   llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2369   llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2370   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2371   llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2372 
2373   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2374 
2375   // Get the mask of active threads in the warp.
2376   llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2377       CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
2378   // Fetch team-local id of the thread.
2379   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
2380 
2381   // Get the width of the team.
2382   llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
2383 
2384   // Initialize the counter variable for the loop.
2385   QualType Int32Ty =
2386       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2387   Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2388   LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2389   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2390                         /*isInit=*/true);
2391 
2392   // Block checks if loop counter exceeds upper bound.
2393   CGF.EmitBlock(LoopBB);
2394   llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2395   llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2396   CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2397 
2398   // Block tests which single thread should execute region, and which threads
2399   // should go straight to synchronisation point.
2400   CGF.EmitBlock(TestBB);
2401   CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2402   llvm::Value *CmpThreadToCounter =
2403       CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2404   CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2405 
2406   // Block emits the body of the critical region.
2407   CGF.EmitBlock(BodyBB);
2408 
2409   // Output the critical statement.
2410   CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2411                                       Hint);
2412 
2413   // After the body surrounded by the critical region, the single executing
2414   // thread will jump to the synchronisation point.
2415   // Block waits for all threads in current team to finish then increments the
2416   // counter variable and returns to the loop.
2417   CGF.EmitBlock(SyncBB);
2418   // Reconverge active threads in the warp.
2419   (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2420                                 CGM.getModule(), OMPRTL___kmpc_syncwarp),
2421                             Mask);
2422 
2423   llvm::Value *IncCounterVal =
2424       CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2425   CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2426   CGF.EmitBranch(LoopBB);
2427 
2428   // Block that is reached when  all threads in the team complete the region.
2429   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2430 }
2431 
2432 /// Cast value to the specified type.
2433 static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2434                                     QualType ValTy, QualType CastTy,
2435                                     SourceLocation Loc) {
2436   assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2437          "Cast type must sized.");
2438   assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2439          "Val type must sized.");
2440   llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2441   if (ValTy == CastTy)
2442     return Val;
2443   if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2444       CGF.getContext().getTypeSizeInChars(CastTy))
2445     return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2446   if (CastTy->isIntegerType() && ValTy->isIntegerType())
2447     return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2448                                      CastTy->hasSignedIntegerRepresentation());
2449   Address CastItem = CGF.CreateMemTemp(CastTy);
2450   Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2451       CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
2452   CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
2453                         LValueBaseInfo(AlignmentSource::Type),
2454                         TBAAAccessInfo());
2455   return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
2456                               LValueBaseInfo(AlignmentSource::Type),
2457                               TBAAAccessInfo());
2458 }
2459 
2460 /// This function creates calls to one of two shuffle functions to copy
2461 /// variables between lanes in a warp.
2462 static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
2463                                                  llvm::Value *Elem,
2464                                                  QualType ElemType,
2465                                                  llvm::Value *Offset,
2466                                                  SourceLocation Loc) {
2467   CodeGenModule &CGM = CGF.CGM;
2468   CGBuilderTy &Bld = CGF.Builder;
2469   CGOpenMPRuntimeGPU &RT =
2470       *(static_cast<CGOpenMPRuntimeGPU *>(&CGM.getOpenMPRuntime()));
2471   llvm::OpenMPIRBuilder &OMPBuilder = RT.getOMPBuilder();
2472 
2473   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2474   assert(Size.getQuantity() <= 8 &&
2475          "Unsupported bitwidth in shuffle instruction.");
2476 
2477   RuntimeFunction ShuffleFn = Size.getQuantity() <= 4
2478                                   ? OMPRTL___kmpc_shuffle_int32
2479                                   : OMPRTL___kmpc_shuffle_int64;
2480 
2481   // Cast all types to 32- or 64-bit values before calling shuffle routines.
2482   QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2483       Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2484   llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
2485   llvm::Value *WarpSize =
2486       Bld.CreateIntCast(RT.getGPUWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
2487 
2488   llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2489       OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), ShuffleFn),
2490       {ElemCast, Offset, WarpSize});
2491 
2492   return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
2493 }
2494 
2495 static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2496                             Address DestAddr, QualType ElemType,
2497                             llvm::Value *Offset, SourceLocation Loc) {
2498   CGBuilderTy &Bld = CGF.Builder;
2499 
2500   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2501   // Create the loop over the big sized data.
2502   // ptr = (void*)Elem;
2503   // ptrEnd = (void*) Elem + 1;
2504   // Step = 8;
2505   // while (ptr + Step < ptrEnd)
2506   //   shuffle((int64_t)*ptr);
2507   // Step = 4;
2508   // while (ptr + Step < ptrEnd)
2509   //   shuffle((int32_t)*ptr);
2510   // ...
2511   Address ElemPtr = DestAddr;
2512   Address Ptr = SrcAddr;
2513   Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2514       Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
2515   for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2516     if (Size < CharUnits::fromQuantity(IntSize))
2517       continue;
2518     QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2519         CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2520         /*Signed=*/1);
2521     llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2522     Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2523     ElemPtr =
2524         Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2525     if (Size.getQuantity() / IntSize > 1) {
2526       llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2527       llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2528       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2529       llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2530       CGF.EmitBlock(PreCondBB);
2531       llvm::PHINode *PhiSrc =
2532           Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2533       PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2534       llvm::PHINode *PhiDest =
2535           Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2536       PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2537       Ptr = Address(PhiSrc, Ptr.getAlignment());
2538       ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2539       llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2540           PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2541                                    Ptr.getPointer(), CGF.VoidPtrTy));
2542       Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2543                        ThenBB, ExitBB);
2544       CGF.EmitBlock(ThenBB);
2545       llvm::Value *Res = createRuntimeShuffleFunction(
2546           CGF,
2547           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
2548                                LValueBaseInfo(AlignmentSource::Type),
2549                                TBAAAccessInfo()),
2550           IntType, Offset, Loc);
2551       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
2552                             LValueBaseInfo(AlignmentSource::Type),
2553                             TBAAAccessInfo());
2554       Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2555       Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2556       PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2557       PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
2558       CGF.EmitBranch(PreCondBB);
2559       CGF.EmitBlock(ExitBB);
2560     } else {
2561       llvm::Value *Res = createRuntimeShuffleFunction(
2562           CGF,
2563           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
2564                                LValueBaseInfo(AlignmentSource::Type),
2565                                TBAAAccessInfo()),
2566           IntType, Offset, Loc);
2567       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
2568                             LValueBaseInfo(AlignmentSource::Type),
2569                             TBAAAccessInfo());
2570       Ptr = Bld.CreateConstGEP(Ptr, 1);
2571       ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
2572     }
2573     Size = Size % IntSize;
2574   }
2575 }
2576 
2577 namespace {
2578 enum CopyAction : unsigned {
2579   // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2580   // the warp using shuffle instructions.
2581   RemoteLaneToThread,
2582   // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2583   ThreadCopy,
2584   // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2585   ThreadToScratchpad,
2586   // ScratchpadToThread: Copy from a scratchpad array in global memory
2587   // containing team-reduced data to a thread's stack.
2588   ScratchpadToThread,
2589 };
2590 } // namespace
2591 
2592 struct CopyOptionsTy {
2593   llvm::Value *RemoteLaneOffset;
2594   llvm::Value *ScratchpadIndex;
2595   llvm::Value *ScratchpadWidth;
2596 };
2597 
2598 /// Emit instructions to copy a Reduce list, which contains partially
2599 /// aggregated values, in the specified direction.
2600 static void emitReductionListCopy(
2601     CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2602     ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2603     CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
2604 
2605   CodeGenModule &CGM = CGF.CGM;
2606   ASTContext &C = CGM.getContext();
2607   CGBuilderTy &Bld = CGF.Builder;
2608 
2609   llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2610   llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2611   llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
2612 
2613   // Iterates, element-by-element, through the source Reduce list and
2614   // make a copy.
2615   unsigned Idx = 0;
2616   unsigned Size = Privates.size();
2617   for (const Expr *Private : Privates) {
2618     Address SrcElementAddr = Address::invalid();
2619     Address DestElementAddr = Address::invalid();
2620     Address DestElementPtrAddr = Address::invalid();
2621     // Should we shuffle in an element from a remote lane?
2622     bool ShuffleInElement = false;
2623     // Set to true to update the pointer in the dest Reduce list to a
2624     // newly created element.
2625     bool UpdateDestListPtr = false;
2626     // Increment the src or dest pointer to the scratchpad, for each
2627     // new element.
2628     bool IncrScratchpadSrc = false;
2629     bool IncrScratchpadDest = false;
2630 
2631     switch (Action) {
2632     case RemoteLaneToThread: {
2633       // Step 1.1: Get the address for the src element in the Reduce list.
2634       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
2635       SrcElementAddr = CGF.EmitLoadOfPointer(
2636           SrcElementPtrAddr,
2637           C.getPointerType(Private->getType())->castAs<PointerType>());
2638 
2639       // Step 1.2: Create a temporary to store the element in the destination
2640       // Reduce list.
2641       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
2642       DestElementAddr =
2643           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2644       ShuffleInElement = true;
2645       UpdateDestListPtr = true;
2646       break;
2647     }
2648     case ThreadCopy: {
2649       // Step 1.1: Get the address for the src element in the Reduce list.
2650       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
2651       SrcElementAddr = CGF.EmitLoadOfPointer(
2652           SrcElementPtrAddr,
2653           C.getPointerType(Private->getType())->castAs<PointerType>());
2654 
2655       // Step 1.2: Get the address for dest element.  The destination
2656       // element has already been created on the thread's stack.
2657       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
2658       DestElementAddr = CGF.EmitLoadOfPointer(
2659           DestElementPtrAddr,
2660           C.getPointerType(Private->getType())->castAs<PointerType>());
2661       break;
2662     }
2663     case ThreadToScratchpad: {
2664       // Step 1.1: Get the address for the src element in the Reduce list.
2665       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
2666       SrcElementAddr = CGF.EmitLoadOfPointer(
2667           SrcElementPtrAddr,
2668           C.getPointerType(Private->getType())->castAs<PointerType>());
2669 
2670       // Step 1.2: Get the address for dest element:
2671       // address = base + index * ElementSizeInChars.
2672       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2673       llvm::Value *CurrentOffset =
2674           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
2675       llvm::Value *ScratchPadElemAbsolutePtrVal =
2676           Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
2677       ScratchPadElemAbsolutePtrVal =
2678           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2679       DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2680                                 C.getTypeAlignInChars(Private->getType()));
2681       IncrScratchpadDest = true;
2682       break;
2683     }
2684     case ScratchpadToThread: {
2685       // Step 1.1: Get the address for the src element in the scratchpad.
2686       // address = base + index * ElementSizeInChars.
2687       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2688       llvm::Value *CurrentOffset =
2689           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
2690       llvm::Value *ScratchPadElemAbsolutePtrVal =
2691           Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
2692       ScratchPadElemAbsolutePtrVal =
2693           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2694       SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2695                                C.getTypeAlignInChars(Private->getType()));
2696       IncrScratchpadSrc = true;
2697 
2698       // Step 1.2: Create a temporary to store the element in the destination
2699       // Reduce list.
2700       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
2701       DestElementAddr =
2702           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2703       UpdateDestListPtr = true;
2704       break;
2705     }
2706     }
2707 
2708     // Regardless of src and dest of copy, we emit the load of src
2709     // element as this is required in all directions
2710     SrcElementAddr = Bld.CreateElementBitCast(
2711         SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
2712     DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
2713                                                SrcElementAddr.getElementType());
2714 
2715     // Now that all active lanes have read the element in the
2716     // Reduce list, shuffle over the value from the remote lane.
2717     if (ShuffleInElement) {
2718       shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
2719                       RemoteLaneOffset, Private->getExprLoc());
2720     } else {
2721       switch (CGF.getEvaluationKind(Private->getType())) {
2722       case TEK_Scalar: {
2723         llvm::Value *Elem = CGF.EmitLoadOfScalar(
2724             SrcElementAddr, /*Volatile=*/false, Private->getType(),
2725             Private->getExprLoc(), LValueBaseInfo(AlignmentSource::Type),
2726             TBAAAccessInfo());
2727         // Store the source element value to the dest element address.
2728         CGF.EmitStoreOfScalar(
2729             Elem, DestElementAddr, /*Volatile=*/false, Private->getType(),
2730             LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2731         break;
2732       }
2733       case TEK_Complex: {
2734         CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
2735             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2736             Private->getExprLoc());
2737         CGF.EmitStoreOfComplex(
2738             Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2739             /*isInit=*/false);
2740         break;
2741       }
2742       case TEK_Aggregate:
2743         CGF.EmitAggregateCopy(
2744             CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
2745             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
2746             Private->getType(), AggValueSlot::DoesNotOverlap);
2747         break;
2748       }
2749     }
2750 
2751     // Step 3.1: Modify reference in dest Reduce list as needed.
2752     // Modifying the reference in Reduce list to point to the newly
2753     // created element.  The element is live in the current function
2754     // scope and that of functions it invokes (i.e., reduce_function).
2755     // RemoteReduceData[i] = (void*)&RemoteElem
2756     if (UpdateDestListPtr) {
2757       CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
2758                                 DestElementAddr.getPointer(), CGF.VoidPtrTy),
2759                             DestElementPtrAddr, /*Volatile=*/false,
2760                             C.VoidPtrTy);
2761     }
2762 
2763     // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2764     // address of the next element in scratchpad memory, unless we're currently
2765     // processing the last one.  Memory alignment is also taken care of here.
2766     if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2767       llvm::Value *ScratchpadBasePtr =
2768           IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
2769       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2770       ScratchpadBasePtr = Bld.CreateNUWAdd(
2771           ScratchpadBasePtr,
2772           Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
2773 
2774       // Take care of global memory alignment for performance
2775       ScratchpadBasePtr = Bld.CreateNUWSub(
2776           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2777       ScratchpadBasePtr = Bld.CreateUDiv(
2778           ScratchpadBasePtr,
2779           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2780       ScratchpadBasePtr = Bld.CreateNUWAdd(
2781           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2782       ScratchpadBasePtr = Bld.CreateNUWMul(
2783           ScratchpadBasePtr,
2784           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2785 
2786       if (IncrScratchpadDest)
2787         DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2788       else /* IncrScratchpadSrc = true */
2789         SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2790     }
2791 
2792     ++Idx;
2793   }
2794 }
2795 
2796 /// This function emits a helper that gathers Reduce lists from the first
2797 /// lane of every active warp to lanes in the first warp.
2798 ///
2799 /// void inter_warp_copy_func(void* reduce_data, num_warps)
2800 ///   shared smem[warp_size];
2801 ///   For all data entries D in reduce_data:
2802 ///     sync
2803 ///     If (I am the first lane in each warp)
2804 ///       Copy my local D to smem[warp_id]
2805 ///     sync
2806 ///     if (I am the first warp)
2807 ///       Copy smem[thread_id] to my local D
2808 static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2809                                               ArrayRef<const Expr *> Privates,
2810                                               QualType ReductionArrayTy,
2811                                               SourceLocation Loc) {
2812   ASTContext &C = CGM.getContext();
2813   llvm::Module &M = CGM.getModule();
2814 
2815   // ReduceList: thread local Reduce list.
2816   // At the stage of the computation when this function is called, partially
2817   // aggregated values reside in the first lane of every active warp.
2818   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2819                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2820   // NumWarps: number of warps active in the parallel region.  This could
2821   // be smaller than 32 (max warps in a CTA) for partial block reduction.
2822   ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2823                                 C.getIntTypeForBitwidth(32, /* Signed */ true),
2824                                 ImplicitParamDecl::Other);
2825   FunctionArgList Args;
2826   Args.push_back(&ReduceListArg);
2827   Args.push_back(&NumWarpsArg);
2828 
2829   const CGFunctionInfo &CGFI =
2830       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2831   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2832                                     llvm::GlobalValue::InternalLinkage,
2833                                     "_omp_reduction_inter_warp_copy_func", &M);
2834   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2835   Fn->setDoesNotRecurse();
2836   CodeGenFunction CGF(CGM);
2837   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2838 
2839   CGBuilderTy &Bld = CGF.Builder;
2840 
2841   // This array is used as a medium to transfer, one reduce element at a time,
2842   // the data from the first lane of every warp to lanes in the first warp
2843   // in order to perform the final step of a reduction in a parallel region
2844   // (reduction across warps).  The array is placed in NVPTX __shared__ memory
2845   // for reduced latency, as well as to have a distinct copy for concurrently
2846   // executing target regions.  The array is declared with common linkage so
2847   // as to be shared across compilation units.
2848   StringRef TransferMediumName =
2849       "__openmp_nvptx_data_transfer_temporary_storage";
2850   llvm::GlobalVariable *TransferMedium =
2851       M.getGlobalVariable(TransferMediumName);
2852   unsigned WarpSize = CGF.getTarget().getGridValue(llvm::omp::GV_Warp_Size);
2853   if (!TransferMedium) {
2854     auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
2855     unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2856     TransferMedium = new llvm::GlobalVariable(
2857         M, Ty, /*isConstant=*/false, llvm::GlobalVariable::WeakAnyLinkage,
2858         llvm::UndefValue::get(Ty), TransferMediumName,
2859         /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2860         SharedAddressSpace);
2861     CGM.addCompilerUsedGlobal(TransferMedium);
2862   }
2863 
2864   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2865   // Get the CUDA thread id of the current OpenMP thread on the GPU.
2866   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
2867   // nvptx_lane_id = nvptx_id % warpsize
2868   llvm::Value *LaneID = getNVPTXLaneID(CGF);
2869   // nvptx_warp_id = nvptx_id / warpsize
2870   llvm::Value *WarpID = getNVPTXWarpID(CGF);
2871 
2872   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2873   Address LocalReduceList(
2874       Bld.CreatePointerBitCastOrAddrSpaceCast(
2875           CGF.EmitLoadOfScalar(
2876               AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc,
2877               LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo()),
2878           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2879       CGF.getPointerAlign());
2880 
2881   unsigned Idx = 0;
2882   for (const Expr *Private : Privates) {
2883     //
2884     // Warp master copies reduce element to transfer medium in __shared__
2885     // memory.
2886     //
2887     unsigned RealTySize =
2888         C.getTypeSizeInChars(Private->getType())
2889             .alignTo(C.getTypeAlignInChars(Private->getType()))
2890             .getQuantity();
2891     for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
2892       unsigned NumIters = RealTySize / TySize;
2893       if (NumIters == 0)
2894         continue;
2895       QualType CType = C.getIntTypeForBitwidth(
2896           C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
2897       llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
2898       CharUnits Align = CharUnits::fromQuantity(TySize);
2899       llvm::Value *Cnt = nullptr;
2900       Address CntAddr = Address::invalid();
2901       llvm::BasicBlock *PrecondBB = nullptr;
2902       llvm::BasicBlock *ExitBB = nullptr;
2903       if (NumIters > 1) {
2904         CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
2905         CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
2906                               /*Volatile=*/false, C.IntTy);
2907         PrecondBB = CGF.createBasicBlock("precond");
2908         ExitBB = CGF.createBasicBlock("exit");
2909         llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
2910         // There is no need to emit line number for unconditional branch.
2911         (void)ApplyDebugLocation::CreateEmpty(CGF);
2912         CGF.EmitBlock(PrecondBB);
2913         Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
2914         llvm::Value *Cmp =
2915             Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
2916         Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
2917         CGF.EmitBlock(BodyBB);
2918       }
2919       // kmpc_barrier.
2920       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2921                                              /*EmitChecks=*/false,
2922                                              /*ForceSimpleCall=*/true);
2923       llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2924       llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2925       llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2926 
2927       // if (lane_id == 0)
2928       llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
2929       Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2930       CGF.EmitBlock(ThenBB);
2931 
2932       // Reduce element = LocalReduceList[i]
2933       Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2934       llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2935           ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2936       // elemptr = ((CopyType*)(elemptrptr)) + I
2937       Address ElemPtr = Address(ElemPtrPtr, Align);
2938       ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
2939       if (NumIters > 1) {
2940         ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
2941                           ElemPtr.getAlignment());
2942       }
2943 
2944       // Get pointer to location in transfer medium.
2945       // MediumPtr = &medium[warp_id]
2946       llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2947           TransferMedium->getValueType(), TransferMedium,
2948           {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2949       Address MediumPtr(MediumPtrVal, Align);
2950       // Casting to actual data type.
2951       // MediumPtr = (CopyType*)MediumPtrAddr;
2952       MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
2953 
2954       // elem = *elemptr
2955       //*MediumPtr = elem
2956       llvm::Value *Elem = CGF.EmitLoadOfScalar(
2957           ElemPtr, /*Volatile=*/false, CType, Loc,
2958           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2959       // Store the source element value to the dest element address.
2960       CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType,
2961                             LValueBaseInfo(AlignmentSource::Type),
2962                             TBAAAccessInfo());
2963 
2964       Bld.CreateBr(MergeBB);
2965 
2966       CGF.EmitBlock(ElseBB);
2967       Bld.CreateBr(MergeBB);
2968 
2969       CGF.EmitBlock(MergeBB);
2970 
2971       // kmpc_barrier.
2972       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2973                                              /*EmitChecks=*/false,
2974                                              /*ForceSimpleCall=*/true);
2975 
2976       //
2977       // Warp 0 copies reduce element from transfer medium.
2978       //
2979       llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2980       llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2981       llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2982 
2983       Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2984       llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2985           AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
2986 
2987       // Up to 32 threads in warp 0 are active.
2988       llvm::Value *IsActiveThread =
2989           Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2990       Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2991 
2992       CGF.EmitBlock(W0ThenBB);
2993 
2994       // SrcMediumPtr = &medium[tid]
2995       llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2996           TransferMedium->getValueType(), TransferMedium,
2997           {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2998       Address SrcMediumPtr(SrcMediumPtrVal, Align);
2999       // SrcMediumVal = *SrcMediumPtr;
3000       SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
3001 
3002       // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3003       Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3004       llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3005           TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3006       Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3007       TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3008       if (NumIters > 1) {
3009         TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3010                                 TargetElemPtr.getAlignment());
3011       }
3012 
3013       // *TargetElemPtr = SrcMediumVal;
3014       llvm::Value *SrcMediumValue =
3015           CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
3016       CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
3017                             CType);
3018       Bld.CreateBr(W0MergeBB);
3019 
3020       CGF.EmitBlock(W0ElseBB);
3021       Bld.CreateBr(W0MergeBB);
3022 
3023       CGF.EmitBlock(W0MergeBB);
3024 
3025       if (NumIters > 1) {
3026         Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3027         CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3028         CGF.EmitBranch(PrecondBB);
3029         (void)ApplyDebugLocation::CreateEmpty(CGF);
3030         CGF.EmitBlock(ExitBB);
3031       }
3032       RealTySize %= TySize;
3033     }
3034     ++Idx;
3035   }
3036 
3037   CGF.FinishFunction();
3038   return Fn;
3039 }
3040 
3041 /// Emit a helper that reduces data across two OpenMP threads (lanes)
3042 /// in the same warp.  It uses shuffle instructions to copy over data from
3043 /// a remote lane's stack.  The reduction algorithm performed is specified
3044 /// by the fourth parameter.
3045 ///
3046 /// Algorithm Versions.
3047 /// Full Warp Reduce (argument value 0):
3048 ///   This algorithm assumes that all 32 lanes are active and gathers
3049 ///   data from these 32 lanes, producing a single resultant value.
3050 /// Contiguous Partial Warp Reduce (argument value 1):
3051 ///   This algorithm assumes that only a *contiguous* subset of lanes
3052 ///   are active.  This happens for the last warp in a parallel region
3053 ///   when the user specified num_threads is not an integer multiple of
3054 ///   32.  This contiguous subset always starts with the zeroth lane.
3055 /// Partial Warp Reduce (argument value 2):
3056 ///   This algorithm gathers data from any number of lanes at any position.
3057 /// All reduced values are stored in the lowest possible lane.  The set
3058 /// of problems every algorithm addresses is a super set of those
3059 /// addressable by algorithms with a lower version number.  Overhead
3060 /// increases as algorithm version increases.
3061 ///
3062 /// Terminology
3063 /// Reduce element:
3064 ///   Reduce element refers to the individual data field with primitive
3065 ///   data types to be combined and reduced across threads.
3066 /// Reduce list:
3067 ///   Reduce list refers to a collection of local, thread-private
3068 ///   reduce elements.
3069 /// Remote Reduce list:
3070 ///   Remote Reduce list refers to a collection of remote (relative to
3071 ///   the current thread) reduce elements.
3072 ///
3073 /// We distinguish between three states of threads that are important to
3074 /// the implementation of this function.
3075 /// Alive threads:
3076 ///   Threads in a warp executing the SIMT instruction, as distinguished from
3077 ///   threads that are inactive due to divergent control flow.
3078 /// Active threads:
3079 ///   The minimal set of threads that has to be alive upon entry to this
3080 ///   function.  The computation is correct iff active threads are alive.
3081 ///   Some threads are alive but they are not active because they do not
3082 ///   contribute to the computation in any useful manner.  Turning them off
3083 ///   may introduce control flow overheads without any tangible benefits.
3084 /// Effective threads:
3085 ///   In order to comply with the argument requirements of the shuffle
3086 ///   function, we must keep all lanes holding data alive.  But at most
3087 ///   half of them perform value aggregation; we refer to this half of
3088 ///   threads as effective. The other half is simply handing off their
3089 ///   data.
3090 ///
3091 /// Procedure
3092 /// Value shuffle:
3093 ///   In this step active threads transfer data from higher lane positions
3094 ///   in the warp to lower lane positions, creating Remote Reduce list.
3095 /// Value aggregation:
3096 ///   In this step, effective threads combine their thread local Reduce list
3097 ///   with Remote Reduce list and store the result in the thread local
3098 ///   Reduce list.
3099 /// Value copy:
3100 ///   In this step, we deal with the assumption made by algorithm 2
3101 ///   (i.e. contiguity assumption).  When we have an odd number of lanes
3102 ///   active, say 2k+1, only k threads will be effective and therefore k
3103 ///   new values will be produced.  However, the Reduce list owned by the
3104 ///   (2k+1)th thread is ignored in the value aggregation.  Therefore
3105 ///   we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3106 ///   that the contiguity assumption still holds.
3107 static llvm::Function *emitShuffleAndReduceFunction(
3108     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3109     QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
3110   ASTContext &C = CGM.getContext();
3111 
3112   // Thread local Reduce list used to host the values of data to be reduced.
3113   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3114                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3115   // Current lane id; could be logical.
3116   ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3117                               ImplicitParamDecl::Other);
3118   // Offset of the remote source lane relative to the current lane.
3119   ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3120                                         C.ShortTy, ImplicitParamDecl::Other);
3121   // Algorithm version.  This is expected to be known at compile time.
3122   ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3123                                C.ShortTy, ImplicitParamDecl::Other);
3124   FunctionArgList Args;
3125   Args.push_back(&ReduceListArg);
3126   Args.push_back(&LaneIDArg);
3127   Args.push_back(&RemoteLaneOffsetArg);
3128   Args.push_back(&AlgoVerArg);
3129 
3130   const CGFunctionInfo &CGFI =
3131       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3132   auto *Fn = llvm::Function::Create(
3133       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3134       "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
3135   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3136   Fn->setDoesNotRecurse();
3137 
3138   CodeGenFunction CGF(CGM);
3139   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3140 
3141   CGBuilderTy &Bld = CGF.Builder;
3142 
3143   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3144   Address LocalReduceList(
3145       Bld.CreatePointerBitCastOrAddrSpaceCast(
3146           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3147                                C.VoidPtrTy, SourceLocation()),
3148           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3149       CGF.getPointerAlign());
3150 
3151   Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3152   llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3153       AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3154 
3155   Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3156   llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3157       AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3158 
3159   Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3160   llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3161       AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3162 
3163   // Create a local thread-private variable to host the Reduce list
3164   // from a remote lane.
3165   Address RemoteReduceList =
3166       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3167 
3168   // This loop iterates through the list of reduce elements and copies,
3169   // element by element, from a remote lane in the warp to RemoteReduceList,
3170   // hosted on the thread's stack.
3171   emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3172                         LocalReduceList, RemoteReduceList,
3173                         {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3174                          /*ScratchpadIndex=*/nullptr,
3175                          /*ScratchpadWidth=*/nullptr});
3176 
3177   // The actions to be performed on the Remote Reduce list is dependent
3178   // on the algorithm version.
3179   //
3180   //  if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3181   //  LaneId % 2 == 0 && Offset > 0):
3182   //    do the reduction value aggregation
3183   //
3184   //  The thread local variable Reduce list is mutated in place to host the
3185   //  reduced data, which is the aggregated value produced from local and
3186   //  remote lanes.
3187   //
3188   //  Note that AlgoVer is expected to be a constant integer known at compile
3189   //  time.
3190   //  When AlgoVer==0, the first conjunction evaluates to true, making
3191   //    the entire predicate true during compile time.
3192   //  When AlgoVer==1, the second conjunction has only the second part to be
3193   //    evaluated during runtime.  Other conjunctions evaluates to false
3194   //    during compile time.
3195   //  When AlgoVer==2, the third conjunction has only the second part to be
3196   //    evaluated during runtime.  Other conjunctions evaluates to false
3197   //    during compile time.
3198   llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
3199 
3200   llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3201   llvm::Value *CondAlgo1 = Bld.CreateAnd(
3202       Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3203 
3204   llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3205   llvm::Value *CondAlgo2 = Bld.CreateAnd(
3206       Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
3207   CondAlgo2 = Bld.CreateAnd(
3208       CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3209 
3210   llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
3211   CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3212 
3213   llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3214   llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3215   llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3216   Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3217 
3218   CGF.EmitBlock(ThenBB);
3219   // reduce_function(LocalReduceList, RemoteReduceList)
3220   llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3221       LocalReduceList.getPointer(), CGF.VoidPtrTy);
3222   llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3223       RemoteReduceList.getPointer(), CGF.VoidPtrTy);
3224   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3225       CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
3226   Bld.CreateBr(MergeBB);
3227 
3228   CGF.EmitBlock(ElseBB);
3229   Bld.CreateBr(MergeBB);
3230 
3231   CGF.EmitBlock(MergeBB);
3232 
3233   // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3234   // Reduce list.
3235   Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3236   llvm::Value *CondCopy = Bld.CreateAnd(
3237       Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3238 
3239   llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3240   llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3241   llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3242   Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3243 
3244   CGF.EmitBlock(CpyThenBB);
3245   emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3246                         RemoteReduceList, LocalReduceList);
3247   Bld.CreateBr(CpyMergeBB);
3248 
3249   CGF.EmitBlock(CpyElseBB);
3250   Bld.CreateBr(CpyMergeBB);
3251 
3252   CGF.EmitBlock(CpyMergeBB);
3253 
3254   CGF.FinishFunction();
3255   return Fn;
3256 }
3257 
3258 /// This function emits a helper that copies all the reduction variables from
3259 /// the team into the provided global buffer for the reduction variables.
3260 ///
3261 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3262 ///   For all data entries D in reduce_data:
3263 ///     Copy local D to buffer.D[Idx]
3264 static llvm::Value *emitListToGlobalCopyFunction(
3265     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3266     QualType ReductionArrayTy, SourceLocation Loc,
3267     const RecordDecl *TeamReductionRec,
3268     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3269         &VarFieldMap) {
3270   ASTContext &C = CGM.getContext();
3271 
3272   // Buffer: global reduction buffer.
3273   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3274                               C.VoidPtrTy, ImplicitParamDecl::Other);
3275   // Idx: index of the buffer.
3276   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3277                            ImplicitParamDecl::Other);
3278   // ReduceList: thread local Reduce list.
3279   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3280                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3281   FunctionArgList Args;
3282   Args.push_back(&BufferArg);
3283   Args.push_back(&IdxArg);
3284   Args.push_back(&ReduceListArg);
3285 
3286   const CGFunctionInfo &CGFI =
3287       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3288   auto *Fn = llvm::Function::Create(
3289       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3290       "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3291   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3292   Fn->setDoesNotRecurse();
3293   CodeGenFunction CGF(CGM);
3294   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3295 
3296   CGBuilderTy &Bld = CGF.Builder;
3297 
3298   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3299   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3300   Address LocalReduceList(
3301       Bld.CreatePointerBitCastOrAddrSpaceCast(
3302           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3303                                C.VoidPtrTy, Loc),
3304           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3305       CGF.getPointerAlign());
3306   QualType StaticTy = C.getRecordType(TeamReductionRec);
3307   llvm::Type *LLVMReductionsBufferTy =
3308       CGM.getTypes().ConvertTypeForMem(StaticTy);
3309   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3310       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3311       LLVMReductionsBufferTy->getPointerTo());
3312   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3313                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3314                                               /*Volatile=*/false, C.IntTy,
3315                                               Loc)};
3316   unsigned Idx = 0;
3317   for (const Expr *Private : Privates) {
3318     // Reduce element = LocalReduceList[i]
3319     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3320     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3321         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3322     // elemptr = ((CopyType*)(elemptrptr)) + I
3323     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3324         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3325     Address ElemPtr =
3326         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3327     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3328     // Global = Buffer.VD[Idx];
3329     const FieldDecl *FD = VarFieldMap.lookup(VD);
3330     LValue GlobLVal = CGF.EmitLValueForField(
3331         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3332     Address GlobAddr = GlobLVal.getAddress(CGF);
3333     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
3334         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
3335     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
3336     switch (CGF.getEvaluationKind(Private->getType())) {
3337     case TEK_Scalar: {
3338       llvm::Value *V = CGF.EmitLoadOfScalar(
3339           ElemPtr, /*Volatile=*/false, Private->getType(), Loc,
3340           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
3341       CGF.EmitStoreOfScalar(V, GlobLVal);
3342       break;
3343     }
3344     case TEK_Complex: {
3345       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3346           CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3347       CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3348       break;
3349     }
3350     case TEK_Aggregate:
3351       CGF.EmitAggregateCopy(GlobLVal,
3352                             CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3353                             Private->getType(), AggValueSlot::DoesNotOverlap);
3354       break;
3355     }
3356     ++Idx;
3357   }
3358 
3359   CGF.FinishFunction();
3360   return Fn;
3361 }
3362 
3363 /// This function emits a helper that reduces all the reduction variables from
3364 /// the team into the provided global buffer for the reduction variables.
3365 ///
3366 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3367 ///  void *GlobPtrs[];
3368 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
3369 ///  ...
3370 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
3371 ///  reduce_function(GlobPtrs, reduce_data);
3372 static llvm::Value *emitListToGlobalReduceFunction(
3373     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3374     QualType ReductionArrayTy, SourceLocation Loc,
3375     const RecordDecl *TeamReductionRec,
3376     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3377         &VarFieldMap,
3378     llvm::Function *ReduceFn) {
3379   ASTContext &C = CGM.getContext();
3380 
3381   // Buffer: global reduction buffer.
3382   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3383                               C.VoidPtrTy, ImplicitParamDecl::Other);
3384   // Idx: index of the buffer.
3385   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3386                            ImplicitParamDecl::Other);
3387   // ReduceList: thread local Reduce list.
3388   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3389                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3390   FunctionArgList Args;
3391   Args.push_back(&BufferArg);
3392   Args.push_back(&IdxArg);
3393   Args.push_back(&ReduceListArg);
3394 
3395   const CGFunctionInfo &CGFI =
3396       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3397   auto *Fn = llvm::Function::Create(
3398       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3399       "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3400   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3401   Fn->setDoesNotRecurse();
3402   CodeGenFunction CGF(CGM);
3403   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3404 
3405   CGBuilderTy &Bld = CGF.Builder;
3406 
3407   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3408   QualType StaticTy = C.getRecordType(TeamReductionRec);
3409   llvm::Type *LLVMReductionsBufferTy =
3410       CGM.getTypes().ConvertTypeForMem(StaticTy);
3411   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3412       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3413       LLVMReductionsBufferTy->getPointerTo());
3414 
3415   // 1. Build a list of reduction variables.
3416   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3417   Address ReductionList =
3418       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3419   auto IPriv = Privates.begin();
3420   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3421                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3422                                               /*Volatile=*/false, C.IntTy,
3423                                               Loc)};
3424   unsigned Idx = 0;
3425   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3426     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3427     // Global = Buffer.VD[Idx];
3428     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3429     const FieldDecl *FD = VarFieldMap.lookup(VD);
3430     LValue GlobLVal = CGF.EmitLValueForField(
3431         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3432     Address GlobAddr = GlobLVal.getAddress(CGF);
3433     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
3434         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
3435     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3436     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3437     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3438       // Store array size.
3439       ++Idx;
3440       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3441       llvm::Value *Size = CGF.Builder.CreateIntCast(
3442           CGF.getVLASize(
3443                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3444               .NumElts,
3445           CGF.SizeTy, /*isSigned=*/false);
3446       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3447                               Elem);
3448     }
3449   }
3450 
3451   // Call reduce_function(GlobalReduceList, ReduceList)
3452   llvm::Value *GlobalReduceList =
3453       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3454   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3455   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3456       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3457   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3458       CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3459   CGF.FinishFunction();
3460   return Fn;
3461 }
3462 
3463 /// This function emits a helper that copies all the reduction variables from
3464 /// the team into the provided global buffer for the reduction variables.
3465 ///
3466 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3467 ///   For all data entries D in reduce_data:
3468 ///     Copy buffer.D[Idx] to local D;
3469 static llvm::Value *emitGlobalToListCopyFunction(
3470     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3471     QualType ReductionArrayTy, SourceLocation Loc,
3472     const RecordDecl *TeamReductionRec,
3473     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3474         &VarFieldMap) {
3475   ASTContext &C = CGM.getContext();
3476 
3477   // Buffer: global reduction buffer.
3478   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3479                               C.VoidPtrTy, ImplicitParamDecl::Other);
3480   // Idx: index of the buffer.
3481   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3482                            ImplicitParamDecl::Other);
3483   // ReduceList: thread local Reduce list.
3484   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3485                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3486   FunctionArgList Args;
3487   Args.push_back(&BufferArg);
3488   Args.push_back(&IdxArg);
3489   Args.push_back(&ReduceListArg);
3490 
3491   const CGFunctionInfo &CGFI =
3492       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3493   auto *Fn = llvm::Function::Create(
3494       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3495       "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3496   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3497   Fn->setDoesNotRecurse();
3498   CodeGenFunction CGF(CGM);
3499   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3500 
3501   CGBuilderTy &Bld = CGF.Builder;
3502 
3503   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3504   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3505   Address LocalReduceList(
3506       Bld.CreatePointerBitCastOrAddrSpaceCast(
3507           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3508                                C.VoidPtrTy, Loc),
3509           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3510       CGF.getPointerAlign());
3511   QualType StaticTy = C.getRecordType(TeamReductionRec);
3512   llvm::Type *LLVMReductionsBufferTy =
3513       CGM.getTypes().ConvertTypeForMem(StaticTy);
3514   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3515       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3516       LLVMReductionsBufferTy->getPointerTo());
3517 
3518   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3519                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3520                                               /*Volatile=*/false, C.IntTy,
3521                                               Loc)};
3522   unsigned Idx = 0;
3523   for (const Expr *Private : Privates) {
3524     // Reduce element = LocalReduceList[i]
3525     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3526     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3527         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3528     // elemptr = ((CopyType*)(elemptrptr)) + I
3529     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3530         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3531     Address ElemPtr =
3532         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3533     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3534     // Global = Buffer.VD[Idx];
3535     const FieldDecl *FD = VarFieldMap.lookup(VD);
3536     LValue GlobLVal = CGF.EmitLValueForField(
3537         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3538     Address GlobAddr = GlobLVal.getAddress(CGF);
3539     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
3540         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
3541     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
3542     switch (CGF.getEvaluationKind(Private->getType())) {
3543     case TEK_Scalar: {
3544       llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3545       CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType(),
3546                             LValueBaseInfo(AlignmentSource::Type),
3547                             TBAAAccessInfo());
3548       break;
3549     }
3550     case TEK_Complex: {
3551       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3552       CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3553                              /*isInit=*/false);
3554       break;
3555     }
3556     case TEK_Aggregate:
3557       CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3558                             GlobLVal, Private->getType(),
3559                             AggValueSlot::DoesNotOverlap);
3560       break;
3561     }
3562     ++Idx;
3563   }
3564 
3565   CGF.FinishFunction();
3566   return Fn;
3567 }
3568 
3569 /// This function emits a helper that reduces all the reduction variables from
3570 /// the team into the provided global buffer for the reduction variables.
3571 ///
3572 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3573 ///  void *GlobPtrs[];
3574 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
3575 ///  ...
3576 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
3577 ///  reduce_function(reduce_data, GlobPtrs);
3578 static llvm::Value *emitGlobalToListReduceFunction(
3579     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3580     QualType ReductionArrayTy, SourceLocation Loc,
3581     const RecordDecl *TeamReductionRec,
3582     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3583         &VarFieldMap,
3584     llvm::Function *ReduceFn) {
3585   ASTContext &C = CGM.getContext();
3586 
3587   // Buffer: global reduction buffer.
3588   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3589                               C.VoidPtrTy, ImplicitParamDecl::Other);
3590   // Idx: index of the buffer.
3591   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3592                            ImplicitParamDecl::Other);
3593   // ReduceList: thread local Reduce list.
3594   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3595                                   C.VoidPtrTy, ImplicitParamDecl::Other);
3596   FunctionArgList Args;
3597   Args.push_back(&BufferArg);
3598   Args.push_back(&IdxArg);
3599   Args.push_back(&ReduceListArg);
3600 
3601   const CGFunctionInfo &CGFI =
3602       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3603   auto *Fn = llvm::Function::Create(
3604       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3605       "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3606   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3607   Fn->setDoesNotRecurse();
3608   CodeGenFunction CGF(CGM);
3609   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3610 
3611   CGBuilderTy &Bld = CGF.Builder;
3612 
3613   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3614   QualType StaticTy = C.getRecordType(TeamReductionRec);
3615   llvm::Type *LLVMReductionsBufferTy =
3616       CGM.getTypes().ConvertTypeForMem(StaticTy);
3617   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3618       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3619       LLVMReductionsBufferTy->getPointerTo());
3620 
3621   // 1. Build a list of reduction variables.
3622   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3623   Address ReductionList =
3624       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3625   auto IPriv = Privates.begin();
3626   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3627                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3628                                               /*Volatile=*/false, C.IntTy,
3629                                               Loc)};
3630   unsigned Idx = 0;
3631   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3632     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3633     // Global = Buffer.VD[Idx];
3634     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3635     const FieldDecl *FD = VarFieldMap.lookup(VD);
3636     LValue GlobLVal = CGF.EmitLValueForField(
3637         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3638     Address GlobAddr = GlobLVal.getAddress(CGF);
3639     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
3640         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
3641     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3642     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3643     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3644       // Store array size.
3645       ++Idx;
3646       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3647       llvm::Value *Size = CGF.Builder.CreateIntCast(
3648           CGF.getVLASize(
3649                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3650               .NumElts,
3651           CGF.SizeTy, /*isSigned=*/false);
3652       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3653                               Elem);
3654     }
3655   }
3656 
3657   // Call reduce_function(ReduceList, GlobalReduceList)
3658   llvm::Value *GlobalReduceList =
3659       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3660   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3661   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3662       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3663   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3664       CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3665   CGF.FinishFunction();
3666   return Fn;
3667 }
3668 
3669 ///
3670 /// Design of OpenMP reductions on the GPU
3671 ///
3672 /// Consider a typical OpenMP program with one or more reduction
3673 /// clauses:
3674 ///
3675 /// float foo;
3676 /// double bar;
3677 /// #pragma omp target teams distribute parallel for \
3678 ///             reduction(+:foo) reduction(*:bar)
3679 /// for (int i = 0; i < N; i++) {
3680 ///   foo += A[i]; bar *= B[i];
3681 /// }
3682 ///
3683 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
3684 /// all teams.  In our OpenMP implementation on the NVPTX device an
3685 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3686 /// within a team are mapped to CUDA threads within a threadblock.
3687 /// Our goal is to efficiently aggregate values across all OpenMP
3688 /// threads such that:
3689 ///
3690 ///   - the compiler and runtime are logically concise, and
3691 ///   - the reduction is performed efficiently in a hierarchical
3692 ///     manner as follows: within OpenMP threads in the same warp,
3693 ///     across warps in a threadblock, and finally across teams on
3694 ///     the NVPTX device.
3695 ///
3696 /// Introduction to Decoupling
3697 ///
3698 /// We would like to decouple the compiler and the runtime so that the
3699 /// latter is ignorant of the reduction variables (number, data types)
3700 /// and the reduction operators.  This allows a simpler interface
3701 /// and implementation while still attaining good performance.
3702 ///
3703 /// Pseudocode for the aforementioned OpenMP program generated by the
3704 /// compiler is as follows:
3705 ///
3706 /// 1. Create private copies of reduction variables on each OpenMP
3707 ///    thread: 'foo_private', 'bar_private'
3708 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3709 ///    to it and writes the result in 'foo_private' and 'bar_private'
3710 ///    respectively.
3711 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
3712 ///    and store the result on the team master:
3713 ///
3714 ///     __kmpc_nvptx_parallel_reduce_nowait_v2(...,
3715 ///        reduceData, shuffleReduceFn, interWarpCpyFn)
3716 ///
3717 ///     where:
3718 ///       struct ReduceData {
3719 ///         double *foo;
3720 ///         double *bar;
3721 ///       } reduceData
3722 ///       reduceData.foo = &foo_private
3723 ///       reduceData.bar = &bar_private
3724 ///
3725 ///     'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3726 ///     auxiliary functions generated by the compiler that operate on
3727 ///     variables of type 'ReduceData'.  They aid the runtime perform
3728 ///     algorithmic steps in a data agnostic manner.
3729 ///
3730 ///     'shuffleReduceFn' is a pointer to a function that reduces data
3731 ///     of type 'ReduceData' across two OpenMP threads (lanes) in the
3732 ///     same warp.  It takes the following arguments as input:
3733 ///
3734 ///     a. variable of type 'ReduceData' on the calling lane,
3735 ///     b. its lane_id,
3736 ///     c. an offset relative to the current lane_id to generate a
3737 ///        remote_lane_id.  The remote lane contains the second
3738 ///        variable of type 'ReduceData' that is to be reduced.
3739 ///     d. an algorithm version parameter determining which reduction
3740 ///        algorithm to use.
3741 ///
3742 ///     'shuffleReduceFn' retrieves data from the remote lane using
3743 ///     efficient GPU shuffle intrinsics and reduces, using the
3744 ///     algorithm specified by the 4th parameter, the two operands
3745 ///     element-wise.  The result is written to the first operand.
3746 ///
3747 ///     Different reduction algorithms are implemented in different
3748 ///     runtime functions, all calling 'shuffleReduceFn' to perform
3749 ///     the essential reduction step.  Therefore, based on the 4th
3750 ///     parameter, this function behaves slightly differently to
3751 ///     cooperate with the runtime to ensure correctness under
3752 ///     different circumstances.
3753 ///
3754 ///     'InterWarpCpyFn' is a pointer to a function that transfers
3755 ///     reduced variables across warps.  It tunnels, through CUDA
3756 ///     shared memory, the thread-private data of type 'ReduceData'
3757 ///     from lane 0 of each warp to a lane in the first warp.
3758 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3759 ///    The last team writes the global reduced value to memory.
3760 ///
3761 ///     ret = __kmpc_nvptx_teams_reduce_nowait(...,
3762 ///             reduceData, shuffleReduceFn, interWarpCpyFn,
3763 ///             scratchpadCopyFn, loadAndReduceFn)
3764 ///
3765 ///     'scratchpadCopyFn' is a helper that stores reduced
3766 ///     data from the team master to a scratchpad array in
3767 ///     global memory.
3768 ///
3769 ///     'loadAndReduceFn' is a helper that loads data from
3770 ///     the scratchpad array and reduces it with the input
3771 ///     operand.
3772 ///
3773 ///     These compiler generated functions hide address
3774 ///     calculation and alignment information from the runtime.
3775 /// 5. if ret == 1:
3776 ///     The team master of the last team stores the reduced
3777 ///     result to the globals in memory.
3778 ///     foo += reduceData.foo; bar *= reduceData.bar
3779 ///
3780 ///
3781 /// Warp Reduction Algorithms
3782 ///
3783 /// On the warp level, we have three algorithms implemented in the
3784 /// OpenMP runtime depending on the number of active lanes:
3785 ///
3786 /// Full Warp Reduction
3787 ///
3788 /// The reduce algorithm within a warp where all lanes are active
3789 /// is implemented in the runtime as follows:
3790 ///
3791 /// full_warp_reduce(void *reduce_data,
3792 ///                  kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3793 ///   for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3794 ///     ShuffleReduceFn(reduce_data, 0, offset, 0);
3795 /// }
3796 ///
3797 /// The algorithm completes in log(2, WARPSIZE) steps.
3798 ///
3799 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3800 /// not used therefore we save instructions by not retrieving lane_id
3801 /// from the corresponding special registers.  The 4th parameter, which
3802 /// represents the version of the algorithm being used, is set to 0 to
3803 /// signify full warp reduction.
3804 ///
3805 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3806 ///
3807 /// #reduce_elem refers to an element in the local lane's data structure
3808 /// #remote_elem is retrieved from a remote lane
3809 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3810 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3811 ///
3812 /// Contiguous Partial Warp Reduction
3813 ///
3814 /// This reduce algorithm is used within a warp where only the first
3815 /// 'n' (n <= WARPSIZE) lanes are active.  It is typically used when the
3816 /// number of OpenMP threads in a parallel region is not a multiple of
3817 /// WARPSIZE.  The algorithm is implemented in the runtime as follows:
3818 ///
3819 /// void
3820 /// contiguous_partial_reduce(void *reduce_data,
3821 ///                           kmp_ShuffleReductFctPtr ShuffleReduceFn,
3822 ///                           int size, int lane_id) {
3823 ///   int curr_size;
3824 ///   int offset;
3825 ///   curr_size = size;
3826 ///   mask = curr_size/2;
3827 ///   while (offset>0) {
3828 ///     ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3829 ///     curr_size = (curr_size+1)/2;
3830 ///     offset = curr_size/2;
3831 ///   }
3832 /// }
3833 ///
3834 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3835 ///
3836 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3837 /// if (lane_id < offset)
3838 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3839 /// else
3840 ///     reduce_elem = remote_elem
3841 ///
3842 /// This algorithm assumes that the data to be reduced are located in a
3843 /// contiguous subset of lanes starting from the first.  When there is
3844 /// an odd number of active lanes, the data in the last lane is not
3845 /// aggregated with any other lane's dat but is instead copied over.
3846 ///
3847 /// Dispersed Partial Warp Reduction
3848 ///
3849 /// This algorithm is used within a warp when any discontiguous subset of
3850 /// lanes are active.  It is used to implement the reduction operation
3851 /// across lanes in an OpenMP simd region or in a nested parallel region.
3852 ///
3853 /// void
3854 /// dispersed_partial_reduce(void *reduce_data,
3855 ///                          kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3856 ///   int size, remote_id;
3857 ///   int logical_lane_id = number_of_active_lanes_before_me() * 2;
3858 ///   do {
3859 ///       remote_id = next_active_lane_id_right_after_me();
3860 ///       # the above function returns 0 of no active lane
3861 ///       # is present right after the current lane.
3862 ///       size = number_of_active_lanes_in_this_warp();
3863 ///       logical_lane_id /= 2;
3864 ///       ShuffleReduceFn(reduce_data, logical_lane_id,
3865 ///                       remote_id-1-threadIdx.x, 2);
3866 ///   } while (logical_lane_id % 2 == 0 && size > 1);
3867 /// }
3868 ///
3869 /// There is no assumption made about the initial state of the reduction.
3870 /// Any number of lanes (>=1) could be active at any position.  The reduction
3871 /// result is returned in the first active lane.
3872 ///
3873 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3874 ///
3875 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3876 /// if (lane_id % 2 == 0 && offset > 0)
3877 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3878 /// else
3879 ///     reduce_elem = remote_elem
3880 ///
3881 ///
3882 /// Intra-Team Reduction
3883 ///
3884 /// This function, as implemented in the runtime call
3885 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
3886 /// threads in a team.  It first reduces within a warp using the
3887 /// aforementioned algorithms.  We then proceed to gather all such
3888 /// reduced values at the first warp.
3889 ///
3890 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
3891 /// data from each of the "warp master" (zeroth lane of each warp, where
3892 /// warp-reduced data is held) to the zeroth warp.  This step reduces (in
3893 /// a mathematical sense) the problem of reduction across warp masters in
3894 /// a block to the problem of warp reduction.
3895 ///
3896 ///
3897 /// Inter-Team Reduction
3898 ///
3899 /// Once a team has reduced its data to a single value, it is stored in
3900 /// a global scratchpad array.  Since each team has a distinct slot, this
3901 /// can be done without locking.
3902 ///
3903 /// The last team to write to the scratchpad array proceeds to reduce the
3904 /// scratchpad array.  One or more workers in the last team use the helper
3905 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3906 /// the k'th worker reduces every k'th element.
3907 ///
3908 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
3909 /// reduce across workers and compute a globally reduced value.
3910 ///
3911 void CGOpenMPRuntimeGPU::emitReduction(
3912     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3913     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3914     ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3915   if (!CGF.HaveInsertPoint())
3916     return;
3917 
3918   bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
3919 #ifndef NDEBUG
3920   bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
3921 #endif
3922 
3923   if (Options.SimpleReduction) {
3924     assert(!TeamsReduction && !ParallelReduction &&
3925            "Invalid reduction selection in emitReduction.");
3926     CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3927                                    ReductionOps, Options);
3928     return;
3929   }
3930 
3931   assert((TeamsReduction || ParallelReduction) &&
3932          "Invalid reduction selection in emitReduction.");
3933 
3934   // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3935   // RedList, shuffle_reduce_func, interwarp_copy_func);
3936   // or
3937   // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
3938   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3939   llvm::Value *ThreadId = getThreadID(CGF, Loc);
3940 
3941   llvm::Value *Res;
3942   ASTContext &C = CGM.getContext();
3943   // 1. Build a list of reduction variables.
3944   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3945   auto Size = RHSExprs.size();
3946   for (const Expr *E : Privates) {
3947     if (E->getType()->isVariablyModifiedType())
3948       // Reserve place for array size.
3949       ++Size;
3950   }
3951   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3952   QualType ReductionArrayTy =
3953       C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
3954                              /*IndexTypeQuals=*/0);
3955   Address ReductionList =
3956       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3957   auto IPriv = Privates.begin();
3958   unsigned Idx = 0;
3959   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3960     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3961     CGF.Builder.CreateStore(
3962         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3963             CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
3964         Elem);
3965     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3966       // Store array size.
3967       ++Idx;
3968       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3969       llvm::Value *Size = CGF.Builder.CreateIntCast(
3970           CGF.getVLASize(
3971                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3972               .NumElts,
3973           CGF.SizeTy, /*isSigned=*/false);
3974       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3975                               Elem);
3976     }
3977   }
3978 
3979   llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3980       ReductionList.getPointer(), CGF.VoidPtrTy);
3981   llvm::Function *ReductionFn = emitReductionFunction(
3982       Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3983       LHSExprs, RHSExprs, ReductionOps);
3984   llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3985   llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3986       CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3987   llvm::Value *InterWarpCopyFn =
3988       emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3989 
3990   if (ParallelReduction) {
3991     llvm::Value *Args[] = {RTLoc,
3992                            ThreadId,
3993                            CGF.Builder.getInt32(RHSExprs.size()),
3994                            ReductionArrayTySize,
3995                            RL,
3996                            ShuffleAndReduceFn,
3997                            InterWarpCopyFn};
3998 
3999     Res = CGF.EmitRuntimeCall(
4000         OMPBuilder.getOrCreateRuntimeFunction(
4001             CGM.getModule(), OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2),
4002         Args);
4003   } else {
4004     assert(TeamsReduction && "expected teams reduction.");
4005     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4006     llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4007     int Cnt = 0;
4008     for (const Expr *DRE : Privates) {
4009       PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4010       ++Cnt;
4011     }
4012     const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4013         CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4014         C.getLangOpts().OpenMPCUDAReductionBufNum);
4015     TeamsReductions.push_back(TeamReductionRec);
4016     if (!KernelTeamsReductionPtr) {
4017       KernelTeamsReductionPtr = new llvm::GlobalVariable(
4018           CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4019           llvm::GlobalValue::InternalLinkage, nullptr,
4020           "_openmp_teams_reductions_buffer_$_$ptr");
4021     }
4022     llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4023         Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4024         /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4025     llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4026         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4027     llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4028         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4029         ReductionFn);
4030     llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4031         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4032     llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4033         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4034         ReductionFn);
4035 
4036     llvm::Value *Args[] = {
4037         RTLoc,
4038         ThreadId,
4039         GlobalBufferPtr,
4040         CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4041         RL,
4042         ShuffleAndReduceFn,
4043         InterWarpCopyFn,
4044         GlobalToBufferCpyFn,
4045         GlobalToBufferRedFn,
4046         BufferToGlobalCpyFn,
4047         BufferToGlobalRedFn};
4048 
4049     Res = CGF.EmitRuntimeCall(
4050         OMPBuilder.getOrCreateRuntimeFunction(
4051             CGM.getModule(), OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2),
4052         Args);
4053   }
4054 
4055   // 5. Build if (res == 1)
4056   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4057   llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4058   llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4059       Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4060   CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
4061 
4062   // 6. Build then branch: where we have reduced values in the master
4063   //    thread in each team.
4064   //    __kmpc_end_reduce{_nowait}(<gtid>);
4065   //    break;
4066   CGF.EmitBlock(ThenBB);
4067 
4068   // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
4069   auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
4070                     this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4071     auto IPriv = Privates.begin();
4072     auto ILHS = LHSExprs.begin();
4073     auto IRHS = RHSExprs.begin();
4074     for (const Expr *E : ReductionOps) {
4075       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4076                                   cast<DeclRefExpr>(*IRHS));
4077       ++IPriv;
4078       ++ILHS;
4079       ++IRHS;
4080     }
4081   };
4082   llvm::Value *EndArgs[] = {ThreadId};
4083   RegionCodeGenTy RCG(CodeGen);
4084   NVPTXActionTy Action(
4085       nullptr, llvm::None,
4086       OMPBuilder.getOrCreateRuntimeFunction(
4087           CGM.getModule(), OMPRTL___kmpc_nvptx_end_reduce_nowait),
4088       EndArgs);
4089   RCG.setAction(Action);
4090   RCG(CGF);
4091   // There is no need to emit line number for unconditional branch.
4092   (void)ApplyDebugLocation::CreateEmpty(CGF);
4093   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
4094 }
4095 
4096 const VarDecl *
4097 CGOpenMPRuntimeGPU::translateParameter(const FieldDecl *FD,
4098                                        const VarDecl *NativeParam) const {
4099   if (!NativeParam->getType()->isReferenceType())
4100     return NativeParam;
4101   QualType ArgType = NativeParam->getType();
4102   QualifierCollector QC;
4103   const Type *NonQualTy = QC.strip(ArgType);
4104   QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4105   if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4106     if (Attr->getCaptureKind() == OMPC_map) {
4107       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4108                                                         LangAS::opencl_global);
4109     } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4110                PointeeTy.isConstant(CGM.getContext())) {
4111       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4112                                                         LangAS::opencl_generic);
4113     }
4114   }
4115   ArgType = CGM.getContext().getPointerType(PointeeTy);
4116   QC.addRestrict();
4117   enum { NVPTX_local_addr = 5 };
4118   QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
4119   ArgType = QC.apply(CGM.getContext(), ArgType);
4120   if (isa<ImplicitParamDecl>(NativeParam))
4121     return ImplicitParamDecl::Create(
4122         CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4123         NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
4124   return ParmVarDecl::Create(
4125       CGM.getContext(),
4126       const_cast<DeclContext *>(NativeParam->getDeclContext()),
4127       NativeParam->getBeginLoc(), NativeParam->getLocation(),
4128       NativeParam->getIdentifier(), ArgType,
4129       /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
4130 }
4131 
4132 Address
4133 CGOpenMPRuntimeGPU::getParameterAddress(CodeGenFunction &CGF,
4134                                           const VarDecl *NativeParam,
4135                                           const VarDecl *TargetParam) const {
4136   assert(NativeParam != TargetParam &&
4137          NativeParam->getType()->isReferenceType() &&
4138          "Native arg must not be the same as target arg.");
4139   Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4140   QualType NativeParamType = NativeParam->getType();
4141   QualifierCollector QC;
4142   const Type *NonQualTy = QC.strip(NativeParamType);
4143   QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4144   unsigned NativePointeeAddrSpace =
4145       CGF.getContext().getTargetAddressSpace(NativePointeeTy);
4146   QualType TargetTy = TargetParam->getType();
4147   llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
4148       LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
4149   // First cast to generic.
4150   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4151       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4152                       /*AddrSpace=*/0));
4153   // Cast from generic to native address space.
4154   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4155       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4156                       NativePointeeAddrSpace));
4157   Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4158   CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
4159                         NativeParamType);
4160   return NativeParamAddr;
4161 }
4162 
4163 void CGOpenMPRuntimeGPU::emitOutlinedFunctionCall(
4164     CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
4165     ArrayRef<llvm::Value *> Args) const {
4166   SmallVector<llvm::Value *, 4> TargetArgs;
4167   TargetArgs.reserve(Args.size());
4168   auto *FnType = OutlinedFn.getFunctionType();
4169   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
4170     if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4171       TargetArgs.append(std::next(Args.begin(), I), Args.end());
4172       break;
4173     }
4174     llvm::Type *TargetType = FnType->getParamType(I);
4175     llvm::Value *NativeArg = Args[I];
4176     if (!TargetType->isPointerTy()) {
4177       TargetArgs.emplace_back(NativeArg);
4178       continue;
4179     }
4180     llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4181         NativeArg,
4182         NativeArg->getType()->getPointerElementType()->getPointerTo());
4183     TargetArgs.emplace_back(
4184         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4185   }
4186   CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
4187 }
4188 
4189 /// Emit function which wraps the outline parallel region
4190 /// and controls the arguments which are passed to this function.
4191 /// The wrapper ensures that the outlined function is called
4192 /// with the correct arguments when data is shared.
4193 llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
4194     llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4195   ASTContext &Ctx = CGM.getContext();
4196   const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4197 
4198   // Create a function that takes as argument the source thread.
4199   FunctionArgList WrapperArgs;
4200   QualType Int16QTy =
4201       Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4202   QualType Int32QTy =
4203       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
4204   ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4205                                      /*Id=*/nullptr, Int16QTy,
4206                                      ImplicitParamDecl::Other);
4207   ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
4208                                /*Id=*/nullptr, Int32QTy,
4209                                ImplicitParamDecl::Other);
4210   WrapperArgs.emplace_back(&ParallelLevelArg);
4211   WrapperArgs.emplace_back(&WrapperArg);
4212 
4213   const CGFunctionInfo &CGFI =
4214       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4215 
4216   auto *Fn = llvm::Function::Create(
4217       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4218       Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
4219   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
4220   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
4221   Fn->setDoesNotRecurse();
4222 
4223   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4224   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
4225                     D.getBeginLoc(), D.getBeginLoc());
4226 
4227   const auto *RD = CS.getCapturedRecordDecl();
4228   auto CurField = RD->field_begin();
4229 
4230   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4231                                                       /*Name=*/".zero.addr");
4232   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
4233   // Get the array of arguments.
4234   SmallVector<llvm::Value *, 8> Args;
4235 
4236   Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4237   Args.emplace_back(ZeroAddr.getPointer());
4238 
4239   CGBuilderTy &Bld = CGF.Builder;
4240   auto CI = CS.capture_begin();
4241 
4242   // Use global memory for data sharing.
4243   // Handle passing of global args to workers.
4244   Address GlobalArgs =
4245       CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4246   llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4247   llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4248   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4249                           CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
4250                       DataSharingArgs);
4251 
4252   // Retrieve the shared variables from the list of references returned
4253   // by the runtime. Pass the variables to the outlined function.
4254   Address SharedArgListAddress = Address::invalid();
4255   if (CS.capture_size() > 0 ||
4256       isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4257     SharedArgListAddress = CGF.EmitLoadOfPointer(
4258         GlobalArgs, CGF.getContext()
4259                         .getPointerType(CGF.getContext().getPointerType(
4260                             CGF.getContext().VoidPtrTy))
4261                         .castAs<PointerType>());
4262   }
4263   unsigned Idx = 0;
4264   if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4265     Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4266     Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4267         Src, CGF.SizeTy->getPointerTo());
4268     llvm::Value *LB = CGF.EmitLoadOfScalar(
4269         TypedAddress,
4270         /*Volatile=*/false,
4271         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4272         cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4273     Args.emplace_back(LB);
4274     ++Idx;
4275     Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
4276     TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4277         Src, CGF.SizeTy->getPointerTo());
4278     llvm::Value *UB = CGF.EmitLoadOfScalar(
4279         TypedAddress,
4280         /*Volatile=*/false,
4281         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4282         cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4283     Args.emplace_back(UB);
4284     ++Idx;
4285   }
4286   if (CS.capture_size() > 0) {
4287     ASTContext &CGFContext = CGF.getContext();
4288     for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4289       QualType ElemTy = CurField->getType();
4290       Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
4291       Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4292           Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4293       llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4294                                               /*Volatile=*/false,
4295                                               CGFContext.getPointerType(ElemTy),
4296                                               CI->getLocation());
4297       if (CI->capturesVariableByCopy() &&
4298           !CI->getCapturedVar()->getType()->isAnyPointerType()) {
4299         Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4300                               CI->getLocation());
4301       }
4302       Args.emplace_back(Arg);
4303     }
4304   }
4305 
4306   emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
4307   CGF.FinishFunction();
4308   return Fn;
4309 }
4310 
4311 void CGOpenMPRuntimeGPU::emitFunctionProlog(CodeGenFunction &CGF,
4312                                               const Decl *D) {
4313   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
4314     return;
4315 
4316   assert(D && "Expected function or captured|block decl.");
4317   assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4318          "Function is registered already.");
4319   assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4320          "Team is set but not processed.");
4321   const Stmt *Body = nullptr;
4322   bool NeedToDelayGlobalization = false;
4323   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4324     Body = FD->getBody();
4325   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4326     Body = BD->getBody();
4327   } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4328     Body = CD->getBody();
4329     NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
4330     if (NeedToDelayGlobalization &&
4331         getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
4332       return;
4333   }
4334   if (!Body)
4335     return;
4336   CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
4337   VarChecker.Visit(Body);
4338   const RecordDecl *GlobalizedVarsRecord =
4339       VarChecker.getGlobalizedRecord(IsInTTDRegion);
4340   TeamAndReductions.first = nullptr;
4341   TeamAndReductions.second.clear();
4342   ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4343       VarChecker.getEscapedVariableLengthDecls();
4344   if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
4345     return;
4346   auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4347   I->getSecond().MappedParams =
4348       std::make_unique<CodeGenFunction::OMPMapVars>();
4349   I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4350   I->getSecond().EscapedParameters.insert(
4351       VarChecker.getEscapedParameters().begin(),
4352       VarChecker.getEscapedParameters().end());
4353   I->getSecond().EscapedVariableLengthDecls.append(
4354       EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
4355   DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
4356   for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4357     assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4358     const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4359     Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
4360   }
4361   if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
4362     CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
4363     VarChecker.Visit(Body);
4364     I->getSecond().SecondaryGlobalRecord =
4365         VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
4366     I->getSecond().SecondaryLocalVarData.emplace();
4367     DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4368     for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4369       assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4370       const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
4371       Data.insert(
4372           std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
4373     }
4374   }
4375   if (!NeedToDelayGlobalization) {
4376     emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
4377     struct GlobalizationScope final : EHScopeStack::Cleanup {
4378       GlobalizationScope() = default;
4379 
4380       void Emit(CodeGenFunction &CGF, Flags flags) override {
4381         static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
4382             .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
4383       }
4384     };
4385     CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
4386   }
4387 }
4388 
4389 Address CGOpenMPRuntimeGPU::getAddressOfLocalVariable(CodeGenFunction &CGF,
4390                                                         const VarDecl *VD) {
4391   if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4392     const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4393     auto AS = LangAS::Default;
4394     switch (A->getAllocatorType()) {
4395       // Use the default allocator here as by default local vars are
4396       // threadlocal.
4397     case OMPAllocateDeclAttr::OMPNullMemAlloc:
4398     case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4399     case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4400     case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4401     case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4402       // Follow the user decision - use default allocation.
4403       return Address::invalid();
4404     case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4405       // TODO: implement aupport for user-defined allocators.
4406       return Address::invalid();
4407     case OMPAllocateDeclAttr::OMPConstMemAlloc:
4408       AS = LangAS::cuda_constant;
4409       break;
4410     case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4411       AS = LangAS::cuda_shared;
4412       break;
4413     case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4414     case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4415       break;
4416     }
4417     llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4418     auto *GV = new llvm::GlobalVariable(
4419         CGM.getModule(), VarTy, /*isConstant=*/false,
4420         llvm::GlobalValue::InternalLinkage, llvm::Constant::getNullValue(VarTy),
4421         VD->getName(),
4422         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4423         CGM.getContext().getTargetAddressSpace(AS));
4424     CharUnits Align = CGM.getContext().getDeclAlign(VD);
4425     GV->setAlignment(Align.getAsAlign());
4426     return Address(
4427         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4428             GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
4429                     VD->getType().getAddressSpace()))),
4430         Align);
4431   }
4432 
4433   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
4434     return Address::invalid();
4435 
4436   VD = VD->getCanonicalDecl();
4437   auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4438   if (I == FunctionGlobalizedDecls.end())
4439     return Address::invalid();
4440   auto VDI = I->getSecond().LocalVarData.find(VD);
4441   if (VDI != I->getSecond().LocalVarData.end())
4442     return VDI->second.PrivateAddr;
4443   if (VD->hasAttrs()) {
4444     for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4445          E(VD->attr_end());
4446          IT != E; ++IT) {
4447       auto VDI = I->getSecond().LocalVarData.find(
4448           cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4449               ->getCanonicalDecl());
4450       if (VDI != I->getSecond().LocalVarData.end())
4451         return VDI->second.PrivateAddr;
4452     }
4453   }
4454 
4455   return Address::invalid();
4456 }
4457 
4458 void CGOpenMPRuntimeGPU::functionFinished(CodeGenFunction &CGF) {
4459   FunctionGlobalizedDecls.erase(CGF.CurFn);
4460   CGOpenMPRuntime::functionFinished(CGF);
4461 }
4462 
4463 void CGOpenMPRuntimeGPU::getDefaultDistScheduleAndChunk(
4464     CodeGenFunction &CGF, const OMPLoopDirective &S,
4465     OpenMPDistScheduleClauseKind &ScheduleKind,
4466     llvm::Value *&Chunk) const {
4467   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
4468   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
4469     ScheduleKind = OMPC_DIST_SCHEDULE_static;
4470     Chunk = CGF.EmitScalarConversion(
4471         RT.getGPUNumThreads(CGF),
4472         CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4473         S.getIterationVariable()->getType(), S.getBeginLoc());
4474     return;
4475   }
4476   CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4477       CGF, S, ScheduleKind, Chunk);
4478 }
4479 
4480 void CGOpenMPRuntimeGPU::getDefaultScheduleAndChunk(
4481     CodeGenFunction &CGF, const OMPLoopDirective &S,
4482     OpenMPScheduleClauseKind &ScheduleKind,
4483     const Expr *&ChunkExpr) const {
4484   ScheduleKind = OMPC_SCHEDULE_static;
4485   // Chunk size is 1 in this case.
4486   llvm::APInt ChunkSize(32, 1);
4487   ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4488       CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4489       SourceLocation());
4490 }
4491 
4492 void CGOpenMPRuntimeGPU::adjustTargetSpecificDataForLambdas(
4493     CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4494   assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4495          " Expected target-based directive.");
4496   const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4497   for (const CapturedStmt::Capture &C : CS->captures()) {
4498     // Capture variables captured by reference in lambdas for target-based
4499     // directives.
4500     if (!C.capturesVariable())
4501       continue;
4502     const VarDecl *VD = C.getCapturedVar();
4503     const auto *RD = VD->getType()
4504                          .getCanonicalType()
4505                          .getNonReferenceType()
4506                          ->getAsCXXRecordDecl();
4507     if (!RD || !RD->isLambda())
4508       continue;
4509     Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4510     LValue VDLVal;
4511     if (VD->getType().getCanonicalType()->isReferenceType())
4512       VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4513     else
4514       VDLVal = CGF.MakeAddrLValue(
4515           VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4516     llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4517     FieldDecl *ThisCapture = nullptr;
4518     RD->getCaptureFields(Captures, ThisCapture);
4519     if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4520       LValue ThisLVal =
4521           CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4522       llvm::Value *CXXThis = CGF.LoadCXXThis();
4523       CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4524     }
4525     for (const LambdaCapture &LC : RD->captures()) {
4526       if (LC.getCaptureKind() != LCK_ByRef)
4527         continue;
4528       const VarDecl *VD = LC.getCapturedVar();
4529       if (!CS->capturesVariable(VD))
4530         continue;
4531       auto It = Captures.find(VD);
4532       assert(It != Captures.end() && "Found lambda capture without field.");
4533       LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4534       Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4535       if (VD->getType().getCanonicalType()->isReferenceType())
4536         VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4537                                                VD->getType().getCanonicalType())
4538                      .getAddress(CGF);
4539       CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4540     }
4541   }
4542 }
4543 
4544 unsigned CGOpenMPRuntimeGPU::getDefaultFirstprivateAddressSpace() const {
4545   return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4546 }
4547 
4548 bool CGOpenMPRuntimeGPU::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4549                                                             LangAS &AS) {
4550   if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4551     return false;
4552   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4553   switch(A->getAllocatorType()) {
4554   case OMPAllocateDeclAttr::OMPNullMemAlloc:
4555   case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4556   // Not supported, fallback to the default mem space.
4557   case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4558   case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4559   case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4560   case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4561   case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4562     AS = LangAS::Default;
4563     return true;
4564   case OMPAllocateDeclAttr::OMPConstMemAlloc:
4565     AS = LangAS::cuda_constant;
4566     return true;
4567   case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4568     AS = LangAS::cuda_shared;
4569     return true;
4570   case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4571     llvm_unreachable("Expected predefined allocator for the variables with the "
4572                      "static storage.");
4573   }
4574   return false;
4575 }
4576 
4577 // Get current CudaArch and ignore any unknown values
4578 static CudaArch getCudaArch(CodeGenModule &CGM) {
4579   if (!CGM.getTarget().hasFeature("ptx"))
4580     return CudaArch::UNKNOWN;
4581   for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
4582     if (Feature.getValue()) {
4583       CudaArch Arch = StringToCudaArch(Feature.getKey());
4584       if (Arch != CudaArch::UNKNOWN)
4585         return Arch;
4586     }
4587   }
4588   return CudaArch::UNKNOWN;
4589 }
4590 
4591 /// Check to see if target architecture supports unified addressing which is
4592 /// a restriction for OpenMP requires clause "unified_shared_memory".
4593 void CGOpenMPRuntimeGPU::processRequiresDirective(
4594     const OMPRequiresDecl *D) {
4595   for (const OMPClause *Clause : D->clauselists()) {
4596     if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4597       CudaArch Arch = getCudaArch(CGM);
4598       switch (Arch) {
4599       case CudaArch::SM_20:
4600       case CudaArch::SM_21:
4601       case CudaArch::SM_30:
4602       case CudaArch::SM_32:
4603       case CudaArch::SM_35:
4604       case CudaArch::SM_37:
4605       case CudaArch::SM_50:
4606       case CudaArch::SM_52:
4607       case CudaArch::SM_53:
4608       case CudaArch::SM_60:
4609       case CudaArch::SM_61:
4610       case CudaArch::SM_62: {
4611         SmallString<256> Buffer;
4612         llvm::raw_svector_ostream Out(Buffer);
4613         Out << "Target architecture " << CudaArchToString(Arch)
4614             << " does not support unified addressing";
4615         CGM.Error(Clause->getBeginLoc(), Out.str());
4616         return;
4617       }
4618       case CudaArch::SM_70:
4619       case CudaArch::SM_72:
4620       case CudaArch::SM_75:
4621       case CudaArch::SM_80:
4622       case CudaArch::SM_86:
4623       case CudaArch::GFX600:
4624       case CudaArch::GFX601:
4625       case CudaArch::GFX602:
4626       case CudaArch::GFX700:
4627       case CudaArch::GFX701:
4628       case CudaArch::GFX702:
4629       case CudaArch::GFX703:
4630       case CudaArch::GFX704:
4631       case CudaArch::GFX705:
4632       case CudaArch::GFX801:
4633       case CudaArch::GFX802:
4634       case CudaArch::GFX803:
4635       case CudaArch::GFX805:
4636       case CudaArch::GFX810:
4637       case CudaArch::GFX900:
4638       case CudaArch::GFX902:
4639       case CudaArch::GFX904:
4640       case CudaArch::GFX906:
4641       case CudaArch::GFX908:
4642       case CudaArch::GFX909:
4643       case CudaArch::GFX90a:
4644       case CudaArch::GFX90c:
4645       case CudaArch::GFX1010:
4646       case CudaArch::GFX1011:
4647       case CudaArch::GFX1012:
4648       case CudaArch::GFX1030:
4649       case CudaArch::GFX1031:
4650       case CudaArch::GFX1032:
4651       case CudaArch::GFX1033:
4652       case CudaArch::UNUSED:
4653       case CudaArch::UNKNOWN:
4654         break;
4655       case CudaArch::LAST:
4656         llvm_unreachable("Unexpected Cuda arch.");
4657       }
4658     }
4659   }
4660   CGOpenMPRuntime::processRequiresDirective(D);
4661 }
4662 
4663 /// Get number of SMs and number of blocks per SM.
4664 static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4665   std::pair<unsigned, unsigned> Data;
4666   if (CGM.getLangOpts().OpenMPCUDANumSMs)
4667     Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4668   if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4669     Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4670   if (Data.first && Data.second)
4671     return Data;
4672   switch (getCudaArch(CGM)) {
4673   case CudaArch::SM_20:
4674   case CudaArch::SM_21:
4675   case CudaArch::SM_30:
4676   case CudaArch::SM_32:
4677   case CudaArch::SM_35:
4678   case CudaArch::SM_37:
4679   case CudaArch::SM_50:
4680   case CudaArch::SM_52:
4681   case CudaArch::SM_53:
4682     return {16, 16};
4683   case CudaArch::SM_60:
4684   case CudaArch::SM_61:
4685   case CudaArch::SM_62:
4686     return {56, 32};
4687   case CudaArch::SM_70:
4688   case CudaArch::SM_72:
4689   case CudaArch::SM_75:
4690   case CudaArch::SM_80:
4691   case CudaArch::SM_86:
4692     return {84, 32};
4693   case CudaArch::GFX600:
4694   case CudaArch::GFX601:
4695   case CudaArch::GFX602:
4696   case CudaArch::GFX700:
4697   case CudaArch::GFX701:
4698   case CudaArch::GFX702:
4699   case CudaArch::GFX703:
4700   case CudaArch::GFX704:
4701   case CudaArch::GFX705:
4702   case CudaArch::GFX801:
4703   case CudaArch::GFX802:
4704   case CudaArch::GFX803:
4705   case CudaArch::GFX805:
4706   case CudaArch::GFX810:
4707   case CudaArch::GFX900:
4708   case CudaArch::GFX902:
4709   case CudaArch::GFX904:
4710   case CudaArch::GFX906:
4711   case CudaArch::GFX908:
4712   case CudaArch::GFX909:
4713   case CudaArch::GFX90a:
4714   case CudaArch::GFX90c:
4715   case CudaArch::GFX1010:
4716   case CudaArch::GFX1011:
4717   case CudaArch::GFX1012:
4718   case CudaArch::GFX1030:
4719   case CudaArch::GFX1031:
4720   case CudaArch::GFX1032:
4721   case CudaArch::GFX1033:
4722   case CudaArch::UNUSED:
4723   case CudaArch::UNKNOWN:
4724     break;
4725   case CudaArch::LAST:
4726     llvm_unreachable("Unexpected Cuda arch.");
4727   }
4728   llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4729 }
4730 
4731 void CGOpenMPRuntimeGPU::clear() {
4732   if (!GlobalizedRecords.empty() &&
4733       !CGM.getLangOpts().OpenMPCUDATargetParallel) {
4734     ASTContext &C = CGM.getContext();
4735     llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4736     llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
4737     RecordDecl *StaticRD = C.buildImplicitRecord(
4738         "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4739     StaticRD->startDefinition();
4740     RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4741         "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4742     SharedStaticRD->startDefinition();
4743     for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4744       if (Records.Records.empty())
4745         continue;
4746       unsigned Size = 0;
4747       unsigned RecAlignment = 0;
4748       for (const RecordDecl *RD : Records.Records) {
4749         QualType RDTy = C.getRecordType(RD);
4750         unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
4751         RecAlignment = std::max(RecAlignment, Alignment);
4752         unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
4753         Size =
4754             llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4755       }
4756       Size = llvm::alignTo(Size, RecAlignment);
4757       llvm::APInt ArySize(/*numBits=*/64, Size);
4758       QualType SubTy = C.getConstantArrayType(
4759           C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
4760       const bool UseSharedMemory = Size <= SharedMemorySize;
4761       auto *Field =
4762           FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4763                             SourceLocation(), SourceLocation(), nullptr, SubTy,
4764                             C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4765                             /*BW=*/nullptr, /*Mutable=*/false,
4766                             /*InitStyle=*/ICIS_NoInit);
4767       Field->setAccess(AS_public);
4768       if (UseSharedMemory) {
4769         SharedStaticRD->addDecl(Field);
4770         SharedRecs.push_back(&Records);
4771       } else {
4772         StaticRD->addDecl(Field);
4773         GlobalRecs.push_back(&Records);
4774       }
4775       Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
4776       Records.UseSharedMemory->setInitializer(
4777           llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4778     }
4779     // Allocate SharedMemorySize buffer for the shared memory.
4780     // FIXME: nvlink does not handle weak linkage correctly (object with the
4781     // different size are reported as erroneous).
4782     // Restore this code as sson as nvlink is fixed.
4783     if (!SharedStaticRD->field_empty()) {
4784       llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4785       QualType SubTy = C.getConstantArrayType(
4786           C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
4787       auto *Field = FieldDecl::Create(
4788           C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4789           C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4790           /*BW=*/nullptr, /*Mutable=*/false,
4791           /*InitStyle=*/ICIS_NoInit);
4792       Field->setAccess(AS_public);
4793       SharedStaticRD->addDecl(Field);
4794     }
4795     SharedStaticRD->completeDefinition();
4796     if (!SharedStaticRD->field_empty()) {
4797       QualType StaticTy = C.getRecordType(SharedStaticRD);
4798       llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4799       auto *GV = new llvm::GlobalVariable(
4800           CGM.getModule(), LLVMStaticTy,
4801           /*isConstant=*/false, llvm::GlobalValue::WeakAnyLinkage,
4802           llvm::UndefValue::get(LLVMStaticTy),
4803           "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4804           llvm::GlobalValue::NotThreadLocal,
4805           C.getTargetAddressSpace(LangAS::cuda_shared));
4806       auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4807           GV, CGM.VoidPtrTy);
4808       for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4809         Rec->Buffer->replaceAllUsesWith(Replacement);
4810         Rec->Buffer->eraseFromParent();
4811       }
4812     }
4813     StaticRD->completeDefinition();
4814     if (!StaticRD->field_empty()) {
4815       QualType StaticTy = C.getRecordType(StaticRD);
4816       std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4817       llvm::APInt Size1(32, SMsBlockPerSM.second);
4818       QualType Arr1Ty =
4819           C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
4820                                  /*IndexTypeQuals=*/0);
4821       llvm::APInt Size2(32, SMsBlockPerSM.first);
4822       QualType Arr2Ty =
4823           C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
4824                                  /*IndexTypeQuals=*/0);
4825       llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4826       // FIXME: nvlink does not handle weak linkage correctly (object with the
4827       // different size are reported as erroneous).
4828       // Restore CommonLinkage as soon as nvlink is fixed.
4829       auto *GV = new llvm::GlobalVariable(
4830           CGM.getModule(), LLVMArr2Ty,
4831           /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
4832           llvm::Constant::getNullValue(LLVMArr2Ty),
4833           "_openmp_static_glob_rd_$_");
4834       auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4835           GV, CGM.VoidPtrTy);
4836       for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4837         Rec->Buffer->replaceAllUsesWith(Replacement);
4838         Rec->Buffer->eraseFromParent();
4839       }
4840     }
4841   }
4842   if (!TeamsReductions.empty()) {
4843     ASTContext &C = CGM.getContext();
4844     RecordDecl *StaticRD = C.buildImplicitRecord(
4845         "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
4846     StaticRD->startDefinition();
4847     for (const RecordDecl *TeamReductionRec : TeamsReductions) {
4848       QualType RecTy = C.getRecordType(TeamReductionRec);
4849       auto *Field = FieldDecl::Create(
4850           C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
4851           C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
4852           /*BW=*/nullptr, /*Mutable=*/false,
4853           /*InitStyle=*/ICIS_NoInit);
4854       Field->setAccess(AS_public);
4855       StaticRD->addDecl(Field);
4856     }
4857     StaticRD->completeDefinition();
4858     QualType StaticTy = C.getRecordType(StaticRD);
4859     llvm::Type *LLVMReductionsBufferTy =
4860         CGM.getTypes().ConvertTypeForMem(StaticTy);
4861     // FIXME: nvlink does not handle weak linkage correctly (object with the
4862     // different size are reported as erroneous).
4863     // Restore CommonLinkage as soon as nvlink is fixed.
4864     auto *GV = new llvm::GlobalVariable(
4865         CGM.getModule(), LLVMReductionsBufferTy,
4866         /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
4867         llvm::Constant::getNullValue(LLVMReductionsBufferTy),
4868         "_openmp_teams_reductions_buffer_$_");
4869     KernelTeamsReductionPtr->setInitializer(
4870         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4871                                                              CGM.VoidPtrTy));
4872   }
4873   CGOpenMPRuntime::clear();
4874 }
4875