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().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 = CGF.getTarget().getGridValue().GV_Warp_Size_Log2;
539   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
540   return Bld.CreateAShr(RT.getGPUThreadID(CGF), LaneIDBits, "nvptx_warp_id");
541 }
542 
543 /// Get the id of the current lane in the Warp.
544 /// We assume that the warp size is 32, which is always the case
545 /// on the NVPTX device, to generate more efficient code.
546 static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
547   CGBuilderTy &Bld = CGF.Builder;
548   unsigned LaneIDMask =
549       CGF.getContext().getTargetInfo().getGridValue().GV_Warp_Size_Log2_Mask;
550   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
551   return Bld.CreateAnd(RT.getGPUThreadID(CGF), Bld.getInt32(LaneIDMask),
552                        "nvptx_lane_id");
553 }
554 
555 CGOpenMPRuntimeGPU::ExecutionMode
556 CGOpenMPRuntimeGPU::getExecutionMode() const {
557   return CurrentExecutionMode;
558 }
559 
560 static CGOpenMPRuntimeGPU::DataSharingMode
561 getDataSharingMode(CodeGenModule &CGM) {
562   return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeGPU::CUDA
563                                           : CGOpenMPRuntimeGPU::Generic;
564 }
565 
566 /// Check for inner (nested) SPMD construct, if any
567 static bool hasNestedSPMDDirective(ASTContext &Ctx,
568                                    const OMPExecutableDirective &D) {
569   const auto *CS = D.getInnermostCapturedStmt();
570   const auto *Body =
571       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
572   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
573 
574   if (const auto *NestedDir =
575           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
576     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
577     switch (D.getDirectiveKind()) {
578     case OMPD_target:
579       if (isOpenMPParallelDirective(DKind))
580         return true;
581       if (DKind == OMPD_teams) {
582         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
583             /*IgnoreCaptured=*/true);
584         if (!Body)
585           return false;
586         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
587         if (const auto *NND =
588                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
589           DKind = NND->getDirectiveKind();
590           if (isOpenMPParallelDirective(DKind))
591             return true;
592         }
593       }
594       return false;
595     case OMPD_target_teams:
596       return isOpenMPParallelDirective(DKind);
597     case OMPD_target_simd:
598     case OMPD_target_parallel:
599     case OMPD_target_parallel_for:
600     case OMPD_target_parallel_for_simd:
601     case OMPD_target_teams_distribute:
602     case OMPD_target_teams_distribute_simd:
603     case OMPD_target_teams_distribute_parallel_for:
604     case OMPD_target_teams_distribute_parallel_for_simd:
605     case OMPD_parallel:
606     case OMPD_for:
607     case OMPD_parallel_for:
608     case OMPD_parallel_master:
609     case OMPD_parallel_sections:
610     case OMPD_for_simd:
611     case OMPD_parallel_for_simd:
612     case OMPD_cancel:
613     case OMPD_cancellation_point:
614     case OMPD_ordered:
615     case OMPD_threadprivate:
616     case OMPD_allocate:
617     case OMPD_task:
618     case OMPD_simd:
619     case OMPD_sections:
620     case OMPD_section:
621     case OMPD_single:
622     case OMPD_master:
623     case OMPD_critical:
624     case OMPD_taskyield:
625     case OMPD_barrier:
626     case OMPD_taskwait:
627     case OMPD_taskgroup:
628     case OMPD_atomic:
629     case OMPD_flush:
630     case OMPD_depobj:
631     case OMPD_scan:
632     case OMPD_teams:
633     case OMPD_target_data:
634     case OMPD_target_exit_data:
635     case OMPD_target_enter_data:
636     case OMPD_distribute:
637     case OMPD_distribute_simd:
638     case OMPD_distribute_parallel_for:
639     case OMPD_distribute_parallel_for_simd:
640     case OMPD_teams_distribute:
641     case OMPD_teams_distribute_simd:
642     case OMPD_teams_distribute_parallel_for:
643     case OMPD_teams_distribute_parallel_for_simd:
644     case OMPD_target_update:
645     case OMPD_declare_simd:
646     case OMPD_declare_variant:
647     case OMPD_begin_declare_variant:
648     case OMPD_end_declare_variant:
649     case OMPD_declare_target:
650     case OMPD_end_declare_target:
651     case OMPD_declare_reduction:
652     case OMPD_declare_mapper:
653     case OMPD_taskloop:
654     case OMPD_taskloop_simd:
655     case OMPD_master_taskloop:
656     case OMPD_master_taskloop_simd:
657     case OMPD_parallel_master_taskloop:
658     case OMPD_parallel_master_taskloop_simd:
659     case OMPD_requires:
660     case OMPD_unknown:
661     default:
662       llvm_unreachable("Unexpected directive.");
663     }
664   }
665 
666   return false;
667 }
668 
669 static bool supportsSPMDExecutionMode(ASTContext &Ctx,
670                                       const OMPExecutableDirective &D) {
671   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
672   switch (DirectiveKind) {
673   case OMPD_target:
674   case OMPD_target_teams:
675     return hasNestedSPMDDirective(Ctx, D);
676   case OMPD_target_parallel:
677   case OMPD_target_parallel_for:
678   case OMPD_target_parallel_for_simd:
679   case OMPD_target_teams_distribute_parallel_for:
680   case OMPD_target_teams_distribute_parallel_for_simd:
681   case OMPD_target_simd:
682   case OMPD_target_teams_distribute_simd:
683     return true;
684   case OMPD_target_teams_distribute:
685     return false;
686   case OMPD_parallel:
687   case OMPD_for:
688   case OMPD_parallel_for:
689   case OMPD_parallel_master:
690   case OMPD_parallel_sections:
691   case OMPD_for_simd:
692   case OMPD_parallel_for_simd:
693   case OMPD_cancel:
694   case OMPD_cancellation_point:
695   case OMPD_ordered:
696   case OMPD_threadprivate:
697   case OMPD_allocate:
698   case OMPD_task:
699   case OMPD_simd:
700   case OMPD_sections:
701   case OMPD_section:
702   case OMPD_single:
703   case OMPD_master:
704   case OMPD_critical:
705   case OMPD_taskyield:
706   case OMPD_barrier:
707   case OMPD_taskwait:
708   case OMPD_taskgroup:
709   case OMPD_atomic:
710   case OMPD_flush:
711   case OMPD_depobj:
712   case OMPD_scan:
713   case OMPD_teams:
714   case OMPD_target_data:
715   case OMPD_target_exit_data:
716   case OMPD_target_enter_data:
717   case OMPD_distribute:
718   case OMPD_distribute_simd:
719   case OMPD_distribute_parallel_for:
720   case OMPD_distribute_parallel_for_simd:
721   case OMPD_teams_distribute:
722   case OMPD_teams_distribute_simd:
723   case OMPD_teams_distribute_parallel_for:
724   case OMPD_teams_distribute_parallel_for_simd:
725   case OMPD_target_update:
726   case OMPD_declare_simd:
727   case OMPD_declare_variant:
728   case OMPD_begin_declare_variant:
729   case OMPD_end_declare_variant:
730   case OMPD_declare_target:
731   case OMPD_end_declare_target:
732   case OMPD_declare_reduction:
733   case OMPD_declare_mapper:
734   case OMPD_taskloop:
735   case OMPD_taskloop_simd:
736   case OMPD_master_taskloop:
737   case OMPD_master_taskloop_simd:
738   case OMPD_parallel_master_taskloop:
739   case OMPD_parallel_master_taskloop_simd:
740   case OMPD_requires:
741   case OMPD_unknown:
742   default:
743     break;
744   }
745   llvm_unreachable(
746       "Unknown programming model for OpenMP directive on NVPTX target.");
747 }
748 
749 /// Check if the directive is loops based and has schedule clause at all or has
750 /// static scheduling.
751 static bool hasStaticScheduling(const OMPExecutableDirective &D) {
752   assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
753          isOpenMPLoopDirective(D.getDirectiveKind()) &&
754          "Expected loop-based directive.");
755   return !D.hasClausesOfKind<OMPOrderedClause>() &&
756          (!D.hasClausesOfKind<OMPScheduleClause>() ||
757           llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
758                        [](const OMPScheduleClause *C) {
759                          return C->getScheduleKind() == OMPC_SCHEDULE_static;
760                        }));
761 }
762 
763 /// Check for inner (nested) lightweight runtime construct, if any
764 static bool hasNestedLightweightDirective(ASTContext &Ctx,
765                                           const OMPExecutableDirective &D) {
766   assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
767   const auto *CS = D.getInnermostCapturedStmt();
768   const auto *Body =
769       CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
770   const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
771 
772   if (const auto *NestedDir =
773           dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
774     OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
775     switch (D.getDirectiveKind()) {
776     case OMPD_target:
777       if (isOpenMPParallelDirective(DKind) &&
778           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
779           hasStaticScheduling(*NestedDir))
780         return true;
781       if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
782         return true;
783       if (DKind == OMPD_parallel) {
784         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
785             /*IgnoreCaptured=*/true);
786         if (!Body)
787           return false;
788         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
789         if (const auto *NND =
790                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
791           DKind = NND->getDirectiveKind();
792           if (isOpenMPWorksharingDirective(DKind) &&
793               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
794             return true;
795         }
796       } else if (DKind == OMPD_teams) {
797         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
798             /*IgnoreCaptured=*/true);
799         if (!Body)
800           return false;
801         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
802         if (const auto *NND =
803                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
804           DKind = NND->getDirectiveKind();
805           if (isOpenMPParallelDirective(DKind) &&
806               isOpenMPWorksharingDirective(DKind) &&
807               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
808             return true;
809           if (DKind == OMPD_parallel) {
810             Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
811                 /*IgnoreCaptured=*/true);
812             if (!Body)
813               return false;
814             ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
815             if (const auto *NND =
816                     dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
817               DKind = NND->getDirectiveKind();
818               if (isOpenMPWorksharingDirective(DKind) &&
819                   isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
820                 return true;
821             }
822           }
823         }
824       }
825       return false;
826     case OMPD_target_teams:
827       if (isOpenMPParallelDirective(DKind) &&
828           isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
829           hasStaticScheduling(*NestedDir))
830         return true;
831       if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
832         return true;
833       if (DKind == OMPD_parallel) {
834         Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
835             /*IgnoreCaptured=*/true);
836         if (!Body)
837           return false;
838         ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
839         if (const auto *NND =
840                 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
841           DKind = NND->getDirectiveKind();
842           if (isOpenMPWorksharingDirective(DKind) &&
843               isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
844             return true;
845         }
846       }
847       return false;
848     case OMPD_target_parallel:
849       if (DKind == OMPD_simd)
850         return true;
851       return isOpenMPWorksharingDirective(DKind) &&
852              isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
853     case OMPD_target_teams_distribute:
854     case OMPD_target_simd:
855     case OMPD_target_parallel_for:
856     case OMPD_target_parallel_for_simd:
857     case OMPD_target_teams_distribute_simd:
858     case OMPD_target_teams_distribute_parallel_for:
859     case OMPD_target_teams_distribute_parallel_for_simd:
860     case OMPD_parallel:
861     case OMPD_for:
862     case OMPD_parallel_for:
863     case OMPD_parallel_master:
864     case OMPD_parallel_sections:
865     case OMPD_for_simd:
866     case OMPD_parallel_for_simd:
867     case OMPD_cancel:
868     case OMPD_cancellation_point:
869     case OMPD_ordered:
870     case OMPD_threadprivate:
871     case OMPD_allocate:
872     case OMPD_task:
873     case OMPD_simd:
874     case OMPD_sections:
875     case OMPD_section:
876     case OMPD_single:
877     case OMPD_master:
878     case OMPD_critical:
879     case OMPD_taskyield:
880     case OMPD_barrier:
881     case OMPD_taskwait:
882     case OMPD_taskgroup:
883     case OMPD_atomic:
884     case OMPD_flush:
885     case OMPD_depobj:
886     case OMPD_scan:
887     case OMPD_teams:
888     case OMPD_target_data:
889     case OMPD_target_exit_data:
890     case OMPD_target_enter_data:
891     case OMPD_distribute:
892     case OMPD_distribute_simd:
893     case OMPD_distribute_parallel_for:
894     case OMPD_distribute_parallel_for_simd:
895     case OMPD_teams_distribute:
896     case OMPD_teams_distribute_simd:
897     case OMPD_teams_distribute_parallel_for:
898     case OMPD_teams_distribute_parallel_for_simd:
899     case OMPD_target_update:
900     case OMPD_declare_simd:
901     case OMPD_declare_variant:
902     case OMPD_begin_declare_variant:
903     case OMPD_end_declare_variant:
904     case OMPD_declare_target:
905     case OMPD_end_declare_target:
906     case OMPD_declare_reduction:
907     case OMPD_declare_mapper:
908     case OMPD_taskloop:
909     case OMPD_taskloop_simd:
910     case OMPD_master_taskloop:
911     case OMPD_master_taskloop_simd:
912     case OMPD_parallel_master_taskloop:
913     case OMPD_parallel_master_taskloop_simd:
914     case OMPD_requires:
915     case OMPD_unknown:
916     default:
917       llvm_unreachable("Unexpected directive.");
918     }
919   }
920 
921   return false;
922 }
923 
924 /// Checks if the construct supports lightweight runtime. It must be SPMD
925 /// construct + inner loop-based construct with static scheduling.
926 static bool supportsLightweightRuntime(ASTContext &Ctx,
927                                        const OMPExecutableDirective &D) {
928   if (!supportsSPMDExecutionMode(Ctx, D))
929     return false;
930   OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
931   switch (DirectiveKind) {
932   case OMPD_target:
933   case OMPD_target_teams:
934   case OMPD_target_parallel:
935     return hasNestedLightweightDirective(Ctx, D);
936   case OMPD_target_parallel_for:
937   case OMPD_target_parallel_for_simd:
938   case OMPD_target_teams_distribute_parallel_for:
939   case OMPD_target_teams_distribute_parallel_for_simd:
940     // (Last|First)-privates must be shared in parallel region.
941     return hasStaticScheduling(D);
942   case OMPD_target_simd:
943   case OMPD_target_teams_distribute_simd:
944     return true;
945   case OMPD_target_teams_distribute:
946     return false;
947   case OMPD_parallel:
948   case OMPD_for:
949   case OMPD_parallel_for:
950   case OMPD_parallel_master:
951   case OMPD_parallel_sections:
952   case OMPD_for_simd:
953   case OMPD_parallel_for_simd:
954   case OMPD_cancel:
955   case OMPD_cancellation_point:
956   case OMPD_ordered:
957   case OMPD_threadprivate:
958   case OMPD_allocate:
959   case OMPD_task:
960   case OMPD_simd:
961   case OMPD_sections:
962   case OMPD_section:
963   case OMPD_single:
964   case OMPD_master:
965   case OMPD_critical:
966   case OMPD_taskyield:
967   case OMPD_barrier:
968   case OMPD_taskwait:
969   case OMPD_taskgroup:
970   case OMPD_atomic:
971   case OMPD_flush:
972   case OMPD_depobj:
973   case OMPD_scan:
974   case OMPD_teams:
975   case OMPD_target_data:
976   case OMPD_target_exit_data:
977   case OMPD_target_enter_data:
978   case OMPD_distribute:
979   case OMPD_distribute_simd:
980   case OMPD_distribute_parallel_for:
981   case OMPD_distribute_parallel_for_simd:
982   case OMPD_teams_distribute:
983   case OMPD_teams_distribute_simd:
984   case OMPD_teams_distribute_parallel_for:
985   case OMPD_teams_distribute_parallel_for_simd:
986   case OMPD_target_update:
987   case OMPD_declare_simd:
988   case OMPD_declare_variant:
989   case OMPD_begin_declare_variant:
990   case OMPD_end_declare_variant:
991   case OMPD_declare_target:
992   case OMPD_end_declare_target:
993   case OMPD_declare_reduction:
994   case OMPD_declare_mapper:
995   case OMPD_taskloop:
996   case OMPD_taskloop_simd:
997   case OMPD_master_taskloop:
998   case OMPD_master_taskloop_simd:
999   case OMPD_parallel_master_taskloop:
1000   case OMPD_parallel_master_taskloop_simd:
1001   case OMPD_requires:
1002   case OMPD_unknown:
1003   default:
1004     break;
1005   }
1006   llvm_unreachable(
1007       "Unknown programming model for OpenMP directive on NVPTX target.");
1008 }
1009 
1010 void CGOpenMPRuntimeGPU::emitNonSPMDKernel(const OMPExecutableDirective &D,
1011                                              StringRef ParentName,
1012                                              llvm::Function *&OutlinedFn,
1013                                              llvm::Constant *&OutlinedFnID,
1014                                              bool IsOffloadEntry,
1015                                              const RegionCodeGenTy &CodeGen) {
1016   ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
1017   EntryFunctionState EST;
1018   WrapperFunctionsMap.clear();
1019 
1020   // Emit target region as a standalone region.
1021   class NVPTXPrePostActionTy : public PrePostActionTy {
1022     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1023 
1024   public:
1025     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU::EntryFunctionState &EST)
1026         : EST(EST) {}
1027     void Enter(CodeGenFunction &CGF) override {
1028       auto &RT =
1029           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1030       RT.emitKernelInit(CGF, EST, /* IsSPMD */ false);
1031       // Skip target region initialization.
1032       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1033     }
1034     void Exit(CodeGenFunction &CGF) override {
1035       auto &RT =
1036           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1037       RT.clearLocThreadIdInsertPt(CGF);
1038       RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ false);
1039     }
1040   } Action(EST);
1041   CodeGen.setAction(Action);
1042   IsInTTDRegion = true;
1043   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1044                                    IsOffloadEntry, CodeGen);
1045   IsInTTDRegion = false;
1046 }
1047 
1048 void CGOpenMPRuntimeGPU::emitKernelInit(CodeGenFunction &CGF,
1049                                         EntryFunctionState &EST, bool IsSPMD) {
1050   CGBuilderTy &Bld = CGF.Builder;
1051   Bld.restoreIP(OMPBuilder.createTargetInit(Bld, IsSPMD, requiresFullRuntime()));
1052   IsInTargetMasterThreadRegion = IsSPMD;
1053   if (!IsSPMD)
1054     emitGenericVarsProlog(CGF, EST.Loc);
1055 }
1056 
1057 void CGOpenMPRuntimeGPU::emitKernelDeinit(CodeGenFunction &CGF,
1058                                           EntryFunctionState &EST,
1059                                           bool IsSPMD) {
1060   if (!IsSPMD)
1061     emitGenericVarsEpilog(CGF);
1062 
1063   CGBuilderTy &Bld = CGF.Builder;
1064   OMPBuilder.createTargetDeinit(Bld, IsSPMD, requiresFullRuntime());
1065 }
1066 
1067 void CGOpenMPRuntimeGPU::emitSPMDKernel(const OMPExecutableDirective &D,
1068                                           StringRef ParentName,
1069                                           llvm::Function *&OutlinedFn,
1070                                           llvm::Constant *&OutlinedFnID,
1071                                           bool IsOffloadEntry,
1072                                           const RegionCodeGenTy &CodeGen) {
1073   ExecutionRuntimeModesRAII ModeRAII(
1074       CurrentExecutionMode, RequiresFullRuntime,
1075       CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1076           !supportsLightweightRuntime(CGM.getContext(), D));
1077   EntryFunctionState EST;
1078 
1079   // Emit target region as a standalone region.
1080   class NVPTXPrePostActionTy : public PrePostActionTy {
1081     CGOpenMPRuntimeGPU &RT;
1082     CGOpenMPRuntimeGPU::EntryFunctionState &EST;
1083 
1084   public:
1085     NVPTXPrePostActionTy(CGOpenMPRuntimeGPU &RT,
1086                          CGOpenMPRuntimeGPU::EntryFunctionState &EST)
1087         : RT(RT), EST(EST) {}
1088     void Enter(CodeGenFunction &CGF) override {
1089       RT.emitKernelInit(CGF, EST, /* IsSPMD */ true);
1090       // Skip target region initialization.
1091       RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
1092     }
1093     void Exit(CodeGenFunction &CGF) override {
1094       RT.clearLocThreadIdInsertPt(CGF);
1095       RT.emitKernelDeinit(CGF, EST, /* IsSPMD */ true);
1096     }
1097   } Action(*this, EST);
1098   CodeGen.setAction(Action);
1099   IsInTTDRegion = true;
1100   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1101                                    IsOffloadEntry, CodeGen);
1102   IsInTTDRegion = false;
1103 }
1104 
1105 // Create a unique global variable to indicate the execution mode of this target
1106 // region. The execution mode is either 'generic', or 'spmd' depending on the
1107 // target directive. This variable is picked up by the offload library to setup
1108 // the device appropriately before kernel launch. If the execution mode is
1109 // 'generic', the runtime reserves one warp for the master, otherwise, all
1110 // warps participate in parallel work.
1111 static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
1112                                      bool Mode) {
1113   auto *GVMode =
1114       new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1115                                llvm::GlobalValue::WeakAnyLinkage,
1116                                llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1117                                Twine(Name, "_exec_mode"));
1118   CGM.addCompilerUsedGlobal(GVMode);
1119 }
1120 
1121 void CGOpenMPRuntimeGPU::createOffloadEntry(llvm::Constant *ID,
1122                                               llvm::Constant *Addr,
1123                                               uint64_t Size, int32_t,
1124                                               llvm::GlobalValue::LinkageTypes) {
1125   // TODO: Add support for global variables on the device after declare target
1126   // support.
1127   if (!isa<llvm::Function>(Addr))
1128     return;
1129   llvm::Module &M = CGM.getModule();
1130   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1131 
1132   // Get "nvvm.annotations" metadata node
1133   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1134 
1135   llvm::Metadata *MDVals[] = {
1136       llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
1137       llvm::ConstantAsMetadata::get(
1138           llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1139   // Append metadata to nvvm.annotations
1140   MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1141 }
1142 
1143 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
1144     const OMPExecutableDirective &D, StringRef ParentName,
1145     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
1146     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
1147   if (!IsOffloadEntry) // Nothing to do.
1148     return;
1149 
1150   assert(!ParentName.empty() && "Invalid target region parent name!");
1151 
1152   bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
1153   if (Mode)
1154     emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1155                    CodeGen);
1156   else
1157     emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1158                       CodeGen);
1159 
1160   setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
1161 }
1162 
1163 namespace {
1164 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1165 /// Enum for accesseing the reserved_2 field of the ident_t struct.
1166 enum ModeFlagsTy : unsigned {
1167   /// Bit set to 1 when in SPMD mode.
1168   KMP_IDENT_SPMD_MODE = 0x01,
1169   /// Bit set to 1 when a simplified runtime is used.
1170   KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1171   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1172 };
1173 
1174 /// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1175 static const ModeFlagsTy UndefinedMode =
1176     (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1177 } // anonymous namespace
1178 
1179 unsigned CGOpenMPRuntimeGPU::getDefaultLocationReserved2Flags() const {
1180   switch (getExecutionMode()) {
1181   case EM_SPMD:
1182     if (requiresFullRuntime())
1183       return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1184     return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1185   case EM_NonSPMD:
1186     assert(requiresFullRuntime() && "Expected full runtime.");
1187     return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1188   case EM_Unknown:
1189     return UndefinedMode;
1190   }
1191   llvm_unreachable("Unknown flags are requested.");
1192 }
1193 
1194 CGOpenMPRuntimeGPU::CGOpenMPRuntimeGPU(CodeGenModule &CGM)
1195     : CGOpenMPRuntime(CGM, "_", "$") {
1196   if (!CGM.getLangOpts().OpenMPIsDevice)
1197     llvm_unreachable("OpenMP NVPTX can only handle device code.");
1198 }
1199 
1200 void CGOpenMPRuntimeGPU::emitProcBindClause(CodeGenFunction &CGF,
1201                                               ProcBindKind ProcBind,
1202                                               SourceLocation Loc) {
1203   // Do nothing in case of SPMD mode and L0 parallel.
1204   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1205     return;
1206 
1207   CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1208 }
1209 
1210 void CGOpenMPRuntimeGPU::emitNumThreadsClause(CodeGenFunction &CGF,
1211                                                 llvm::Value *NumThreads,
1212                                                 SourceLocation Loc) {
1213   // Do nothing in case of SPMD mode and L0 parallel.
1214   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
1215     return;
1216 
1217   CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1218 }
1219 
1220 void CGOpenMPRuntimeGPU::emitNumTeamsClause(CodeGenFunction &CGF,
1221                                               const Expr *NumTeams,
1222                                               const Expr *ThreadLimit,
1223                                               SourceLocation Loc) {}
1224 
1225 llvm::Function *CGOpenMPRuntimeGPU::emitParallelOutlinedFunction(
1226     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1227     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1228   // Emit target region as a standalone region.
1229   class NVPTXPrePostActionTy : public PrePostActionTy {
1230     bool &IsInParallelRegion;
1231     bool PrevIsInParallelRegion;
1232 
1233   public:
1234     NVPTXPrePostActionTy(bool &IsInParallelRegion)
1235         : IsInParallelRegion(IsInParallelRegion) {}
1236     void Enter(CodeGenFunction &CGF) override {
1237       PrevIsInParallelRegion = IsInParallelRegion;
1238       IsInParallelRegion = true;
1239     }
1240     void Exit(CodeGenFunction &CGF) override {
1241       IsInParallelRegion = PrevIsInParallelRegion;
1242     }
1243   } Action(IsInParallelRegion);
1244   CodeGen.setAction(Action);
1245   bool PrevIsInTTDRegion = IsInTTDRegion;
1246   IsInTTDRegion = false;
1247   bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1248   IsInTargetMasterThreadRegion = false;
1249   auto *OutlinedFun =
1250       cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1251           D, ThreadIDVar, InnermostKind, CodeGen));
1252   IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
1253   IsInTTDRegion = PrevIsInTTDRegion;
1254   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD &&
1255       !IsInParallelRegion) {
1256     llvm::Function *WrapperFun =
1257         createParallelDataSharingWrapper(OutlinedFun, D);
1258     WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1259   }
1260 
1261   return OutlinedFun;
1262 }
1263 
1264 /// Get list of lastprivate variables from the teams distribute ... or
1265 /// teams {distribute ...} directives.
1266 static void
1267 getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1268                              llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1269   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1270          "expected teams directive.");
1271   const OMPExecutableDirective *Dir = &D;
1272   if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1273     if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
1274             Ctx,
1275             D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1276                 /*IgnoreCaptured=*/true))) {
1277       Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
1278       if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1279         Dir = nullptr;
1280     }
1281   }
1282   if (!Dir)
1283     return;
1284   for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
1285     for (const Expr *E : C->getVarRefs())
1286       Vars.push_back(getPrivateItem(E));
1287   }
1288 }
1289 
1290 /// Get list of reduction variables from the teams ... directives.
1291 static void
1292 getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1293                       llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1294   assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1295          "expected teams directive.");
1296   for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1297     for (const Expr *E : C->privates())
1298       Vars.push_back(getPrivateItem(E));
1299   }
1300 }
1301 
1302 llvm::Function *CGOpenMPRuntimeGPU::emitTeamsOutlinedFunction(
1303     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1304     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1305   SourceLocation Loc = D.getBeginLoc();
1306 
1307   const RecordDecl *GlobalizedRD = nullptr;
1308   llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
1309   llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
1310   unsigned WarpSize = CGM.getTarget().getGridValue().GV_Warp_Size;
1311   // Globalize team reductions variable unconditionally in all modes.
1312   if (getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1313     getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
1314   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
1315     getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1316     if (!LastPrivatesReductions.empty()) {
1317       GlobalizedRD = ::buildRecordForGlobalizedVars(
1318           CGM.getContext(), llvm::None, LastPrivatesReductions,
1319           MappedDeclsFields, WarpSize);
1320     }
1321   } else if (!LastPrivatesReductions.empty()) {
1322     assert(!TeamAndReductions.first &&
1323            "Previous team declaration is not expected.");
1324     TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
1325     std::swap(TeamAndReductions.second, LastPrivatesReductions);
1326   }
1327 
1328   // Emit target region as a standalone region.
1329   class NVPTXPrePostActionTy : public PrePostActionTy {
1330     SourceLocation &Loc;
1331     const RecordDecl *GlobalizedRD;
1332     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1333         &MappedDeclsFields;
1334 
1335   public:
1336     NVPTXPrePostActionTy(
1337         SourceLocation &Loc, const RecordDecl *GlobalizedRD,
1338         llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
1339             &MappedDeclsFields)
1340         : Loc(Loc), GlobalizedRD(GlobalizedRD),
1341           MappedDeclsFields(MappedDeclsFields) {}
1342     void Enter(CodeGenFunction &CGF) override {
1343       auto &Rt =
1344           static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1345       if (GlobalizedRD) {
1346         auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
1347         I->getSecond().MappedParams =
1348             std::make_unique<CodeGenFunction::OMPMapVars>();
1349         DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
1350         for (const auto &Pair : MappedDeclsFields) {
1351           assert(Pair.getFirst()->isCanonicalDecl() &&
1352                  "Expected canonical declaration");
1353           Data.insert(std::make_pair(Pair.getFirst(), MappedVarData()));
1354         }
1355       }
1356       Rt.emitGenericVarsProlog(CGF, Loc);
1357     }
1358     void Exit(CodeGenFunction &CGF) override {
1359       static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
1360           .emitGenericVarsEpilog(CGF);
1361     }
1362   } Action(Loc, GlobalizedRD, MappedDeclsFields);
1363   CodeGen.setAction(Action);
1364   llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
1365       D, ThreadIDVar, InnermostKind, CodeGen);
1366 
1367   return OutlinedFun;
1368 }
1369 
1370 void CGOpenMPRuntimeGPU::emitGenericVarsProlog(CodeGenFunction &CGF,
1371                                                  SourceLocation Loc,
1372                                                  bool WithSPMDCheck) {
1373   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
1374       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1375     return;
1376 
1377   CGBuilderTy &Bld = CGF.Builder;
1378 
1379   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1380   if (I == FunctionGlobalizedDecls.end())
1381     return;
1382 
1383   for (auto &Rec : I->getSecond().LocalVarData) {
1384     const auto *VD = cast<VarDecl>(Rec.first);
1385     bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
1386     QualType VarTy = VD->getType();
1387 
1388     // Get the local allocation of a firstprivate variable before sharing
1389     llvm::Value *ParValue;
1390     if (EscapedParam) {
1391       LValue ParLVal =
1392           CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
1393       ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
1394     }
1395 
1396     // Allocate space for the variable to be globalized
1397     llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
1398     llvm::Instruction *VoidPtr =
1399         CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1400                                 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1401                             AllocArgs, VD->getName());
1402 
1403     // Cast the void pointer and get the address of the globalized variable.
1404     llvm::PointerType *VarPtrTy = CGF.ConvertTypeForMem(VarTy)->getPointerTo();
1405     llvm::Value *CastedVoidPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
1406         VoidPtr, VarPtrTy, VD->getName() + "_on_stack");
1407     LValue VarAddr = CGF.MakeNaturalAlignAddrLValue(CastedVoidPtr, VarTy);
1408     Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
1409     Rec.second.GlobalizedVal = VoidPtr;
1410 
1411     // Assign the local allocation to the newly globalized location.
1412     if (EscapedParam) {
1413       CGF.EmitStoreOfScalar(ParValue, VarAddr);
1414       I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress(CGF));
1415     }
1416     if (auto *DI = CGF.getDebugInfo())
1417       VoidPtr->setDebugLoc(DI->SourceLocToDebugLoc(VD->getLocation()));
1418   }
1419   for (const auto *VD : I->getSecond().EscapedVariableLengthDecls) {
1420     // Use actual memory size of the VLA object including the padding
1421     // for alignment purposes.
1422     llvm::Value *Size = CGF.getTypeSize(VD->getType());
1423     CharUnits Align = CGM.getContext().getDeclAlign(VD);
1424     Size = Bld.CreateNUWAdd(
1425         Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
1426     llvm::Value *AlignVal =
1427         llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
1428 
1429     Size = Bld.CreateUDiv(Size, AlignVal);
1430     Size = Bld.CreateNUWMul(Size, AlignVal);
1431 
1432     // Allocate space for this VLA object to be globalized.
1433     llvm::Value *AllocArgs[] = {CGF.getTypeSize(VD->getType())};
1434     llvm::Instruction *VoidPtr =
1435         CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1436                                 CGM.getModule(), OMPRTL___kmpc_alloc_shared),
1437                             AllocArgs, VD->getName());
1438 
1439     I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(
1440         std::pair<llvm::Value *, llvm::Value *>(
1441             {VoidPtr, CGF.getTypeSize(VD->getType())}));
1442     LValue Base = CGF.MakeAddrLValue(VoidPtr, VD->getType(),
1443                                      CGM.getContext().getDeclAlign(VD),
1444                                      AlignmentSource::Decl);
1445     I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
1446                                             Base.getAddress(CGF));
1447   }
1448   I->getSecond().MappedParams->apply(CGF);
1449 }
1450 
1451 void CGOpenMPRuntimeGPU::emitGenericVarsEpilog(CodeGenFunction &CGF,
1452                                                  bool WithSPMDCheck) {
1453   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic &&
1454       getExecutionMode() != CGOpenMPRuntimeGPU::EM_SPMD)
1455     return;
1456 
1457   const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
1458   if (I != FunctionGlobalizedDecls.end()) {
1459     // Deallocate the memory for each globalized VLA object
1460     for (auto AddrSizePair :
1461          llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
1462       CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1463                               CGM.getModule(), OMPRTL___kmpc_free_shared),
1464                           {AddrSizePair.first, AddrSizePair.second});
1465     }
1466     // Deallocate the memory for each globalized value
1467     for (auto &Rec : llvm::reverse(I->getSecond().LocalVarData)) {
1468       const auto *VD = cast<VarDecl>(Rec.first);
1469       I->getSecond().MappedParams->restore(CGF);
1470 
1471       llvm::Value *FreeArgs[] = {Rec.second.GlobalizedVal,
1472                                  CGF.getTypeSize(VD->getType())};
1473       CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1474                               CGM.getModule(), OMPRTL___kmpc_free_shared),
1475                           FreeArgs);
1476     }
1477   }
1478 }
1479 
1480 void CGOpenMPRuntimeGPU::emitTeamsCall(CodeGenFunction &CGF,
1481                                          const OMPExecutableDirective &D,
1482                                          SourceLocation Loc,
1483                                          llvm::Function *OutlinedFn,
1484                                          ArrayRef<llvm::Value *> CapturedVars) {
1485   if (!CGF.HaveInsertPoint())
1486     return;
1487 
1488   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
1489                                                       /*Name=*/".zero.addr");
1490   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
1491   llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1492   OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
1493   OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1494   OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
1495   emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
1496 }
1497 
1498 void CGOpenMPRuntimeGPU::emitParallelCall(CodeGenFunction &CGF,
1499                                           SourceLocation Loc,
1500                                           llvm::Function *OutlinedFn,
1501                                           ArrayRef<llvm::Value *> CapturedVars,
1502                                           const Expr *IfCond) {
1503   if (!CGF.HaveInsertPoint())
1504     return;
1505 
1506   auto &&ParallelGen = [this, Loc, OutlinedFn, CapturedVars,
1507                         IfCond](CodeGenFunction &CGF, PrePostActionTy &Action) {
1508     CGBuilderTy &Bld = CGF.Builder;
1509     llvm::Function *WFn = WrapperFunctionsMap[OutlinedFn];
1510     llvm::Value *ID = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
1511     if (WFn)
1512       ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
1513     llvm::Value *FnPtr = Bld.CreateBitOrPointerCast(OutlinedFn, CGM.Int8PtrTy);
1514 
1515     // Create a private scope that will globalize the arguments
1516     // passed from the outside of the target region.
1517     // TODO: Is that needed?
1518     CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
1519 
1520     Address CapturedVarsAddrs = CGF.CreateDefaultAlignTempAlloca(
1521         llvm::ArrayType::get(CGM.VoidPtrTy, CapturedVars.size()),
1522         "captured_vars_addrs");
1523     // There's something to share.
1524     if (!CapturedVars.empty()) {
1525       // Prepare for parallel region. Indicate the outlined function.
1526       ASTContext &Ctx = CGF.getContext();
1527       unsigned Idx = 0;
1528       for (llvm::Value *V : CapturedVars) {
1529         Address Dst = Bld.CreateConstArrayGEP(CapturedVarsAddrs, Idx);
1530         llvm::Value *PtrV;
1531         if (V->getType()->isIntegerTy())
1532           PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
1533         else
1534           PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
1535         CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
1536                               Ctx.getPointerType(Ctx.VoidPtrTy));
1537         ++Idx;
1538       }
1539     }
1540 
1541     llvm::Value *IfCondVal = nullptr;
1542     if (IfCond)
1543       IfCondVal = Bld.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.Int32Ty,
1544                                     /* isSigned */ false);
1545     else
1546       IfCondVal = llvm::ConstantInt::get(CGF.Int32Ty, 1);
1547 
1548     assert(IfCondVal && "Expected a value");
1549     llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
1550     llvm::Value *Args[] = {
1551         RTLoc,
1552         getThreadID(CGF, Loc),
1553         IfCondVal,
1554         llvm::ConstantInt::get(CGF.Int32Ty, -1),
1555         llvm::ConstantInt::get(CGF.Int32Ty, -1),
1556         FnPtr,
1557         ID,
1558         Bld.CreateBitOrPointerCast(CapturedVarsAddrs.getPointer(),
1559                                    CGF.VoidPtrPtrTy),
1560         llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
1561     CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1562                             CGM.getModule(), OMPRTL___kmpc_parallel_51),
1563                         Args);
1564   };
1565 
1566   RegionCodeGenTy RCG(ParallelGen);
1567   RCG(CGF);
1568 }
1569 
1570 void CGOpenMPRuntimeGPU::syncCTAThreads(CodeGenFunction &CGF) {
1571   // Always emit simple barriers!
1572   if (!CGF.HaveInsertPoint())
1573     return;
1574   // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
1575   // This function does not use parameters, so we can emit just default values.
1576   llvm::Value *Args[] = {
1577       llvm::ConstantPointerNull::get(
1578           cast<llvm::PointerType>(getIdentTyPointerTy())),
1579       llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
1580   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1581                           CGM.getModule(), OMPRTL___kmpc_barrier_simple_spmd),
1582                       Args);
1583 }
1584 
1585 void CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
1586                                            SourceLocation Loc,
1587                                            OpenMPDirectiveKind Kind, bool,
1588                                            bool) {
1589   // Always emit simple barriers!
1590   if (!CGF.HaveInsertPoint())
1591     return;
1592   // Build call __kmpc_cancel_barrier(loc, thread_id);
1593   unsigned Flags = getDefaultFlagsForBarriers(Kind);
1594   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
1595                          getThreadID(CGF, Loc)};
1596 
1597   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1598                           CGM.getModule(), OMPRTL___kmpc_barrier),
1599                       Args);
1600 }
1601 
1602 void CGOpenMPRuntimeGPU::emitCriticalRegion(
1603     CodeGenFunction &CGF, StringRef CriticalName,
1604     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
1605     const Expr *Hint) {
1606   llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
1607   llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
1608   llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
1609   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
1610   llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
1611 
1612   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
1613 
1614   // Get the mask of active threads in the warp.
1615   llvm::Value *Mask = CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1616       CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
1617   // Fetch team-local id of the thread.
1618   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
1619 
1620   // Get the width of the team.
1621   llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
1622 
1623   // Initialize the counter variable for the loop.
1624   QualType Int32Ty =
1625       CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
1626   Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
1627   LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
1628   CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
1629                         /*isInit=*/true);
1630 
1631   // Block checks if loop counter exceeds upper bound.
1632   CGF.EmitBlock(LoopBB);
1633   llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1634   llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
1635   CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
1636 
1637   // Block tests which single thread should execute region, and which threads
1638   // should go straight to synchronisation point.
1639   CGF.EmitBlock(TestBB);
1640   CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
1641   llvm::Value *CmpThreadToCounter =
1642       CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
1643   CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
1644 
1645   // Block emits the body of the critical region.
1646   CGF.EmitBlock(BodyBB);
1647 
1648   // Output the critical statement.
1649   CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
1650                                       Hint);
1651 
1652   // After the body surrounded by the critical region, the single executing
1653   // thread will jump to the synchronisation point.
1654   // Block waits for all threads in current team to finish then increments the
1655   // counter variable and returns to the loop.
1656   CGF.EmitBlock(SyncBB);
1657   // Reconverge active threads in the warp.
1658   (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1659                                 CGM.getModule(), OMPRTL___kmpc_syncwarp),
1660                             Mask);
1661 
1662   llvm::Value *IncCounterVal =
1663       CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
1664   CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
1665   CGF.EmitBranch(LoopBB);
1666 
1667   // Block that is reached when  all threads in the team complete the region.
1668   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1669 }
1670 
1671 /// Cast value to the specified type.
1672 static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
1673                                     QualType ValTy, QualType CastTy,
1674                                     SourceLocation Loc) {
1675   assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
1676          "Cast type must sized.");
1677   assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
1678          "Val type must sized.");
1679   llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
1680   if (ValTy == CastTy)
1681     return Val;
1682   if (CGF.getContext().getTypeSizeInChars(ValTy) ==
1683       CGF.getContext().getTypeSizeInChars(CastTy))
1684     return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
1685   if (CastTy->isIntegerType() && ValTy->isIntegerType())
1686     return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
1687                                      CastTy->hasSignedIntegerRepresentation());
1688   Address CastItem = CGF.CreateMemTemp(CastTy);
1689   Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1690       CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
1691   CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
1692                         LValueBaseInfo(AlignmentSource::Type),
1693                         TBAAAccessInfo());
1694   return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc,
1695                               LValueBaseInfo(AlignmentSource::Type),
1696                               TBAAAccessInfo());
1697 }
1698 
1699 /// This function creates calls to one of two shuffle functions to copy
1700 /// variables between lanes in a warp.
1701 static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
1702                                                  llvm::Value *Elem,
1703                                                  QualType ElemType,
1704                                                  llvm::Value *Offset,
1705                                                  SourceLocation Loc) {
1706   CodeGenModule &CGM = CGF.CGM;
1707   CGBuilderTy &Bld = CGF.Builder;
1708   CGOpenMPRuntimeGPU &RT =
1709       *(static_cast<CGOpenMPRuntimeGPU *>(&CGM.getOpenMPRuntime()));
1710   llvm::OpenMPIRBuilder &OMPBuilder = RT.getOMPBuilder();
1711 
1712   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
1713   assert(Size.getQuantity() <= 8 &&
1714          "Unsupported bitwidth in shuffle instruction.");
1715 
1716   RuntimeFunction ShuffleFn = Size.getQuantity() <= 4
1717                                   ? OMPRTL___kmpc_shuffle_int32
1718                                   : OMPRTL___kmpc_shuffle_int64;
1719 
1720   // Cast all types to 32- or 64-bit values before calling shuffle routines.
1721   QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
1722       Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
1723   llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
1724   llvm::Value *WarpSize =
1725       Bld.CreateIntCast(RT.getGPUWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
1726 
1727   llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
1728       OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(), ShuffleFn),
1729       {ElemCast, Offset, WarpSize});
1730 
1731   return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
1732 }
1733 
1734 static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
1735                             Address DestAddr, QualType ElemType,
1736                             llvm::Value *Offset, SourceLocation Loc) {
1737   CGBuilderTy &Bld = CGF.Builder;
1738 
1739   CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
1740   // Create the loop over the big sized data.
1741   // ptr = (void*)Elem;
1742   // ptrEnd = (void*) Elem + 1;
1743   // Step = 8;
1744   // while (ptr + Step < ptrEnd)
1745   //   shuffle((int64_t)*ptr);
1746   // Step = 4;
1747   // while (ptr + Step < ptrEnd)
1748   //   shuffle((int32_t)*ptr);
1749   // ...
1750   Address ElemPtr = DestAddr;
1751   Address Ptr = SrcAddr;
1752   Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
1753       Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
1754   for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
1755     if (Size < CharUnits::fromQuantity(IntSize))
1756       continue;
1757     QualType IntType = CGF.getContext().getIntTypeForBitwidth(
1758         CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
1759         /*Signed=*/1);
1760     llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
1761     Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
1762     ElemPtr =
1763         Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
1764     if (Size.getQuantity() / IntSize > 1) {
1765       llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
1766       llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
1767       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
1768       llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
1769       CGF.EmitBlock(PreCondBB);
1770       llvm::PHINode *PhiSrc =
1771           Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
1772       PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
1773       llvm::PHINode *PhiDest =
1774           Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
1775       PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
1776       Ptr = Address(PhiSrc, Ptr.getAlignment());
1777       ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
1778       llvm::Value *PtrDiff = Bld.CreatePtrDiff(
1779           PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
1780                                    Ptr.getPointer(), CGF.VoidPtrTy));
1781       Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
1782                        ThenBB, ExitBB);
1783       CGF.EmitBlock(ThenBB);
1784       llvm::Value *Res = createRuntimeShuffleFunction(
1785           CGF,
1786           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
1787                                LValueBaseInfo(AlignmentSource::Type),
1788                                TBAAAccessInfo()),
1789           IntType, Offset, Loc);
1790       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
1791                             LValueBaseInfo(AlignmentSource::Type),
1792                             TBAAAccessInfo());
1793       Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
1794       Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
1795       PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
1796       PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
1797       CGF.EmitBranch(PreCondBB);
1798       CGF.EmitBlock(ExitBB);
1799     } else {
1800       llvm::Value *Res = createRuntimeShuffleFunction(
1801           CGF,
1802           CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc,
1803                                LValueBaseInfo(AlignmentSource::Type),
1804                                TBAAAccessInfo()),
1805           IntType, Offset, Loc);
1806       CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType,
1807                             LValueBaseInfo(AlignmentSource::Type),
1808                             TBAAAccessInfo());
1809       Ptr = Bld.CreateConstGEP(Ptr, 1);
1810       ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
1811     }
1812     Size = Size % IntSize;
1813   }
1814 }
1815 
1816 namespace {
1817 enum CopyAction : unsigned {
1818   // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
1819   // the warp using shuffle instructions.
1820   RemoteLaneToThread,
1821   // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
1822   ThreadCopy,
1823   // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
1824   ThreadToScratchpad,
1825   // ScratchpadToThread: Copy from a scratchpad array in global memory
1826   // containing team-reduced data to a thread's stack.
1827   ScratchpadToThread,
1828 };
1829 } // namespace
1830 
1831 struct CopyOptionsTy {
1832   llvm::Value *RemoteLaneOffset;
1833   llvm::Value *ScratchpadIndex;
1834   llvm::Value *ScratchpadWidth;
1835 };
1836 
1837 /// Emit instructions to copy a Reduce list, which contains partially
1838 /// aggregated values, in the specified direction.
1839 static void emitReductionListCopy(
1840     CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
1841     ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
1842     CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
1843 
1844   CodeGenModule &CGM = CGF.CGM;
1845   ASTContext &C = CGM.getContext();
1846   CGBuilderTy &Bld = CGF.Builder;
1847 
1848   llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
1849   llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
1850   llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
1851 
1852   // Iterates, element-by-element, through the source Reduce list and
1853   // make a copy.
1854   unsigned Idx = 0;
1855   unsigned Size = Privates.size();
1856   for (const Expr *Private : Privates) {
1857     Address SrcElementAddr = Address::invalid();
1858     Address DestElementAddr = Address::invalid();
1859     Address DestElementPtrAddr = Address::invalid();
1860     // Should we shuffle in an element from a remote lane?
1861     bool ShuffleInElement = false;
1862     // Set to true to update the pointer in the dest Reduce list to a
1863     // newly created element.
1864     bool UpdateDestListPtr = false;
1865     // Increment the src or dest pointer to the scratchpad, for each
1866     // new element.
1867     bool IncrScratchpadSrc = false;
1868     bool IncrScratchpadDest = false;
1869 
1870     switch (Action) {
1871     case RemoteLaneToThread: {
1872       // Step 1.1: Get the address for the src element in the Reduce list.
1873       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1874       SrcElementAddr = CGF.EmitLoadOfPointer(
1875           SrcElementPtrAddr,
1876           C.getPointerType(Private->getType())->castAs<PointerType>());
1877 
1878       // Step 1.2: Create a temporary to store the element in the destination
1879       // Reduce list.
1880       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1881       DestElementAddr =
1882           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1883       ShuffleInElement = true;
1884       UpdateDestListPtr = true;
1885       break;
1886     }
1887     case ThreadCopy: {
1888       // Step 1.1: Get the address for the src element in the Reduce list.
1889       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1890       SrcElementAddr = CGF.EmitLoadOfPointer(
1891           SrcElementPtrAddr,
1892           C.getPointerType(Private->getType())->castAs<PointerType>());
1893 
1894       // Step 1.2: Get the address for dest element.  The destination
1895       // element has already been created on the thread's stack.
1896       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1897       DestElementAddr = CGF.EmitLoadOfPointer(
1898           DestElementPtrAddr,
1899           C.getPointerType(Private->getType())->castAs<PointerType>());
1900       break;
1901     }
1902     case ThreadToScratchpad: {
1903       // Step 1.1: Get the address for the src element in the Reduce list.
1904       Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
1905       SrcElementAddr = CGF.EmitLoadOfPointer(
1906           SrcElementPtrAddr,
1907           C.getPointerType(Private->getType())->castAs<PointerType>());
1908 
1909       // Step 1.2: Get the address for dest element:
1910       // address = base + index * ElementSizeInChars.
1911       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
1912       llvm::Value *CurrentOffset =
1913           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
1914       llvm::Value *ScratchPadElemAbsolutePtrVal =
1915           Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
1916       ScratchPadElemAbsolutePtrVal =
1917           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1918       DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1919                                 C.getTypeAlignInChars(Private->getType()));
1920       IncrScratchpadDest = true;
1921       break;
1922     }
1923     case ScratchpadToThread: {
1924       // Step 1.1: Get the address for the src element in the scratchpad.
1925       // address = base + index * ElementSizeInChars.
1926       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
1927       llvm::Value *CurrentOffset =
1928           Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
1929       llvm::Value *ScratchPadElemAbsolutePtrVal =
1930           Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
1931       ScratchPadElemAbsolutePtrVal =
1932           Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
1933       SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
1934                                C.getTypeAlignInChars(Private->getType()));
1935       IncrScratchpadSrc = true;
1936 
1937       // Step 1.2: Create a temporary to store the element in the destination
1938       // Reduce list.
1939       DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
1940       DestElementAddr =
1941           CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
1942       UpdateDestListPtr = true;
1943       break;
1944     }
1945     }
1946 
1947     // Regardless of src and dest of copy, we emit the load of src
1948     // element as this is required in all directions
1949     SrcElementAddr = Bld.CreateElementBitCast(
1950         SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
1951     DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
1952                                                SrcElementAddr.getElementType());
1953 
1954     // Now that all active lanes have read the element in the
1955     // Reduce list, shuffle over the value from the remote lane.
1956     if (ShuffleInElement) {
1957       shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
1958                       RemoteLaneOffset, Private->getExprLoc());
1959     } else {
1960       switch (CGF.getEvaluationKind(Private->getType())) {
1961       case TEK_Scalar: {
1962         llvm::Value *Elem = CGF.EmitLoadOfScalar(
1963             SrcElementAddr, /*Volatile=*/false, Private->getType(),
1964             Private->getExprLoc(), LValueBaseInfo(AlignmentSource::Type),
1965             TBAAAccessInfo());
1966         // Store the source element value to the dest element address.
1967         CGF.EmitStoreOfScalar(
1968             Elem, DestElementAddr, /*Volatile=*/false, Private->getType(),
1969             LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
1970         break;
1971       }
1972       case TEK_Complex: {
1973         CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
1974             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
1975             Private->getExprLoc());
1976         CGF.EmitStoreOfComplex(
1977             Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
1978             /*isInit=*/false);
1979         break;
1980       }
1981       case TEK_Aggregate:
1982         CGF.EmitAggregateCopy(
1983             CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
1984             CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
1985             Private->getType(), AggValueSlot::DoesNotOverlap);
1986         break;
1987       }
1988     }
1989 
1990     // Step 3.1: Modify reference in dest Reduce list as needed.
1991     // Modifying the reference in Reduce list to point to the newly
1992     // created element.  The element is live in the current function
1993     // scope and that of functions it invokes (i.e., reduce_function).
1994     // RemoteReduceData[i] = (void*)&RemoteElem
1995     if (UpdateDestListPtr) {
1996       CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
1997                                 DestElementAddr.getPointer(), CGF.VoidPtrTy),
1998                             DestElementPtrAddr, /*Volatile=*/false,
1999                             C.VoidPtrTy);
2000     }
2001 
2002     // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
2003     // address of the next element in scratchpad memory, unless we're currently
2004     // processing the last one.  Memory alignment is also taken care of here.
2005     if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
2006       llvm::Value *ScratchpadBasePtr =
2007           IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
2008       llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
2009       ScratchpadBasePtr = Bld.CreateNUWAdd(
2010           ScratchpadBasePtr,
2011           Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
2012 
2013       // Take care of global memory alignment for performance
2014       ScratchpadBasePtr = Bld.CreateNUWSub(
2015           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2016       ScratchpadBasePtr = Bld.CreateUDiv(
2017           ScratchpadBasePtr,
2018           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2019       ScratchpadBasePtr = Bld.CreateNUWAdd(
2020           ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
2021       ScratchpadBasePtr = Bld.CreateNUWMul(
2022           ScratchpadBasePtr,
2023           llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
2024 
2025       if (IncrScratchpadDest)
2026         DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2027       else /* IncrScratchpadSrc = true */
2028         SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
2029     }
2030 
2031     ++Idx;
2032   }
2033 }
2034 
2035 /// This function emits a helper that gathers Reduce lists from the first
2036 /// lane of every active warp to lanes in the first warp.
2037 ///
2038 /// void inter_warp_copy_func(void* reduce_data, num_warps)
2039 ///   shared smem[warp_size];
2040 ///   For all data entries D in reduce_data:
2041 ///     sync
2042 ///     If (I am the first lane in each warp)
2043 ///       Copy my local D to smem[warp_id]
2044 ///     sync
2045 ///     if (I am the first warp)
2046 ///       Copy smem[thread_id] to my local D
2047 static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
2048                                               ArrayRef<const Expr *> Privates,
2049                                               QualType ReductionArrayTy,
2050                                               SourceLocation Loc) {
2051   ASTContext &C = CGM.getContext();
2052   llvm::Module &M = CGM.getModule();
2053 
2054   // ReduceList: thread local Reduce list.
2055   // At the stage of the computation when this function is called, partially
2056   // aggregated values reside in the first lane of every active warp.
2057   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2058                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2059   // NumWarps: number of warps active in the parallel region.  This could
2060   // be smaller than 32 (max warps in a CTA) for partial block reduction.
2061   ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2062                                 C.getIntTypeForBitwidth(32, /* Signed */ true),
2063                                 ImplicitParamDecl::Other);
2064   FunctionArgList Args;
2065   Args.push_back(&ReduceListArg);
2066   Args.push_back(&NumWarpsArg);
2067 
2068   const CGFunctionInfo &CGFI =
2069       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2070   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2071                                     llvm::GlobalValue::InternalLinkage,
2072                                     "_omp_reduction_inter_warp_copy_func", &M);
2073   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2074   Fn->setDoesNotRecurse();
2075   CodeGenFunction CGF(CGM);
2076   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2077 
2078   CGBuilderTy &Bld = CGF.Builder;
2079 
2080   // This array is used as a medium to transfer, one reduce element at a time,
2081   // the data from the first lane of every warp to lanes in the first warp
2082   // in order to perform the final step of a reduction in a parallel region
2083   // (reduction across warps).  The array is placed in NVPTX __shared__ memory
2084   // for reduced latency, as well as to have a distinct copy for concurrently
2085   // executing target regions.  The array is declared with common linkage so
2086   // as to be shared across compilation units.
2087   StringRef TransferMediumName =
2088       "__openmp_nvptx_data_transfer_temporary_storage";
2089   llvm::GlobalVariable *TransferMedium =
2090       M.getGlobalVariable(TransferMediumName);
2091   unsigned WarpSize = CGF.getTarget().getGridValue().GV_Warp_Size;
2092   if (!TransferMedium) {
2093     auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
2094     unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
2095     TransferMedium = new llvm::GlobalVariable(
2096         M, Ty, /*isConstant=*/false, llvm::GlobalVariable::WeakAnyLinkage,
2097         llvm::UndefValue::get(Ty), TransferMediumName,
2098         /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
2099         SharedAddressSpace);
2100     CGM.addCompilerUsedGlobal(TransferMedium);
2101   }
2102 
2103   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
2104   // Get the CUDA thread id of the current OpenMP thread on the GPU.
2105   llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
2106   // nvptx_lane_id = nvptx_id % warpsize
2107   llvm::Value *LaneID = getNVPTXLaneID(CGF);
2108   // nvptx_warp_id = nvptx_id / warpsize
2109   llvm::Value *WarpID = getNVPTXWarpID(CGF);
2110 
2111   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2112   Address LocalReduceList(
2113       Bld.CreatePointerBitCastOrAddrSpaceCast(
2114           CGF.EmitLoadOfScalar(
2115               AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc,
2116               LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo()),
2117           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2118       CGF.getPointerAlign());
2119 
2120   unsigned Idx = 0;
2121   for (const Expr *Private : Privates) {
2122     //
2123     // Warp master copies reduce element to transfer medium in __shared__
2124     // memory.
2125     //
2126     unsigned RealTySize =
2127         C.getTypeSizeInChars(Private->getType())
2128             .alignTo(C.getTypeAlignInChars(Private->getType()))
2129             .getQuantity();
2130     for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
2131       unsigned NumIters = RealTySize / TySize;
2132       if (NumIters == 0)
2133         continue;
2134       QualType CType = C.getIntTypeForBitwidth(
2135           C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
2136       llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
2137       CharUnits Align = CharUnits::fromQuantity(TySize);
2138       llvm::Value *Cnt = nullptr;
2139       Address CntAddr = Address::invalid();
2140       llvm::BasicBlock *PrecondBB = nullptr;
2141       llvm::BasicBlock *ExitBB = nullptr;
2142       if (NumIters > 1) {
2143         CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
2144         CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
2145                               /*Volatile=*/false, C.IntTy);
2146         PrecondBB = CGF.createBasicBlock("precond");
2147         ExitBB = CGF.createBasicBlock("exit");
2148         llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
2149         // There is no need to emit line number for unconditional branch.
2150         (void)ApplyDebugLocation::CreateEmpty(CGF);
2151         CGF.EmitBlock(PrecondBB);
2152         Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
2153         llvm::Value *Cmp =
2154             Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
2155         Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
2156         CGF.EmitBlock(BodyBB);
2157       }
2158       // kmpc_barrier.
2159       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2160                                              /*EmitChecks=*/false,
2161                                              /*ForceSimpleCall=*/true);
2162       llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2163       llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2164       llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2165 
2166       // if (lane_id == 0)
2167       llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
2168       Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
2169       CGF.EmitBlock(ThenBB);
2170 
2171       // Reduce element = LocalReduceList[i]
2172       Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2173       llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2174           ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2175       // elemptr = ((CopyType*)(elemptrptr)) + I
2176       Address ElemPtr = Address(ElemPtrPtr, Align);
2177       ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
2178       if (NumIters > 1) {
2179         ElemPtr = Address(Bld.CreateGEP(ElemPtr.getElementType(),
2180                                         ElemPtr.getPointer(), Cnt),
2181                           ElemPtr.getAlignment());
2182       }
2183 
2184       // Get pointer to location in transfer medium.
2185       // MediumPtr = &medium[warp_id]
2186       llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
2187           TransferMedium->getValueType(), TransferMedium,
2188           {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
2189       Address MediumPtr(MediumPtrVal, Align);
2190       // Casting to actual data type.
2191       // MediumPtr = (CopyType*)MediumPtrAddr;
2192       MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
2193 
2194       // elem = *elemptr
2195       //*MediumPtr = elem
2196       llvm::Value *Elem = CGF.EmitLoadOfScalar(
2197           ElemPtr, /*Volatile=*/false, CType, Loc,
2198           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2199       // Store the source element value to the dest element address.
2200       CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType,
2201                             LValueBaseInfo(AlignmentSource::Type),
2202                             TBAAAccessInfo());
2203 
2204       Bld.CreateBr(MergeBB);
2205 
2206       CGF.EmitBlock(ElseBB);
2207       Bld.CreateBr(MergeBB);
2208 
2209       CGF.EmitBlock(MergeBB);
2210 
2211       // kmpc_barrier.
2212       CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
2213                                              /*EmitChecks=*/false,
2214                                              /*ForceSimpleCall=*/true);
2215 
2216       //
2217       // Warp 0 copies reduce element from transfer medium.
2218       //
2219       llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
2220       llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
2221       llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
2222 
2223       Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
2224       llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
2225           AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
2226 
2227       // Up to 32 threads in warp 0 are active.
2228       llvm::Value *IsActiveThread =
2229           Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
2230       Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
2231 
2232       CGF.EmitBlock(W0ThenBB);
2233 
2234       // SrcMediumPtr = &medium[tid]
2235       llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
2236           TransferMedium->getValueType(), TransferMedium,
2237           {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
2238       Address SrcMediumPtr(SrcMediumPtrVal, Align);
2239       // SrcMediumVal = *SrcMediumPtr;
2240       SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
2241 
2242       // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
2243       Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2244       llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
2245           TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
2246       Address TargetElemPtr = Address(TargetElemPtrVal, Align);
2247       TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
2248       if (NumIters > 1) {
2249         TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getElementType(),
2250                                               TargetElemPtr.getPointer(), Cnt),
2251                                 TargetElemPtr.getAlignment());
2252       }
2253 
2254       // *TargetElemPtr = SrcMediumVal;
2255       llvm::Value *SrcMediumValue =
2256           CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
2257       CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
2258                             CType);
2259       Bld.CreateBr(W0MergeBB);
2260 
2261       CGF.EmitBlock(W0ElseBB);
2262       Bld.CreateBr(W0MergeBB);
2263 
2264       CGF.EmitBlock(W0MergeBB);
2265 
2266       if (NumIters > 1) {
2267         Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
2268         CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
2269         CGF.EmitBranch(PrecondBB);
2270         (void)ApplyDebugLocation::CreateEmpty(CGF);
2271         CGF.EmitBlock(ExitBB);
2272       }
2273       RealTySize %= TySize;
2274     }
2275     ++Idx;
2276   }
2277 
2278   CGF.FinishFunction();
2279   return Fn;
2280 }
2281 
2282 /// Emit a helper that reduces data across two OpenMP threads (lanes)
2283 /// in the same warp.  It uses shuffle instructions to copy over data from
2284 /// a remote lane's stack.  The reduction algorithm performed is specified
2285 /// by the fourth parameter.
2286 ///
2287 /// Algorithm Versions.
2288 /// Full Warp Reduce (argument value 0):
2289 ///   This algorithm assumes that all 32 lanes are active and gathers
2290 ///   data from these 32 lanes, producing a single resultant value.
2291 /// Contiguous Partial Warp Reduce (argument value 1):
2292 ///   This algorithm assumes that only a *contiguous* subset of lanes
2293 ///   are active.  This happens for the last warp in a parallel region
2294 ///   when the user specified num_threads is not an integer multiple of
2295 ///   32.  This contiguous subset always starts with the zeroth lane.
2296 /// Partial Warp Reduce (argument value 2):
2297 ///   This algorithm gathers data from any number of lanes at any position.
2298 /// All reduced values are stored in the lowest possible lane.  The set
2299 /// of problems every algorithm addresses is a super set of those
2300 /// addressable by algorithms with a lower version number.  Overhead
2301 /// increases as algorithm version increases.
2302 ///
2303 /// Terminology
2304 /// Reduce element:
2305 ///   Reduce element refers to the individual data field with primitive
2306 ///   data types to be combined and reduced across threads.
2307 /// Reduce list:
2308 ///   Reduce list refers to a collection of local, thread-private
2309 ///   reduce elements.
2310 /// Remote Reduce list:
2311 ///   Remote Reduce list refers to a collection of remote (relative to
2312 ///   the current thread) reduce elements.
2313 ///
2314 /// We distinguish between three states of threads that are important to
2315 /// the implementation of this function.
2316 /// Alive threads:
2317 ///   Threads in a warp executing the SIMT instruction, as distinguished from
2318 ///   threads that are inactive due to divergent control flow.
2319 /// Active threads:
2320 ///   The minimal set of threads that has to be alive upon entry to this
2321 ///   function.  The computation is correct iff active threads are alive.
2322 ///   Some threads are alive but they are not active because they do not
2323 ///   contribute to the computation in any useful manner.  Turning them off
2324 ///   may introduce control flow overheads without any tangible benefits.
2325 /// Effective threads:
2326 ///   In order to comply with the argument requirements of the shuffle
2327 ///   function, we must keep all lanes holding data alive.  But at most
2328 ///   half of them perform value aggregation; we refer to this half of
2329 ///   threads as effective. The other half is simply handing off their
2330 ///   data.
2331 ///
2332 /// Procedure
2333 /// Value shuffle:
2334 ///   In this step active threads transfer data from higher lane positions
2335 ///   in the warp to lower lane positions, creating Remote Reduce list.
2336 /// Value aggregation:
2337 ///   In this step, effective threads combine their thread local Reduce list
2338 ///   with Remote Reduce list and store the result in the thread local
2339 ///   Reduce list.
2340 /// Value copy:
2341 ///   In this step, we deal with the assumption made by algorithm 2
2342 ///   (i.e. contiguity assumption).  When we have an odd number of lanes
2343 ///   active, say 2k+1, only k threads will be effective and therefore k
2344 ///   new values will be produced.  However, the Reduce list owned by the
2345 ///   (2k+1)th thread is ignored in the value aggregation.  Therefore
2346 ///   we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
2347 ///   that the contiguity assumption still holds.
2348 static llvm::Function *emitShuffleAndReduceFunction(
2349     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2350     QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
2351   ASTContext &C = CGM.getContext();
2352 
2353   // Thread local Reduce list used to host the values of data to be reduced.
2354   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2355                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2356   // Current lane id; could be logical.
2357   ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
2358                               ImplicitParamDecl::Other);
2359   // Offset of the remote source lane relative to the current lane.
2360   ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2361                                         C.ShortTy, ImplicitParamDecl::Other);
2362   // Algorithm version.  This is expected to be known at compile time.
2363   ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2364                                C.ShortTy, ImplicitParamDecl::Other);
2365   FunctionArgList Args;
2366   Args.push_back(&ReduceListArg);
2367   Args.push_back(&LaneIDArg);
2368   Args.push_back(&RemoteLaneOffsetArg);
2369   Args.push_back(&AlgoVerArg);
2370 
2371   const CGFunctionInfo &CGFI =
2372       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2373   auto *Fn = llvm::Function::Create(
2374       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2375       "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
2376   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2377   Fn->setDoesNotRecurse();
2378 
2379   CodeGenFunction CGF(CGM);
2380   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2381 
2382   CGBuilderTy &Bld = CGF.Builder;
2383 
2384   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2385   Address LocalReduceList(
2386       Bld.CreatePointerBitCastOrAddrSpaceCast(
2387           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2388                                C.VoidPtrTy, SourceLocation()),
2389           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2390       CGF.getPointerAlign());
2391 
2392   Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
2393   llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
2394       AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2395 
2396   Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
2397   llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
2398       AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2399 
2400   Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
2401   llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
2402       AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
2403 
2404   // Create a local thread-private variable to host the Reduce list
2405   // from a remote lane.
2406   Address RemoteReduceList =
2407       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
2408 
2409   // This loop iterates through the list of reduce elements and copies,
2410   // element by element, from a remote lane in the warp to RemoteReduceList,
2411   // hosted on the thread's stack.
2412   emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
2413                         LocalReduceList, RemoteReduceList,
2414                         {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
2415                          /*ScratchpadIndex=*/nullptr,
2416                          /*ScratchpadWidth=*/nullptr});
2417 
2418   // The actions to be performed on the Remote Reduce list is dependent
2419   // on the algorithm version.
2420   //
2421   //  if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
2422   //  LaneId % 2 == 0 && Offset > 0):
2423   //    do the reduction value aggregation
2424   //
2425   //  The thread local variable Reduce list is mutated in place to host the
2426   //  reduced data, which is the aggregated value produced from local and
2427   //  remote lanes.
2428   //
2429   //  Note that AlgoVer is expected to be a constant integer known at compile
2430   //  time.
2431   //  When AlgoVer==0, the first conjunction evaluates to true, making
2432   //    the entire predicate true during compile time.
2433   //  When AlgoVer==1, the second conjunction has only the second part to be
2434   //    evaluated during runtime.  Other conjunctions evaluates to false
2435   //    during compile time.
2436   //  When AlgoVer==2, the third conjunction has only the second part to be
2437   //    evaluated during runtime.  Other conjunctions evaluates to false
2438   //    during compile time.
2439   llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
2440 
2441   llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2442   llvm::Value *CondAlgo1 = Bld.CreateAnd(
2443       Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
2444 
2445   llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
2446   llvm::Value *CondAlgo2 = Bld.CreateAnd(
2447       Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
2448   CondAlgo2 = Bld.CreateAnd(
2449       CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
2450 
2451   llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
2452   CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
2453 
2454   llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
2455   llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
2456   llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
2457   Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
2458 
2459   CGF.EmitBlock(ThenBB);
2460   // reduce_function(LocalReduceList, RemoteReduceList)
2461   llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2462       LocalReduceList.getPointer(), CGF.VoidPtrTy);
2463   llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2464       RemoteReduceList.getPointer(), CGF.VoidPtrTy);
2465   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2466       CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
2467   Bld.CreateBr(MergeBB);
2468 
2469   CGF.EmitBlock(ElseBB);
2470   Bld.CreateBr(MergeBB);
2471 
2472   CGF.EmitBlock(MergeBB);
2473 
2474   // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
2475   // Reduce list.
2476   Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
2477   llvm::Value *CondCopy = Bld.CreateAnd(
2478       Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
2479 
2480   llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
2481   llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
2482   llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
2483   Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
2484 
2485   CGF.EmitBlock(CpyThenBB);
2486   emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
2487                         RemoteReduceList, LocalReduceList);
2488   Bld.CreateBr(CpyMergeBB);
2489 
2490   CGF.EmitBlock(CpyElseBB);
2491   Bld.CreateBr(CpyMergeBB);
2492 
2493   CGF.EmitBlock(CpyMergeBB);
2494 
2495   CGF.FinishFunction();
2496   return Fn;
2497 }
2498 
2499 /// This function emits a helper that copies all the reduction variables from
2500 /// the team into the provided global buffer for the reduction variables.
2501 ///
2502 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2503 ///   For all data entries D in reduce_data:
2504 ///     Copy local D to buffer.D[Idx]
2505 static llvm::Value *emitListToGlobalCopyFunction(
2506     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2507     QualType ReductionArrayTy, SourceLocation Loc,
2508     const RecordDecl *TeamReductionRec,
2509     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2510         &VarFieldMap) {
2511   ASTContext &C = CGM.getContext();
2512 
2513   // Buffer: global reduction buffer.
2514   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2515                               C.VoidPtrTy, ImplicitParamDecl::Other);
2516   // Idx: index of the buffer.
2517   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2518                            ImplicitParamDecl::Other);
2519   // ReduceList: thread local Reduce list.
2520   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2521                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2522   FunctionArgList Args;
2523   Args.push_back(&BufferArg);
2524   Args.push_back(&IdxArg);
2525   Args.push_back(&ReduceListArg);
2526 
2527   const CGFunctionInfo &CGFI =
2528       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2529   auto *Fn = llvm::Function::Create(
2530       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2531       "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
2532   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2533   Fn->setDoesNotRecurse();
2534   CodeGenFunction CGF(CGM);
2535   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2536 
2537   CGBuilderTy &Bld = CGF.Builder;
2538 
2539   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2540   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2541   Address LocalReduceList(
2542       Bld.CreatePointerBitCastOrAddrSpaceCast(
2543           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2544                                C.VoidPtrTy, Loc),
2545           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2546       CGF.getPointerAlign());
2547   QualType StaticTy = C.getRecordType(TeamReductionRec);
2548   llvm::Type *LLVMReductionsBufferTy =
2549       CGM.getTypes().ConvertTypeForMem(StaticTy);
2550   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2551       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2552       LLVMReductionsBufferTy->getPointerTo());
2553   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2554                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2555                                               /*Volatile=*/false, C.IntTy,
2556                                               Loc)};
2557   unsigned Idx = 0;
2558   for (const Expr *Private : Privates) {
2559     // Reduce element = LocalReduceList[i]
2560     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2561     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2562         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2563     // elemptr = ((CopyType*)(elemptrptr)) + I
2564     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2565         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
2566     Address ElemPtr =
2567         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2568     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
2569     // Global = Buffer.VD[Idx];
2570     const FieldDecl *FD = VarFieldMap.lookup(VD);
2571     LValue GlobLVal = CGF.EmitLValueForField(
2572         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2573     Address GlobAddr = GlobLVal.getAddress(CGF);
2574     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2575         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2576     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
2577     switch (CGF.getEvaluationKind(Private->getType())) {
2578     case TEK_Scalar: {
2579       llvm::Value *V = CGF.EmitLoadOfScalar(
2580           ElemPtr, /*Volatile=*/false, Private->getType(), Loc,
2581           LValueBaseInfo(AlignmentSource::Type), TBAAAccessInfo());
2582       CGF.EmitStoreOfScalar(V, GlobLVal);
2583       break;
2584     }
2585     case TEK_Complex: {
2586       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
2587           CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
2588       CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
2589       break;
2590     }
2591     case TEK_Aggregate:
2592       CGF.EmitAggregateCopy(GlobLVal,
2593                             CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2594                             Private->getType(), AggValueSlot::DoesNotOverlap);
2595       break;
2596     }
2597     ++Idx;
2598   }
2599 
2600   CGF.FinishFunction();
2601   return Fn;
2602 }
2603 
2604 /// This function emits a helper that reduces all the reduction variables from
2605 /// the team into the provided global buffer for the reduction variables.
2606 ///
2607 /// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
2608 ///  void *GlobPtrs[];
2609 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
2610 ///  ...
2611 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
2612 ///  reduce_function(GlobPtrs, reduce_data);
2613 static llvm::Value *emitListToGlobalReduceFunction(
2614     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2615     QualType ReductionArrayTy, SourceLocation Loc,
2616     const RecordDecl *TeamReductionRec,
2617     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2618         &VarFieldMap,
2619     llvm::Function *ReduceFn) {
2620   ASTContext &C = CGM.getContext();
2621 
2622   // Buffer: global reduction buffer.
2623   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2624                               C.VoidPtrTy, ImplicitParamDecl::Other);
2625   // Idx: index of the buffer.
2626   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2627                            ImplicitParamDecl::Other);
2628   // ReduceList: thread local Reduce list.
2629   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2630                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2631   FunctionArgList Args;
2632   Args.push_back(&BufferArg);
2633   Args.push_back(&IdxArg);
2634   Args.push_back(&ReduceListArg);
2635 
2636   const CGFunctionInfo &CGFI =
2637       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2638   auto *Fn = llvm::Function::Create(
2639       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2640       "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
2641   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2642   Fn->setDoesNotRecurse();
2643   CodeGenFunction CGF(CGM);
2644   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2645 
2646   CGBuilderTy &Bld = CGF.Builder;
2647 
2648   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2649   QualType StaticTy = C.getRecordType(TeamReductionRec);
2650   llvm::Type *LLVMReductionsBufferTy =
2651       CGM.getTypes().ConvertTypeForMem(StaticTy);
2652   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2653       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2654       LLVMReductionsBufferTy->getPointerTo());
2655 
2656   // 1. Build a list of reduction variables.
2657   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2658   Address ReductionList =
2659       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2660   auto IPriv = Privates.begin();
2661   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2662                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2663                                               /*Volatile=*/false, C.IntTy,
2664                                               Loc)};
2665   unsigned Idx = 0;
2666   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
2667     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2668     // Global = Buffer.VD[Idx];
2669     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
2670     const FieldDecl *FD = VarFieldMap.lookup(VD);
2671     LValue GlobLVal = CGF.EmitLValueForField(
2672         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2673     Address GlobAddr = GlobLVal.getAddress(CGF);
2674     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2675         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2676     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
2677     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
2678     if ((*IPriv)->getType()->isVariablyModifiedType()) {
2679       // Store array size.
2680       ++Idx;
2681       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2682       llvm::Value *Size = CGF.Builder.CreateIntCast(
2683           CGF.getVLASize(
2684                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2685               .NumElts,
2686           CGF.SizeTy, /*isSigned=*/false);
2687       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2688                               Elem);
2689     }
2690   }
2691 
2692   // Call reduce_function(GlobalReduceList, ReduceList)
2693   llvm::Value *GlobalReduceList =
2694       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
2695   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2696   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
2697       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
2698   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2699       CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
2700   CGF.FinishFunction();
2701   return Fn;
2702 }
2703 
2704 /// This function emits a helper that copies all the reduction variables from
2705 /// the team into the provided global buffer for the reduction variables.
2706 ///
2707 /// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
2708 ///   For all data entries D in reduce_data:
2709 ///     Copy buffer.D[Idx] to local D;
2710 static llvm::Value *emitGlobalToListCopyFunction(
2711     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2712     QualType ReductionArrayTy, SourceLocation Loc,
2713     const RecordDecl *TeamReductionRec,
2714     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2715         &VarFieldMap) {
2716   ASTContext &C = CGM.getContext();
2717 
2718   // Buffer: global reduction buffer.
2719   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2720                               C.VoidPtrTy, ImplicitParamDecl::Other);
2721   // Idx: index of the buffer.
2722   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2723                            ImplicitParamDecl::Other);
2724   // ReduceList: thread local Reduce list.
2725   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2726                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2727   FunctionArgList Args;
2728   Args.push_back(&BufferArg);
2729   Args.push_back(&IdxArg);
2730   Args.push_back(&ReduceListArg);
2731 
2732   const CGFunctionInfo &CGFI =
2733       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2734   auto *Fn = llvm::Function::Create(
2735       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2736       "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
2737   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2738   Fn->setDoesNotRecurse();
2739   CodeGenFunction CGF(CGM);
2740   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2741 
2742   CGBuilderTy &Bld = CGF.Builder;
2743 
2744   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2745   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2746   Address LocalReduceList(
2747       Bld.CreatePointerBitCastOrAddrSpaceCast(
2748           CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
2749                                C.VoidPtrTy, Loc),
2750           CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
2751       CGF.getPointerAlign());
2752   QualType StaticTy = C.getRecordType(TeamReductionRec);
2753   llvm::Type *LLVMReductionsBufferTy =
2754       CGM.getTypes().ConvertTypeForMem(StaticTy);
2755   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2756       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2757       LLVMReductionsBufferTy->getPointerTo());
2758 
2759   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2760                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2761                                               /*Volatile=*/false, C.IntTy,
2762                                               Loc)};
2763   unsigned Idx = 0;
2764   for (const Expr *Private : Privates) {
2765     // Reduce element = LocalReduceList[i]
2766     Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
2767     llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
2768         ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
2769     // elemptr = ((CopyType*)(elemptrptr)) + I
2770     ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2771         ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
2772     Address ElemPtr =
2773         Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
2774     const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
2775     // Global = Buffer.VD[Idx];
2776     const FieldDecl *FD = VarFieldMap.lookup(VD);
2777     LValue GlobLVal = CGF.EmitLValueForField(
2778         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2779     Address GlobAddr = GlobLVal.getAddress(CGF);
2780     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2781         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2782     GlobLVal.setAddress(Address(BufferPtr, GlobAddr.getAlignment()));
2783     switch (CGF.getEvaluationKind(Private->getType())) {
2784     case TEK_Scalar: {
2785       llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
2786       CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType(),
2787                             LValueBaseInfo(AlignmentSource::Type),
2788                             TBAAAccessInfo());
2789       break;
2790     }
2791     case TEK_Complex: {
2792       CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
2793       CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2794                              /*isInit=*/false);
2795       break;
2796     }
2797     case TEK_Aggregate:
2798       CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
2799                             GlobLVal, Private->getType(),
2800                             AggValueSlot::DoesNotOverlap);
2801       break;
2802     }
2803     ++Idx;
2804   }
2805 
2806   CGF.FinishFunction();
2807   return Fn;
2808 }
2809 
2810 /// This function emits a helper that reduces all the reduction variables from
2811 /// the team into the provided global buffer for the reduction variables.
2812 ///
2813 /// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
2814 ///  void *GlobPtrs[];
2815 ///  GlobPtrs[0] = (void*)&buffer.D0[Idx];
2816 ///  ...
2817 ///  GlobPtrs[N] = (void*)&buffer.DN[Idx];
2818 ///  reduce_function(reduce_data, GlobPtrs);
2819 static llvm::Value *emitGlobalToListReduceFunction(
2820     CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
2821     QualType ReductionArrayTy, SourceLocation Loc,
2822     const RecordDecl *TeamReductionRec,
2823     const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2824         &VarFieldMap,
2825     llvm::Function *ReduceFn) {
2826   ASTContext &C = CGM.getContext();
2827 
2828   // Buffer: global reduction buffer.
2829   ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2830                               C.VoidPtrTy, ImplicitParamDecl::Other);
2831   // Idx: index of the buffer.
2832   ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
2833                            ImplicitParamDecl::Other);
2834   // ReduceList: thread local Reduce list.
2835   ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
2836                                   C.VoidPtrTy, ImplicitParamDecl::Other);
2837   FunctionArgList Args;
2838   Args.push_back(&BufferArg);
2839   Args.push_back(&IdxArg);
2840   Args.push_back(&ReduceListArg);
2841 
2842   const CGFunctionInfo &CGFI =
2843       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2844   auto *Fn = llvm::Function::Create(
2845       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2846       "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
2847   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2848   Fn->setDoesNotRecurse();
2849   CodeGenFunction CGF(CGM);
2850   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2851 
2852   CGBuilderTy &Bld = CGF.Builder;
2853 
2854   Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
2855   QualType StaticTy = C.getRecordType(TeamReductionRec);
2856   llvm::Type *LLVMReductionsBufferTy =
2857       CGM.getTypes().ConvertTypeForMem(StaticTy);
2858   llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2859       CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
2860       LLVMReductionsBufferTy->getPointerTo());
2861 
2862   // 1. Build a list of reduction variables.
2863   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
2864   Address ReductionList =
2865       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
2866   auto IPriv = Privates.begin();
2867   llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
2868                          CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
2869                                               /*Volatile=*/false, C.IntTy,
2870                                               Loc)};
2871   unsigned Idx = 0;
2872   for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
2873     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2874     // Global = Buffer.VD[Idx];
2875     const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
2876     const FieldDecl *FD = VarFieldMap.lookup(VD);
2877     LValue GlobLVal = CGF.EmitLValueForField(
2878         CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
2879     Address GlobAddr = GlobLVal.getAddress(CGF);
2880     llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(
2881         GlobAddr.getElementType(), GlobAddr.getPointer(), Idxs);
2882     llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
2883     CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
2884     if ((*IPriv)->getType()->isVariablyModifiedType()) {
2885       // Store array size.
2886       ++Idx;
2887       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
2888       llvm::Value *Size = CGF.Builder.CreateIntCast(
2889           CGF.getVLASize(
2890                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
2891               .NumElts,
2892           CGF.SizeTy, /*isSigned=*/false);
2893       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
2894                               Elem);
2895     }
2896   }
2897 
2898   // Call reduce_function(ReduceList, GlobalReduceList)
2899   llvm::Value *GlobalReduceList =
2900       CGF.EmitCastToVoidPtr(ReductionList.getPointer());
2901   Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
2902   llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
2903       AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
2904   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
2905       CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
2906   CGF.FinishFunction();
2907   return Fn;
2908 }
2909 
2910 ///
2911 /// Design of OpenMP reductions on the GPU
2912 ///
2913 /// Consider a typical OpenMP program with one or more reduction
2914 /// clauses:
2915 ///
2916 /// float foo;
2917 /// double bar;
2918 /// #pragma omp target teams distribute parallel for \
2919 ///             reduction(+:foo) reduction(*:bar)
2920 /// for (int i = 0; i < N; i++) {
2921 ///   foo += A[i]; bar *= B[i];
2922 /// }
2923 ///
2924 /// where 'foo' and 'bar' are reduced across all OpenMP threads in
2925 /// all teams.  In our OpenMP implementation on the NVPTX device an
2926 /// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
2927 /// within a team are mapped to CUDA threads within a threadblock.
2928 /// Our goal is to efficiently aggregate values across all OpenMP
2929 /// threads such that:
2930 ///
2931 ///   - the compiler and runtime are logically concise, and
2932 ///   - the reduction is performed efficiently in a hierarchical
2933 ///     manner as follows: within OpenMP threads in the same warp,
2934 ///     across warps in a threadblock, and finally across teams on
2935 ///     the NVPTX device.
2936 ///
2937 /// Introduction to Decoupling
2938 ///
2939 /// We would like to decouple the compiler and the runtime so that the
2940 /// latter is ignorant of the reduction variables (number, data types)
2941 /// and the reduction operators.  This allows a simpler interface
2942 /// and implementation while still attaining good performance.
2943 ///
2944 /// Pseudocode for the aforementioned OpenMP program generated by the
2945 /// compiler is as follows:
2946 ///
2947 /// 1. Create private copies of reduction variables on each OpenMP
2948 ///    thread: 'foo_private', 'bar_private'
2949 /// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
2950 ///    to it and writes the result in 'foo_private' and 'bar_private'
2951 ///    respectively.
2952 /// 3. Call the OpenMP runtime on the GPU to reduce within a team
2953 ///    and store the result on the team master:
2954 ///
2955 ///     __kmpc_nvptx_parallel_reduce_nowait_v2(...,
2956 ///        reduceData, shuffleReduceFn, interWarpCpyFn)
2957 ///
2958 ///     where:
2959 ///       struct ReduceData {
2960 ///         double *foo;
2961 ///         double *bar;
2962 ///       } reduceData
2963 ///       reduceData.foo = &foo_private
2964 ///       reduceData.bar = &bar_private
2965 ///
2966 ///     'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
2967 ///     auxiliary functions generated by the compiler that operate on
2968 ///     variables of type 'ReduceData'.  They aid the runtime perform
2969 ///     algorithmic steps in a data agnostic manner.
2970 ///
2971 ///     'shuffleReduceFn' is a pointer to a function that reduces data
2972 ///     of type 'ReduceData' across two OpenMP threads (lanes) in the
2973 ///     same warp.  It takes the following arguments as input:
2974 ///
2975 ///     a. variable of type 'ReduceData' on the calling lane,
2976 ///     b. its lane_id,
2977 ///     c. an offset relative to the current lane_id to generate a
2978 ///        remote_lane_id.  The remote lane contains the second
2979 ///        variable of type 'ReduceData' that is to be reduced.
2980 ///     d. an algorithm version parameter determining which reduction
2981 ///        algorithm to use.
2982 ///
2983 ///     'shuffleReduceFn' retrieves data from the remote lane using
2984 ///     efficient GPU shuffle intrinsics and reduces, using the
2985 ///     algorithm specified by the 4th parameter, the two operands
2986 ///     element-wise.  The result is written to the first operand.
2987 ///
2988 ///     Different reduction algorithms are implemented in different
2989 ///     runtime functions, all calling 'shuffleReduceFn' to perform
2990 ///     the essential reduction step.  Therefore, based on the 4th
2991 ///     parameter, this function behaves slightly differently to
2992 ///     cooperate with the runtime to ensure correctness under
2993 ///     different circumstances.
2994 ///
2995 ///     'InterWarpCpyFn' is a pointer to a function that transfers
2996 ///     reduced variables across warps.  It tunnels, through CUDA
2997 ///     shared memory, the thread-private data of type 'ReduceData'
2998 ///     from lane 0 of each warp to a lane in the first warp.
2999 /// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3000 ///    The last team writes the global reduced value to memory.
3001 ///
3002 ///     ret = __kmpc_nvptx_teams_reduce_nowait(...,
3003 ///             reduceData, shuffleReduceFn, interWarpCpyFn,
3004 ///             scratchpadCopyFn, loadAndReduceFn)
3005 ///
3006 ///     'scratchpadCopyFn' is a helper that stores reduced
3007 ///     data from the team master to a scratchpad array in
3008 ///     global memory.
3009 ///
3010 ///     'loadAndReduceFn' is a helper that loads data from
3011 ///     the scratchpad array and reduces it with the input
3012 ///     operand.
3013 ///
3014 ///     These compiler generated functions hide address
3015 ///     calculation and alignment information from the runtime.
3016 /// 5. if ret == 1:
3017 ///     The team master of the last team stores the reduced
3018 ///     result to the globals in memory.
3019 ///     foo += reduceData.foo; bar *= reduceData.bar
3020 ///
3021 ///
3022 /// Warp Reduction Algorithms
3023 ///
3024 /// On the warp level, we have three algorithms implemented in the
3025 /// OpenMP runtime depending on the number of active lanes:
3026 ///
3027 /// Full Warp Reduction
3028 ///
3029 /// The reduce algorithm within a warp where all lanes are active
3030 /// is implemented in the runtime as follows:
3031 ///
3032 /// full_warp_reduce(void *reduce_data,
3033 ///                  kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3034 ///   for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3035 ///     ShuffleReduceFn(reduce_data, 0, offset, 0);
3036 /// }
3037 ///
3038 /// The algorithm completes in log(2, WARPSIZE) steps.
3039 ///
3040 /// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3041 /// not used therefore we save instructions by not retrieving lane_id
3042 /// from the corresponding special registers.  The 4th parameter, which
3043 /// represents the version of the algorithm being used, is set to 0 to
3044 /// signify full warp reduction.
3045 ///
3046 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3047 ///
3048 /// #reduce_elem refers to an element in the local lane's data structure
3049 /// #remote_elem is retrieved from a remote lane
3050 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3051 /// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3052 ///
3053 /// Contiguous Partial Warp Reduction
3054 ///
3055 /// This reduce algorithm is used within a warp where only the first
3056 /// 'n' (n <= WARPSIZE) lanes are active.  It is typically used when the
3057 /// number of OpenMP threads in a parallel region is not a multiple of
3058 /// WARPSIZE.  The algorithm is implemented in the runtime as follows:
3059 ///
3060 /// void
3061 /// contiguous_partial_reduce(void *reduce_data,
3062 ///                           kmp_ShuffleReductFctPtr ShuffleReduceFn,
3063 ///                           int size, int lane_id) {
3064 ///   int curr_size;
3065 ///   int offset;
3066 ///   curr_size = size;
3067 ///   mask = curr_size/2;
3068 ///   while (offset>0) {
3069 ///     ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3070 ///     curr_size = (curr_size+1)/2;
3071 ///     offset = curr_size/2;
3072 ///   }
3073 /// }
3074 ///
3075 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3076 ///
3077 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3078 /// if (lane_id < offset)
3079 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3080 /// else
3081 ///     reduce_elem = remote_elem
3082 ///
3083 /// This algorithm assumes that the data to be reduced are located in a
3084 /// contiguous subset of lanes starting from the first.  When there is
3085 /// an odd number of active lanes, the data in the last lane is not
3086 /// aggregated with any other lane's dat but is instead copied over.
3087 ///
3088 /// Dispersed Partial Warp Reduction
3089 ///
3090 /// This algorithm is used within a warp when any discontiguous subset of
3091 /// lanes are active.  It is used to implement the reduction operation
3092 /// across lanes in an OpenMP simd region or in a nested parallel region.
3093 ///
3094 /// void
3095 /// dispersed_partial_reduce(void *reduce_data,
3096 ///                          kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3097 ///   int size, remote_id;
3098 ///   int logical_lane_id = number_of_active_lanes_before_me() * 2;
3099 ///   do {
3100 ///       remote_id = next_active_lane_id_right_after_me();
3101 ///       # the above function returns 0 of no active lane
3102 ///       # is present right after the current lane.
3103 ///       size = number_of_active_lanes_in_this_warp();
3104 ///       logical_lane_id /= 2;
3105 ///       ShuffleReduceFn(reduce_data, logical_lane_id,
3106 ///                       remote_id-1-threadIdx.x, 2);
3107 ///   } while (logical_lane_id % 2 == 0 && size > 1);
3108 /// }
3109 ///
3110 /// There is no assumption made about the initial state of the reduction.
3111 /// Any number of lanes (>=1) could be active at any position.  The reduction
3112 /// result is returned in the first active lane.
3113 ///
3114 /// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3115 ///
3116 /// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3117 /// if (lane_id % 2 == 0 && offset > 0)
3118 ///     reduce_elem = reduce_elem REDUCE_OP remote_elem
3119 /// else
3120 ///     reduce_elem = remote_elem
3121 ///
3122 ///
3123 /// Intra-Team Reduction
3124 ///
3125 /// This function, as implemented in the runtime call
3126 /// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
3127 /// threads in a team.  It first reduces within a warp using the
3128 /// aforementioned algorithms.  We then proceed to gather all such
3129 /// reduced values at the first warp.
3130 ///
3131 /// The runtime makes use of the function 'InterWarpCpyFn', which copies
3132 /// data from each of the "warp master" (zeroth lane of each warp, where
3133 /// warp-reduced data is held) to the zeroth warp.  This step reduces (in
3134 /// a mathematical sense) the problem of reduction across warp masters in
3135 /// a block to the problem of warp reduction.
3136 ///
3137 ///
3138 /// Inter-Team Reduction
3139 ///
3140 /// Once a team has reduced its data to a single value, it is stored in
3141 /// a global scratchpad array.  Since each team has a distinct slot, this
3142 /// can be done without locking.
3143 ///
3144 /// The last team to write to the scratchpad array proceeds to reduce the
3145 /// scratchpad array.  One or more workers in the last team use the helper
3146 /// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3147 /// the k'th worker reduces every k'th element.
3148 ///
3149 /// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
3150 /// reduce across workers and compute a globally reduced value.
3151 ///
3152 void CGOpenMPRuntimeGPU::emitReduction(
3153     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3154     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3155     ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3156   if (!CGF.HaveInsertPoint())
3157     return;
3158 
3159   bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
3160 #ifndef NDEBUG
3161   bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
3162 #endif
3163 
3164   if (Options.SimpleReduction) {
3165     assert(!TeamsReduction && !ParallelReduction &&
3166            "Invalid reduction selection in emitReduction.");
3167     CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3168                                    ReductionOps, Options);
3169     return;
3170   }
3171 
3172   assert((TeamsReduction || ParallelReduction) &&
3173          "Invalid reduction selection in emitReduction.");
3174 
3175   // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
3176   // RedList, shuffle_reduce_func, interwarp_copy_func);
3177   // or
3178   // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
3179   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3180   llvm::Value *ThreadId = getThreadID(CGF, Loc);
3181 
3182   llvm::Value *Res;
3183   ASTContext &C = CGM.getContext();
3184   // 1. Build a list of reduction variables.
3185   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3186   auto Size = RHSExprs.size();
3187   for (const Expr *E : Privates) {
3188     if (E->getType()->isVariablyModifiedType())
3189       // Reserve place for array size.
3190       ++Size;
3191   }
3192   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3193   QualType ReductionArrayTy =
3194       C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
3195                              /*IndexTypeQuals=*/0);
3196   Address ReductionList =
3197       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3198   auto IPriv = Privates.begin();
3199   unsigned Idx = 0;
3200   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3201     Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3202     CGF.Builder.CreateStore(
3203         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3204             CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
3205         Elem);
3206     if ((*IPriv)->getType()->isVariablyModifiedType()) {
3207       // Store array size.
3208       ++Idx;
3209       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3210       llvm::Value *Size = CGF.Builder.CreateIntCast(
3211           CGF.getVLASize(
3212                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3213               .NumElts,
3214           CGF.SizeTy, /*isSigned=*/false);
3215       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3216                               Elem);
3217     }
3218   }
3219 
3220   llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3221       ReductionList.getPointer(), CGF.VoidPtrTy);
3222   llvm::Function *ReductionFn = emitReductionFunction(
3223       Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
3224       LHSExprs, RHSExprs, ReductionOps);
3225   llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3226   llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3227       CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3228   llvm::Value *InterWarpCopyFn =
3229       emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3230 
3231   if (ParallelReduction) {
3232     llvm::Value *Args[] = {RTLoc,
3233                            ThreadId,
3234                            CGF.Builder.getInt32(RHSExprs.size()),
3235                            ReductionArrayTySize,
3236                            RL,
3237                            ShuffleAndReduceFn,
3238                            InterWarpCopyFn};
3239 
3240     Res = CGF.EmitRuntimeCall(
3241         OMPBuilder.getOrCreateRuntimeFunction(
3242             CGM.getModule(), OMPRTL___kmpc_nvptx_parallel_reduce_nowait_v2),
3243         Args);
3244   } else {
3245     assert(TeamsReduction && "expected teams reduction.");
3246     llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
3247     llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
3248     int Cnt = 0;
3249     for (const Expr *DRE : Privates) {
3250       PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
3251       ++Cnt;
3252     }
3253     const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
3254         CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
3255         C.getLangOpts().OpenMPCUDAReductionBufNum);
3256     TeamsReductions.push_back(TeamReductionRec);
3257     if (!KernelTeamsReductionPtr) {
3258       KernelTeamsReductionPtr = new llvm::GlobalVariable(
3259           CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
3260           llvm::GlobalValue::InternalLinkage, nullptr,
3261           "_openmp_teams_reductions_buffer_$_$ptr");
3262     }
3263     llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
3264         Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
3265         /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
3266     llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
3267         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
3268     llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
3269         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
3270         ReductionFn);
3271     llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
3272         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
3273     llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
3274         CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
3275         ReductionFn);
3276 
3277     llvm::Value *Args[] = {
3278         RTLoc,
3279         ThreadId,
3280         GlobalBufferPtr,
3281         CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
3282         RL,
3283         ShuffleAndReduceFn,
3284         InterWarpCopyFn,
3285         GlobalToBufferCpyFn,
3286         GlobalToBufferRedFn,
3287         BufferToGlobalCpyFn,
3288         BufferToGlobalRedFn};
3289 
3290     Res = CGF.EmitRuntimeCall(
3291         OMPBuilder.getOrCreateRuntimeFunction(
3292             CGM.getModule(), OMPRTL___kmpc_nvptx_teams_reduce_nowait_v2),
3293         Args);
3294   }
3295 
3296   // 5. Build if (res == 1)
3297   llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3298   llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3299   llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3300       Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3301   CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
3302 
3303   // 6. Build then branch: where we have reduced values in the master
3304   //    thread in each team.
3305   //    __kmpc_end_reduce{_nowait}(<gtid>);
3306   //    break;
3307   CGF.EmitBlock(ThenBB);
3308 
3309   // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
3310   auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
3311                     this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3312     auto IPriv = Privates.begin();
3313     auto ILHS = LHSExprs.begin();
3314     auto IRHS = RHSExprs.begin();
3315     for (const Expr *E : ReductionOps) {
3316       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3317                                   cast<DeclRefExpr>(*IRHS));
3318       ++IPriv;
3319       ++ILHS;
3320       ++IRHS;
3321     }
3322   };
3323   llvm::Value *EndArgs[] = {ThreadId};
3324   RegionCodeGenTy RCG(CodeGen);
3325   NVPTXActionTy Action(
3326       nullptr, llvm::None,
3327       OMPBuilder.getOrCreateRuntimeFunction(
3328           CGM.getModule(), OMPRTL___kmpc_nvptx_end_reduce_nowait),
3329       EndArgs);
3330   RCG.setAction(Action);
3331   RCG(CGF);
3332   // There is no need to emit line number for unconditional branch.
3333   (void)ApplyDebugLocation::CreateEmpty(CGF);
3334   CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
3335 }
3336 
3337 const VarDecl *
3338 CGOpenMPRuntimeGPU::translateParameter(const FieldDecl *FD,
3339                                        const VarDecl *NativeParam) const {
3340   if (!NativeParam->getType()->isReferenceType())
3341     return NativeParam;
3342   QualType ArgType = NativeParam->getType();
3343   QualifierCollector QC;
3344   const Type *NonQualTy = QC.strip(ArgType);
3345   QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3346   if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3347     if (Attr->getCaptureKind() == OMPC_map) {
3348       PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3349                                                         LangAS::opencl_global);
3350     }
3351   }
3352   ArgType = CGM.getContext().getPointerType(PointeeTy);
3353   QC.addRestrict();
3354   enum { NVPTX_local_addr = 5 };
3355   QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
3356   ArgType = QC.apply(CGM.getContext(), ArgType);
3357   if (isa<ImplicitParamDecl>(NativeParam))
3358     return ImplicitParamDecl::Create(
3359         CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
3360         NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
3361   return ParmVarDecl::Create(
3362       CGM.getContext(),
3363       const_cast<DeclContext *>(NativeParam->getDeclContext()),
3364       NativeParam->getBeginLoc(), NativeParam->getLocation(),
3365       NativeParam->getIdentifier(), ArgType,
3366       /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
3367 }
3368 
3369 Address
3370 CGOpenMPRuntimeGPU::getParameterAddress(CodeGenFunction &CGF,
3371                                           const VarDecl *NativeParam,
3372                                           const VarDecl *TargetParam) const {
3373   assert(NativeParam != TargetParam &&
3374          NativeParam->getType()->isReferenceType() &&
3375          "Native arg must not be the same as target arg.");
3376   Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
3377   QualType NativeParamType = NativeParam->getType();
3378   QualifierCollector QC;
3379   const Type *NonQualTy = QC.strip(NativeParamType);
3380   QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3381   unsigned NativePointeeAddrSpace =
3382       CGF.getContext().getTargetAddressSpace(NativePointeeTy);
3383   QualType TargetTy = TargetParam->getType();
3384   llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
3385       LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
3386   // First cast to generic.
3387   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3388       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3389                       /*AddrSpace=*/0));
3390   // Cast from generic to native address space.
3391   TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3392       TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
3393                       NativePointeeAddrSpace));
3394   Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
3395   CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
3396                         NativeParamType);
3397   return NativeParamAddr;
3398 }
3399 
3400 void CGOpenMPRuntimeGPU::emitOutlinedFunctionCall(
3401     CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
3402     ArrayRef<llvm::Value *> Args) const {
3403   SmallVector<llvm::Value *, 4> TargetArgs;
3404   TargetArgs.reserve(Args.size());
3405   auto *FnType = OutlinedFn.getFunctionType();
3406   for (unsigned I = 0, E = Args.size(); I < E; ++I) {
3407     if (FnType->isVarArg() && FnType->getNumParams() <= I) {
3408       TargetArgs.append(std::next(Args.begin(), I), Args.end());
3409       break;
3410     }
3411     llvm::Type *TargetType = FnType->getParamType(I);
3412     llvm::Value *NativeArg = Args[I];
3413     if (!TargetType->isPointerTy()) {
3414       TargetArgs.emplace_back(NativeArg);
3415       continue;
3416     }
3417     llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3418         NativeArg,
3419         NativeArg->getType()->getPointerElementType()->getPointerTo());
3420     TargetArgs.emplace_back(
3421         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
3422   }
3423   CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
3424 }
3425 
3426 /// Emit function which wraps the outline parallel region
3427 /// and controls the arguments which are passed to this function.
3428 /// The wrapper ensures that the outlined function is called
3429 /// with the correct arguments when data is shared.
3430 llvm::Function *CGOpenMPRuntimeGPU::createParallelDataSharingWrapper(
3431     llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
3432   ASTContext &Ctx = CGM.getContext();
3433   const auto &CS = *D.getCapturedStmt(OMPD_parallel);
3434 
3435   // Create a function that takes as argument the source thread.
3436   FunctionArgList WrapperArgs;
3437   QualType Int16QTy =
3438       Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
3439   QualType Int32QTy =
3440       Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
3441   ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
3442                                      /*Id=*/nullptr, Int16QTy,
3443                                      ImplicitParamDecl::Other);
3444   ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
3445                                /*Id=*/nullptr, Int32QTy,
3446                                ImplicitParamDecl::Other);
3447   WrapperArgs.emplace_back(&ParallelLevelArg);
3448   WrapperArgs.emplace_back(&WrapperArg);
3449 
3450   const CGFunctionInfo &CGFI =
3451       CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
3452 
3453   auto *Fn = llvm::Function::Create(
3454       CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3455       Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
3456 
3457   // Ensure we do not inline the function. This is trivially true for the ones
3458   // passed to __kmpc_fork_call but the ones calles in serialized regions
3459   // could be inlined. This is not a perfect but it is closer to the invariant
3460   // we want, namely, every data environment starts with a new function.
3461   // TODO: We should pass the if condition to the runtime function and do the
3462   //       handling there. Much cleaner code.
3463   Fn->addFnAttr(llvm::Attribute::NoInline);
3464 
3465   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3466   Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
3467   Fn->setDoesNotRecurse();
3468 
3469   CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
3470   CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
3471                     D.getBeginLoc(), D.getBeginLoc());
3472 
3473   const auto *RD = CS.getCapturedRecordDecl();
3474   auto CurField = RD->field_begin();
3475 
3476   Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
3477                                                       /*Name=*/".zero.addr");
3478   CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
3479   // Get the array of arguments.
3480   SmallVector<llvm::Value *, 8> Args;
3481 
3482   Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
3483   Args.emplace_back(ZeroAddr.getPointer());
3484 
3485   CGBuilderTy &Bld = CGF.Builder;
3486   auto CI = CS.capture_begin();
3487 
3488   // Use global memory for data sharing.
3489   // Handle passing of global args to workers.
3490   Address GlobalArgs =
3491       CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
3492   llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
3493   llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
3494   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
3495                           CGM.getModule(), OMPRTL___kmpc_get_shared_variables),
3496                       DataSharingArgs);
3497 
3498   // Retrieve the shared variables from the list of references returned
3499   // by the runtime. Pass the variables to the outlined function.
3500   Address SharedArgListAddress = Address::invalid();
3501   if (CS.capture_size() > 0 ||
3502       isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3503     SharedArgListAddress = CGF.EmitLoadOfPointer(
3504         GlobalArgs, CGF.getContext()
3505                         .getPointerType(CGF.getContext().getPointerType(
3506                             CGF.getContext().VoidPtrTy))
3507                         .castAs<PointerType>());
3508   }
3509   unsigned Idx = 0;
3510   if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
3511     Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
3512     Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3513         Src, CGF.SizeTy->getPointerTo());
3514     llvm::Value *LB = CGF.EmitLoadOfScalar(
3515         TypedAddress,
3516         /*Volatile=*/false,
3517         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3518         cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
3519     Args.emplace_back(LB);
3520     ++Idx;
3521     Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
3522     TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3523         Src, CGF.SizeTy->getPointerTo());
3524     llvm::Value *UB = CGF.EmitLoadOfScalar(
3525         TypedAddress,
3526         /*Volatile=*/false,
3527         CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
3528         cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
3529     Args.emplace_back(UB);
3530     ++Idx;
3531   }
3532   if (CS.capture_size() > 0) {
3533     ASTContext &CGFContext = CGF.getContext();
3534     for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
3535       QualType ElemTy = CurField->getType();
3536       Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
3537       Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
3538           Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
3539       llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
3540                                               /*Volatile=*/false,
3541                                               CGFContext.getPointerType(ElemTy),
3542                                               CI->getLocation());
3543       if (CI->capturesVariableByCopy() &&
3544           !CI->getCapturedVar()->getType()->isAnyPointerType()) {
3545         Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
3546                               CI->getLocation());
3547       }
3548       Args.emplace_back(Arg);
3549     }
3550   }
3551 
3552   emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
3553   CGF.FinishFunction();
3554   return Fn;
3555 }
3556 
3557 void CGOpenMPRuntimeGPU::emitFunctionProlog(CodeGenFunction &CGF,
3558                                               const Decl *D) {
3559   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
3560     return;
3561 
3562   assert(D && "Expected function or captured|block decl.");
3563   assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
3564          "Function is registered already.");
3565   assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
3566          "Team is set but not processed.");
3567   const Stmt *Body = nullptr;
3568   bool NeedToDelayGlobalization = false;
3569   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3570     Body = FD->getBody();
3571   } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3572     Body = BD->getBody();
3573   } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
3574     Body = CD->getBody();
3575     NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
3576     if (NeedToDelayGlobalization &&
3577         getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD)
3578       return;
3579   }
3580   if (!Body)
3581     return;
3582   CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
3583   VarChecker.Visit(Body);
3584   const RecordDecl *GlobalizedVarsRecord =
3585       VarChecker.getGlobalizedRecord(IsInTTDRegion);
3586   TeamAndReductions.first = nullptr;
3587   TeamAndReductions.second.clear();
3588   ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
3589       VarChecker.getEscapedVariableLengthDecls();
3590   if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
3591     return;
3592   auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
3593   I->getSecond().MappedParams =
3594       std::make_unique<CodeGenFunction::OMPMapVars>();
3595   I->getSecond().EscapedParameters.insert(
3596       VarChecker.getEscapedParameters().begin(),
3597       VarChecker.getEscapedParameters().end());
3598   I->getSecond().EscapedVariableLengthDecls.append(
3599       EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
3600   DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
3601   for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
3602     assert(VD->isCanonicalDecl() && "Expected canonical declaration");
3603     Data.insert(std::make_pair(VD, MappedVarData()));
3604   }
3605   if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
3606     CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
3607     VarChecker.Visit(Body);
3608     I->getSecond().SecondaryLocalVarData.emplace();
3609     DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
3610     for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
3611       assert(VD->isCanonicalDecl() && "Expected canonical declaration");
3612       Data.insert(std::make_pair(VD, MappedVarData()));
3613     }
3614   }
3615   if (!NeedToDelayGlobalization) {
3616     emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
3617     struct GlobalizationScope final : EHScopeStack::Cleanup {
3618       GlobalizationScope() = default;
3619 
3620       void Emit(CodeGenFunction &CGF, Flags flags) override {
3621         static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime())
3622             .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
3623       }
3624     };
3625     CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
3626   }
3627 }
3628 
3629 Address CGOpenMPRuntimeGPU::getAddressOfLocalVariable(CodeGenFunction &CGF,
3630                                                         const VarDecl *VD) {
3631   if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
3632     const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3633     auto AS = LangAS::Default;
3634     switch (A->getAllocatorType()) {
3635       // Use the default allocator here as by default local vars are
3636       // threadlocal.
3637     case OMPAllocateDeclAttr::OMPNullMemAlloc:
3638     case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
3639     case OMPAllocateDeclAttr::OMPThreadMemAlloc:
3640     case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
3641     case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
3642       // Follow the user decision - use default allocation.
3643       return Address::invalid();
3644     case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
3645       // TODO: implement aupport for user-defined allocators.
3646       return Address::invalid();
3647     case OMPAllocateDeclAttr::OMPConstMemAlloc:
3648       AS = LangAS::cuda_constant;
3649       break;
3650     case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
3651       AS = LangAS::cuda_shared;
3652       break;
3653     case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
3654     case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
3655       break;
3656     }
3657     llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
3658     auto *GV = new llvm::GlobalVariable(
3659         CGM.getModule(), VarTy, /*isConstant=*/false,
3660         llvm::GlobalValue::InternalLinkage, llvm::Constant::getNullValue(VarTy),
3661         VD->getName(),
3662         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
3663         CGM.getContext().getTargetAddressSpace(AS));
3664     CharUnits Align = CGM.getContext().getDeclAlign(VD);
3665     GV->setAlignment(Align.getAsAlign());
3666     return Address(
3667         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3668             GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
3669                     VD->getType().getAddressSpace()))),
3670         Align);
3671   }
3672 
3673   if (getDataSharingMode(CGM) != CGOpenMPRuntimeGPU::Generic)
3674     return Address::invalid();
3675 
3676   VD = VD->getCanonicalDecl();
3677   auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
3678   if (I == FunctionGlobalizedDecls.end())
3679     return Address::invalid();
3680   auto VDI = I->getSecond().LocalVarData.find(VD);
3681   if (VDI != I->getSecond().LocalVarData.end())
3682     return VDI->second.PrivateAddr;
3683   if (VD->hasAttrs()) {
3684     for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
3685          E(VD->attr_end());
3686          IT != E; ++IT) {
3687       auto VDI = I->getSecond().LocalVarData.find(
3688           cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
3689               ->getCanonicalDecl());
3690       if (VDI != I->getSecond().LocalVarData.end())
3691         return VDI->second.PrivateAddr;
3692     }
3693   }
3694 
3695   return Address::invalid();
3696 }
3697 
3698 void CGOpenMPRuntimeGPU::functionFinished(CodeGenFunction &CGF) {
3699   FunctionGlobalizedDecls.erase(CGF.CurFn);
3700   CGOpenMPRuntime::functionFinished(CGF);
3701 }
3702 
3703 void CGOpenMPRuntimeGPU::getDefaultDistScheduleAndChunk(
3704     CodeGenFunction &CGF, const OMPLoopDirective &S,
3705     OpenMPDistScheduleClauseKind &ScheduleKind,
3706     llvm::Value *&Chunk) const {
3707   auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
3708   if (getExecutionMode() == CGOpenMPRuntimeGPU::EM_SPMD) {
3709     ScheduleKind = OMPC_DIST_SCHEDULE_static;
3710     Chunk = CGF.EmitScalarConversion(
3711         RT.getGPUNumThreads(CGF),
3712         CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3713         S.getIterationVariable()->getType(), S.getBeginLoc());
3714     return;
3715   }
3716   CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
3717       CGF, S, ScheduleKind, Chunk);
3718 }
3719 
3720 void CGOpenMPRuntimeGPU::getDefaultScheduleAndChunk(
3721     CodeGenFunction &CGF, const OMPLoopDirective &S,
3722     OpenMPScheduleClauseKind &ScheduleKind,
3723     const Expr *&ChunkExpr) const {
3724   ScheduleKind = OMPC_SCHEDULE_static;
3725   // Chunk size is 1 in this case.
3726   llvm::APInt ChunkSize(32, 1);
3727   ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
3728       CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
3729       SourceLocation());
3730 }
3731 
3732 void CGOpenMPRuntimeGPU::adjustTargetSpecificDataForLambdas(
3733     CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
3734   assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
3735          " Expected target-based directive.");
3736   const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
3737   for (const CapturedStmt::Capture &C : CS->captures()) {
3738     // Capture variables captured by reference in lambdas for target-based
3739     // directives.
3740     if (!C.capturesVariable())
3741       continue;
3742     const VarDecl *VD = C.getCapturedVar();
3743     const auto *RD = VD->getType()
3744                          .getCanonicalType()
3745                          .getNonReferenceType()
3746                          ->getAsCXXRecordDecl();
3747     if (!RD || !RD->isLambda())
3748       continue;
3749     Address VDAddr = CGF.GetAddrOfLocalVar(VD);
3750     LValue VDLVal;
3751     if (VD->getType().getCanonicalType()->isReferenceType())
3752       VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
3753     else
3754       VDLVal = CGF.MakeAddrLValue(
3755           VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
3756     llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3757     FieldDecl *ThisCapture = nullptr;
3758     RD->getCaptureFields(Captures, ThisCapture);
3759     if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
3760       LValue ThisLVal =
3761           CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
3762       llvm::Value *CXXThis = CGF.LoadCXXThis();
3763       CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
3764     }
3765     for (const LambdaCapture &LC : RD->captures()) {
3766       if (LC.getCaptureKind() != LCK_ByRef)
3767         continue;
3768       const VarDecl *VD = LC.getCapturedVar();
3769       if (!CS->capturesVariable(VD))
3770         continue;
3771       auto It = Captures.find(VD);
3772       assert(It != Captures.end() && "Found lambda capture without field.");
3773       LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
3774       Address VDAddr = CGF.GetAddrOfLocalVar(VD);
3775       if (VD->getType().getCanonicalType()->isReferenceType())
3776         VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
3777                                                VD->getType().getCanonicalType())
3778                      .getAddress(CGF);
3779       CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
3780     }
3781   }
3782 }
3783 
3784 bool CGOpenMPRuntimeGPU::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
3785                                                             LangAS &AS) {
3786   if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
3787     return false;
3788   const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3789   switch(A->getAllocatorType()) {
3790   case OMPAllocateDeclAttr::OMPNullMemAlloc:
3791   case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
3792   // Not supported, fallback to the default mem space.
3793   case OMPAllocateDeclAttr::OMPThreadMemAlloc:
3794   case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
3795   case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
3796   case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
3797   case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
3798     AS = LangAS::Default;
3799     return true;
3800   case OMPAllocateDeclAttr::OMPConstMemAlloc:
3801     AS = LangAS::cuda_constant;
3802     return true;
3803   case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
3804     AS = LangAS::cuda_shared;
3805     return true;
3806   case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
3807     llvm_unreachable("Expected predefined allocator for the variables with the "
3808                      "static storage.");
3809   }
3810   return false;
3811 }
3812 
3813 // Get current CudaArch and ignore any unknown values
3814 static CudaArch getCudaArch(CodeGenModule &CGM) {
3815   if (!CGM.getTarget().hasFeature("ptx"))
3816     return CudaArch::UNKNOWN;
3817   for (const auto &Feature : CGM.getTarget().getTargetOpts().FeatureMap) {
3818     if (Feature.getValue()) {
3819       CudaArch Arch = StringToCudaArch(Feature.getKey());
3820       if (Arch != CudaArch::UNKNOWN)
3821         return Arch;
3822     }
3823   }
3824   return CudaArch::UNKNOWN;
3825 }
3826 
3827 /// Check to see if target architecture supports unified addressing which is
3828 /// a restriction for OpenMP requires clause "unified_shared_memory".
3829 void CGOpenMPRuntimeGPU::processRequiresDirective(
3830     const OMPRequiresDecl *D) {
3831   for (const OMPClause *Clause : D->clauselists()) {
3832     if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
3833       CudaArch Arch = getCudaArch(CGM);
3834       switch (Arch) {
3835       case CudaArch::SM_20:
3836       case CudaArch::SM_21:
3837       case CudaArch::SM_30:
3838       case CudaArch::SM_32:
3839       case CudaArch::SM_35:
3840       case CudaArch::SM_37:
3841       case CudaArch::SM_50:
3842       case CudaArch::SM_52:
3843       case CudaArch::SM_53: {
3844         SmallString<256> Buffer;
3845         llvm::raw_svector_ostream Out(Buffer);
3846         Out << "Target architecture " << CudaArchToString(Arch)
3847             << " does not support unified addressing";
3848         CGM.Error(Clause->getBeginLoc(), Out.str());
3849         return;
3850       }
3851       case CudaArch::SM_60:
3852       case CudaArch::SM_61:
3853       case CudaArch::SM_62:
3854       case CudaArch::SM_70:
3855       case CudaArch::SM_72:
3856       case CudaArch::SM_75:
3857       case CudaArch::SM_80:
3858       case CudaArch::SM_86:
3859       case CudaArch::GFX600:
3860       case CudaArch::GFX601:
3861       case CudaArch::GFX602:
3862       case CudaArch::GFX700:
3863       case CudaArch::GFX701:
3864       case CudaArch::GFX702:
3865       case CudaArch::GFX703:
3866       case CudaArch::GFX704:
3867       case CudaArch::GFX705:
3868       case CudaArch::GFX801:
3869       case CudaArch::GFX802:
3870       case CudaArch::GFX803:
3871       case CudaArch::GFX805:
3872       case CudaArch::GFX810:
3873       case CudaArch::GFX900:
3874       case CudaArch::GFX902:
3875       case CudaArch::GFX904:
3876       case CudaArch::GFX906:
3877       case CudaArch::GFX908:
3878       case CudaArch::GFX909:
3879       case CudaArch::GFX90a:
3880       case CudaArch::GFX90c:
3881       case CudaArch::GFX1010:
3882       case CudaArch::GFX1011:
3883       case CudaArch::GFX1012:
3884       case CudaArch::GFX1013:
3885       case CudaArch::GFX1030:
3886       case CudaArch::GFX1031:
3887       case CudaArch::GFX1032:
3888       case CudaArch::GFX1033:
3889       case CudaArch::GFX1034:
3890       case CudaArch::GFX1035:
3891       case CudaArch::UNUSED:
3892       case CudaArch::UNKNOWN:
3893         break;
3894       case CudaArch::LAST:
3895         llvm_unreachable("Unexpected Cuda arch.");
3896       }
3897     }
3898   }
3899   CGOpenMPRuntime::processRequiresDirective(D);
3900 }
3901 
3902 void CGOpenMPRuntimeGPU::clear() {
3903 
3904   if (!TeamsReductions.empty()) {
3905     ASTContext &C = CGM.getContext();
3906     RecordDecl *StaticRD = C.buildImplicitRecord(
3907         "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
3908     StaticRD->startDefinition();
3909     for (const RecordDecl *TeamReductionRec : TeamsReductions) {
3910       QualType RecTy = C.getRecordType(TeamReductionRec);
3911       auto *Field = FieldDecl::Create(
3912           C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
3913           C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
3914           /*BW=*/nullptr, /*Mutable=*/false,
3915           /*InitStyle=*/ICIS_NoInit);
3916       Field->setAccess(AS_public);
3917       StaticRD->addDecl(Field);
3918     }
3919     StaticRD->completeDefinition();
3920     QualType StaticTy = C.getRecordType(StaticRD);
3921     llvm::Type *LLVMReductionsBufferTy =
3922         CGM.getTypes().ConvertTypeForMem(StaticTy);
3923     // FIXME: nvlink does not handle weak linkage correctly (object with the
3924     // different size are reported as erroneous).
3925     // Restore CommonLinkage as soon as nvlink is fixed.
3926     auto *GV = new llvm::GlobalVariable(
3927         CGM.getModule(), LLVMReductionsBufferTy,
3928         /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
3929         llvm::Constant::getNullValue(LLVMReductionsBufferTy),
3930         "_openmp_teams_reductions_buffer_$_");
3931     KernelTeamsReductionPtr->setInitializer(
3932         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
3933                                                              CGM.VoidPtrTy));
3934   }
3935   CGOpenMPRuntime::clear();
3936 }
3937