1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides a class for OpenMP runtime code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCXXABI.h"
15 #include "CGCleanup.h"
16 #include "CGOpenMPRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "clang/CodeGen/ConstantInitBuilder.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/StmtOpenMP.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/BitmaskEnum.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/Value.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <cassert>
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 namespace {
37 /// \brief Base class for handling code generation inside OpenMP regions.
38 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39 public:
40   /// \brief Kinds of OpenMP regions used in codegen.
41   enum CGOpenMPRegionKind {
42     /// \brief Region with outlined function for standalone 'parallel'
43     /// directive.
44     ParallelOutlinedRegion,
45     /// \brief Region with outlined function for standalone 'task' directive.
46     TaskOutlinedRegion,
47     /// \brief Region for constructs that do not require function outlining,
48     /// like 'for', 'sections', 'atomic' etc. directives.
49     InlinedRegion,
50     /// \brief Region with outlined function for standalone 'target' directive.
51     TargetRegion,
52   };
53 
54   CGOpenMPRegionInfo(const CapturedStmt &CS,
55                      const CGOpenMPRegionKind RegionKind,
56                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57                      bool HasCancel)
58       : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
59         CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
60 
61   CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
62                      const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63                      bool HasCancel)
64       : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
65         Kind(Kind), HasCancel(HasCancel) {}
66 
67   /// \brief Get a variable or parameter for storing global thread id
68   /// inside OpenMP construct.
69   virtual const VarDecl *getThreadIDVariable() const = 0;
70 
71   /// \brief Emit the captured statement body.
72   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
73 
74   /// \brief Get an LValue for the current ThreadID variable.
75   /// \return LValue for thread id variable. This LValue always has type int32*.
76   virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
77 
78   virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79 
80   CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
81 
82   OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83 
84   bool hasCancel() const { return HasCancel; }
85 
86   static bool classof(const CGCapturedStmtInfo *Info) {
87     return Info->getKind() == CR_OpenMP;
88   }
89 
90   ~CGOpenMPRegionInfo() override = default;
91 
92 protected:
93   CGOpenMPRegionKind RegionKind;
94   RegionCodeGenTy CodeGen;
95   OpenMPDirectiveKind Kind;
96   bool HasCancel;
97 };
98 
99 /// \brief API for captured statement code generation in OpenMP constructs.
100 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
101 public:
102   CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
103                              const RegionCodeGenTy &CodeGen,
104                              OpenMPDirectiveKind Kind, bool HasCancel,
105                              StringRef HelperName)
106       : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107                            HasCancel),
108         ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
109     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110   }
111 
112   /// \brief Get a variable or parameter for storing global thread id
113   /// inside OpenMP construct.
114   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
115 
116   /// \brief Get the name of the capture helper.
117   StringRef getHelperName() const override { return HelperName; }
118 
119   static bool classof(const CGCapturedStmtInfo *Info) {
120     return CGOpenMPRegionInfo::classof(Info) &&
121            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122                ParallelOutlinedRegion;
123   }
124 
125 private:
126   /// \brief A variable or parameter storing global thread id for OpenMP
127   /// constructs.
128   const VarDecl *ThreadIDVar;
129   StringRef HelperName;
130 };
131 
132 /// \brief API for captured statement code generation in OpenMP constructs.
133 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
134 public:
135   class UntiedTaskActionTy final : public PrePostActionTy {
136     bool Untied;
137     const VarDecl *PartIDVar;
138     const RegionCodeGenTy UntiedCodeGen;
139     llvm::SwitchInst *UntiedSwitch = nullptr;
140 
141   public:
142     UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143                        const RegionCodeGenTy &UntiedCodeGen)
144         : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145     void Enter(CodeGenFunction &CGF) override {
146       if (Untied) {
147         // Emit task switching point.
148         LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
149             CGF.GetAddrOfLocalVar(PartIDVar),
150             PartIDVar->getType()->castAs<PointerType>());
151         llvm::Value *Res =
152             CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153         llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
154         UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155         CGF.EmitBlock(DoneBB);
156         CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157         CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158         UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159                               CGF.Builder.GetInsertBlock());
160         emitUntiedSwitch(CGF);
161       }
162     }
163     void emitUntiedSwitch(CodeGenFunction &CGF) const {
164       if (Untied) {
165         LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
166             CGF.GetAddrOfLocalVar(PartIDVar),
167             PartIDVar->getType()->castAs<PointerType>());
168         CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169                               PartIdLVal);
170         UntiedCodeGen(CGF);
171         CodeGenFunction::JumpDest CurPoint =
172             CGF.getJumpDestInCurrentScope(".untied.next.");
173         CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174         CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175         UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176                               CGF.Builder.GetInsertBlock());
177         CGF.EmitBranchThroughCleanup(CurPoint);
178         CGF.EmitBlock(CurPoint.getBlock());
179       }
180     }
181     unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182   };
183   CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
184                                  const VarDecl *ThreadIDVar,
185                                  const RegionCodeGenTy &CodeGen,
186                                  OpenMPDirectiveKind Kind, bool HasCancel,
187                                  const UntiedTaskActionTy &Action)
188       : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
189         ThreadIDVar(ThreadIDVar), Action(Action) {
190     assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191   }
192 
193   /// \brief Get a variable or parameter for storing global thread id
194   /// inside OpenMP construct.
195   const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
196 
197   /// \brief Get an LValue for the current ThreadID variable.
198   LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
199 
200   /// \brief Get the name of the capture helper.
201   StringRef getHelperName() const override { return ".omp_outlined."; }
202 
203   void emitUntiedSwitch(CodeGenFunction &CGF) override {
204     Action.emitUntiedSwitch(CGF);
205   }
206 
207   static bool classof(const CGCapturedStmtInfo *Info) {
208     return CGOpenMPRegionInfo::classof(Info) &&
209            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210                TaskOutlinedRegion;
211   }
212 
213 private:
214   /// \brief A variable or parameter storing global thread id for OpenMP
215   /// constructs.
216   const VarDecl *ThreadIDVar;
217   /// Action for emitting code for untied tasks.
218   const UntiedTaskActionTy &Action;
219 };
220 
221 /// \brief API for inlined captured statement code generation in OpenMP
222 /// constructs.
223 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224 public:
225   CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
226                             const RegionCodeGenTy &CodeGen,
227                             OpenMPDirectiveKind Kind, bool HasCancel)
228       : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229         OldCSI(OldCSI),
230         OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
231 
232   // \brief Retrieve the value of the context parameter.
233   llvm::Value *getContextValue() const override {
234     if (OuterRegionInfo)
235       return OuterRegionInfo->getContextValue();
236     llvm_unreachable("No context value for inlined OpenMP region");
237   }
238 
239   void setContextValue(llvm::Value *V) override {
240     if (OuterRegionInfo) {
241       OuterRegionInfo->setContextValue(V);
242       return;
243     }
244     llvm_unreachable("No context value for inlined OpenMP region");
245   }
246 
247   /// \brief Lookup the captured field decl for a variable.
248   const FieldDecl *lookup(const VarDecl *VD) const override {
249     if (OuterRegionInfo)
250       return OuterRegionInfo->lookup(VD);
251     // If there is no outer outlined region,no need to lookup in a list of
252     // captured variables, we can use the original one.
253     return nullptr;
254   }
255 
256   FieldDecl *getThisFieldDecl() const override {
257     if (OuterRegionInfo)
258       return OuterRegionInfo->getThisFieldDecl();
259     return nullptr;
260   }
261 
262   /// \brief Get a variable or parameter for storing global thread id
263   /// inside OpenMP construct.
264   const VarDecl *getThreadIDVariable() const override {
265     if (OuterRegionInfo)
266       return OuterRegionInfo->getThreadIDVariable();
267     return nullptr;
268   }
269 
270   /// \brief Get an LValue for the current ThreadID variable.
271   LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272     if (OuterRegionInfo)
273       return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274     llvm_unreachable("No LValue for inlined OpenMP construct");
275   }
276 
277   /// \brief Get the name of the capture helper.
278   StringRef getHelperName() const override {
279     if (auto *OuterRegionInfo = getOldCSI())
280       return OuterRegionInfo->getHelperName();
281     llvm_unreachable("No helper name for inlined OpenMP construct");
282   }
283 
284   void emitUntiedSwitch(CodeGenFunction &CGF) override {
285     if (OuterRegionInfo)
286       OuterRegionInfo->emitUntiedSwitch(CGF);
287   }
288 
289   CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290 
291   static bool classof(const CGCapturedStmtInfo *Info) {
292     return CGOpenMPRegionInfo::classof(Info) &&
293            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294   }
295 
296   ~CGOpenMPInlinedRegionInfo() override = default;
297 
298 private:
299   /// \brief CodeGen info about outer OpenMP region.
300   CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301   CGOpenMPRegionInfo *OuterRegionInfo;
302 };
303 
304 /// \brief API for captured statement code generation in OpenMP target
305 /// constructs. For this captures, implicit parameters are used instead of the
306 /// captured fields. The name of the target region has to be unique in a given
307 /// application so it is provided by the client, because only the client has
308 /// the information to generate that.
309 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
310 public:
311   CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
312                            const RegionCodeGenTy &CodeGen, StringRef HelperName)
313       : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
314                            /*HasCancel=*/false),
315         HelperName(HelperName) {}
316 
317   /// \brief This is unused for target regions because each starts executing
318   /// with a single thread.
319   const VarDecl *getThreadIDVariable() const override { return nullptr; }
320 
321   /// \brief Get the name of the capture helper.
322   StringRef getHelperName() const override { return HelperName; }
323 
324   static bool classof(const CGCapturedStmtInfo *Info) {
325     return CGOpenMPRegionInfo::classof(Info) &&
326            cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327   }
328 
329 private:
330   StringRef HelperName;
331 };
332 
333 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
334   llvm_unreachable("No codegen for expressions");
335 }
336 /// \brief API for generation of expressions captured in a innermost OpenMP
337 /// region.
338 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
339 public:
340   CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341       : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342                                   OMPD_unknown,
343                                   /*HasCancel=*/false),
344         PrivScope(CGF) {
345     // Make sure the globals captured in the provided statement are local by
346     // using the privatization logic. We assume the same variable is not
347     // captured more than once.
348     for (const auto &C : CS.captures()) {
349       if (!C.capturesVariable() && !C.capturesVariableByCopy())
350         continue;
351 
352       const VarDecl *VD = C.getCapturedVar();
353       if (VD->isLocalVarDeclOrParm())
354         continue;
355 
356       DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357                       /*RefersToEnclosingVariableOrCapture=*/false,
358                       VD->getType().getNonReferenceType(), VK_LValue,
359                       C.getLocation());
360       PrivScope.addPrivate(
361           VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
362     }
363     (void)PrivScope.Privatize();
364   }
365 
366   /// \brief Lookup the captured field decl for a variable.
367   const FieldDecl *lookup(const VarDecl *VD) const override {
368     if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
369       return FD;
370     return nullptr;
371   }
372 
373   /// \brief Emit the captured statement body.
374   void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375     llvm_unreachable("No body for expressions");
376   }
377 
378   /// \brief Get a variable or parameter for storing global thread id
379   /// inside OpenMP construct.
380   const VarDecl *getThreadIDVariable() const override {
381     llvm_unreachable("No thread id for expressions");
382   }
383 
384   /// \brief Get the name of the capture helper.
385   StringRef getHelperName() const override {
386     llvm_unreachable("No helper name for expressions");
387   }
388 
389   static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390 
391 private:
392   /// Private scope to capture global variables.
393   CodeGenFunction::OMPPrivateScope PrivScope;
394 };
395 
396 /// \brief RAII for emitting code of OpenMP constructs.
397 class InlinedOpenMPRegionRAII {
398   CodeGenFunction &CGF;
399   llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400   FieldDecl *LambdaThisCaptureField = nullptr;
401   const CodeGen::CGBlockInfo *BlockInfo = nullptr;
402 
403 public:
404   /// \brief Constructs region for combined constructs.
405   /// \param CodeGen Code generation sequence for combined directives. Includes
406   /// a list of functions used for code generation of implicitly inlined
407   /// regions.
408   InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
409                           OpenMPDirectiveKind Kind, bool HasCancel)
410       : CGF(CGF) {
411     // Start emission for the construct.
412     CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413         CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
414     std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415     LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416     CGF.LambdaThisCaptureField = nullptr;
417     BlockInfo = CGF.BlockInfo;
418     CGF.BlockInfo = nullptr;
419   }
420 
421   ~InlinedOpenMPRegionRAII() {
422     // Restore original CapturedStmtInfo only if we're done with code emission.
423     auto *OldCSI =
424         cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425     delete CGF.CapturedStmtInfo;
426     CGF.CapturedStmtInfo = OldCSI;
427     std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428     CGF.LambdaThisCaptureField = LambdaThisCaptureField;
429     CGF.BlockInfo = BlockInfo;
430   }
431 };
432 
433 /// \brief Values for bit flags used in the ident_t to describe the fields.
434 /// All enumeric elements are named and described in accordance with the code
435 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
436 enum OpenMPLocationFlags : unsigned {
437   /// \brief Use trampoline for internal microtask.
438   OMP_IDENT_IMD = 0x01,
439   /// \brief Use c-style ident structure.
440   OMP_IDENT_KMPC = 0x02,
441   /// \brief Atomic reduction option for kmpc_reduce.
442   OMP_ATOMIC_REDUCE = 0x10,
443   /// \brief Explicit 'barrier' directive.
444   OMP_IDENT_BARRIER_EXPL = 0x20,
445   /// \brief Implicit barrier in code.
446   OMP_IDENT_BARRIER_IMPL = 0x40,
447   /// \brief Implicit barrier in 'for' directive.
448   OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
449   /// \brief Implicit barrier in 'sections' directive.
450   OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
451   /// \brief Implicit barrier in 'single' directive.
452   OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453   /// Call of __kmp_for_static_init for static loop.
454   OMP_IDENT_WORK_LOOP = 0x200,
455   /// Call of __kmp_for_static_init for sections.
456   OMP_IDENT_WORK_SECTIONS = 0x400,
457   /// Call of __kmp_for_static_init for distribute.
458   OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459   LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
460 };
461 
462 /// \brief Describes ident structure that describes a source location.
463 /// All descriptions are taken from
464 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465 /// Original structure:
466 /// typedef struct ident {
467 ///    kmp_int32 reserved_1;   /**<  might be used in Fortran;
468 ///                                  see above  */
469 ///    kmp_int32 flags;        /**<  also f.flags; KMP_IDENT_xxx flags;
470 ///                                  KMP_IDENT_KMPC identifies this union
471 ///                                  member  */
472 ///    kmp_int32 reserved_2;   /**<  not really used in Fortran any more;
473 ///                                  see above */
474 ///#if USE_ITT_BUILD
475 ///                            /*  but currently used for storing
476 ///                                region-specific ITT */
477 ///                            /*  contextual information. */
478 ///#endif /* USE_ITT_BUILD */
479 ///    kmp_int32 reserved_3;   /**< source[4] in Fortran, do not use for
480 ///                                 C++  */
481 ///    char const *psource;    /**< String describing the source location.
482 ///                            The string is composed of semi-colon separated
483 //                             fields which describe the source file,
484 ///                            the function and a pair of line numbers that
485 ///                            delimit the construct.
486 ///                             */
487 /// } ident_t;
488 enum IdentFieldIndex {
489   /// \brief might be used in Fortran
490   IdentField_Reserved_1,
491   /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
492   IdentField_Flags,
493   /// \brief Not really used in Fortran any more
494   IdentField_Reserved_2,
495   /// \brief Source[4] in Fortran, do not use for C++
496   IdentField_Reserved_3,
497   /// \brief String describing the source location. The string is composed of
498   /// semi-colon separated fields which describe the source file, the function
499   /// and a pair of line numbers that delimit the construct.
500   IdentField_PSource
501 };
502 
503 /// \brief Schedule types for 'omp for' loops (these enumerators are taken from
504 /// the enum sched_type in kmp.h).
505 enum OpenMPSchedType {
506   /// \brief Lower bound for default (unordered) versions.
507   OMP_sch_lower = 32,
508   OMP_sch_static_chunked = 33,
509   OMP_sch_static = 34,
510   OMP_sch_dynamic_chunked = 35,
511   OMP_sch_guided_chunked = 36,
512   OMP_sch_runtime = 37,
513   OMP_sch_auto = 38,
514   /// static with chunk adjustment (e.g., simd)
515   OMP_sch_static_balanced_chunked = 45,
516   /// \brief Lower bound for 'ordered' versions.
517   OMP_ord_lower = 64,
518   OMP_ord_static_chunked = 65,
519   OMP_ord_static = 66,
520   OMP_ord_dynamic_chunked = 67,
521   OMP_ord_guided_chunked = 68,
522   OMP_ord_runtime = 69,
523   OMP_ord_auto = 70,
524   OMP_sch_default = OMP_sch_static,
525   /// \brief dist_schedule types
526   OMP_dist_sch_static_chunked = 91,
527   OMP_dist_sch_static = 92,
528   /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529   /// Set if the monotonic schedule modifier was present.
530   OMP_sch_modifier_monotonic = (1 << 29),
531   /// Set if the nonmonotonic schedule modifier was present.
532   OMP_sch_modifier_nonmonotonic = (1 << 30),
533 };
534 
535 enum OpenMPRTLFunction {
536   /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
537   /// kmpc_micro microtask, ...);
538   OMPRTL__kmpc_fork_call,
539   /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
540   /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541   OMPRTL__kmpc_threadprivate_cached,
542   /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
543   /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544   OMPRTL__kmpc_threadprivate_register,
545   // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546   OMPRTL__kmpc_global_thread_num,
547   // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548   // kmp_critical_name *crit);
549   OMPRTL__kmpc_critical,
550   // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551   // global_tid, kmp_critical_name *crit, uintptr_t hint);
552   OMPRTL__kmpc_critical_with_hint,
553   // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554   // kmp_critical_name *crit);
555   OMPRTL__kmpc_end_critical,
556   // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557   // global_tid);
558   OMPRTL__kmpc_cancel_barrier,
559   // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560   OMPRTL__kmpc_barrier,
561   // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562   OMPRTL__kmpc_for_static_fini,
563   // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564   // global_tid);
565   OMPRTL__kmpc_serialized_parallel,
566   // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567   // global_tid);
568   OMPRTL__kmpc_end_serialized_parallel,
569   // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570   // kmp_int32 num_threads);
571   OMPRTL__kmpc_push_num_threads,
572   // Call to void __kmpc_flush(ident_t *loc);
573   OMPRTL__kmpc_flush,
574   // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575   OMPRTL__kmpc_master,
576   // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577   OMPRTL__kmpc_end_master,
578   // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579   // int end_part);
580   OMPRTL__kmpc_omp_taskyield,
581   // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582   OMPRTL__kmpc_single,
583   // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584   OMPRTL__kmpc_end_single,
585   // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587   // kmp_routine_entry_t *task_entry);
588   OMPRTL__kmpc_omp_task_alloc,
589   // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590   // new_task);
591   OMPRTL__kmpc_omp_task,
592   // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593   // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594   // kmp_int32 didit);
595   OMPRTL__kmpc_copyprivate,
596   // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597   // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598   // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599   OMPRTL__kmpc_reduce,
600   // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601   // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602   // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603   // *lck);
604   OMPRTL__kmpc_reduce_nowait,
605   // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606   // kmp_critical_name *lck);
607   OMPRTL__kmpc_end_reduce,
608   // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609   // kmp_critical_name *lck);
610   OMPRTL__kmpc_end_reduce_nowait,
611   // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612   // kmp_task_t * new_task);
613   OMPRTL__kmpc_omp_task_begin_if0,
614   // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615   // kmp_task_t * new_task);
616   OMPRTL__kmpc_omp_task_complete_if0,
617   // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618   OMPRTL__kmpc_ordered,
619   // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620   OMPRTL__kmpc_end_ordered,
621   // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622   // global_tid);
623   OMPRTL__kmpc_omp_taskwait,
624   // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625   OMPRTL__kmpc_taskgroup,
626   // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627   OMPRTL__kmpc_end_taskgroup,
628   // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629   // int proc_bind);
630   OMPRTL__kmpc_push_proc_bind,
631   // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632   // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633   // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634   OMPRTL__kmpc_omp_task_with_deps,
635   // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636   // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637   // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638   OMPRTL__kmpc_omp_wait_deps,
639   // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640   // global_tid, kmp_int32 cncl_kind);
641   OMPRTL__kmpc_cancellationpoint,
642   // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643   // kmp_int32 cncl_kind);
644   OMPRTL__kmpc_cancel,
645   // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646   // kmp_int32 num_teams, kmp_int32 thread_limit);
647   OMPRTL__kmpc_push_num_teams,
648   // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649   // microtask, ...);
650   OMPRTL__kmpc_fork_teams,
651   // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652   // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653   // sched, kmp_uint64 grainsize, void *task_dup);
654   OMPRTL__kmpc_taskloop,
655   // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656   // num_dims, struct kmp_dim *dims);
657   OMPRTL__kmpc_doacross_init,
658   // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659   OMPRTL__kmpc_doacross_fini,
660   // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661   // *vec);
662   OMPRTL__kmpc_doacross_post,
663   // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664   // *vec);
665   OMPRTL__kmpc_doacross_wait,
666   // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667   // *data);
668   OMPRTL__kmpc_task_reduction_init,
669   // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670   // *d);
671   OMPRTL__kmpc_task_reduction_get_th_data,
672 
673   //
674   // Offloading related calls
675   //
676   // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677   // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
678   // *arg_types);
679   OMPRTL__tgt_target,
680   // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681   // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682   // *arg_types);
683   OMPRTL__tgt_target_nowait,
684   // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685   // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686   // *arg_types, int32_t num_teams, int32_t thread_limit);
687   OMPRTL__tgt_target_teams,
688   // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689   // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690   // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691   OMPRTL__tgt_target_teams_nowait,
692   // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693   OMPRTL__tgt_register_lib,
694   // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695   OMPRTL__tgt_unregister_lib,
696   // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697   // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
698   OMPRTL__tgt_target_data_begin,
699   // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700   // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701   // *arg_types);
702   OMPRTL__tgt_target_data_begin_nowait,
703   // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704   // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
705   OMPRTL__tgt_target_data_end,
706   // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707   // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708   // *arg_types);
709   OMPRTL__tgt_target_data_end_nowait,
710   // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711   // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
712   OMPRTL__tgt_target_data_update,
713   // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714   // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715   // *arg_types);
716   OMPRTL__tgt_target_data_update_nowait,
717 };
718 
719 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720 /// region.
721 class CleanupTy final : public EHScopeStack::Cleanup {
722   PrePostActionTy *Action;
723 
724 public:
725   explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726   void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727     if (!CGF.HaveInsertPoint())
728       return;
729     Action->Exit(CGF);
730   }
731 };
732 
733 } // anonymous namespace
734 
735 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736   CodeGenFunction::RunCleanupsScope Scope(CGF);
737   if (PrePostAction) {
738     CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739     Callback(CodeGen, CGF, *PrePostAction);
740   } else {
741     PrePostActionTy Action;
742     Callback(CodeGen, CGF, Action);
743   }
744 }
745 
746 /// Check if the combiner is a call to UDR combiner and if it is so return the
747 /// UDR decl used for reduction.
748 static const OMPDeclareReductionDecl *
749 getReductionInit(const Expr *ReductionOp) {
750   if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752       if (const auto *DRE =
753               dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
754         if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
755           return DRD;
756   return nullptr;
757 }
758 
759 static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760                                              const OMPDeclareReductionDecl *DRD,
761                                              const Expr *InitOp,
762                                              Address Private, Address Original,
763                                              QualType Ty) {
764   if (DRD->getInitializer()) {
765     std::pair<llvm::Function *, llvm::Function *> Reduction =
766         CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
767     const auto *CE = cast<CallExpr>(InitOp);
768     const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
769     const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770     const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
771     const auto *LHSDRE =
772         cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773     const auto *RHSDRE =
774         cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
775     CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776     PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
777                             [=]() { return Private; });
778     PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
779                             [=]() { return Original; });
780     (void)PrivateScope.Privatize();
781     RValue Func = RValue::get(Reduction.second);
782     CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783     CGF.EmitIgnoredExpr(InitOp);
784   } else {
785     llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
786     std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
787     auto *GV = new llvm::GlobalVariable(
788         CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
789         llvm::GlobalValue::PrivateLinkage, Init, Name);
790     LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791     RValue InitRVal;
792     switch (CGF.getEvaluationKind(Ty)) {
793     case TEK_Scalar:
794       InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
795       break;
796     case TEK_Complex:
797       InitRVal =
798           RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
799       break;
800     case TEK_Aggregate:
801       InitRVal = RValue::getAggregate(LV.getAddress());
802       break;
803     }
804     OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
805     CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806     CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807                          /*IsInitializer=*/false);
808   }
809 }
810 
811 /// \brief Emit initialization of arrays of complex types.
812 /// \param DestAddr Address of the array.
813 /// \param Type Type of array.
814 /// \param Init Initial expression of array.
815 /// \param SrcAddr Address of the original array.
816 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
817                                  QualType Type, bool EmitDeclareReductionInit,
818                                  const Expr *Init,
819                                  const OMPDeclareReductionDecl *DRD,
820                                  Address SrcAddr = Address::invalid()) {
821   // Perform element-by-element initialization.
822   QualType ElementTy;
823 
824   // Drill down to the base element type on both arrays.
825   const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826   llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
827   DestAddr =
828       CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829   if (DRD)
830     SrcAddr =
831         CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832 
833   llvm::Value *SrcBegin = nullptr;
834   if (DRD)
835     SrcBegin = SrcAddr.getPointer();
836   llvm::Value *DestBegin = DestAddr.getPointer();
837   // Cast from pointer to array type to pointer to single element.
838   llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
839   // The basic structure here is a while-do loop.
840   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841   llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842   llvm::Value *IsEmpty =
843       CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845 
846   // Enter the loop body, making that address the current address.
847   llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
848   CGF.EmitBlock(BodyBB);
849 
850   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851 
852   llvm::PHINode *SrcElementPHI = nullptr;
853   Address SrcElementCurrent = Address::invalid();
854   if (DRD) {
855     SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856                                           "omp.arraycpy.srcElementPast");
857     SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858     SrcElementCurrent =
859         Address(SrcElementPHI,
860                 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861   }
862   llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863       DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864   DestElementPHI->addIncoming(DestBegin, EntryBB);
865   Address DestElementCurrent =
866       Address(DestElementPHI,
867               DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868 
869   // Emit copy.
870   {
871     CodeGenFunction::RunCleanupsScope InitScope(CGF);
872     if (EmitDeclareReductionInit) {
873       emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874                                        SrcElementCurrent, ElementTy);
875     } else
876       CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877                            /*IsInitializer=*/false);
878   }
879 
880   if (DRD) {
881     // Shift the address forward by one element.
882     llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
883         SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884     SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885   }
886 
887   // Shift the address forward by one element.
888   llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
889       DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890   // Check whether we've reached the end.
891   llvm::Value *Done =
892       CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894   DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895 
896   // Done.
897   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898 }
899 
900 static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
901 isDeclareTargetDeclaration(const ValueDecl *VD) {
902   for (const Decl *D : VD->redecls()) {
903     if (!D->hasAttrs())
904       continue;
905     if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
906       return Attr->getMapType();
907   }
908   if (const auto *V = dyn_cast<VarDecl>(VD)) {
909     if (const VarDecl *TD = V->getTemplateInstantiationPattern())
910       return isDeclareTargetDeclaration(TD);
911   } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
912     if (const auto *TD = FD->getTemplateInstantiationPattern())
913       return isDeclareTargetDeclaration(TD);
914   }
915 
916   return llvm::None;
917 }
918 
919 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
920   return CGF.EmitOMPSharedLValue(E);
921 }
922 
923 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
924                                             const Expr *E) {
925   if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
926     return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
927   return LValue();
928 }
929 
930 void ReductionCodeGen::emitAggregateInitialization(
931     CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
932     const OMPDeclareReductionDecl *DRD) {
933   // Emit VarDecl with copy init for arrays.
934   // Get the address of the original variable captured in current
935   // captured region.
936   const auto *PrivateVD =
937       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
938   bool EmitDeclareReductionInit =
939       DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
940   EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
941                        EmitDeclareReductionInit,
942                        EmitDeclareReductionInit ? ClausesData[N].ReductionOp
943                                                 : PrivateVD->getInit(),
944                        DRD, SharedLVal.getAddress());
945 }
946 
947 ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
948                                    ArrayRef<const Expr *> Privates,
949                                    ArrayRef<const Expr *> ReductionOps) {
950   ClausesData.reserve(Shareds.size());
951   SharedAddresses.reserve(Shareds.size());
952   Sizes.reserve(Shareds.size());
953   BaseDecls.reserve(Shareds.size());
954   auto IPriv = Privates.begin();
955   auto IRed = ReductionOps.begin();
956   for (const Expr *Ref : Shareds) {
957     ClausesData.emplace_back(Ref, *IPriv, *IRed);
958     std::advance(IPriv, 1);
959     std::advance(IRed, 1);
960   }
961 }
962 
963 void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
964   assert(SharedAddresses.size() == N &&
965          "Number of generated lvalues must be exactly N.");
966   LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
967   LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
968   SharedAddresses.emplace_back(First, Second);
969 }
970 
971 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
972   const auto *PrivateVD =
973       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
974   QualType PrivateType = PrivateVD->getType();
975   bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
976   if (!PrivateType->isVariablyModifiedType()) {
977     Sizes.emplace_back(
978         CGF.getTypeSize(
979             SharedAddresses[N].first.getType().getNonReferenceType()),
980         nullptr);
981     return;
982   }
983   llvm::Value *Size;
984   llvm::Value *SizeInChars;
985   auto *ElemType =
986       cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
987           ->getElementType();
988   auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
989   if (AsArraySection) {
990     Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
991                                      SharedAddresses[N].first.getPointer());
992     Size = CGF.Builder.CreateNUWAdd(
993         Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
994     SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
995   } else {
996     SizeInChars = CGF.getTypeSize(
997         SharedAddresses[N].first.getType().getNonReferenceType());
998     Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
999   }
1000   Sizes.emplace_back(SizeInChars, Size);
1001   CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002       CGF,
1003       cast<OpaqueValueExpr>(
1004           CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005       RValue::get(Size));
1006   CGF.EmitVariablyModifiedType(PrivateType);
1007 }
1008 
1009 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1010                                          llvm::Value *Size) {
1011   const auto *PrivateVD =
1012       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013   QualType PrivateType = PrivateVD->getType();
1014   if (!PrivateType->isVariablyModifiedType()) {
1015     assert(!Size && !Sizes[N].second &&
1016            "Size should be nullptr for non-variably modified reduction "
1017            "items.");
1018     return;
1019   }
1020   CodeGenFunction::OpaqueValueMapping OpaqueMap(
1021       CGF,
1022       cast<OpaqueValueExpr>(
1023           CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1024       RValue::get(Size));
1025   CGF.EmitVariablyModifiedType(PrivateType);
1026 }
1027 
1028 void ReductionCodeGen::emitInitialization(
1029     CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1030     llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1031   assert(SharedAddresses.size() > N && "No variable was generated");
1032   const auto *PrivateVD =
1033       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1034   const OMPDeclareReductionDecl *DRD =
1035       getReductionInit(ClausesData[N].ReductionOp);
1036   QualType PrivateType = PrivateVD->getType();
1037   PrivateAddr = CGF.Builder.CreateElementBitCast(
1038       PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1039   QualType SharedType = SharedAddresses[N].first.getType();
1040   SharedLVal = CGF.MakeAddrLValue(
1041       CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1042                                        CGF.ConvertTypeForMem(SharedType)),
1043       SharedType, SharedAddresses[N].first.getBaseInfo(),
1044       CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
1045   if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
1046     emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
1047   } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1048     emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1049                                      PrivateAddr, SharedLVal.getAddress(),
1050                                      SharedLVal.getType());
1051   } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1052              !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1053     CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1054                          PrivateVD->getType().getQualifiers(),
1055                          /*IsInitializer=*/false);
1056   }
1057 }
1058 
1059 bool ReductionCodeGen::needCleanups(unsigned N) {
1060   const auto *PrivateVD =
1061       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1062   QualType PrivateType = PrivateVD->getType();
1063   QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1064   return DTorKind != QualType::DK_none;
1065 }
1066 
1067 void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1068                                     Address PrivateAddr) {
1069   const auto *PrivateVD =
1070       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1071   QualType PrivateType = PrivateVD->getType();
1072   QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1073   if (needCleanups(N)) {
1074     PrivateAddr = CGF.Builder.CreateElementBitCast(
1075         PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1076     CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1077   }
1078 }
1079 
1080 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1081                           LValue BaseLV) {
1082   BaseTy = BaseTy.getNonReferenceType();
1083   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1085     if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
1086       BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1087     } else {
1088       LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1089       BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
1090     }
1091     BaseTy = BaseTy->getPointeeType();
1092   }
1093   return CGF.MakeAddrLValue(
1094       CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1095                                        CGF.ConvertTypeForMem(ElTy)),
1096       BaseLV.getType(), BaseLV.getBaseInfo(),
1097       CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
1098 }
1099 
1100 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1101                           llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1102                           llvm::Value *Addr) {
1103   Address Tmp = Address::invalid();
1104   Address TopTmp = Address::invalid();
1105   Address MostTopTmp = Address::invalid();
1106   BaseTy = BaseTy.getNonReferenceType();
1107   while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1108          !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1109     Tmp = CGF.CreateMemTemp(BaseTy);
1110     if (TopTmp.isValid())
1111       CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1112     else
1113       MostTopTmp = Tmp;
1114     TopTmp = Tmp;
1115     BaseTy = BaseTy->getPointeeType();
1116   }
1117   llvm::Type *Ty = BaseLVType;
1118   if (Tmp.isValid())
1119     Ty = Tmp.getElementType();
1120   Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1121   if (Tmp.isValid()) {
1122     CGF.Builder.CreateStore(Addr, Tmp);
1123     return MostTopTmp;
1124   }
1125   return Address(Addr, BaseLVAlignment);
1126 }
1127 
1128 static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
1129   const VarDecl *OrigVD = nullptr;
1130   if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1131     const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1132     while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1133       Base = TempOASE->getBase()->IgnoreParenImpCasts();
1134     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1135       Base = TempASE->getBase()->IgnoreParenImpCasts();
1136     DE = cast<DeclRefExpr>(Base);
1137     OrigVD = cast<VarDecl>(DE->getDecl());
1138   } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1139     const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1140     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1141       Base = TempASE->getBase()->IgnoreParenImpCasts();
1142     DE = cast<DeclRefExpr>(Base);
1143     OrigVD = cast<VarDecl>(DE->getDecl());
1144   }
1145   return OrigVD;
1146 }
1147 
1148 Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1149                                                Address PrivateAddr) {
1150   const DeclRefExpr *DE;
1151   if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
1152     BaseDecls.emplace_back(OrigVD);
1153     LValue OriginalBaseLValue = CGF.EmitLValue(DE);
1154     LValue BaseLValue =
1155         loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1156                     OriginalBaseLValue);
1157     llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1158         BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1159     llvm::Value *PrivatePointer =
1160         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1161             PrivateAddr.getPointer(),
1162             SharedAddresses[N].first.getAddress().getType());
1163     llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
1164     return castToBase(CGF, OrigVD->getType(),
1165                       SharedAddresses[N].first.getType(),
1166                       OriginalBaseLValue.getAddress().getType(),
1167                       OriginalBaseLValue.getAlignment(), Ptr);
1168   }
1169   BaseDecls.emplace_back(
1170       cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1171   return PrivateAddr;
1172 }
1173 
1174 bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1175   const OMPDeclareReductionDecl *DRD =
1176       getReductionInit(ClausesData[N].ReductionOp);
1177   return DRD && DRD->getInitializer();
1178 }
1179 
1180 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1181   return CGF.EmitLoadOfPointerLValue(
1182       CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183       getThreadIDVariable()->getType()->castAs<PointerType>());
1184 }
1185 
1186 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
1187   if (!CGF.HaveInsertPoint())
1188     return;
1189   // 1.2.2 OpenMP Language Terminology
1190   // Structured block - An executable statement with a single entry at the
1191   // top and a single exit at the bottom.
1192   // The point of exit cannot be a branch out of the structured block.
1193   // longjmp() and throw() must not violate the entry/exit criteria.
1194   CGF.EHStack.pushTerminate();
1195   CodeGen(CGF);
1196   CGF.EHStack.popTerminate();
1197 }
1198 
1199 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1200     CodeGenFunction &CGF) {
1201   return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1202                             getThreadIDVariable()->getType(),
1203                             AlignmentSource::Decl);
1204 }
1205 
1206 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1207                                        QualType FieldTy) {
1208   auto *Field = FieldDecl::Create(
1209       C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1210       C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1211       /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1212   Field->setAccess(AS_public);
1213   DC->addDecl(Field);
1214   return Field;
1215 }
1216 
1217 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1218                                  StringRef Separator)
1219     : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1220       OffloadEntriesInfoManager(CGM) {
1221   ASTContext &C = CGM.getContext();
1222   RecordDecl *RD = C.buildImplicitRecord("ident_t");
1223   QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1224   RD->startDefinition();
1225   // reserved_1
1226   addFieldToRecordDecl(C, RD, KmpInt32Ty);
1227   // flags
1228   addFieldToRecordDecl(C, RD, KmpInt32Ty);
1229   // reserved_2
1230   addFieldToRecordDecl(C, RD, KmpInt32Ty);
1231   // reserved_3
1232   addFieldToRecordDecl(C, RD, KmpInt32Ty);
1233   // psource
1234   addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1235   RD->completeDefinition();
1236   IdentQTy = C.getRecordType(RD);
1237   IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
1238   KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1239 
1240   loadOffloadInfoMetadata();
1241 }
1242 
1243 void CGOpenMPRuntime::clear() {
1244   InternalVars.clear();
1245 }
1246 
1247 std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1248   SmallString<128> Buffer;
1249   llvm::raw_svector_ostream OS(Buffer);
1250   StringRef Sep = FirstSeparator;
1251   for (StringRef Part : Parts) {
1252     OS << Sep << Part;
1253     Sep = Separator;
1254   }
1255   return OS.str();
1256 }
1257 
1258 static llvm::Function *
1259 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1260                           const Expr *CombinerInitializer, const VarDecl *In,
1261                           const VarDecl *Out, bool IsCombiner) {
1262   // void .omp_combiner.(Ty *in, Ty *out);
1263   ASTContext &C = CGM.getContext();
1264   QualType PtrTy = C.getPointerType(Ty).withRestrict();
1265   FunctionArgList Args;
1266   ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1267                                /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1268   ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1269                               /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1270   Args.push_back(&OmpOutParm);
1271   Args.push_back(&OmpInParm);
1272   const CGFunctionInfo &FnInfo =
1273       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1274   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1275   std::string Name = CGM.getOpenMPRuntime().getName(
1276       {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1277   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1278                                     Name, &CGM.getModule());
1279   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1280   Fn->removeFnAttr(llvm::Attribute::NoInline);
1281   Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1282   Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1283   CodeGenFunction CGF(CGM);
1284   // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1285   // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1286   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1287                     Out->getLocation());
1288   CodeGenFunction::OMPPrivateScope Scope(CGF);
1289   Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1290   Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
1291     return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1292         .getAddress();
1293   });
1294   Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1295   Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
1296     return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1297         .getAddress();
1298   });
1299   (void)Scope.Privatize();
1300   if (!IsCombiner && Out->hasInit() &&
1301       !CGF.isTrivialInitializer(Out->getInit())) {
1302     CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1303                          Out->getType().getQualifiers(),
1304                          /*IsInitializer=*/true);
1305   }
1306   if (CombinerInitializer)
1307     CGF.EmitIgnoredExpr(CombinerInitializer);
1308   Scope.ForceCleanup();
1309   CGF.FinishFunction();
1310   return Fn;
1311 }
1312 
1313 void CGOpenMPRuntime::emitUserDefinedReduction(
1314     CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1315   if (UDRMap.count(D) > 0)
1316     return;
1317   ASTContext &C = CGM.getContext();
1318   if (!In || !Out) {
1319     In = &C.Idents.get("omp_in");
1320     Out = &C.Idents.get("omp_out");
1321   }
1322   llvm::Function *Combiner = emitCombinerOrInitializer(
1323       CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1324       cast<VarDecl>(D->lookup(Out).front()),
1325       /*IsCombiner=*/true);
1326   llvm::Function *Initializer = nullptr;
1327   if (const Expr *Init = D->getInitializer()) {
1328     if (!Priv || !Orig) {
1329       Priv = &C.Idents.get("omp_priv");
1330       Orig = &C.Idents.get("omp_orig");
1331     }
1332     Initializer = emitCombinerOrInitializer(
1333         CGM, D->getType(),
1334         D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1335                                                                      : nullptr,
1336         cast<VarDecl>(D->lookup(Orig).front()),
1337         cast<VarDecl>(D->lookup(Priv).front()),
1338         /*IsCombiner=*/false);
1339   }
1340   UDRMap.try_emplace(D, Combiner, Initializer);
1341   if (CGF) {
1342     auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1343     Decls.second.push_back(D);
1344   }
1345 }
1346 
1347 std::pair<llvm::Function *, llvm::Function *>
1348 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1349   auto I = UDRMap.find(D);
1350   if (I != UDRMap.end())
1351     return I->second;
1352   emitUserDefinedReduction(/*CGF=*/nullptr, D);
1353   return UDRMap.lookup(D);
1354 }
1355 
1356 static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1357     CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1358     const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1359     const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1360   assert(ThreadIDVar->getType()->isPointerType() &&
1361          "thread id variable must be of type kmp_int32 *");
1362   CodeGenFunction CGF(CGM, true);
1363   bool HasCancel = false;
1364   if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1365     HasCancel = OPD->hasCancel();
1366   else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1367     HasCancel = OPSD->hasCancel();
1368   else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1369     HasCancel = OPFD->hasCancel();
1370   else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1371     HasCancel = OPFD->hasCancel();
1372   else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1373     HasCancel = OPFD->hasCancel();
1374   else if (const auto *OPFD =
1375                dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1376     HasCancel = OPFD->hasCancel();
1377   else if (const auto *OPFD =
1378                dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1379     HasCancel = OPFD->hasCancel();
1380   CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1381                                     HasCancel, OutlinedHelperName);
1382   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1383   return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
1384 }
1385 
1386 llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1387     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1388     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1389   const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1390   return emitParallelOrTeamsOutlinedFunction(
1391       CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1392 }
1393 
1394 llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1395     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1396     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1397   const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1398   return emitParallelOrTeamsOutlinedFunction(
1399       CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1400 }
1401 
1402 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1403     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1404     const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1405     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1406     bool Tied, unsigned &NumberOfParts) {
1407   auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1408                                               PrePostActionTy &) {
1409     llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1410     llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1411     llvm::Value *TaskArgs[] = {
1412         UpLoc, ThreadID,
1413         CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1414                                     TaskTVar->getType()->castAs<PointerType>())
1415             .getPointer()};
1416     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1417   };
1418   CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1419                                                             UntiedCodeGen);
1420   CodeGen.setAction(Action);
1421   assert(!ThreadIDVar->getType()->isPointerType() &&
1422          "thread id variable must be of type kmp_int32 for tasks");
1423   const OpenMPDirectiveKind Region =
1424       isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1425                                                       : OMPD_task;
1426   const CapturedStmt *CS = D.getCapturedStmt(Region);
1427   const auto *TD = dyn_cast<OMPTaskDirective>(&D);
1428   CodeGenFunction CGF(CGM, true);
1429   CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1430                                         InnermostKind,
1431                                         TD ? TD->hasCancel() : false, Action);
1432   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1433   llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
1434   if (!Tied)
1435     NumberOfParts = Action.getNumberOfParts();
1436   return Res;
1437 }
1438 
1439 static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1440                              const RecordDecl *RD, const CGRecordLayout &RL,
1441                              ArrayRef<llvm::Constant *> Data) {
1442   llvm::StructType *StructTy = RL.getLLVMType();
1443   unsigned PrevIdx = 0;
1444   ConstantInitBuilder CIBuilder(CGM);
1445   auto DI = Data.begin();
1446   for (const FieldDecl *FD : RD->fields()) {
1447     unsigned Idx = RL.getLLVMFieldNo(FD);
1448     // Fill the alignment.
1449     for (unsigned I = PrevIdx; I < Idx; ++I)
1450       Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1451     PrevIdx = Idx + 1;
1452     Fields.add(*DI);
1453     ++DI;
1454   }
1455 }
1456 
1457 template <class... As>
1458 static llvm::GlobalVariable *
1459 createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1460                            ArrayRef<llvm::Constant *> Data, const Twine &Name,
1461                            As &&... Args) {
1462   const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463   const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464   ConstantInitBuilder CIBuilder(CGM);
1465   ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1466   buildStructValue(Fields, CGM, RD, RL, Data);
1467   return Fields.finishAndCreateGlobal(
1468       Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1469       /*isConstant=*/true, std::forward<As>(Args)...);
1470 }
1471 
1472 template <typename T>
1473 void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1474                                               ArrayRef<llvm::Constant *> Data,
1475                                               T &Parent) {
1476   const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1477   const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1478   ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1479   buildStructValue(Fields, CGM, RD, RL, Data);
1480   Fields.finishAndAddTo(Parent);
1481 }
1482 
1483 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
1484   CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1485   llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
1486   if (!Entry) {
1487     if (!DefaultOpenMPPSource) {
1488       // Initialize default location for psource field of ident_t structure of
1489       // all ident_t objects. Format is ";file;function;line;column;;".
1490       // Taken from
1491       // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1492       DefaultOpenMPPSource =
1493           CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
1494       DefaultOpenMPPSource =
1495           llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1496     }
1497 
1498     llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1499                               llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1500                               llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1501                               llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502                               DefaultOpenMPPSource};
1503     llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1504         CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1505     DefaultOpenMPLocation->setUnnamedAddr(
1506         llvm::GlobalValue::UnnamedAddr::Global);
1507 
1508     OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
1509   }
1510   return Address(Entry, Align);
1511 }
1512 
1513 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1514                                                  SourceLocation Loc,
1515                                                  unsigned Flags) {
1516   Flags |= OMP_IDENT_KMPC;
1517   // If no debug info is generated - return global default location.
1518   if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1519       Loc.isInvalid())
1520     return getOrCreateDefaultLocation(Flags).getPointer();
1521 
1522   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1523 
1524   CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
1525   Address LocValue = Address::invalid();
1526   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1527   if (I != OpenMPLocThreadIDMap.end())
1528     LocValue = Address(I->second.DebugLoc, Align);
1529 
1530   // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1531   // GetOpenMPThreadID was called before this routine.
1532   if (!LocValue.isValid()) {
1533     // Generate "ident_t .kmpc_loc.addr;"
1534     Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
1535     auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1536     Elem.second.DebugLoc = AI.getPointer();
1537     LocValue = AI;
1538 
1539     CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1540     CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1541     CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
1542                              CGF.getTypeSize(IdentQTy));
1543   }
1544 
1545   // char **psource = &.kmpc_loc_<flags>.addr.psource;
1546   LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1547   auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1548   LValue PSource =
1549       CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
1550 
1551   llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1552   if (OMPDebugLoc == nullptr) {
1553     SmallString<128> Buffer2;
1554     llvm::raw_svector_ostream OS2(Buffer2);
1555     // Build debug location
1556     PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1557     OS2 << ";" << PLoc.getFilename() << ";";
1558     if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1559       OS2 << FD->getQualifiedNameAsString();
1560     OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1561     OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1562     OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
1563   }
1564   // *psource = ";<File>;<Function>;<Line>;<Column>;;";
1565   CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
1566 
1567   // Our callers always pass this to a runtime function, so for
1568   // convenience, go ahead and return a naked pointer.
1569   return LocValue.getPointer();
1570 }
1571 
1572 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1573                                           SourceLocation Loc) {
1574   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1575 
1576   llvm::Value *ThreadID = nullptr;
1577   // Check whether we've already cached a load of the thread id in this
1578   // function.
1579   auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1580   if (I != OpenMPLocThreadIDMap.end()) {
1581     ThreadID = I->second.ThreadID;
1582     if (ThreadID != nullptr)
1583       return ThreadID;
1584   }
1585   // If exceptions are enabled, do not use parameter to avoid possible crash.
1586   if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1587       !CGF.getLangOpts().CXXExceptions ||
1588       CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1589     if (auto *OMPRegionInfo =
1590             dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1591       if (OMPRegionInfo->getThreadIDVariable()) {
1592         // Check if this an outlined function with thread id passed as argument.
1593         LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1594         ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1595         // If value loaded in entry block, cache it and use it everywhere in
1596         // function.
1597         if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1598           auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1599           Elem.second.ThreadID = ThreadID;
1600         }
1601         return ThreadID;
1602       }
1603     }
1604   }
1605 
1606   // This is not an outlined function region - need to call __kmpc_int32
1607   // kmpc_global_thread_num(ident_t *loc).
1608   // Generate thread id value and cache this value for use across the
1609   // function.
1610   CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1611   CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1612   llvm::CallInst *Call = CGF.Builder.CreateCall(
1613       createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1614       emitUpdateLocation(CGF, Loc));
1615   Call->setCallingConv(CGF.getRuntimeCC());
1616   auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1617   Elem.second.ThreadID = Call;
1618   return Call;
1619 }
1620 
1621 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1622   assert(CGF.CurFn && "No function in current CodeGenFunction.");
1623   if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1624     OpenMPLocThreadIDMap.erase(CGF.CurFn);
1625   if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1626     for(auto *D : FunctionUDRMap[CGF.CurFn])
1627       UDRMap.erase(D);
1628     FunctionUDRMap.erase(CGF.CurFn);
1629   }
1630 }
1631 
1632 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1633   return IdentTy->getPointerTo();
1634 }
1635 
1636 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1637   if (!Kmpc_MicroTy) {
1638     // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1639     llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1640                                  llvm::PointerType::getUnqual(CGM.Int32Ty)};
1641     Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1642   }
1643   return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1644 }
1645 
1646 llvm::Constant *
1647 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1648   llvm::Constant *RTLFn = nullptr;
1649   switch (static_cast<OpenMPRTLFunction>(Function)) {
1650   case OMPRTL__kmpc_fork_call: {
1651     // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1652     // microtask, ...);
1653     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1654                                 getKmpc_MicroPointerTy()};
1655     auto *FnTy =
1656         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1657     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1658     break;
1659   }
1660   case OMPRTL__kmpc_global_thread_num: {
1661     // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
1662     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1663     auto *FnTy =
1664         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1665     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1666     break;
1667   }
1668   case OMPRTL__kmpc_threadprivate_cached: {
1669     // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1670     // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1671     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1672                                 CGM.VoidPtrTy, CGM.SizeTy,
1673                                 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1674     auto *FnTy =
1675         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1676     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1677     break;
1678   }
1679   case OMPRTL__kmpc_critical: {
1680     // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1681     // kmp_critical_name *crit);
1682     llvm::Type *TypeParams[] = {
1683         getIdentTyPointerTy(), CGM.Int32Ty,
1684         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1685     auto *FnTy =
1686         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1687     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1688     break;
1689   }
1690   case OMPRTL__kmpc_critical_with_hint: {
1691     // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1692     // kmp_critical_name *crit, uintptr_t hint);
1693     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1694                                 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1695                                 CGM.IntPtrTy};
1696     auto *FnTy =
1697         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1698     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1699     break;
1700   }
1701   case OMPRTL__kmpc_threadprivate_register: {
1702     // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1703     // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1704     // typedef void *(*kmpc_ctor)(void *);
1705     auto *KmpcCtorTy =
1706         llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1707                                 /*isVarArg*/ false)->getPointerTo();
1708     // typedef void *(*kmpc_cctor)(void *, void *);
1709     llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1710     auto *KmpcCopyCtorTy =
1711         llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1712                                 /*isVarArg*/ false)
1713             ->getPointerTo();
1714     // typedef void (*kmpc_dtor)(void *);
1715     auto *KmpcDtorTy =
1716         llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1717             ->getPointerTo();
1718     llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1719                               KmpcCopyCtorTy, KmpcDtorTy};
1720     auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1721                                         /*isVarArg*/ false);
1722     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1723     break;
1724   }
1725   case OMPRTL__kmpc_end_critical: {
1726     // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1727     // kmp_critical_name *crit);
1728     llvm::Type *TypeParams[] = {
1729         getIdentTyPointerTy(), CGM.Int32Ty,
1730         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1731     auto *FnTy =
1732         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1734     break;
1735   }
1736   case OMPRTL__kmpc_cancel_barrier: {
1737     // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1738     // global_tid);
1739     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1740     auto *FnTy =
1741         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1742     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
1743     break;
1744   }
1745   case OMPRTL__kmpc_barrier: {
1746     // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1747     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1748     auto *FnTy =
1749         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1751     break;
1752   }
1753   case OMPRTL__kmpc_for_static_fini: {
1754     // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1755     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1756     auto *FnTy =
1757         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1758     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1759     break;
1760   }
1761   case OMPRTL__kmpc_push_num_threads: {
1762     // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1763     // kmp_int32 num_threads)
1764     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1765                                 CGM.Int32Ty};
1766     auto *FnTy =
1767         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1769     break;
1770   }
1771   case OMPRTL__kmpc_serialized_parallel: {
1772     // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1773     // global_tid);
1774     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1775     auto *FnTy =
1776         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1777     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1778     break;
1779   }
1780   case OMPRTL__kmpc_end_serialized_parallel: {
1781     // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1782     // global_tid);
1783     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1784     auto *FnTy =
1785         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1786     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1787     break;
1788   }
1789   case OMPRTL__kmpc_flush: {
1790     // Build void __kmpc_flush(ident_t *loc);
1791     llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1792     auto *FnTy =
1793         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1795     break;
1796   }
1797   case OMPRTL__kmpc_master: {
1798     // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1799     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1800     auto *FnTy =
1801         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1803     break;
1804   }
1805   case OMPRTL__kmpc_end_master: {
1806     // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1807     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1808     auto *FnTy =
1809         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1811     break;
1812   }
1813   case OMPRTL__kmpc_omp_taskyield: {
1814     // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1815     // int end_part);
1816     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1817     auto *FnTy =
1818         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1819     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1820     break;
1821   }
1822   case OMPRTL__kmpc_single: {
1823     // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1824     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1825     auto *FnTy =
1826         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1827     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1828     break;
1829   }
1830   case OMPRTL__kmpc_end_single: {
1831     // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1832     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1833     auto *FnTy =
1834         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1835     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1836     break;
1837   }
1838   case OMPRTL__kmpc_omp_task_alloc: {
1839     // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1840     // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1841     // kmp_routine_entry_t *task_entry);
1842     assert(KmpRoutineEntryPtrTy != nullptr &&
1843            "Type kmp_routine_entry_t must be created.");
1844     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1845                                 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1846     // Return void * and then cast to particular kmp_task_t type.
1847     auto *FnTy =
1848         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1849     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1850     break;
1851   }
1852   case OMPRTL__kmpc_omp_task: {
1853     // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1854     // *new_task);
1855     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1856                                 CGM.VoidPtrTy};
1857     auto *FnTy =
1858         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1859     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1860     break;
1861   }
1862   case OMPRTL__kmpc_copyprivate: {
1863     // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
1864     // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
1865     // kmp_int32 didit);
1866     llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1867     auto *CpyFnTy =
1868         llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
1869     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
1870                                 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1871                                 CGM.Int32Ty};
1872     auto *FnTy =
1873         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1874     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1875     break;
1876   }
1877   case OMPRTL__kmpc_reduce: {
1878     // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1879     // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1880     // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1881     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1882     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1883                                                /*isVarArg=*/false);
1884     llvm::Type *TypeParams[] = {
1885         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1886         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1887         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1888     auto *FnTy =
1889         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1890     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1891     break;
1892   }
1893   case OMPRTL__kmpc_reduce_nowait: {
1894     // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1895     // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1896     // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1897     // *lck);
1898     llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1899     auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1900                                                /*isVarArg=*/false);
1901     llvm::Type *TypeParams[] = {
1902         getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1903         CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1904         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1905     auto *FnTy =
1906         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1907     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1908     break;
1909   }
1910   case OMPRTL__kmpc_end_reduce: {
1911     // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1912     // kmp_critical_name *lck);
1913     llvm::Type *TypeParams[] = {
1914         getIdentTyPointerTy(), CGM.Int32Ty,
1915         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1916     auto *FnTy =
1917         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1918     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1919     break;
1920   }
1921   case OMPRTL__kmpc_end_reduce_nowait: {
1922     // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1923     // kmp_critical_name *lck);
1924     llvm::Type *TypeParams[] = {
1925         getIdentTyPointerTy(), CGM.Int32Ty,
1926         llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1927     auto *FnTy =
1928         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1929     RTLFn =
1930         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1931     break;
1932   }
1933   case OMPRTL__kmpc_omp_task_begin_if0: {
1934     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1935     // *new_task);
1936     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1937                                 CGM.VoidPtrTy};
1938     auto *FnTy =
1939         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940     RTLFn =
1941         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1942     break;
1943   }
1944   case OMPRTL__kmpc_omp_task_complete_if0: {
1945     // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1946     // *new_task);
1947     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1948                                 CGM.VoidPtrTy};
1949     auto *FnTy =
1950         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951     RTLFn = CGM.CreateRuntimeFunction(FnTy,
1952                                       /*Name=*/"__kmpc_omp_task_complete_if0");
1953     break;
1954   }
1955   case OMPRTL__kmpc_ordered: {
1956     // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1957     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1958     auto *FnTy =
1959         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1960     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1961     break;
1962   }
1963   case OMPRTL__kmpc_end_ordered: {
1964     // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
1965     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1966     auto *FnTy =
1967         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1969     break;
1970   }
1971   case OMPRTL__kmpc_omp_taskwait: {
1972     // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1973     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1974     auto *FnTy =
1975         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1976     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1977     break;
1978   }
1979   case OMPRTL__kmpc_taskgroup: {
1980     // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1981     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1982     auto *FnTy =
1983         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1984     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1985     break;
1986   }
1987   case OMPRTL__kmpc_end_taskgroup: {
1988     // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1989     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1990     auto *FnTy =
1991         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1992     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1993     break;
1994   }
1995   case OMPRTL__kmpc_push_proc_bind: {
1996     // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1997     // int proc_bind)
1998     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1999     auto *FnTy =
2000         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2001     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2002     break;
2003   }
2004   case OMPRTL__kmpc_omp_task_with_deps: {
2005     // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2006     // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2007     // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2008     llvm::Type *TypeParams[] = {
2009         getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2010         CGM.VoidPtrTy,         CGM.Int32Ty, CGM.VoidPtrTy};
2011     auto *FnTy =
2012         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2013     RTLFn =
2014         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2015     break;
2016   }
2017   case OMPRTL__kmpc_omp_wait_deps: {
2018     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2019     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2020     // kmp_depend_info_t *noalias_dep_list);
2021     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2022                                 CGM.Int32Ty,           CGM.VoidPtrTy,
2023                                 CGM.Int32Ty,           CGM.VoidPtrTy};
2024     auto *FnTy =
2025         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2027     break;
2028   }
2029   case OMPRTL__kmpc_cancellationpoint: {
2030     // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2031     // global_tid, kmp_int32 cncl_kind)
2032     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2033     auto *FnTy =
2034         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2035     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2036     break;
2037   }
2038   case OMPRTL__kmpc_cancel: {
2039     // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2040     // kmp_int32 cncl_kind)
2041     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
2042     auto *FnTy =
2043         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2044     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2045     break;
2046   }
2047   case OMPRTL__kmpc_push_num_teams: {
2048     // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2049     // kmp_int32 num_teams, kmp_int32 num_threads)
2050     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2051         CGM.Int32Ty};
2052     auto *FnTy =
2053         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2055     break;
2056   }
2057   case OMPRTL__kmpc_fork_teams: {
2058     // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2059     // microtask, ...);
2060     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2061                                 getKmpc_MicroPointerTy()};
2062     auto *FnTy =
2063         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2064     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2065     break;
2066   }
2067   case OMPRTL__kmpc_taskloop: {
2068     // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2069     // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2070     // sched, kmp_uint64 grainsize, void *task_dup);
2071     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2072                                 CGM.IntTy,
2073                                 CGM.VoidPtrTy,
2074                                 CGM.IntTy,
2075                                 CGM.Int64Ty->getPointerTo(),
2076                                 CGM.Int64Ty->getPointerTo(),
2077                                 CGM.Int64Ty,
2078                                 CGM.IntTy,
2079                                 CGM.IntTy,
2080                                 CGM.Int64Ty,
2081                                 CGM.VoidPtrTy};
2082     auto *FnTy =
2083         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2084     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2085     break;
2086   }
2087   case OMPRTL__kmpc_doacross_init: {
2088     // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2089     // num_dims, struct kmp_dim *dims);
2090     llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2091                                 CGM.Int32Ty,
2092                                 CGM.Int32Ty,
2093                                 CGM.VoidPtrTy};
2094     auto *FnTy =
2095         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2096     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2097     break;
2098   }
2099   case OMPRTL__kmpc_doacross_fini: {
2100     // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2101     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2102     auto *FnTy =
2103         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2104     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2105     break;
2106   }
2107   case OMPRTL__kmpc_doacross_post: {
2108     // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2109     // *vec);
2110     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2111                                 CGM.Int64Ty->getPointerTo()};
2112     auto *FnTy =
2113         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2114     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2115     break;
2116   }
2117   case OMPRTL__kmpc_doacross_wait: {
2118     // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2119     // *vec);
2120     llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2121                                 CGM.Int64Ty->getPointerTo()};
2122     auto *FnTy =
2123         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2124     RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2125     break;
2126   }
2127   case OMPRTL__kmpc_task_reduction_init: {
2128     // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2129     // *data);
2130     llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2131     auto *FnTy =
2132         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2133     RTLFn =
2134         CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2135     break;
2136   }
2137   case OMPRTL__kmpc_task_reduction_get_th_data: {
2138     // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2139     // *d);
2140     llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2141     auto *FnTy =
2142         llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2143     RTLFn = CGM.CreateRuntimeFunction(
2144         FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2145     break;
2146   }
2147   case OMPRTL__tgt_target: {
2148     // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2149     // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2150     // *arg_types);
2151     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2152                                 CGM.VoidPtrTy,
2153                                 CGM.Int32Ty,
2154                                 CGM.VoidPtrPtrTy,
2155                                 CGM.VoidPtrPtrTy,
2156                                 CGM.SizeTy->getPointerTo(),
2157                                 CGM.Int64Ty->getPointerTo()};
2158     auto *FnTy =
2159         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2160     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2161     break;
2162   }
2163   case OMPRTL__tgt_target_nowait: {
2164     // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2165     // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2166     // int64_t *arg_types);
2167     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2168                                 CGM.VoidPtrTy,
2169                                 CGM.Int32Ty,
2170                                 CGM.VoidPtrPtrTy,
2171                                 CGM.VoidPtrPtrTy,
2172                                 CGM.SizeTy->getPointerTo(),
2173                                 CGM.Int64Ty->getPointerTo()};
2174     auto *FnTy =
2175         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2176     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2177     break;
2178   }
2179   case OMPRTL__tgt_target_teams: {
2180     // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
2181     // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2182     // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2183     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2184                                 CGM.VoidPtrTy,
2185                                 CGM.Int32Ty,
2186                                 CGM.VoidPtrPtrTy,
2187                                 CGM.VoidPtrPtrTy,
2188                                 CGM.SizeTy->getPointerTo(),
2189                                 CGM.Int64Ty->getPointerTo(),
2190                                 CGM.Int32Ty,
2191                                 CGM.Int32Ty};
2192     auto *FnTy =
2193         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2194     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2195     break;
2196   }
2197   case OMPRTL__tgt_target_teams_nowait: {
2198     // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2199     // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2200     // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2201     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2202                                 CGM.VoidPtrTy,
2203                                 CGM.Int32Ty,
2204                                 CGM.VoidPtrPtrTy,
2205                                 CGM.VoidPtrPtrTy,
2206                                 CGM.SizeTy->getPointerTo(),
2207                                 CGM.Int64Ty->getPointerTo(),
2208                                 CGM.Int32Ty,
2209                                 CGM.Int32Ty};
2210     auto *FnTy =
2211         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2212     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2213     break;
2214   }
2215   case OMPRTL__tgt_register_lib: {
2216     // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2217     QualType ParamTy =
2218         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2219     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2220     auto *FnTy =
2221         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2222     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2223     break;
2224   }
2225   case OMPRTL__tgt_unregister_lib: {
2226     // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2227     QualType ParamTy =
2228         CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2229     llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2230     auto *FnTy =
2231         llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2232     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2233     break;
2234   }
2235   case OMPRTL__tgt_target_data_begin: {
2236     // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2237     // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2238     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2239                                 CGM.Int32Ty,
2240                                 CGM.VoidPtrPtrTy,
2241                                 CGM.VoidPtrPtrTy,
2242                                 CGM.SizeTy->getPointerTo(),
2243                                 CGM.Int64Ty->getPointerTo()};
2244     auto *FnTy =
2245         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2246     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2247     break;
2248   }
2249   case OMPRTL__tgt_target_data_begin_nowait: {
2250     // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2251     // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2252     // *arg_types);
2253     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2254                                 CGM.Int32Ty,
2255                                 CGM.VoidPtrPtrTy,
2256                                 CGM.VoidPtrPtrTy,
2257                                 CGM.SizeTy->getPointerTo(),
2258                                 CGM.Int64Ty->getPointerTo()};
2259     auto *FnTy =
2260         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2261     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2262     break;
2263   }
2264   case OMPRTL__tgt_target_data_end: {
2265     // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2266     // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2267     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2268                                 CGM.Int32Ty,
2269                                 CGM.VoidPtrPtrTy,
2270                                 CGM.VoidPtrPtrTy,
2271                                 CGM.SizeTy->getPointerTo(),
2272                                 CGM.Int64Ty->getPointerTo()};
2273     auto *FnTy =
2274         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2276     break;
2277   }
2278   case OMPRTL__tgt_target_data_end_nowait: {
2279     // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2280     // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2281     // *arg_types);
2282     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2283                                 CGM.Int32Ty,
2284                                 CGM.VoidPtrPtrTy,
2285                                 CGM.VoidPtrPtrTy,
2286                                 CGM.SizeTy->getPointerTo(),
2287                                 CGM.Int64Ty->getPointerTo()};
2288     auto *FnTy =
2289         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2290     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2291     break;
2292   }
2293   case OMPRTL__tgt_target_data_update: {
2294     // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2295     // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2296     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2297                                 CGM.Int32Ty,
2298                                 CGM.VoidPtrPtrTy,
2299                                 CGM.VoidPtrPtrTy,
2300                                 CGM.SizeTy->getPointerTo(),
2301                                 CGM.Int64Ty->getPointerTo()};
2302     auto *FnTy =
2303         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2304     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2305     break;
2306   }
2307   case OMPRTL__tgt_target_data_update_nowait: {
2308     // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2309     // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2310     // *arg_types);
2311     llvm::Type *TypeParams[] = {CGM.Int64Ty,
2312                                 CGM.Int32Ty,
2313                                 CGM.VoidPtrPtrTy,
2314                                 CGM.VoidPtrPtrTy,
2315                                 CGM.SizeTy->getPointerTo(),
2316                                 CGM.Int64Ty->getPointerTo()};
2317     auto *FnTy =
2318         llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2319     RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2320     break;
2321   }
2322   }
2323   assert(RTLFn && "Unable to find OpenMP runtime function");
2324   return RTLFn;
2325 }
2326 
2327 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2328                                                              bool IVSigned) {
2329   assert((IVSize == 32 || IVSize == 64) &&
2330          "IV size is not compatible with the omp runtime");
2331   StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2332                                             : "__kmpc_for_static_init_4u")
2333                                 : (IVSigned ? "__kmpc_for_static_init_8"
2334                                             : "__kmpc_for_static_init_8u");
2335   llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2336   auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2337   llvm::Type *TypeParams[] = {
2338     getIdentTyPointerTy(),                     // loc
2339     CGM.Int32Ty,                               // tid
2340     CGM.Int32Ty,                               // schedtype
2341     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2342     PtrTy,                                     // p_lower
2343     PtrTy,                                     // p_upper
2344     PtrTy,                                     // p_stride
2345     ITy,                                       // incr
2346     ITy                                        // chunk
2347   };
2348   auto *FnTy =
2349       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2350   return CGM.CreateRuntimeFunction(FnTy, Name);
2351 }
2352 
2353 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2354                                                             bool IVSigned) {
2355   assert((IVSize == 32 || IVSize == 64) &&
2356          "IV size is not compatible with the omp runtime");
2357   StringRef Name =
2358       IVSize == 32
2359           ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2360           : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2361   llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2362   llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2363                                CGM.Int32Ty,           // tid
2364                                CGM.Int32Ty,           // schedtype
2365                                ITy,                   // lower
2366                                ITy,                   // upper
2367                                ITy,                   // stride
2368                                ITy                    // chunk
2369   };
2370   auto *FnTy =
2371       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2372   return CGM.CreateRuntimeFunction(FnTy, Name);
2373 }
2374 
2375 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2376                                                             bool IVSigned) {
2377   assert((IVSize == 32 || IVSize == 64) &&
2378          "IV size is not compatible with the omp runtime");
2379   StringRef Name =
2380       IVSize == 32
2381           ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2382           : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2383   llvm::Type *TypeParams[] = {
2384       getIdentTyPointerTy(), // loc
2385       CGM.Int32Ty,           // tid
2386   };
2387   auto *FnTy =
2388       llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2389   return CGM.CreateRuntimeFunction(FnTy, Name);
2390 }
2391 
2392 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2393                                                             bool IVSigned) {
2394   assert((IVSize == 32 || IVSize == 64) &&
2395          "IV size is not compatible with the omp runtime");
2396   StringRef Name =
2397       IVSize == 32
2398           ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2399           : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2400   llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2401   auto *PtrTy = llvm::PointerType::getUnqual(ITy);
2402   llvm::Type *TypeParams[] = {
2403     getIdentTyPointerTy(),                     // loc
2404     CGM.Int32Ty,                               // tid
2405     llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2406     PtrTy,                                     // p_lower
2407     PtrTy,                                     // p_upper
2408     PtrTy                                      // p_stride
2409   };
2410   auto *FnTy =
2411       llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2412   return CGM.CreateRuntimeFunction(FnTy, Name);
2413 }
2414 
2415 Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2416   if (CGM.getLangOpts().OpenMPSimd)
2417     return Address::invalid();
2418   llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2419       isDeclareTargetDeclaration(VD);
2420   if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2421     SmallString<64> PtrName;
2422     {
2423       llvm::raw_svector_ostream OS(PtrName);
2424       OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2425     }
2426     llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2427     if (!Ptr) {
2428       QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2429       Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2430                                         PtrName);
2431       if (!CGM.getLangOpts().OpenMPIsDevice) {
2432         auto *GV = cast<llvm::GlobalVariable>(Ptr);
2433         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2434         GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2435       }
2436       CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2437       registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
2438     }
2439     return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2440   }
2441   return Address::invalid();
2442 }
2443 
2444 llvm::Constant *
2445 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
2446   assert(!CGM.getLangOpts().OpenMPUseTLS ||
2447          !CGM.getContext().getTargetInfo().isTLSSupported());
2448   // Lookup the entry, lazily creating it if necessary.
2449   std::string Suffix = getName({"cache", ""});
2450   return getOrCreateInternalVariable(
2451       CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
2452 }
2453 
2454 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2455                                                 const VarDecl *VD,
2456                                                 Address VDAddr,
2457                                                 SourceLocation Loc) {
2458   if (CGM.getLangOpts().OpenMPUseTLS &&
2459       CGM.getContext().getTargetInfo().isTLSSupported())
2460     return VDAddr;
2461 
2462   llvm::Type *VarTy = VDAddr.getElementType();
2463   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2464                          CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2465                                                        CGM.Int8PtrTy),
2466                          CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2467                          getOrCreateThreadPrivateCache(VD)};
2468   return Address(CGF.EmitRuntimeCall(
2469       createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2470                  VDAddr.getAlignment());
2471 }
2472 
2473 void CGOpenMPRuntime::emitThreadPrivateVarInit(
2474     CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
2475     llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2476   // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2477   // library.
2478   llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
2479   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
2480                       OMPLoc);
2481   // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2482   // to register constructor/destructor for variable.
2483   llvm::Value *Args[] = {
2484       OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2485       Ctor, CopyCtor, Dtor};
2486   CGF.EmitRuntimeCall(
2487       createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
2488 }
2489 
2490 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
2491     const VarDecl *VD, Address VDAddr, SourceLocation Loc,
2492     bool PerformInit, CodeGenFunction *CGF) {
2493   if (CGM.getLangOpts().OpenMPUseTLS &&
2494       CGM.getContext().getTargetInfo().isTLSSupported())
2495     return nullptr;
2496 
2497   VD = VD->getDefinition(CGM.getContext());
2498   if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2499     ThreadPrivateWithDefinition.insert(VD);
2500     QualType ASTTy = VD->getType();
2501 
2502     llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2503     const Expr *Init = VD->getAnyInitializer();
2504     if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2505       // Generate function that re-emits the declaration's initializer into the
2506       // threadprivate copy of the variable VD
2507       CodeGenFunction CtorCGF(CGM);
2508       FunctionArgList Args;
2509       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2510                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2511                             ImplicitParamDecl::Other);
2512       Args.push_back(&Dst);
2513 
2514       const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2515           CGM.getContext().VoidPtrTy, Args);
2516       llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2517       std::string Name = getName({"__kmpc_global_ctor_", ""});
2518       llvm::Function *Fn =
2519           CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2520       CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2521                             Args, Loc, Loc);
2522       llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
2523           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2524           CGM.getContext().VoidPtrTy, Dst.getLocation());
2525       Address Arg = Address(ArgVal, VDAddr.getAlignment());
2526       Arg = CtorCGF.Builder.CreateElementBitCast(
2527           Arg, CtorCGF.ConvertTypeForMem(ASTTy));
2528       CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2529                                /*IsInitializer=*/true);
2530       ArgVal = CtorCGF.EmitLoadOfScalar(
2531           CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
2532           CGM.getContext().VoidPtrTy, Dst.getLocation());
2533       CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2534       CtorCGF.FinishFunction();
2535       Ctor = Fn;
2536     }
2537     if (VD->getType().isDestructedType() != QualType::DK_none) {
2538       // Generate function that emits destructor call for the threadprivate copy
2539       // of the variable VD
2540       CodeGenFunction DtorCGF(CGM);
2541       FunctionArgList Args;
2542       ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2543                             /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
2544                             ImplicitParamDecl::Other);
2545       Args.push_back(&Dst);
2546 
2547       const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2548           CGM.getContext().VoidTy, Args);
2549       llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2550       std::string Name = getName({"__kmpc_global_dtor_", ""});
2551       llvm::Function *Fn =
2552           CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
2553       auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2554       DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2555                             Loc, Loc);
2556       // Create a scope with an artificial location for the body of this function.
2557       auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2558       llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
2559           DtorCGF.GetAddrOfLocalVar(&Dst),
2560           /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2561       DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
2562                           DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2563                           DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2564       DtorCGF.FinishFunction();
2565       Dtor = Fn;
2566     }
2567     // Do not emit init function if it is not required.
2568     if (!Ctor && !Dtor)
2569       return nullptr;
2570 
2571     llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2572     auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2573                                                /*isVarArg=*/false)
2574                            ->getPointerTo();
2575     // Copying constructor for the threadprivate variable.
2576     // Must be NULL - reserved by runtime, but currently it requires that this
2577     // parameter is always NULL. Otherwise it fires assertion.
2578     CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2579     if (Ctor == nullptr) {
2580       auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2581                                              /*isVarArg=*/false)
2582                          ->getPointerTo();
2583       Ctor = llvm::Constant::getNullValue(CtorTy);
2584     }
2585     if (Dtor == nullptr) {
2586       auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2587                                              /*isVarArg=*/false)
2588                          ->getPointerTo();
2589       Dtor = llvm::Constant::getNullValue(DtorTy);
2590     }
2591     if (!CGF) {
2592       auto *InitFunctionTy =
2593           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2594       std::string Name = getName({"__omp_threadprivate_init_", ""});
2595       llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
2596           InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
2597       CodeGenFunction InitCGF(CGM);
2598       FunctionArgList ArgList;
2599       InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2600                             CGM.getTypes().arrangeNullaryFunction(), ArgList,
2601                             Loc, Loc);
2602       emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2603       InitCGF.FinishFunction();
2604       return InitFunction;
2605     }
2606     emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
2607   }
2608   return nullptr;
2609 }
2610 
2611 /// \brief Obtain information that uniquely identifies a target entry. This
2612 /// consists of the file and device IDs as well as line number associated with
2613 /// the relevant entry source location.
2614 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2615                                      unsigned &DeviceID, unsigned &FileID,
2616                                      unsigned &LineNum) {
2617   SourceManager &SM = C.getSourceManager();
2618 
2619   // The loc should be always valid and have a file ID (the user cannot use
2620   // #pragma directives in macros)
2621 
2622   assert(Loc.isValid() && "Source location is expected to be always valid.");
2623 
2624   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2625   assert(PLoc.isValid() && "Source location is expected to be always valid.");
2626 
2627   llvm::sys::fs::UniqueID ID;
2628   if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2629     SM.getDiagnostics().Report(diag::err_cannot_open_file)
2630         << PLoc.getFilename() << EC.message();
2631 
2632   DeviceID = ID.getDevice();
2633   FileID = ID.getFile();
2634   LineNum = PLoc.getLine();
2635 }
2636 
2637 bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2638                                                      llvm::GlobalVariable *Addr,
2639                                                      bool PerformInit) {
2640   Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2641       isDeclareTargetDeclaration(VD);
2642   if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2643     return false;
2644   VD = VD->getDefinition(CGM.getContext());
2645   if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2646     return CGM.getLangOpts().OpenMPIsDevice;
2647 
2648   QualType ASTTy = VD->getType();
2649 
2650   SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2651   // Produce the unique prefix to identify the new target regions. We use
2652   // the source location of the variable declaration which we know to not
2653   // conflict with any target region.
2654   unsigned DeviceID;
2655   unsigned FileID;
2656   unsigned Line;
2657   getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2658   SmallString<128> Buffer, Out;
2659   {
2660     llvm::raw_svector_ostream OS(Buffer);
2661     OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2662        << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2663   }
2664 
2665   const Expr *Init = VD->getAnyInitializer();
2666   if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2667     llvm::Constant *Ctor;
2668     llvm::Constant *ID;
2669     if (CGM.getLangOpts().OpenMPIsDevice) {
2670       // Generate function that re-emits the declaration's initializer into
2671       // the threadprivate copy of the variable VD
2672       CodeGenFunction CtorCGF(CGM);
2673 
2674       const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2675       llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2676       llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2677           FTy, Twine(Buffer, "_ctor"), FI, Loc);
2678       auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2679       CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2680                             FunctionArgList(), Loc, Loc);
2681       auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2682       CtorCGF.EmitAnyExprToMem(Init,
2683                                Address(Addr, CGM.getContext().getDeclAlign(VD)),
2684                                Init->getType().getQualifiers(),
2685                                /*IsInitializer=*/true);
2686       CtorCGF.FinishFunction();
2687       Ctor = Fn;
2688       ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2689     } else {
2690       Ctor = new llvm::GlobalVariable(
2691           CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2692           llvm::GlobalValue::PrivateLinkage,
2693           llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2694       ID = Ctor;
2695     }
2696 
2697     // Register the information for the entry associated with the constructor.
2698     Out.clear();
2699     OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2700         DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
2701         ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
2702   }
2703   if (VD->getType().isDestructedType() != QualType::DK_none) {
2704     llvm::Constant *Dtor;
2705     llvm::Constant *ID;
2706     if (CGM.getLangOpts().OpenMPIsDevice) {
2707       // Generate function that emits destructor call for the threadprivate
2708       // copy of the variable VD
2709       CodeGenFunction DtorCGF(CGM);
2710 
2711       const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2712       llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2713       llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2714           FTy, Twine(Buffer, "_dtor"), FI, Loc);
2715       auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2716       DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2717                             FunctionArgList(), Loc, Loc);
2718       // Create a scope with an artificial location for the body of this
2719       // function.
2720       auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2721       DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2722                           ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2723                           DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2724       DtorCGF.FinishFunction();
2725       Dtor = Fn;
2726       ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2727     } else {
2728       Dtor = new llvm::GlobalVariable(
2729           CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2730           llvm::GlobalValue::PrivateLinkage,
2731           llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2732       ID = Dtor;
2733     }
2734     // Register the information for the entry associated with the destructor.
2735     Out.clear();
2736     OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2737         DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
2738         ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
2739   }
2740   return CGM.getLangOpts().OpenMPIsDevice;
2741 }
2742 
2743 Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2744                                                           QualType VarType,
2745                                                           StringRef Name) {
2746   std::string Suffix = getName({"artificial", ""});
2747   std::string CacheSuffix = getName({"cache", ""});
2748   llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2749   llvm::Value *GAddr =
2750       getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
2751   llvm::Value *Args[] = {
2752       emitUpdateLocation(CGF, SourceLocation()),
2753       getThreadID(CGF, SourceLocation()),
2754       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2755       CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2756                                 /*IsSigned=*/false),
2757       getOrCreateInternalVariable(
2758           CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
2759   return Address(
2760       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2761           CGF.EmitRuntimeCall(
2762               createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2763           VarLVType->getPointerTo(/*AddrSpace=*/0)),
2764       CGM.getPointerAlign());
2765 }
2766 
2767 /// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2768 /// function. Here is the logic:
2769 /// if (Cond) {
2770 ///   ThenGen();
2771 /// } else {
2772 ///   ElseGen();
2773 /// }
2774 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2775                                       const RegionCodeGenTy &ThenGen,
2776                                       const RegionCodeGenTy &ElseGen) {
2777   CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2778 
2779   // If the condition constant folds and can be elided, try to avoid emitting
2780   // the condition and the dead arm of the if/else.
2781   bool CondConstant;
2782   if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2783     if (CondConstant)
2784       ThenGen(CGF);
2785     else
2786       ElseGen(CGF);
2787     return;
2788   }
2789 
2790   // Otherwise, the condition did not fold, or we couldn't elide it.  Just
2791   // emit the conditional branch.
2792   llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2793   llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2794   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
2795   CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2796 
2797   // Emit the 'then' code.
2798   CGF.EmitBlock(ThenBlock);
2799   ThenGen(CGF);
2800   CGF.EmitBranch(ContBlock);
2801   // Emit the 'else' code if present.
2802   // There is no need to emit line number for unconditional branch.
2803   (void)ApplyDebugLocation::CreateEmpty(CGF);
2804   CGF.EmitBlock(ElseBlock);
2805   ElseGen(CGF);
2806   // There is no need to emit line number for unconditional branch.
2807   (void)ApplyDebugLocation::CreateEmpty(CGF);
2808   CGF.EmitBranch(ContBlock);
2809   // Emit the continuation block for code after the if.
2810   CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2811 }
2812 
2813 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2814                                        llvm::Value *OutlinedFn,
2815                                        ArrayRef<llvm::Value *> CapturedVars,
2816                                        const Expr *IfCond) {
2817   if (!CGF.HaveInsertPoint())
2818     return;
2819   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2820   auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2821                                                      PrePostActionTy &) {
2822     // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2823     CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2824     llvm::Value *Args[] = {
2825         RTLoc,
2826         CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2827         CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2828     llvm::SmallVector<llvm::Value *, 16> RealArgs;
2829     RealArgs.append(std::begin(Args), std::end(Args));
2830     RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2831 
2832     llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
2833     CGF.EmitRuntimeCall(RTLFn, RealArgs);
2834   };
2835   auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2836                                                           PrePostActionTy &) {
2837     CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2838     llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
2839     // Build calls:
2840     // __kmpc_serialized_parallel(&Loc, GTid);
2841     llvm::Value *Args[] = {RTLoc, ThreadID};
2842     CGF.EmitRuntimeCall(
2843         RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
2844 
2845     // OutlinedFn(&GTid, &zero, CapturedStruct);
2846     Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2847     Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2848                                                         /*Name*/ ".zero.addr");
2849     CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2850     llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2851     OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2852     OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2853     OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2854     RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2855 
2856     // __kmpc_end_serialized_parallel(&Loc, GTid);
2857     llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2858     CGF.EmitRuntimeCall(
2859         RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2860         EndArgs);
2861   };
2862   if (IfCond) {
2863     emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
2864   } else {
2865     RegionCodeGenTy ThenRCG(ThenGen);
2866     ThenRCG(CGF);
2867   }
2868 }
2869 
2870 // If we're inside an (outlined) parallel region, use the region info's
2871 // thread-ID variable (it is passed in a first argument of the outlined function
2872 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2873 // regular serial code region, get thread ID by calling kmp_int32
2874 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2875 // return the address of that temp.
2876 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2877                                              SourceLocation Loc) {
2878   if (auto *OMPRegionInfo =
2879           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2880     if (OMPRegionInfo->getThreadIDVariable())
2881       return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
2882 
2883   llvm::Value *ThreadID = getThreadID(CGF, Loc);
2884   QualType Int32Ty =
2885       CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2886   Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2887   CGF.EmitStoreOfScalar(ThreadID,
2888                         CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2889 
2890   return ThreadIDTemp;
2891 }
2892 
2893 llvm::Constant *
2894 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
2895                                              const llvm::Twine &Name) {
2896   SmallString<256> Buffer;
2897   llvm::raw_svector_ostream Out(Buffer);
2898   Out << Name;
2899   StringRef RuntimeName = Out.str();
2900   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
2901   if (Elem.second) {
2902     assert(Elem.second->getType()->getPointerElementType() == Ty &&
2903            "OMP internal variable has different type than requested");
2904     return &*Elem.second;
2905   }
2906 
2907   return Elem.second = new llvm::GlobalVariable(
2908              CGM.getModule(), Ty, /*IsConstant*/ false,
2909              llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2910              Elem.first());
2911 }
2912 
2913 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2914   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2915   std::string Name = getName({Prefix, "var"});
2916   return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2917 }
2918 
2919 namespace {
2920 /// Common pre(post)-action for different OpenMP constructs.
2921 class CommonActionTy final : public PrePostActionTy {
2922   llvm::Value *EnterCallee;
2923   ArrayRef<llvm::Value *> EnterArgs;
2924   llvm::Value *ExitCallee;
2925   ArrayRef<llvm::Value *> ExitArgs;
2926   bool Conditional;
2927   llvm::BasicBlock *ContBlock = nullptr;
2928 
2929 public:
2930   CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2931                  llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2932                  bool Conditional = false)
2933       : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2934         ExitArgs(ExitArgs), Conditional(Conditional) {}
2935   void Enter(CodeGenFunction &CGF) override {
2936     llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2937     if (Conditional) {
2938       llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2939       auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2940       ContBlock = CGF.createBasicBlock("omp_if.end");
2941       // Generate the branch (If-stmt)
2942       CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2943       CGF.EmitBlock(ThenBlock);
2944     }
2945   }
2946   void Done(CodeGenFunction &CGF) {
2947     // Emit the rest of blocks/branches
2948     CGF.EmitBranch(ContBlock);
2949     CGF.EmitBlock(ContBlock, true);
2950   }
2951   void Exit(CodeGenFunction &CGF) override {
2952     CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2953   }
2954 };
2955 } // anonymous namespace
2956 
2957 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2958                                          StringRef CriticalName,
2959                                          const RegionCodeGenTy &CriticalOpGen,
2960                                          SourceLocation Loc, const Expr *Hint) {
2961   // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2962   // CriticalOpGen();
2963   // __kmpc_end_critical(ident_t *, gtid, Lock);
2964   // Prepare arguments and build a call to __kmpc_critical
2965   if (!CGF.HaveInsertPoint())
2966     return;
2967   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2968                          getCriticalRegionLock(CriticalName)};
2969   llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2970                                                 std::end(Args));
2971   if (Hint) {
2972     EnterArgs.push_back(CGF.Builder.CreateIntCast(
2973         CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2974   }
2975   CommonActionTy Action(
2976       createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2977                                  : OMPRTL__kmpc_critical),
2978       EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2979   CriticalOpGen.setAction(Action);
2980   emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2981 }
2982 
2983 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2984                                        const RegionCodeGenTy &MasterOpGen,
2985                                        SourceLocation Loc) {
2986   if (!CGF.HaveInsertPoint())
2987     return;
2988   // if(__kmpc_master(ident_t *, gtid)) {
2989   //   MasterOpGen();
2990   //   __kmpc_end_master(ident_t *, gtid);
2991   // }
2992   // Prepare arguments and build a call to __kmpc_master
2993   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2994   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2995                         createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2996                         /*Conditional=*/true);
2997   MasterOpGen.setAction(Action);
2998   emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2999   Action.Done(CGF);
3000 }
3001 
3002 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3003                                         SourceLocation Loc) {
3004   if (!CGF.HaveInsertPoint())
3005     return;
3006   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3007   llvm::Value *Args[] = {
3008       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3009       llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
3010   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
3011   if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3012     Region->emitUntiedSwitch(CGF);
3013 }
3014 
3015 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3016                                           const RegionCodeGenTy &TaskgroupOpGen,
3017                                           SourceLocation Loc) {
3018   if (!CGF.HaveInsertPoint())
3019     return;
3020   // __kmpc_taskgroup(ident_t *, gtid);
3021   // TaskgroupOpGen();
3022   // __kmpc_end_taskgroup(ident_t *, gtid);
3023   // Prepare arguments and build a call to __kmpc_taskgroup
3024   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3025   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3026                         createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3027                         Args);
3028   TaskgroupOpGen.setAction(Action);
3029   emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
3030 }
3031 
3032 /// Given an array of pointers to variables, project the address of a
3033 /// given variable.
3034 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3035                                       unsigned Index, const VarDecl *Var) {
3036   // Pull out the pointer to the variable.
3037   Address PtrAddr =
3038       CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
3039   llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3040 
3041   Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
3042   Addr = CGF.Builder.CreateElementBitCast(
3043       Addr, CGF.ConvertTypeForMem(Var->getType()));
3044   return Addr;
3045 }
3046 
3047 static llvm::Value *emitCopyprivateCopyFunction(
3048     CodeGenModule &CGM, llvm::Type *ArgsType,
3049     ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
3050     ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3051     SourceLocation Loc) {
3052   ASTContext &C = CGM.getContext();
3053   // void copy_func(void *LHSArg, void *RHSArg);
3054   FunctionArgList Args;
3055   ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3056                            ImplicitParamDecl::Other);
3057   ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3058                            ImplicitParamDecl::Other);
3059   Args.push_back(&LHSArg);
3060   Args.push_back(&RHSArg);
3061   const auto &CGFI =
3062       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3063   std::string Name =
3064       CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3065   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3066                                     llvm::GlobalValue::InternalLinkage, Name,
3067                                     &CGM.getModule());
3068   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3069   Fn->setDoesNotRecurse();
3070   CodeGenFunction CGF(CGM);
3071   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3072   // Dest = (void*[n])(LHSArg);
3073   // Src = (void*[n])(RHSArg);
3074   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3075       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3076       ArgsType), CGF.getPointerAlign());
3077   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3078       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3079       ArgsType), CGF.getPointerAlign());
3080   // *(Type0*)Dst[0] = *(Type0*)Src[0];
3081   // *(Type1*)Dst[1] = *(Type1*)Src[1];
3082   // ...
3083   // *(Typen*)Dst[n] = *(Typen*)Src[n];
3084   for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
3085     const auto *DestVar =
3086         cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
3087     Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3088 
3089     const auto *SrcVar =
3090         cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
3091     Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3092 
3093     const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
3094     QualType Type = VD->getType();
3095     CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
3096   }
3097   CGF.FinishFunction();
3098   return Fn;
3099 }
3100 
3101 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
3102                                        const RegionCodeGenTy &SingleOpGen,
3103                                        SourceLocation Loc,
3104                                        ArrayRef<const Expr *> CopyprivateVars,
3105                                        ArrayRef<const Expr *> SrcExprs,
3106                                        ArrayRef<const Expr *> DstExprs,
3107                                        ArrayRef<const Expr *> AssignmentOps) {
3108   if (!CGF.HaveInsertPoint())
3109     return;
3110   assert(CopyprivateVars.size() == SrcExprs.size() &&
3111          CopyprivateVars.size() == DstExprs.size() &&
3112          CopyprivateVars.size() == AssignmentOps.size());
3113   ASTContext &C = CGM.getContext();
3114   // int32 did_it = 0;
3115   // if(__kmpc_single(ident_t *, gtid)) {
3116   //   SingleOpGen();
3117   //   __kmpc_end_single(ident_t *, gtid);
3118   //   did_it = 1;
3119   // }
3120   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3121   // <copy_func>, did_it);
3122 
3123   Address DidIt = Address::invalid();
3124   if (!CopyprivateVars.empty()) {
3125     // int32 did_it = 0;
3126     QualType KmpInt32Ty =
3127         C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3128     DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
3129     CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
3130   }
3131   // Prepare arguments and build a call to __kmpc_single
3132   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3133   CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3134                         createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3135                         /*Conditional=*/true);
3136   SingleOpGen.setAction(Action);
3137   emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3138   if (DidIt.isValid()) {
3139     // did_it = 1;
3140     CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3141   }
3142   Action.Done(CGF);
3143   // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3144   // <copy_func>, did_it);
3145   if (DidIt.isValid()) {
3146     llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
3147     QualType CopyprivateArrayTy =
3148         C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3149                                /*IndexTypeQuals=*/0);
3150     // Create a list of all private variables for copyprivate.
3151     Address CopyprivateList =
3152         CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3153     for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
3154       Address Elem = CGF.Builder.CreateConstArrayGEP(
3155           CopyprivateList, I, CGF.getPointerSize());
3156       CGF.Builder.CreateStore(
3157           CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3158               CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3159           Elem);
3160     }
3161     // Build function that copies private values from single region to all other
3162     // threads in the corresponding parallel region.
3163     llvm::Value *CpyFn = emitCopyprivateCopyFunction(
3164         CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
3165         CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
3166     llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
3167     Address CL =
3168       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3169                                                       CGF.VoidPtrTy);
3170     llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
3171     llvm::Value *Args[] = {
3172         emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3173         getThreadID(CGF, Loc),        // i32 <gtid>
3174         BufSize,                      // size_t <buf_size>
3175         CL.getPointer(),              // void *<copyprivate list>
3176         CpyFn,                        // void (*) (void *, void *) <copy_func>
3177         DidItVal                      // i32 did_it
3178     };
3179     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3180   }
3181 }
3182 
3183 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3184                                         const RegionCodeGenTy &OrderedOpGen,
3185                                         SourceLocation Loc, bool IsThreads) {
3186   if (!CGF.HaveInsertPoint())
3187     return;
3188   // __kmpc_ordered(ident_t *, gtid);
3189   // OrderedOpGen();
3190   // __kmpc_end_ordered(ident_t *, gtid);
3191   // Prepare arguments and build a call to __kmpc_ordered
3192   if (IsThreads) {
3193     llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3194     CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3195                           createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3196                           Args);
3197     OrderedOpGen.setAction(Action);
3198     emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3199     return;
3200   }
3201   emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3202 }
3203 
3204 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3205                                       OpenMPDirectiveKind Kind, bool EmitChecks,
3206                                       bool ForceSimpleCall) {
3207   if (!CGF.HaveInsertPoint())
3208     return;
3209   // Build call __kmpc_cancel_barrier(loc, thread_id);
3210   // Build call __kmpc_barrier(loc, thread_id);
3211   unsigned Flags;
3212   if (Kind == OMPD_for)
3213     Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3214   else if (Kind == OMPD_sections)
3215     Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3216   else if (Kind == OMPD_single)
3217     Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3218   else if (Kind == OMPD_barrier)
3219     Flags = OMP_IDENT_BARRIER_EXPL;
3220   else
3221     Flags = OMP_IDENT_BARRIER_IMPL;
3222   // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3223   // thread_id);
3224   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3225                          getThreadID(CGF, Loc)};
3226   if (auto *OMPRegionInfo =
3227           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
3228     if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
3229       llvm::Value *Result = CGF.EmitRuntimeCall(
3230           createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
3231       if (EmitChecks) {
3232         // if (__kmpc_cancel_barrier()) {
3233         //   exit from construct;
3234         // }
3235         llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3236         llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3237         llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
3238         CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3239         CGF.EmitBlock(ExitBB);
3240         //   exit from construct;
3241         CodeGenFunction::JumpDest CancelDestination =
3242             CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
3243         CGF.EmitBranchThroughCleanup(CancelDestination);
3244         CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3245       }
3246       return;
3247     }
3248   }
3249   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
3250 }
3251 
3252 /// \brief Map the OpenMP loop schedule to the runtime enumeration.
3253 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
3254                                           bool Chunked, bool Ordered) {
3255   switch (ScheduleKind) {
3256   case OMPC_SCHEDULE_static:
3257     return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3258                    : (Ordered ? OMP_ord_static : OMP_sch_static);
3259   case OMPC_SCHEDULE_dynamic:
3260     return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
3261   case OMPC_SCHEDULE_guided:
3262     return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
3263   case OMPC_SCHEDULE_runtime:
3264     return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3265   case OMPC_SCHEDULE_auto:
3266     return Ordered ? OMP_ord_auto : OMP_sch_auto;
3267   case OMPC_SCHEDULE_unknown:
3268     assert(!Chunked && "chunk was specified but schedule kind not known");
3269     return Ordered ? OMP_ord_static : OMP_sch_static;
3270   }
3271   llvm_unreachable("Unexpected runtime schedule");
3272 }
3273 
3274 /// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3275 static OpenMPSchedType
3276 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3277   // only static is allowed for dist_schedule
3278   return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3279 }
3280 
3281 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3282                                          bool Chunked) const {
3283   OpenMPSchedType Schedule =
3284       getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3285   return Schedule == OMP_sch_static;
3286 }
3287 
3288 bool CGOpenMPRuntime::isStaticNonchunked(
3289     OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3290   OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3291   return Schedule == OMP_dist_sch_static;
3292 }
3293 
3294 
3295 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
3296   OpenMPSchedType Schedule =
3297       getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
3298   assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3299   return Schedule != OMP_sch_static;
3300 }
3301 
3302 static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3303                                   OpenMPScheduleClauseModifier M1,
3304                                   OpenMPScheduleClauseModifier M2) {
3305   int Modifier = 0;
3306   switch (M1) {
3307   case OMPC_SCHEDULE_MODIFIER_monotonic:
3308     Modifier = OMP_sch_modifier_monotonic;
3309     break;
3310   case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3311     Modifier = OMP_sch_modifier_nonmonotonic;
3312     break;
3313   case OMPC_SCHEDULE_MODIFIER_simd:
3314     if (Schedule == OMP_sch_static_chunked)
3315       Schedule = OMP_sch_static_balanced_chunked;
3316     break;
3317   case OMPC_SCHEDULE_MODIFIER_last:
3318   case OMPC_SCHEDULE_MODIFIER_unknown:
3319     break;
3320   }
3321   switch (M2) {
3322   case OMPC_SCHEDULE_MODIFIER_monotonic:
3323     Modifier = OMP_sch_modifier_monotonic;
3324     break;
3325   case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
3326     Modifier = OMP_sch_modifier_nonmonotonic;
3327     break;
3328   case OMPC_SCHEDULE_MODIFIER_simd:
3329     if (Schedule == OMP_sch_static_chunked)
3330       Schedule = OMP_sch_static_balanced_chunked;
3331     break;
3332   case OMPC_SCHEDULE_MODIFIER_last:
3333   case OMPC_SCHEDULE_MODIFIER_unknown:
3334     break;
3335   }
3336   return Schedule | Modifier;
3337 }
3338 
3339 void CGOpenMPRuntime::emitForDispatchInit(
3340     CodeGenFunction &CGF, SourceLocation Loc,
3341     const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3342     bool Ordered, const DispatchRTInput &DispatchValues) {
3343   if (!CGF.HaveInsertPoint())
3344     return;
3345   OpenMPSchedType Schedule = getRuntimeSchedule(
3346       ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
3347   assert(Ordered ||
3348          (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
3349           Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3350           Schedule != OMP_sch_static_balanced_chunked));
3351   // Call __kmpc_dispatch_init(
3352   //          ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3353   //          kmp_int[32|64] lower, kmp_int[32|64] upper,
3354   //          kmp_int[32|64] stride, kmp_int[32|64] chunk);
3355 
3356   // If the Chunk was not specified in the clause - use default value 1.
3357   llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3358                                             : CGF.Builder.getIntN(IVSize, 1);
3359   llvm::Value *Args[] = {
3360       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3361       CGF.Builder.getInt32(addMonoNonMonoModifier(
3362           Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
3363       DispatchValues.LB,                                // Lower
3364       DispatchValues.UB,                                // Upper
3365       CGF.Builder.getIntN(IVSize, 1),                   // Stride
3366       Chunk                                             // Chunk
3367   };
3368   CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3369 }
3370 
3371 static void emitForStaticInitCall(
3372     CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3373     llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3374     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
3375     const CGOpenMPRuntime::StaticRTInput &Values) {
3376   if (!CGF.HaveInsertPoint())
3377     return;
3378 
3379   assert(!Values.Ordered);
3380   assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3381          Schedule == OMP_sch_static_balanced_chunked ||
3382          Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3383          Schedule == OMP_dist_sch_static ||
3384          Schedule == OMP_dist_sch_static_chunked);
3385 
3386   // Call __kmpc_for_static_init(
3387   //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3388   //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3389   //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3390   //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
3391   llvm::Value *Chunk = Values.Chunk;
3392   if (Chunk == nullptr) {
3393     assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3394             Schedule == OMP_dist_sch_static) &&
3395            "expected static non-chunked schedule");
3396     // If the Chunk was not specified in the clause - use default value 1.
3397     Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3398   } else {
3399     assert((Schedule == OMP_sch_static_chunked ||
3400             Schedule == OMP_sch_static_balanced_chunked ||
3401             Schedule == OMP_ord_static_chunked ||
3402             Schedule == OMP_dist_sch_static_chunked) &&
3403            "expected static chunked schedule");
3404   }
3405   llvm::Value *Args[] = {
3406       UpdateLocation,
3407       ThreadId,
3408       CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3409                                                   M2)), // Schedule type
3410       Values.IL.getPointer(),                           // &isLastIter
3411       Values.LB.getPointer(),                           // &LB
3412       Values.UB.getPointer(),                           // &UB
3413       Values.ST.getPointer(),                           // &Stride
3414       CGF.Builder.getIntN(Values.IVSize, 1),            // Incr
3415       Chunk                                             // Chunk
3416   };
3417   CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3418 }
3419 
3420 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3421                                         SourceLocation Loc,
3422                                         OpenMPDirectiveKind DKind,
3423                                         const OpenMPScheduleTy &ScheduleKind,
3424                                         const StaticRTInput &Values) {
3425   OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3426       ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3427   assert(isOpenMPWorksharingDirective(DKind) &&
3428          "Expected loop-based or sections-based directive.");
3429   llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3430                                              isOpenMPLoopDirective(DKind)
3431                                                  ? OMP_IDENT_WORK_LOOP
3432                                                  : OMP_IDENT_WORK_SECTIONS);
3433   llvm::Value *ThreadId = getThreadID(CGF, Loc);
3434   llvm::Constant *StaticInitFunction =
3435       createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3436   emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3437                         ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
3438 }
3439 
3440 void CGOpenMPRuntime::emitDistributeStaticInit(
3441     CodeGenFunction &CGF, SourceLocation Loc,
3442     OpenMPDistScheduleClauseKind SchedKind,
3443     const CGOpenMPRuntime::StaticRTInput &Values) {
3444   OpenMPSchedType ScheduleNum =
3445       getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3446   llvm::Value *UpdatedLocation =
3447       emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
3448   llvm::Value *ThreadId = getThreadID(CGF, Loc);
3449   llvm::Constant *StaticInitFunction =
3450       createForStaticInitFunction(Values.IVSize, Values.IVSigned);
3451   emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3452                         ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3453                         OMPC_SCHEDULE_MODIFIER_unknown, Values);
3454 }
3455 
3456 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3457                                           SourceLocation Loc,
3458                                           OpenMPDirectiveKind DKind) {
3459   if (!CGF.HaveInsertPoint())
3460     return;
3461   // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
3462   llvm::Value *Args[] = {
3463       emitUpdateLocation(CGF, Loc,
3464                          isOpenMPDistributeDirective(DKind)
3465                              ? OMP_IDENT_WORK_DISTRIBUTE
3466                              : isOpenMPLoopDirective(DKind)
3467                                    ? OMP_IDENT_WORK_LOOP
3468                                    : OMP_IDENT_WORK_SECTIONS),
3469       getThreadID(CGF, Loc)};
3470   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3471                       Args);
3472 }
3473 
3474 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3475                                                  SourceLocation Loc,
3476                                                  unsigned IVSize,
3477                                                  bool IVSigned) {
3478   if (!CGF.HaveInsertPoint())
3479     return;
3480   // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
3481   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3482   CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3483 }
3484 
3485 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3486                                           SourceLocation Loc, unsigned IVSize,
3487                                           bool IVSigned, Address IL,
3488                                           Address LB, Address UB,
3489                                           Address ST) {
3490   // Call __kmpc_dispatch_next(
3491   //          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3492   //          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3493   //          kmp_int[32|64] *p_stride);
3494   llvm::Value *Args[] = {
3495       emitUpdateLocation(CGF, Loc),
3496       getThreadID(CGF, Loc),
3497       IL.getPointer(), // &isLastIter
3498       LB.getPointer(), // &Lower
3499       UB.getPointer(), // &Upper
3500       ST.getPointer()  // &Stride
3501   };
3502   llvm::Value *Call =
3503       CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3504   return CGF.EmitScalarConversion(
3505       Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
3506       CGF.getContext().BoolTy, Loc);
3507 }
3508 
3509 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3510                                            llvm::Value *NumThreads,
3511                                            SourceLocation Loc) {
3512   if (!CGF.HaveInsertPoint())
3513     return;
3514   // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3515   llvm::Value *Args[] = {
3516       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3517       CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
3518   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3519                       Args);
3520 }
3521 
3522 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3523                                          OpenMPProcBindClauseKind ProcBind,
3524                                          SourceLocation Loc) {
3525   if (!CGF.HaveInsertPoint())
3526     return;
3527   // Constants for proc bind value accepted by the runtime.
3528   enum ProcBindTy {
3529     ProcBindFalse = 0,
3530     ProcBindTrue,
3531     ProcBindMaster,
3532     ProcBindClose,
3533     ProcBindSpread,
3534     ProcBindIntel,
3535     ProcBindDefault
3536   } RuntimeProcBind;
3537   switch (ProcBind) {
3538   case OMPC_PROC_BIND_master:
3539     RuntimeProcBind = ProcBindMaster;
3540     break;
3541   case OMPC_PROC_BIND_close:
3542     RuntimeProcBind = ProcBindClose;
3543     break;
3544   case OMPC_PROC_BIND_spread:
3545     RuntimeProcBind = ProcBindSpread;
3546     break;
3547   case OMPC_PROC_BIND_unknown:
3548     llvm_unreachable("Unsupported proc_bind value.");
3549   }
3550   // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3551   llvm::Value *Args[] = {
3552       emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3553       llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3554   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3555 }
3556 
3557 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3558                                 SourceLocation Loc) {
3559   if (!CGF.HaveInsertPoint())
3560     return;
3561   // Build call void __kmpc_flush(ident_t *loc)
3562   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3563                       emitUpdateLocation(CGF, Loc));
3564 }
3565 
3566 namespace {
3567 /// \brief Indexes of fields for type kmp_task_t.
3568 enum KmpTaskTFields {
3569   /// \brief List of shared variables.
3570   KmpTaskTShareds,
3571   /// \brief Task routine.
3572   KmpTaskTRoutine,
3573   /// \brief Partition id for the untied tasks.
3574   KmpTaskTPartId,
3575   /// Function with call of destructors for private variables.
3576   Data1,
3577   /// Task priority.
3578   Data2,
3579   /// (Taskloops only) Lower bound.
3580   KmpTaskTLowerBound,
3581   /// (Taskloops only) Upper bound.
3582   KmpTaskTUpperBound,
3583   /// (Taskloops only) Stride.
3584   KmpTaskTStride,
3585   /// (Taskloops only) Is last iteration flag.
3586   KmpTaskTLastIter,
3587   /// (Taskloops only) Reduction data.
3588   KmpTaskTReductions,
3589 };
3590 } // anonymous namespace
3591 
3592 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3593   return OffloadEntriesTargetRegion.empty() &&
3594          OffloadEntriesDeviceGlobalVar.empty();
3595 }
3596 
3597 /// \brief Initialize target region entry.
3598 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3599     initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3600                                     StringRef ParentName, unsigned LineNum,
3601                                     unsigned Order) {
3602   assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3603                                              "only required for the device "
3604                                              "code generation.");
3605   OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
3606       OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3607                                    OMPTargetRegionEntryTargetRegion);
3608   ++OffloadingEntriesNum;
3609 }
3610 
3611 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3612     registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3613                                   StringRef ParentName, unsigned LineNum,
3614                                   llvm::Constant *Addr, llvm::Constant *ID,
3615                                   OMPTargetRegionEntryKind Flags) {
3616   // If we are emitting code for a target, the entry is already initialized,
3617   // only has to be registered.
3618   if (CGM.getLangOpts().OpenMPIsDevice) {
3619     if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3620       unsigned DiagID = CGM.getDiags().getCustomDiagID(
3621           DiagnosticsEngine::Error,
3622           "Unable to find target region on line '%0' in the device code.");
3623       CGM.getDiags().Report(DiagID) << LineNum;
3624       return;
3625     }
3626     auto &Entry =
3627         OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3628     assert(Entry.isValid() && "Entry not initialized!");
3629     Entry.setAddress(Addr);
3630     Entry.setID(ID);
3631     Entry.setFlags(Flags);
3632   } else {
3633     OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
3634     OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3635     ++OffloadingEntriesNum;
3636   }
3637 }
3638 
3639 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3640     unsigned DeviceID, unsigned FileID, StringRef ParentName,
3641     unsigned LineNum) const {
3642   auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3643   if (PerDevice == OffloadEntriesTargetRegion.end())
3644     return false;
3645   auto PerFile = PerDevice->second.find(FileID);
3646   if (PerFile == PerDevice->second.end())
3647     return false;
3648   auto PerParentName = PerFile->second.find(ParentName);
3649   if (PerParentName == PerFile->second.end())
3650     return false;
3651   auto PerLine = PerParentName->second.find(LineNum);
3652   if (PerLine == PerParentName->second.end())
3653     return false;
3654   // Fail if this entry is already registered.
3655   if (PerLine->second.getAddress() || PerLine->second.getID())
3656     return false;
3657   return true;
3658 }
3659 
3660 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3661     const OffloadTargetRegionEntryInfoActTy &Action) {
3662   // Scan all target region entries and perform the provided action.
3663   for (const auto &D : OffloadEntriesTargetRegion)
3664     for (const auto &F : D.second)
3665       for (const auto &P : F.second)
3666         for (const auto &L : P.second)
3667           Action(D.first, F.first, P.first(), L.first, L.second);
3668 }
3669 
3670 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3671     initializeDeviceGlobalVarEntryInfo(StringRef Name,
3672                                        OMPTargetGlobalVarEntryKind Flags,
3673                                        unsigned Order) {
3674   assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3675                                              "only required for the device "
3676                                              "code generation.");
3677   OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3678   ++OffloadingEntriesNum;
3679 }
3680 
3681 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3682     registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3683                                      CharUnits VarSize,
3684                                      OMPTargetGlobalVarEntryKind Flags,
3685                                      llvm::GlobalValue::LinkageTypes Linkage) {
3686   if (CGM.getLangOpts().OpenMPIsDevice) {
3687     auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3688     assert(Entry.isValid() && Entry.getFlags() == Flags &&
3689            "Entry not initialized!");
3690     assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3691            "Resetting with the new address.");
3692     if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3693       return;
3694     Entry.setAddress(Addr);
3695     Entry.setVarSize(VarSize);
3696     Entry.setLinkage(Linkage);
3697   } else {
3698     if (hasDeviceGlobalVarEntryInfo(VarName))
3699       return;
3700     OffloadEntriesDeviceGlobalVar.try_emplace(
3701         VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3702     ++OffloadingEntriesNum;
3703   }
3704 }
3705 
3706 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3707     actOnDeviceGlobalVarEntriesInfo(
3708         const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3709   // Scan all target region entries and perform the provided action.
3710   for (const auto &E : OffloadEntriesDeviceGlobalVar)
3711     Action(E.getKey(), E.getValue());
3712 }
3713 
3714 llvm::Function *
3715 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3716   // If we don't have entries or if we are emitting code for the device, we
3717   // don't need to do anything.
3718   if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3719     return nullptr;
3720 
3721   llvm::Module &M = CGM.getModule();
3722   ASTContext &C = CGM.getContext();
3723 
3724   // Get list of devices we care about
3725   const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
3726 
3727   // We should be creating an offloading descriptor only if there are devices
3728   // specified.
3729   assert(!Devices.empty() && "No OpenMP offloading devices??");
3730 
3731   // Create the external variables that will point to the begin and end of the
3732   // host entries section. These will be defined by the linker.
3733   llvm::Type *OffloadEntryTy =
3734       CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3735   std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
3736   auto *HostEntriesBegin = new llvm::GlobalVariable(
3737       M, OffloadEntryTy, /*isConstant=*/true,
3738       llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
3739       EntriesBeginName);
3740   std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3741   auto *HostEntriesEnd =
3742       new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3743                                llvm::GlobalValue::ExternalLinkage,
3744                                /*Initializer=*/nullptr, EntriesEndName);
3745 
3746   // Create all device images
3747   auto *DeviceImageTy = cast<llvm::StructType>(
3748       CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
3749   ConstantInitBuilder DeviceImagesBuilder(CGM);
3750   ConstantArrayBuilder DeviceImagesEntries =
3751       DeviceImagesBuilder.beginArray(DeviceImageTy);
3752 
3753   for (const llvm::Triple &Device : Devices) {
3754     StringRef T = Device.getTriple();
3755     std::string BeginName = getName({"omp_offloading", "img_start", ""});
3756     auto *ImgBegin = new llvm::GlobalVariable(
3757         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3758         /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3759     std::string EndName = getName({"omp_offloading", "img_end", ""});
3760     auto *ImgEnd = new llvm::GlobalVariable(
3761         M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
3762         /*Initializer=*/nullptr, Twine(EndName).concat(T));
3763 
3764     llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3765                               HostEntriesEnd};
3766     createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3767                                              DeviceImagesEntries);
3768   }
3769 
3770   // Create device images global array.
3771   std::string ImagesName = getName({"omp_offloading", "device_images"});
3772   llvm::GlobalVariable *DeviceImages =
3773       DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3774                                                 CGM.getPointerAlign(),
3775                                                 /*isConstant=*/true);
3776   DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3777 
3778   // This is a Zero array to be used in the creation of the constant expressions
3779   llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3780                              llvm::Constant::getNullValue(CGM.Int32Ty)};
3781 
3782   // Create the target region descriptor.
3783   llvm::Constant *Data[] = {
3784       llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3785       llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3786                                            DeviceImages, Index),
3787       HostEntriesBegin, HostEntriesEnd};
3788   std::string Descriptor = getName({"omp_offloading", "descriptor"});
3789   llvm::GlobalVariable *Desc = createConstantGlobalStruct(
3790       CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
3791 
3792   // Emit code to register or unregister the descriptor at execution
3793   // startup or closing, respectively.
3794 
3795   llvm::Function *UnRegFn;
3796   {
3797     FunctionArgList Args;
3798     ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3799     Args.push_back(&DummyPtr);
3800 
3801     CodeGenFunction CGF(CGM);
3802     // Disable debug info for global (de-)initializer because they are not part
3803     // of some particular construct.
3804     CGF.disableDebugInfo();
3805     const auto &FI =
3806         CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3807     llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3808     std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3809     UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
3810     CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3811     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3812                         Desc);
3813     CGF.FinishFunction();
3814   }
3815   llvm::Function *RegFn;
3816   {
3817     CodeGenFunction CGF(CGM);
3818     // Disable debug info for global (de-)initializer because they are not part
3819     // of some particular construct.
3820     CGF.disableDebugInfo();
3821     const auto &FI = CGM.getTypes().arrangeNullaryFunction();
3822     llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3823     std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3824     RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
3825     CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3826     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3827     // Create a variable to drive the registration and unregistration of the
3828     // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3829     ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3830                                   SourceLocation(), nullptr, C.CharTy,
3831                                   ImplicitParamDecl::Other);
3832     CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3833     CGF.FinishFunction();
3834   }
3835   if (CGM.supportsCOMDAT()) {
3836     // It is sufficient to call registration function only once, so create a
3837     // COMDAT group for registration/unregistration functions and associated
3838     // data. That would reduce startup time and code size. Registration
3839     // function serves as a COMDAT group key.
3840     llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
3841     RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3842     RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3843     RegFn->setComdat(ComdatKey);
3844     UnRegFn->setComdat(ComdatKey);
3845     DeviceImages->setComdat(ComdatKey);
3846     Desc->setComdat(ComdatKey);
3847   }
3848   return RegFn;
3849 }
3850 
3851 void CGOpenMPRuntime::createOffloadEntry(
3852     llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3853     llvm::GlobalValue::LinkageTypes Linkage) {
3854   StringRef Name = Addr->getName();
3855   llvm::Module &M = CGM.getModule();
3856   llvm::LLVMContext &C = M.getContext();
3857 
3858   // Create constant string with the name.
3859   llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3860 
3861   std::string StringName = getName({"omp_offloading", "entry_name"});
3862   auto *Str = new llvm::GlobalVariable(
3863       M, StrPtrInit->getType(), /*isConstant=*/true,
3864       llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
3865   Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3866 
3867   llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3868                             llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3869                             llvm::ConstantInt::get(CGM.SizeTy, Size),
3870                             llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3871                             llvm::ConstantInt::get(CGM.Int32Ty, 0)};
3872   std::string EntryName = getName({"omp_offloading", "entry", ""});
3873   llvm::GlobalVariable *Entry =
3874       createConstantGlobalStruct(CGM, getTgtOffloadEntryQTy(), Data,
3875                                  Twine(EntryName).concat(Name), Linkage);
3876 
3877   // The entry has to be created in the section the linker expects it to be.
3878   std::string Section = getName({"omp_offloading", "entries"});
3879   Entry->setSection(Section);
3880 }
3881 
3882 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3883   // Emit the offloading entries and metadata so that the device codegen side
3884   // can easily figure out what to emit. The produced metadata looks like
3885   // this:
3886   //
3887   // !omp_offload.info = !{!1, ...}
3888   //
3889   // Right now we only generate metadata for function that contain target
3890   // regions.
3891 
3892   // If we do not have entries, we don't need to do anything.
3893   if (OffloadEntriesInfoManager.empty())
3894     return;
3895 
3896   llvm::Module &M = CGM.getModule();
3897   llvm::LLVMContext &C = M.getContext();
3898   SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3899       OrderedEntries(OffloadEntriesInfoManager.size());
3900 
3901   // Auxiliary methods to create metadata values and strings.
3902   auto &&GetMDInt = [this](unsigned V) {
3903     return llvm::ConstantAsMetadata::get(
3904         llvm::ConstantInt::get(CGM.Int32Ty, V));
3905   };
3906 
3907   auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3908 
3909   // Create the offloading info metadata node.
3910   llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3911 
3912   // Create function that emits metadata for each target region entry;
3913   auto &&TargetRegionMetadataEmitter =
3914       [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3915           unsigned DeviceID, unsigned FileID, StringRef ParentName,
3916           unsigned Line,
3917           const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3918         // Generate metadata for target regions. Each entry of this metadata
3919         // contains:
3920         // - Entry 0 -> Kind of this type of metadata (0).
3921         // - Entry 1 -> Device ID of the file where the entry was identified.
3922         // - Entry 2 -> File ID of the file where the entry was identified.
3923         // - Entry 3 -> Mangled name of the function where the entry was
3924         // identified.
3925         // - Entry 4 -> Line in the file where the entry was identified.
3926         // - Entry 5 -> Order the entry was created.
3927         // The first element of the metadata node is the kind.
3928         llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3929                                  GetMDInt(FileID),      GetMDString(ParentName),
3930                                  GetMDInt(Line),        GetMDInt(E.getOrder())};
3931 
3932         // Save this entry in the right position of the ordered entries array.
3933         OrderedEntries[E.getOrder()] = &E;
3934 
3935         // Add metadata to the named metadata node.
3936         MD->addOperand(llvm::MDNode::get(C, Ops));
3937       };
3938 
3939   OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3940       TargetRegionMetadataEmitter);
3941 
3942   // Create function that emits metadata for each device global variable entry;
3943   auto &&DeviceGlobalVarMetadataEmitter =
3944       [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3945        MD](StringRef MangledName,
3946            const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3947                &E) {
3948         // Generate metadata for global variables. Each entry of this metadata
3949         // contains:
3950         // - Entry 0 -> Kind of this type of metadata (1).
3951         // - Entry 1 -> Mangled name of the variable.
3952         // - Entry 2 -> Declare target kind.
3953         // - Entry 3 -> Order the entry was created.
3954         // The first element of the metadata node is the kind.
3955         llvm::Metadata *Ops[] = {
3956             GetMDInt(E.getKind()), GetMDString(MangledName),
3957             GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3958 
3959         // Save this entry in the right position of the ordered entries array.
3960         OrderedEntries[E.getOrder()] = &E;
3961 
3962         // Add metadata to the named metadata node.
3963         MD->addOperand(llvm::MDNode::get(C, Ops));
3964       };
3965 
3966   OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3967       DeviceGlobalVarMetadataEmitter);
3968 
3969   for (const auto *E : OrderedEntries) {
3970     assert(E && "All ordered entries must exist!");
3971     if (const auto *CE =
3972             dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3973                 E)) {
3974       if (!CE->getID() || !CE->getAddress()) {
3975         unsigned DiagID = CGM.getDiags().getCustomDiagID(
3976             DiagnosticsEngine::Error,
3977             "Offloading entry for target region is incorect: either the "
3978             "address or the ID is invalid.");
3979         CGM.getDiags().Report(DiagID);
3980         continue;
3981       }
3982       createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
3983                          CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3984     } else if (const auto *CE =
3985                    dyn_cast<OffloadEntriesInfoManagerTy::
3986                                 OffloadEntryInfoDeviceGlobalVar>(E)) {
3987       if (!CE->getAddress()) {
3988         unsigned DiagID = CGM.getDiags().getCustomDiagID(
3989             DiagnosticsEngine::Error,
3990             "Offloading entry for declare target varible is inccorect: the "
3991             "address is invalid.");
3992         CGM.getDiags().Report(DiagID);
3993         continue;
3994       }
3995       createOffloadEntry(CE->getAddress(), CE->getAddress(),
3996                          CE->getVarSize().getQuantity(), CE->getFlags(),
3997                          CE->getLinkage());
3998     } else {
3999       llvm_unreachable("Unsupported entry kind.");
4000     }
4001   }
4002 }
4003 
4004 /// \brief Loads all the offload entries information from the host IR
4005 /// metadata.
4006 void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4007   // If we are in target mode, load the metadata from the host IR. This code has
4008   // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4009 
4010   if (!CGM.getLangOpts().OpenMPIsDevice)
4011     return;
4012 
4013   if (CGM.getLangOpts().OMPHostIRFile.empty())
4014     return;
4015 
4016   auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
4017   if (auto EC = Buf.getError()) {
4018     CGM.getDiags().Report(diag::err_cannot_open_file)
4019         << CGM.getLangOpts().OMPHostIRFile << EC.message();
4020     return;
4021   }
4022 
4023   llvm::LLVMContext C;
4024   auto ME = expectedToErrorOrAndEmitErrors(
4025       C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
4026 
4027   if (auto EC = ME.getError()) {
4028     unsigned DiagID = CGM.getDiags().getCustomDiagID(
4029         DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4030     CGM.getDiags().Report(DiagID)
4031         << CGM.getLangOpts().OMPHostIRFile << EC.message();
4032     return;
4033   }
4034 
4035   llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4036   if (!MD)
4037     return;
4038 
4039   for (llvm::MDNode *MN : MD->operands()) {
4040     auto &&GetMDInt = [MN](unsigned Idx) {
4041       auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
4042       return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4043     };
4044 
4045     auto &&GetMDString = [MN](unsigned Idx) {
4046       auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
4047       return V->getString();
4048     };
4049 
4050     switch (GetMDInt(0)) {
4051     default:
4052       llvm_unreachable("Unexpected metadata!");
4053       break;
4054     case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4055         OffloadingEntryInfoTargetRegion:
4056       OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
4057           /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4058           /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4059           /*Order=*/GetMDInt(5));
4060       break;
4061     case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4062         OffloadingEntryInfoDeviceGlobalVar:
4063       OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4064           /*MangledName=*/GetMDString(1),
4065           static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4066               /*Flags=*/GetMDInt(2)),
4067           /*Order=*/GetMDInt(3));
4068       break;
4069     }
4070   }
4071 }
4072 
4073 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4074   if (!KmpRoutineEntryPtrTy) {
4075     // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
4076     ASTContext &C = CGM.getContext();
4077     QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4078     FunctionProtoType::ExtProtoInfo EPI;
4079     KmpRoutineEntryPtrQTy = C.getPointerType(
4080         C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4081     KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4082   }
4083 }
4084 
4085 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
4086   // Make sure the type of the entry is already created. This is the type we
4087   // have to create:
4088   // struct __tgt_offload_entry{
4089   //   void      *addr;       // Pointer to the offload entry info.
4090   //                          // (function or global)
4091   //   char      *name;       // Name of the function or global.
4092   //   size_t     size;       // Size of the entry info (0 if it a function).
4093   //   int32_t    flags;      // Flags associated with the entry, e.g. 'link'.
4094   //   int32_t    reserved;   // Reserved, to use by the runtime library.
4095   // };
4096   if (TgtOffloadEntryQTy.isNull()) {
4097     ASTContext &C = CGM.getContext();
4098     RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
4099     RD->startDefinition();
4100     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4101     addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4102     addFieldToRecordDecl(C, RD, C.getSizeType());
4103     addFieldToRecordDecl(
4104         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4105     addFieldToRecordDecl(
4106         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4107     RD->completeDefinition();
4108     RD->addAttr(PackedAttr::CreateImplicit(C));
4109     TgtOffloadEntryQTy = C.getRecordType(RD);
4110   }
4111   return TgtOffloadEntryQTy;
4112 }
4113 
4114 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4115   // These are the types we need to build:
4116   // struct __tgt_device_image{
4117   // void   *ImageStart;       // Pointer to the target code start.
4118   // void   *ImageEnd;         // Pointer to the target code end.
4119   // // We also add the host entries to the device image, as it may be useful
4120   // // for the target runtime to have access to that information.
4121   // __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all
4122   //                                       // the entries.
4123   // __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
4124   //                                       // entries (non inclusive).
4125   // };
4126   if (TgtDeviceImageQTy.isNull()) {
4127     ASTContext &C = CGM.getContext();
4128     RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
4129     RD->startDefinition();
4130     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4131     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4132     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4133     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4134     RD->completeDefinition();
4135     TgtDeviceImageQTy = C.getRecordType(RD);
4136   }
4137   return TgtDeviceImageQTy;
4138 }
4139 
4140 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4141   // struct __tgt_bin_desc{
4142   //   int32_t              NumDevices;      // Number of devices supported.
4143   //   __tgt_device_image   *DeviceImages;   // Arrays of device images
4144   //                                         // (one per device).
4145   //   __tgt_offload_entry  *EntriesBegin;   // Begin of the table with all the
4146   //                                         // entries.
4147   //   __tgt_offload_entry  *EntriesEnd;     // End of the table with all the
4148   //                                         // entries (non inclusive).
4149   // };
4150   if (TgtBinaryDescriptorQTy.isNull()) {
4151     ASTContext &C = CGM.getContext();
4152     RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
4153     RD->startDefinition();
4154     addFieldToRecordDecl(
4155         C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4156     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4157     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4158     addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4159     RD->completeDefinition();
4160     TgtBinaryDescriptorQTy = C.getRecordType(RD);
4161   }
4162   return TgtBinaryDescriptorQTy;
4163 }
4164 
4165 namespace {
4166 struct PrivateHelpersTy {
4167   PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4168                    const VarDecl *PrivateElemInit)
4169       : Original(Original), PrivateCopy(PrivateCopy),
4170         PrivateElemInit(PrivateElemInit) {}
4171   const VarDecl *Original;
4172   const VarDecl *PrivateCopy;
4173   const VarDecl *PrivateElemInit;
4174 };
4175 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
4176 } // anonymous namespace
4177 
4178 static RecordDecl *
4179 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
4180   if (!Privates.empty()) {
4181     ASTContext &C = CGM.getContext();
4182     // Build struct .kmp_privates_t. {
4183     //         /*  private vars  */
4184     //       };
4185     RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
4186     RD->startDefinition();
4187     for (const auto &Pair : Privates) {
4188       const VarDecl *VD = Pair.second.Original;
4189       QualType Type = VD->getType().getNonReferenceType();
4190       FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
4191       if (VD->hasAttrs()) {
4192         for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4193              E(VD->getAttrs().end());
4194              I != E; ++I)
4195           FD->addAttr(*I);
4196       }
4197     }
4198     RD->completeDefinition();
4199     return RD;
4200   }
4201   return nullptr;
4202 }
4203 
4204 static RecordDecl *
4205 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4206                          QualType KmpInt32Ty,
4207                          QualType KmpRoutineEntryPointerQTy) {
4208   ASTContext &C = CGM.getContext();
4209   // Build struct kmp_task_t {
4210   //         void *              shareds;
4211   //         kmp_routine_entry_t routine;
4212   //         kmp_int32           part_id;
4213   //         kmp_cmplrdata_t data1;
4214   //         kmp_cmplrdata_t data2;
4215   // For taskloops additional fields:
4216   //         kmp_uint64          lb;
4217   //         kmp_uint64          ub;
4218   //         kmp_int64           st;
4219   //         kmp_int32           liter;
4220   //         void *              reductions;
4221   //       };
4222   RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
4223   UD->startDefinition();
4224   addFieldToRecordDecl(C, UD, KmpInt32Ty);
4225   addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4226   UD->completeDefinition();
4227   QualType KmpCmplrdataTy = C.getRecordType(UD);
4228   RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
4229   RD->startDefinition();
4230   addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4231   addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4232   addFieldToRecordDecl(C, RD, KmpInt32Ty);
4233   addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4234   addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4235   if (isOpenMPTaskLoopDirective(Kind)) {
4236     QualType KmpUInt64Ty =
4237         CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4238     QualType KmpInt64Ty =
4239         CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4240     addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4241     addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4242     addFieldToRecordDecl(C, RD, KmpInt64Ty);
4243     addFieldToRecordDecl(C, RD, KmpInt32Ty);
4244     addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4245   }
4246   RD->completeDefinition();
4247   return RD;
4248 }
4249 
4250 static RecordDecl *
4251 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
4252                                      ArrayRef<PrivateDataTy> Privates) {
4253   ASTContext &C = CGM.getContext();
4254   // Build struct kmp_task_t_with_privates {
4255   //         kmp_task_t task_data;
4256   //         .kmp_privates_t. privates;
4257   //       };
4258   RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
4259   RD->startDefinition();
4260   addFieldToRecordDecl(C, RD, KmpTaskTQTy);
4261   if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
4262     addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
4263   RD->completeDefinition();
4264   return RD;
4265 }
4266 
4267 /// \brief Emit a proxy function which accepts kmp_task_t as the second
4268 /// argument.
4269 /// \code
4270 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
4271 ///   TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
4272 ///   For taskloops:
4273 ///   tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4274 ///   tt->reductions, tt->shareds);
4275 ///   return 0;
4276 /// }
4277 /// \endcode
4278 static llvm::Value *
4279 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
4280                       OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4281                       QualType KmpTaskTWithPrivatesPtrQTy,
4282                       QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
4283                       QualType SharedsPtrTy, llvm::Value *TaskFunction,
4284                       llvm::Value *TaskPrivatesMap) {
4285   ASTContext &C = CGM.getContext();
4286   FunctionArgList Args;
4287   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4288                             ImplicitParamDecl::Other);
4289   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4290                                 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4291                                 ImplicitParamDecl::Other);
4292   Args.push_back(&GtidArg);
4293   Args.push_back(&TaskTypeArg);
4294   const auto &TaskEntryFnInfo =
4295       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4296   llvm::FunctionType *TaskEntryTy =
4297       CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
4298   std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4299   auto *TaskEntry = llvm::Function::Create(
4300       TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
4301   CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
4302   TaskEntry->setDoesNotRecurse();
4303   CodeGenFunction CGF(CGM);
4304   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4305                     Loc, Loc);
4306 
4307   // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
4308   // tt,
4309   // For taskloops:
4310   // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4311   // tt->task_data.shareds);
4312   llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
4313       CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
4314   LValue TDBase = CGF.EmitLoadOfPointerLValue(
4315       CGF.GetAddrOfLocalVar(&TaskTypeArg),
4316       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4317   const auto *KmpTaskTWithPrivatesQTyRD =
4318       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4319   LValue Base =
4320       CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4321   const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4322   auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4323   LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4324   llvm::Value *PartidParam = PartIdLVal.getPointer();
4325 
4326   auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4327   LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4328   llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4329       CGF.EmitLoadOfScalar(SharedsLVal, Loc),
4330       CGF.ConvertTypeForMem(SharedsPtrTy));
4331 
4332   auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4333   llvm::Value *PrivatesParam;
4334   if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4335     LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4336     PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4337         PrivatesLVal.getPointer(), CGF.VoidPtrTy);
4338   } else {
4339     PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4340   }
4341 
4342   llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4343                                TaskPrivatesMap,
4344                                CGF.Builder
4345                                    .CreatePointerBitCastOrAddrSpaceCast(
4346                                        TDBase.getAddress(), CGF.VoidPtrTy)
4347                                    .getPointer()};
4348   SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4349                                           std::end(CommonArgs));
4350   if (isOpenMPTaskLoopDirective(Kind)) {
4351     auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4352     LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4353     llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
4354     auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4355     LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4356     llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
4357     auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4358     LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4359     llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
4360     auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4361     LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4362     llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
4363     auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4364     LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4365     llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
4366     CallArgs.push_back(LBParam);
4367     CallArgs.push_back(UBParam);
4368     CallArgs.push_back(StParam);
4369     CallArgs.push_back(LIParam);
4370     CallArgs.push_back(RParam);
4371   }
4372   CallArgs.push_back(SharedsParam);
4373 
4374   CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4375                                                   CallArgs);
4376   CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4377                              CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
4378   CGF.FinishFunction();
4379   return TaskEntry;
4380 }
4381 
4382 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4383                                             SourceLocation Loc,
4384                                             QualType KmpInt32Ty,
4385                                             QualType KmpTaskTWithPrivatesPtrQTy,
4386                                             QualType KmpTaskTWithPrivatesQTy) {
4387   ASTContext &C = CGM.getContext();
4388   FunctionArgList Args;
4389   ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4390                             ImplicitParamDecl::Other);
4391   ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4392                                 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4393                                 ImplicitParamDecl::Other);
4394   Args.push_back(&GtidArg);
4395   Args.push_back(&TaskTypeArg);
4396   const auto &DestructorFnInfo =
4397       CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
4398   llvm::FunctionType *DestructorFnTy =
4399       CGM.getTypes().GetFunctionType(DestructorFnInfo);
4400   std::string Name =
4401       CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
4402   auto *DestructorFn =
4403       llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4404                              Name, &CGM.getModule());
4405   CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
4406                                     DestructorFnInfo);
4407   DestructorFn->setDoesNotRecurse();
4408   CodeGenFunction CGF(CGM);
4409   CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4410                     Args, Loc, Loc);
4411 
4412   LValue Base = CGF.EmitLoadOfPointerLValue(
4413       CGF.GetAddrOfLocalVar(&TaskTypeArg),
4414       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4415   const auto *KmpTaskTWithPrivatesQTyRD =
4416       cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4417   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4418   Base = CGF.EmitLValueForField(Base, *FI);
4419   for (const auto *Field :
4420        cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4421     if (QualType::DestructionKind DtorKind =
4422             Field->getType().isDestructedType()) {
4423       LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
4424       CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4425     }
4426   }
4427   CGF.FinishFunction();
4428   return DestructorFn;
4429 }
4430 
4431 /// \brief Emit a privates mapping function for correct handling of private and
4432 /// firstprivate variables.
4433 /// \code
4434 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4435 /// **noalias priv1,...,  <tyn> **noalias privn) {
4436 ///   *priv1 = &.privates.priv1;
4437 ///   ...;
4438 ///   *privn = &.privates.privn;
4439 /// }
4440 /// \endcode
4441 static llvm::Value *
4442 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
4443                                ArrayRef<const Expr *> PrivateVars,
4444                                ArrayRef<const Expr *> FirstprivateVars,
4445                                ArrayRef<const Expr *> LastprivateVars,
4446                                QualType PrivatesQTy,
4447                                ArrayRef<PrivateDataTy> Privates) {
4448   ASTContext &C = CGM.getContext();
4449   FunctionArgList Args;
4450   ImplicitParamDecl TaskPrivatesArg(
4451       C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4452       C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4453       ImplicitParamDecl::Other);
4454   Args.push_back(&TaskPrivatesArg);
4455   llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4456   unsigned Counter = 1;
4457   for (const Expr *E : PrivateVars) {
4458     Args.push_back(ImplicitParamDecl::Create(
4459         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4460         C.getPointerType(C.getPointerType(E->getType()))
4461             .withConst()
4462             .withRestrict(),
4463         ImplicitParamDecl::Other));
4464     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4465     PrivateVarsPos[VD] = Counter;
4466     ++Counter;
4467   }
4468   for (const Expr *E : FirstprivateVars) {
4469     Args.push_back(ImplicitParamDecl::Create(
4470         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4471         C.getPointerType(C.getPointerType(E->getType()))
4472             .withConst()
4473             .withRestrict(),
4474         ImplicitParamDecl::Other));
4475     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4476     PrivateVarsPos[VD] = Counter;
4477     ++Counter;
4478   }
4479   for (const Expr *E : LastprivateVars) {
4480     Args.push_back(ImplicitParamDecl::Create(
4481         C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4482         C.getPointerType(C.getPointerType(E->getType()))
4483             .withConst()
4484             .withRestrict(),
4485         ImplicitParamDecl::Other));
4486     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4487     PrivateVarsPos[VD] = Counter;
4488     ++Counter;
4489   }
4490   const auto &TaskPrivatesMapFnInfo =
4491       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4492   llvm::FunctionType *TaskPrivatesMapTy =
4493       CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4494   std::string Name =
4495       CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
4496   auto *TaskPrivatesMap = llvm::Function::Create(
4497       TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4498       &CGM.getModule());
4499   CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
4500                                     TaskPrivatesMapFnInfo);
4501   TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
4502   TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
4503   TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
4504   CodeGenFunction CGF(CGM);
4505   CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4506                     TaskPrivatesMapFnInfo, Args, Loc, Loc);
4507 
4508   // *privi = &.privates.privi;
4509   LValue Base = CGF.EmitLoadOfPointerLValue(
4510       CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4511       TaskPrivatesArg.getType()->castAs<PointerType>());
4512   const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4513   Counter = 0;
4514   for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4515     LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4516     const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4517     LValue RefLVal =
4518         CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4519     LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4520         RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
4521     CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
4522     ++Counter;
4523   }
4524   CGF.FinishFunction();
4525   return TaskPrivatesMap;
4526 }
4527 
4528 static bool stable_sort_comparator(const PrivateDataTy P1,
4529                                    const PrivateDataTy P2) {
4530   return P1.first > P2.first;
4531 }
4532 
4533 /// Emit initialization for private variables in task-based directives.
4534 static void emitPrivatesInit(CodeGenFunction &CGF,
4535                              const OMPExecutableDirective &D,
4536                              Address KmpTaskSharedsPtr, LValue TDBase,
4537                              const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4538                              QualType SharedsTy, QualType SharedsPtrTy,
4539                              const OMPTaskDataTy &Data,
4540                              ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4541   ASTContext &C = CGF.getContext();
4542   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4543   LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4544   OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4545                                  ? OMPD_taskloop
4546                                  : OMPD_task;
4547   const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4548   CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
4549   LValue SrcBase;
4550   bool IsTargetTask =
4551       isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4552       isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4553   // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4554   // PointersArray and SizesArray. The original variables for these arrays are
4555   // not captured and we get their addresses explicitly.
4556   if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4557       (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
4558     SrcBase = CGF.MakeAddrLValue(
4559         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4560             KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4561         SharedsTy);
4562   }
4563   FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4564   for (const PrivateDataTy &Pair : Privates) {
4565     const VarDecl *VD = Pair.second.PrivateCopy;
4566     const Expr *Init = VD->getAnyInitializer();
4567     if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4568                              !CGF.isTrivialInitializer(Init)))) {
4569       LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
4570       if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4571         const VarDecl *OriginalVD = Pair.second.Original;
4572         // Check if the variable is the target-based BasePointersArray,
4573         // PointersArray or SizesArray.
4574         LValue SharedRefLValue;
4575         QualType Type = OriginalVD->getType();
4576         const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
4577         if (IsTargetTask && !SharedField) {
4578           assert(isa<ImplicitParamDecl>(OriginalVD) &&
4579                  isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4580                  cast<CapturedDecl>(OriginalVD->getDeclContext())
4581                          ->getNumParams() == 0 &&
4582                  isa<TranslationUnitDecl>(
4583                      cast<CapturedDecl>(OriginalVD->getDeclContext())
4584                          ->getDeclContext()) &&
4585                  "Expected artificial target data variable.");
4586           SharedRefLValue =
4587               CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4588         } else {
4589           SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4590           SharedRefLValue = CGF.MakeAddrLValue(
4591               Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4592               SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4593               SharedRefLValue.getTBAAInfo());
4594         }
4595         if (Type->isArrayType()) {
4596           // Initialize firstprivate array.
4597           if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4598             // Perform simple memcpy.
4599             CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
4600           } else {
4601             // Initialize firstprivate array using element-by-element
4602             // initialization.
4603             CGF.EmitOMPAggregateAssign(
4604                 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4605                 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4606                                                   Address SrcElement) {
4607                   // Clean up any temporaries needed by the initialization.
4608                   CodeGenFunction::OMPPrivateScope InitScope(CGF);
4609                   InitScope.addPrivate(
4610                       Elem, [SrcElement]() -> Address { return SrcElement; });
4611                   (void)InitScope.Privatize();
4612                   // Emit initialization for single element.
4613                   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4614                       CGF, &CapturesInfo);
4615                   CGF.EmitAnyExprToMem(Init, DestElement,
4616                                        Init->getType().getQualifiers(),
4617                                        /*IsInitializer=*/false);
4618                 });
4619           }
4620         } else {
4621           CodeGenFunction::OMPPrivateScope InitScope(CGF);
4622           InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4623             return SharedRefLValue.getAddress();
4624           });
4625           (void)InitScope.Privatize();
4626           CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4627           CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4628                              /*capturedByInit=*/false);
4629         }
4630       } else {
4631         CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4632       }
4633     }
4634     ++FI;
4635   }
4636 }
4637 
4638 /// Check if duplication function is required for taskloops.
4639 static bool checkInitIsRequired(CodeGenFunction &CGF,
4640                                 ArrayRef<PrivateDataTy> Privates) {
4641   bool InitRequired = false;
4642   for (const PrivateDataTy &Pair : Privates) {
4643     const VarDecl *VD = Pair.second.PrivateCopy;
4644     const Expr *Init = VD->getAnyInitializer();
4645     InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4646                                     !CGF.isTrivialInitializer(Init));
4647     if (InitRequired)
4648       break;
4649   }
4650   return InitRequired;
4651 }
4652 
4653 
4654 /// Emit task_dup function (for initialization of
4655 /// private/firstprivate/lastprivate vars and last_iter flag)
4656 /// \code
4657 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4658 /// lastpriv) {
4659 /// // setup lastprivate flag
4660 ///    task_dst->last = lastpriv;
4661 /// // could be constructor calls here...
4662 /// }
4663 /// \endcode
4664 static llvm::Value *
4665 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4666                     const OMPExecutableDirective &D,
4667                     QualType KmpTaskTWithPrivatesPtrQTy,
4668                     const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4669                     const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4670                     QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4671                     ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4672   ASTContext &C = CGM.getContext();
4673   FunctionArgList Args;
4674   ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4675                            KmpTaskTWithPrivatesPtrQTy,
4676                            ImplicitParamDecl::Other);
4677   ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4678                            KmpTaskTWithPrivatesPtrQTy,
4679                            ImplicitParamDecl::Other);
4680   ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4681                                 ImplicitParamDecl::Other);
4682   Args.push_back(&DstArg);
4683   Args.push_back(&SrcArg);
4684   Args.push_back(&LastprivArg);
4685   const auto &TaskDupFnInfo =
4686       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4687   llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4688   std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4689   auto *TaskDup = llvm::Function::Create(
4690       TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
4691   CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
4692   TaskDup->setDoesNotRecurse();
4693   CodeGenFunction CGF(CGM);
4694   CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4695                     Loc);
4696 
4697   LValue TDBase = CGF.EmitLoadOfPointerLValue(
4698       CGF.GetAddrOfLocalVar(&DstArg),
4699       KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4700   // task_dst->liter = lastpriv;
4701   if (WithLastIter) {
4702     auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4703     LValue Base = CGF.EmitLValueForField(
4704         TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4705     LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4706     llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4707         CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4708     CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4709   }
4710 
4711   // Emit initial values for private copies (if any).
4712   assert(!Privates.empty());
4713   Address KmpTaskSharedsPtr = Address::invalid();
4714   if (!Data.FirstprivateVars.empty()) {
4715     LValue TDBase = CGF.EmitLoadOfPointerLValue(
4716         CGF.GetAddrOfLocalVar(&SrcArg),
4717         KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4718     LValue Base = CGF.EmitLValueForField(
4719         TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4720     KmpTaskSharedsPtr = Address(
4721         CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4722                                  Base, *std::next(KmpTaskTQTyRD->field_begin(),
4723                                                   KmpTaskTShareds)),
4724                              Loc),
4725         CGF.getNaturalTypeAlignment(SharedsTy));
4726   }
4727   emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4728                    SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
4729   CGF.FinishFunction();
4730   return TaskDup;
4731 }
4732 
4733 /// Checks if destructor function is required to be generated.
4734 /// \return true if cleanups are required, false otherwise.
4735 static bool
4736 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4737   bool NeedsCleanup = false;
4738   auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4739   const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4740   for (const FieldDecl *FD : PrivateRD->fields()) {
4741     NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4742     if (NeedsCleanup)
4743       break;
4744   }
4745   return NeedsCleanup;
4746 }
4747 
4748 CGOpenMPRuntime::TaskResultTy
4749 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4750                               const OMPExecutableDirective &D,
4751                               llvm::Value *TaskFunction, QualType SharedsTy,
4752                               Address Shareds, const OMPTaskDataTy &Data) {
4753   ASTContext &C = CGM.getContext();
4754   llvm::SmallVector<PrivateDataTy, 4> Privates;
4755   // Aggregate privates and sort them by the alignment.
4756   auto I = Data.PrivateCopies.begin();
4757   for (const Expr *E : Data.PrivateVars) {
4758     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4759     Privates.emplace_back(
4760         C.getDeclAlign(VD),
4761         PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4762                          /*PrivateElemInit=*/nullptr));
4763     ++I;
4764   }
4765   I = Data.FirstprivateCopies.begin();
4766   auto IElemInitRef = Data.FirstprivateInits.begin();
4767   for (const Expr *E : Data.FirstprivateVars) {
4768     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4769     Privates.emplace_back(
4770         C.getDeclAlign(VD),
4771         PrivateHelpersTy(
4772             VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4773             cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
4774     ++I;
4775     ++IElemInitRef;
4776   }
4777   I = Data.LastprivateCopies.begin();
4778   for (const Expr *E : Data.LastprivateVars) {
4779     const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4780     Privates.emplace_back(
4781         C.getDeclAlign(VD),
4782         PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4783                          /*PrivateElemInit=*/nullptr));
4784     ++I;
4785   }
4786   std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
4787   QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4788   // Build type kmp_routine_entry_t (if not built yet).
4789   emitKmpRoutineEntryT(KmpInt32Ty);
4790   // Build type kmp_task_t (if not built yet).
4791   if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4792     if (SavedKmpTaskloopTQTy.isNull()) {
4793       SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4794           CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4795     }
4796     KmpTaskTQTy = SavedKmpTaskloopTQTy;
4797   } else {
4798     assert((D.getDirectiveKind() == OMPD_task ||
4799             isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4800             isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4801            "Expected taskloop, task or target directive");
4802     if (SavedKmpTaskTQTy.isNull()) {
4803       SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4804           CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4805     }
4806     KmpTaskTQTy = SavedKmpTaskTQTy;
4807   }
4808   const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4809   // Build particular struct kmp_task_t for the given task.
4810   const RecordDecl *KmpTaskTWithPrivatesQTyRD =
4811       createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4812   QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4813   QualType KmpTaskTWithPrivatesPtrQTy =
4814       C.getPointerType(KmpTaskTWithPrivatesQTy);
4815   llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4816   llvm::Type *KmpTaskTWithPrivatesPtrTy =
4817       KmpTaskTWithPrivatesTy->getPointerTo();
4818   llvm::Value *KmpTaskTWithPrivatesTySize =
4819       CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
4820   QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4821 
4822   // Emit initial values for private copies (if any).
4823   llvm::Value *TaskPrivatesMap = nullptr;
4824   llvm::Type *TaskPrivatesMapTy =
4825       std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
4826   if (!Privates.empty()) {
4827     auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4828     TaskPrivatesMap = emitTaskPrivateMappingFunction(
4829         CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4830         FI->getType(), Privates);
4831     TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4832         TaskPrivatesMap, TaskPrivatesMapTy);
4833   } else {
4834     TaskPrivatesMap = llvm::ConstantPointerNull::get(
4835         cast<llvm::PointerType>(TaskPrivatesMapTy));
4836   }
4837   // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4838   // kmp_task_t *tt);
4839   llvm::Value *TaskEntry = emitProxyTaskFunction(
4840       CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4841       KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4842       TaskPrivatesMap);
4843 
4844   // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4845   // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4846   // kmp_routine_entry_t *task_entry);
4847   // Task flags. Format is taken from
4848   // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4849   // description of kmp_tasking_flags struct.
4850   enum {
4851     TiedFlag = 0x1,
4852     FinalFlag = 0x2,
4853     DestructorsFlag = 0x8,
4854     PriorityFlag = 0x20
4855   };
4856   unsigned Flags = Data.Tied ? TiedFlag : 0;
4857   bool NeedsCleanup = false;
4858   if (!Privates.empty()) {
4859     NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4860     if (NeedsCleanup)
4861       Flags = Flags | DestructorsFlag;
4862   }
4863   if (Data.Priority.getInt())
4864     Flags = Flags | PriorityFlag;
4865   llvm::Value *TaskFlags =
4866       Data.Final.getPointer()
4867           ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
4868                                      CGF.Builder.getInt32(FinalFlag),
4869                                      CGF.Builder.getInt32(/*C=*/0))
4870           : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
4871   TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
4872   llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
4873   llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4874                               getThreadID(CGF, Loc), TaskFlags,
4875                               KmpTaskTWithPrivatesTySize, SharedsSize,
4876                               CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4877                                   TaskEntry, KmpRoutineEntryPtrTy)};
4878   llvm::Value *NewTask = CGF.EmitRuntimeCall(
4879       createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
4880   llvm::Value *NewTaskNewTaskTTy =
4881       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4882           NewTask, KmpTaskTWithPrivatesPtrTy);
4883   LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4884                                                KmpTaskTWithPrivatesQTy);
4885   LValue TDBase =
4886       CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4887   // Fill the data in the resulting kmp_task_t record.
4888   // Copy shareds if there are any.
4889   Address KmpTaskSharedsPtr = Address::invalid();
4890   if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
4891     KmpTaskSharedsPtr =
4892         Address(CGF.EmitLoadOfScalar(
4893                     CGF.EmitLValueForField(
4894                         TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4895                                            KmpTaskTShareds)),
4896                     Loc),
4897                 CGF.getNaturalTypeAlignment(SharedsTy));
4898     LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4899     LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4900     CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
4901   }
4902   // Emit initial values for private copies (if any).
4903   TaskResultTy Result;
4904   if (!Privates.empty()) {
4905     emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4906                      SharedsTy, SharedsPtrTy, Data, Privates,
4907                      /*ForDup=*/false);
4908     if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4909         (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4910       Result.TaskDupFn = emitTaskDupFunction(
4911           CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4912           KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4913           /*WithLastIter=*/!Data.LastprivateVars.empty());
4914     }
4915   }
4916   // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4917   enum { Priority = 0, Destructors = 1 };
4918   // Provide pointer to function with destructors for privates.
4919   auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4920   const RecordDecl *KmpCmplrdataUD =
4921       (*FI)->getType()->getAsUnionType()->getDecl();
4922   if (NeedsCleanup) {
4923     llvm::Value *DestructorFn = emitDestructorsFunction(
4924         CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4925         KmpTaskTWithPrivatesQTy);
4926     LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4927     LValue DestructorsLV = CGF.EmitLValueForField(
4928         Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4929     CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4930                               DestructorFn, KmpRoutineEntryPtrTy),
4931                           DestructorsLV);
4932   }
4933   // Set priority.
4934   if (Data.Priority.getInt()) {
4935     LValue Data2LV = CGF.EmitLValueForField(
4936         TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4937     LValue PriorityLV = CGF.EmitLValueForField(
4938         Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4939     CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4940   }
4941   Result.NewTask = NewTask;
4942   Result.TaskEntry = TaskEntry;
4943   Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4944   Result.TDBase = TDBase;
4945   Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4946   return Result;
4947 }
4948 
4949 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4950                                    const OMPExecutableDirective &D,
4951                                    llvm::Value *TaskFunction,
4952                                    QualType SharedsTy, Address Shareds,
4953                                    const Expr *IfCond,
4954                                    const OMPTaskDataTy &Data) {
4955   if (!CGF.HaveInsertPoint())
4956     return;
4957 
4958   TaskResultTy Result =
4959       emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4960   llvm::Value *NewTask = Result.NewTask;
4961   llvm::Value *TaskEntry = Result.TaskEntry;
4962   llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4963   LValue TDBase = Result.TDBase;
4964   const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4965   ASTContext &C = CGM.getContext();
4966   // Process list of dependences.
4967   Address DependenciesArray = Address::invalid();
4968   unsigned NumDependencies = Data.Dependences.size();
4969   if (NumDependencies) {
4970     // Dependence kind for RTL.
4971     enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
4972     enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4973     RecordDecl *KmpDependInfoRD;
4974     QualType FlagsTy =
4975         C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4976     llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4977     if (KmpDependInfoTy.isNull()) {
4978       KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4979       KmpDependInfoRD->startDefinition();
4980       addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4981       addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4982       addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4983       KmpDependInfoRD->completeDefinition();
4984       KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
4985     } else {
4986       KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4987     }
4988     CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
4989     // Define type kmp_depend_info[<Dependences.size()>];
4990     QualType KmpDependInfoArrayTy = C.getConstantArrayType(
4991         KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
4992         ArrayType::Normal, /*IndexTypeQuals=*/0);
4993     // kmp_depend_info[<Dependences.size()>] deps;
4994     DependenciesArray =
4995         CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4996     for (unsigned I = 0; I < NumDependencies; ++I) {
4997       const Expr *E = Data.Dependences[I].second;
4998       LValue Addr = CGF.EmitLValue(E);
4999       llvm::Value *Size;
5000       QualType Ty = E->getType();
5001       if (const auto *ASE =
5002               dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
5003         LValue UpAddrLVal =
5004             CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5005         llvm::Value *UpAddr =
5006             CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
5007         llvm::Value *LowIntPtr =
5008             CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
5009         llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5010         Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
5011       } else {
5012         Size = CGF.getTypeSize(Ty);
5013       }
5014       LValue Base = CGF.MakeAddrLValue(
5015           CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
5016           KmpDependInfoTy);
5017       // deps[i].base_addr = &<Dependences[i].second>;
5018       LValue BaseAddrLVal = CGF.EmitLValueForField(
5019           Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
5020       CGF.EmitStoreOfScalar(
5021           CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5022           BaseAddrLVal);
5023       // deps[i].len = sizeof(<Dependences[i].second>);
5024       LValue LenLVal = CGF.EmitLValueForField(
5025           Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5026       CGF.EmitStoreOfScalar(Size, LenLVal);
5027       // deps[i].flags = <Dependences[i].first>;
5028       RTLDependenceKindTy DepKind;
5029       switch (Data.Dependences[I].first) {
5030       case OMPC_DEPEND_in:
5031         DepKind = DepIn;
5032         break;
5033       // Out and InOut dependencies must use the same code.
5034       case OMPC_DEPEND_out:
5035       case OMPC_DEPEND_inout:
5036         DepKind = DepInOut;
5037         break;
5038       case OMPC_DEPEND_source:
5039       case OMPC_DEPEND_sink:
5040       case OMPC_DEPEND_unknown:
5041         llvm_unreachable("Unknown task dependence type");
5042       }
5043       LValue FlagsLVal = CGF.EmitLValueForField(
5044           Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5045       CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5046                             FlagsLVal);
5047     }
5048     DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5049         CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
5050         CGF.VoidPtrTy);
5051   }
5052 
5053   // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
5054   // libcall.
5055   // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5056   // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5057   // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5058   // list is not empty
5059   llvm::Value *ThreadID = getThreadID(CGF, Loc);
5060   llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5061   llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5062   llvm::Value *DepTaskArgs[7];
5063   if (NumDependencies) {
5064     DepTaskArgs[0] = UpLoc;
5065     DepTaskArgs[1] = ThreadID;
5066     DepTaskArgs[2] = NewTask;
5067     DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5068     DepTaskArgs[4] = DependenciesArray.getPointer();
5069     DepTaskArgs[5] = CGF.Builder.getInt32(0);
5070     DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5071   }
5072   auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5073                         &TaskArgs,
5074                         &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
5075     if (!Data.Tied) {
5076       auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
5077       LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
5078       CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5079     }
5080     if (NumDependencies) {
5081       CGF.EmitRuntimeCall(
5082           createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
5083     } else {
5084       CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
5085                           TaskArgs);
5086     }
5087     // Check if parent region is untied and build return for untied task;
5088     if (auto *Region =
5089             dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5090       Region->emitUntiedSwitch(CGF);
5091   };
5092 
5093   llvm::Value *DepWaitTaskArgs[6];
5094   if (NumDependencies) {
5095     DepWaitTaskArgs[0] = UpLoc;
5096     DepWaitTaskArgs[1] = ThreadID;
5097     DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5098     DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5099     DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5100     DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5101   }
5102   auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
5103                         NumDependencies, &DepWaitTaskArgs,
5104                         Loc](CodeGenFunction &CGF, PrePostActionTy &) {
5105     CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
5106     CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5107     // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5108     // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5109     // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5110     // is specified.
5111     if (NumDependencies)
5112       CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
5113                           DepWaitTaskArgs);
5114     // Call proxy_task_entry(gtid, new_task);
5115     auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5116                       Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
5117       Action.Enter(CGF);
5118       llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
5119       CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
5120                                                           OutlinedFnArgs);
5121     };
5122 
5123     // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5124     // kmp_task_t *new_task);
5125     // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5126     // kmp_task_t *new_task);
5127     RegionCodeGenTy RCG(CodeGen);
5128     CommonActionTy Action(
5129         RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5130         RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5131     RCG.setAction(Action);
5132     RCG(CGF);
5133   };
5134 
5135   if (IfCond) {
5136     emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
5137   } else {
5138     RegionCodeGenTy ThenRCG(ThenCodeGen);
5139     ThenRCG(CGF);
5140   }
5141 }
5142 
5143 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5144                                        const OMPLoopDirective &D,
5145                                        llvm::Value *TaskFunction,
5146                                        QualType SharedsTy, Address Shareds,
5147                                        const Expr *IfCond,
5148                                        const OMPTaskDataTy &Data) {
5149   if (!CGF.HaveInsertPoint())
5150     return;
5151   TaskResultTy Result =
5152       emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5153   // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
5154   // libcall.
5155   // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5156   // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5157   // sched, kmp_uint64 grainsize, void *task_dup);
5158   llvm::Value *ThreadID = getThreadID(CGF, Loc);
5159   llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5160   llvm::Value *IfVal;
5161   if (IfCond) {
5162     IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5163                                       /*isSigned=*/true);
5164   } else {
5165     IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
5166   }
5167 
5168   LValue LBLVal = CGF.EmitLValueForField(
5169       Result.TDBase,
5170       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
5171   const auto *LBVar =
5172       cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5173   CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5174                        /*IsInitializer=*/true);
5175   LValue UBLVal = CGF.EmitLValueForField(
5176       Result.TDBase,
5177       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
5178   const auto *UBVar =
5179       cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5180   CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5181                        /*IsInitializer=*/true);
5182   LValue StLVal = CGF.EmitLValueForField(
5183       Result.TDBase,
5184       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
5185   const auto *StVar =
5186       cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5187   CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5188                        /*IsInitializer=*/true);
5189   // Store reductions address.
5190   LValue RedLVal = CGF.EmitLValueForField(
5191       Result.TDBase,
5192       *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
5193   if (Data.Reductions) {
5194     CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
5195   } else {
5196     CGF.EmitNullInitialization(RedLVal.getAddress(),
5197                                CGF.getContext().VoidPtrTy);
5198   }
5199   enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
5200   llvm::Value *TaskArgs[] = {
5201       UpLoc,
5202       ThreadID,
5203       Result.NewTask,
5204       IfVal,
5205       LBLVal.getPointer(),
5206       UBLVal.getPointer(),
5207       CGF.EmitLoadOfScalar(StLVal, Loc),
5208       llvm::ConstantInt::getNullValue(
5209           CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
5210       llvm::ConstantInt::getSigned(
5211           CGF.IntTy, Data.Schedule.getPointer()
5212                          ? Data.Schedule.getInt() ? NumTasks : Grainsize
5213                          : NoSchedule),
5214       Data.Schedule.getPointer()
5215           ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
5216                                       /*isSigned=*/false)
5217           : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
5218       Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5219                              Result.TaskDupFn, CGF.VoidPtrTy)
5220                        : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
5221   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5222 }
5223 
5224 /// \brief Emit reduction operation for each element of array (required for
5225 /// array sections) LHS op = RHS.
5226 /// \param Type Type of array.
5227 /// \param LHSVar Variable on the left side of the reduction operation
5228 /// (references element of array in original variable).
5229 /// \param RHSVar Variable on the right side of the reduction operation
5230 /// (references element of array in original variable).
5231 /// \param RedOpGen Generator of reduction operation with use of LHSVar and
5232 /// RHSVar.
5233 static void EmitOMPAggregateReduction(
5234     CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5235     const VarDecl *RHSVar,
5236     const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5237                                   const Expr *, const Expr *)> &RedOpGen,
5238     const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5239     const Expr *UpExpr = nullptr) {
5240   // Perform element-by-element initialization.
5241   QualType ElementTy;
5242   Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5243   Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5244 
5245   // Drill down to the base element type on both arrays.
5246   const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5247   llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
5248 
5249   llvm::Value *RHSBegin = RHSAddr.getPointer();
5250   llvm::Value *LHSBegin = LHSAddr.getPointer();
5251   // Cast from pointer to array type to pointer to single element.
5252   llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
5253   // The basic structure here is a while-do loop.
5254   llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5255   llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5256   llvm::Value *IsEmpty =
5257       CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5258   CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5259 
5260   // Enter the loop body, making that address the current address.
5261   llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
5262   CGF.EmitBlock(BodyBB);
5263 
5264   CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5265 
5266   llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5267       RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5268   RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5269   Address RHSElementCurrent =
5270       Address(RHSElementPHI,
5271               RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5272 
5273   llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5274       LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5275   LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5276   Address LHSElementCurrent =
5277       Address(LHSElementPHI,
5278               LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5279 
5280   // Emit copy.
5281   CodeGenFunction::OMPPrivateScope Scope(CGF);
5282   Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5283   Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
5284   Scope.Privatize();
5285   RedOpGen(CGF, XExpr, EExpr, UpExpr);
5286   Scope.ForceCleanup();
5287 
5288   // Shift the address forward by one element.
5289   llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
5290       LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
5291   llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
5292       RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5293   // Check whether we've reached the end.
5294   llvm::Value *Done =
5295       CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5296   CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5297   LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5298   RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5299 
5300   // Done.
5301   CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5302 }
5303 
5304 /// Emit reduction combiner. If the combiner is a simple expression emit it as
5305 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5306 /// UDR combiner function.
5307 static void emitReductionCombiner(CodeGenFunction &CGF,
5308                                   const Expr *ReductionOp) {
5309   if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5310     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5311       if (const auto *DRE =
5312               dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
5313         if (const auto *DRD =
5314                 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
5315           std::pair<llvm::Function *, llvm::Function *> Reduction =
5316               CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5317           RValue Func = RValue::get(Reduction.first);
5318           CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5319           CGF.EmitIgnoredExpr(ReductionOp);
5320           return;
5321         }
5322   CGF.EmitIgnoredExpr(ReductionOp);
5323 }
5324 
5325 llvm::Value *CGOpenMPRuntime::emitReductionFunction(
5326     CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5327     ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5328     ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
5329   ASTContext &C = CGM.getContext();
5330 
5331   // void reduction_func(void *LHSArg, void *RHSArg);
5332   FunctionArgList Args;
5333   ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5334                            ImplicitParamDecl::Other);
5335   ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5336                            ImplicitParamDecl::Other);
5337   Args.push_back(&LHSArg);
5338   Args.push_back(&RHSArg);
5339   const auto &CGFI =
5340       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5341   std::string Name = getName({"omp", "reduction", "reduction_func"});
5342   auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5343                                     llvm::GlobalValue::InternalLinkage, Name,
5344                                     &CGM.getModule());
5345   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
5346   Fn->setDoesNotRecurse();
5347   CodeGenFunction CGF(CGM);
5348   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
5349 
5350   // Dst = (void*[n])(LHSArg);
5351   // Src = (void*[n])(RHSArg);
5352   Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5353       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5354       ArgsType), CGF.getPointerAlign());
5355   Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5356       CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5357       ArgsType), CGF.getPointerAlign());
5358 
5359   //  ...
5360   //  *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5361   //  ...
5362   CodeGenFunction::OMPPrivateScope Scope(CGF);
5363   auto IPriv = Privates.begin();
5364   unsigned Idx = 0;
5365   for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
5366     const auto *RHSVar =
5367         cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5368     Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
5369       return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
5370     });
5371     const auto *LHSVar =
5372         cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5373     Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
5374       return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
5375     });
5376     QualType PrivTy = (*IPriv)->getType();
5377     if (PrivTy->isVariablyModifiedType()) {
5378       // Get array size and emit VLA type.
5379       ++Idx;
5380       Address Elem =
5381           CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5382       llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
5383       const VariableArrayType *VLA =
5384           CGF.getContext().getAsVariableArrayType(PrivTy);
5385       const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
5386       CodeGenFunction::OpaqueValueMapping OpaqueMap(
5387           CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
5388       CGF.EmitVariablyModifiedType(PrivTy);
5389     }
5390   }
5391   Scope.Privatize();
5392   IPriv = Privates.begin();
5393   auto ILHS = LHSExprs.begin();
5394   auto IRHS = RHSExprs.begin();
5395   for (const Expr *E : ReductionOps) {
5396     if ((*IPriv)->getType()->isArrayType()) {
5397       // Emit reduction for array section.
5398       const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5399       const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5400       EmitOMPAggregateReduction(
5401           CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5402           [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5403             emitReductionCombiner(CGF, E);
5404           });
5405     } else {
5406       // Emit reduction for array subscript or single variable.
5407       emitReductionCombiner(CGF, E);
5408     }
5409     ++IPriv;
5410     ++ILHS;
5411     ++IRHS;
5412   }
5413   Scope.ForceCleanup();
5414   CGF.FinishFunction();
5415   return Fn;
5416 }
5417 
5418 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5419                                                   const Expr *ReductionOp,
5420                                                   const Expr *PrivateRef,
5421                                                   const DeclRefExpr *LHS,
5422                                                   const DeclRefExpr *RHS) {
5423   if (PrivateRef->getType()->isArrayType()) {
5424     // Emit reduction for array section.
5425     const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5426     const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5427     EmitOMPAggregateReduction(
5428         CGF, PrivateRef->getType(), LHSVar, RHSVar,
5429         [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5430           emitReductionCombiner(CGF, ReductionOp);
5431         });
5432   } else {
5433     // Emit reduction for array subscript or single variable.
5434     emitReductionCombiner(CGF, ReductionOp);
5435   }
5436 }
5437 
5438 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
5439                                     ArrayRef<const Expr *> Privates,
5440                                     ArrayRef<const Expr *> LHSExprs,
5441                                     ArrayRef<const Expr *> RHSExprs,
5442                                     ArrayRef<const Expr *> ReductionOps,
5443                                     ReductionOptionsTy Options) {
5444   if (!CGF.HaveInsertPoint())
5445     return;
5446 
5447   bool WithNowait = Options.WithNowait;
5448   bool SimpleReduction = Options.SimpleReduction;
5449 
5450   // Next code should be emitted for reduction:
5451   //
5452   // static kmp_critical_name lock = { 0 };
5453   //
5454   // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5455   //  *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5456   //  ...
5457   //  *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5458   //  *(Type<n>-1*)rhs[<n>-1]);
5459   // }
5460   //
5461   // ...
5462   // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5463   // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5464   // RedList, reduce_func, &<lock>)) {
5465   // case 1:
5466   //  ...
5467   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5468   //  ...
5469   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5470   // break;
5471   // case 2:
5472   //  ...
5473   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5474   //  ...
5475   // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
5476   // break;
5477   // default:;
5478   // }
5479   //
5480   // if SimpleReduction is true, only the next code is generated:
5481   //  ...
5482   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5483   //  ...
5484 
5485   ASTContext &C = CGM.getContext();
5486 
5487   if (SimpleReduction) {
5488     CodeGenFunction::RunCleanupsScope Scope(CGF);
5489     auto IPriv = Privates.begin();
5490     auto ILHS = LHSExprs.begin();
5491     auto IRHS = RHSExprs.begin();
5492     for (const Expr *E : ReductionOps) {
5493       emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5494                                   cast<DeclRefExpr>(*IRHS));
5495       ++IPriv;
5496       ++ILHS;
5497       ++IRHS;
5498     }
5499     return;
5500   }
5501 
5502   // 1. Build a list of reduction variables.
5503   // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
5504   auto Size = RHSExprs.size();
5505   for (const Expr *E : Privates) {
5506     if (E->getType()->isVariablyModifiedType())
5507       // Reserve place for array size.
5508       ++Size;
5509   }
5510   llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
5511   QualType ReductionArrayTy =
5512       C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5513                              /*IndexTypeQuals=*/0);
5514   Address ReductionList =
5515       CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
5516   auto IPriv = Privates.begin();
5517   unsigned Idx = 0;
5518   for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
5519     Address Elem =
5520       CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
5521     CGF.Builder.CreateStore(
5522         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5523             CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5524         Elem);
5525     if ((*IPriv)->getType()->isVariablyModifiedType()) {
5526       // Store array size.
5527       ++Idx;
5528       Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5529                                              CGF.getPointerSize());
5530       llvm::Value *Size = CGF.Builder.CreateIntCast(
5531           CGF.getVLASize(
5532                  CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5533               .NumElts,
5534           CGF.SizeTy, /*isSigned=*/false);
5535       CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5536                               Elem);
5537     }
5538   }
5539 
5540   // 2. Emit reduce_func().
5541   llvm::Value *ReductionFn = emitReductionFunction(
5542       CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5543       Privates, LHSExprs, RHSExprs, ReductionOps);
5544 
5545   // 3. Create static kmp_critical_name lock = { 0 };
5546   std::string Name = getName({"reduction"});
5547   llvm::Value *Lock = getCriticalRegionLock(Name);
5548 
5549   // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5550   // RedList, reduce_func, &<lock>);
5551   llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5552   llvm::Value *ThreadId = getThreadID(CGF, Loc);
5553   llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5554   llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5555       ReductionList.getPointer(), CGF.VoidPtrTy);
5556   llvm::Value *Args[] = {
5557       IdentTLoc,                             // ident_t *<loc>
5558       ThreadId,                              // i32 <gtid>
5559       CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5560       ReductionArrayTySize,                  // size_type sizeof(RedList)
5561       RL,                                    // void *RedList
5562       ReductionFn, // void (*) (void *, void *) <reduce_func>
5563       Lock         // kmp_critical_name *&<lock>
5564   };
5565   llvm::Value *Res = CGF.EmitRuntimeCall(
5566       createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5567                                        : OMPRTL__kmpc_reduce),
5568       Args);
5569 
5570   // 5. Build switch(res)
5571   llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5572   llvm::SwitchInst *SwInst =
5573       CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5574 
5575   // 6. Build case 1:
5576   //  ...
5577   //  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5578   //  ...
5579   // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5580   // break;
5581   llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5582   SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5583   CGF.EmitBlock(Case1BB);
5584 
5585   // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5586   llvm::Value *EndArgs[] = {
5587       IdentTLoc, // ident_t *<loc>
5588       ThreadId,  // i32 <gtid>
5589       Lock       // kmp_critical_name *&<lock>
5590   };
5591   auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5592                        CodeGenFunction &CGF, PrePostActionTy &Action) {
5593     CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
5594     auto IPriv = Privates.begin();
5595     auto ILHS = LHSExprs.begin();
5596     auto IRHS = RHSExprs.begin();
5597     for (const Expr *E : ReductionOps) {
5598       RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5599                                      cast<DeclRefExpr>(*IRHS));
5600       ++IPriv;
5601       ++ILHS;
5602       ++IRHS;
5603     }
5604   };
5605   RegionCodeGenTy RCG(CodeGen);
5606   CommonActionTy Action(
5607       nullptr, llvm::None,
5608       createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5609                                        : OMPRTL__kmpc_end_reduce),
5610       EndArgs);
5611   RCG.setAction(Action);
5612   RCG(CGF);
5613 
5614   CGF.EmitBranch(DefaultBB);
5615 
5616   // 7. Build case 2:
5617   //  ...
5618   //  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5619   //  ...
5620   // break;
5621   llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5622   SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5623   CGF.EmitBlock(Case2BB);
5624 
5625   auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5626                              CodeGenFunction &CGF, PrePostActionTy &Action) {
5627     auto ILHS = LHSExprs.begin();
5628     auto IRHS = RHSExprs.begin();
5629     auto IPriv = Privates.begin();
5630     for (const Expr *E : ReductionOps) {
5631       const Expr *XExpr = nullptr;
5632       const Expr *EExpr = nullptr;
5633       const Expr *UpExpr = nullptr;
5634       BinaryOperatorKind BO = BO_Comma;
5635       if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
5636         if (BO->getOpcode() == BO_Assign) {
5637           XExpr = BO->getLHS();
5638           UpExpr = BO->getRHS();
5639         }
5640       }
5641       // Try to emit update expression as a simple atomic.
5642       const Expr *RHSExpr = UpExpr;
5643       if (RHSExpr) {
5644         // Analyze RHS part of the whole expression.
5645         if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
5646                 RHSExpr->IgnoreParenImpCasts())) {
5647           // If this is a conditional operator, analyze its condition for
5648           // min/max reduction operator.
5649           RHSExpr = ACO->getCond();
5650         }
5651         if (const auto *BORHS =
5652                 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5653           EExpr = BORHS->getRHS();
5654           BO = BORHS->getOpcode();
5655         }
5656       }
5657       if (XExpr) {
5658         const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5659         auto &&AtomicRedGen = [BO, VD,
5660                                Loc](CodeGenFunction &CGF, const Expr *XExpr,
5661                                     const Expr *EExpr, const Expr *UpExpr) {
5662           LValue X = CGF.EmitLValue(XExpr);
5663           RValue E;
5664           if (EExpr)
5665             E = CGF.EmitAnyExpr(EExpr);
5666           CGF.EmitOMPAtomicSimpleUpdateExpr(
5667               X, E, BO, /*IsXLHSInRHSPart=*/true,
5668               llvm::AtomicOrdering::Monotonic, Loc,
5669               [&CGF, UpExpr, VD, Loc](RValue XRValue) {
5670                 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5671                 PrivateScope.addPrivate(
5672                     VD, [&CGF, VD, XRValue, Loc]() {
5673                       Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5674                       CGF.emitOMPSimpleStore(
5675                           CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5676                           VD->getType().getNonReferenceType(), Loc);
5677                       return LHSTemp;
5678                     });
5679                 (void)PrivateScope.Privatize();
5680                 return CGF.EmitAnyExpr(UpExpr);
5681               });
5682         };
5683         if ((*IPriv)->getType()->isArrayType()) {
5684           // Emit atomic reduction for array section.
5685           const auto *RHSVar =
5686               cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5687           EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5688                                     AtomicRedGen, XExpr, EExpr, UpExpr);
5689         } else {
5690           // Emit atomic reduction for array subscript or single variable.
5691           AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5692         }
5693       } else {
5694         // Emit as a critical region.
5695         auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5696                                            const Expr *, const Expr *) {
5697           CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
5698           std::string Name = RT.getName({"atomic_reduction"});
5699           RT.emitCriticalRegion(
5700               CGF, Name,
5701               [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5702                 Action.Enter(CGF);
5703                 emitReductionCombiner(CGF, E);
5704               },
5705               Loc);
5706         };
5707         if ((*IPriv)->getType()->isArrayType()) {
5708           const auto *LHSVar =
5709               cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5710           const auto *RHSVar =
5711               cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5712           EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5713                                     CritRedGen);
5714         } else {
5715           CritRedGen(CGF, nullptr, nullptr, nullptr);
5716         }
5717       }
5718       ++ILHS;
5719       ++IRHS;
5720       ++IPriv;
5721     }
5722   };
5723   RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5724   if (!WithNowait) {
5725     // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5726     llvm::Value *EndArgs[] = {
5727         IdentTLoc, // ident_t *<loc>
5728         ThreadId,  // i32 <gtid>
5729         Lock       // kmp_critical_name *&<lock>
5730     };
5731     CommonActionTy Action(nullptr, llvm::None,
5732                           createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5733                           EndArgs);
5734     AtomicRCG.setAction(Action);
5735     AtomicRCG(CGF);
5736   } else {
5737     AtomicRCG(CGF);
5738   }
5739 
5740   CGF.EmitBranch(DefaultBB);
5741   CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5742 }
5743 
5744 /// Generates unique name for artificial threadprivate variables.
5745 /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5746 static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5747                                       const Expr *Ref) {
5748   SmallString<256> Buffer;
5749   llvm::raw_svector_ostream Out(Buffer);
5750   const clang::DeclRefExpr *DE;
5751   const VarDecl *D = ::getBaseDecl(Ref, DE);
5752   if (!D)
5753     D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5754   D = D->getCanonicalDecl();
5755   std::string Name = CGM.getOpenMPRuntime().getName(
5756       {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5757   Out << Prefix << Name << "_"
5758       << D->getCanonicalDecl()->getLocStart().getRawEncoding();
5759   return Out.str();
5760 }
5761 
5762 /// Emits reduction initializer function:
5763 /// \code
5764 /// void @.red_init(void* %arg) {
5765 /// %0 = bitcast void* %arg to <type>*
5766 /// store <type> <init>, <type>* %0
5767 /// ret void
5768 /// }
5769 /// \endcode
5770 static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5771                                            SourceLocation Loc,
5772                                            ReductionCodeGen &RCG, unsigned N) {
5773   ASTContext &C = CGM.getContext();
5774   FunctionArgList Args;
5775   ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5776                           ImplicitParamDecl::Other);
5777   Args.emplace_back(&Param);
5778   const auto &FnInfo =
5779       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5780   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5781   std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
5782   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5783                                     Name, &CGM.getModule());
5784   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5785   Fn->setDoesNotRecurse();
5786   CodeGenFunction CGF(CGM);
5787   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5788   Address PrivateAddr = CGF.EmitLoadOfPointer(
5789       CGF.GetAddrOfLocalVar(&Param),
5790       C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5791   llvm::Value *Size = nullptr;
5792   // If the size of the reduction item is non-constant, load it from global
5793   // threadprivate variable.
5794   if (RCG.getSizes(N).second) {
5795     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5796         CGF, CGM.getContext().getSizeType(),
5797         generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5798     Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5799                                 CGM.getContext().getSizeType(), Loc);
5800   }
5801   RCG.emitAggregateType(CGF, N, Size);
5802   LValue SharedLVal;
5803   // If initializer uses initializer from declare reduction construct, emit a
5804   // pointer to the address of the original reduction item (reuired by reduction
5805   // initializer)
5806   if (RCG.usesReductionInitializer(N)) {
5807     Address SharedAddr =
5808         CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5809             CGF, CGM.getContext().VoidPtrTy,
5810             generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
5811     SharedAddr = CGF.EmitLoadOfPointer(
5812         SharedAddr,
5813         CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
5814     SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5815   } else {
5816     SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5817         llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5818         CGM.getContext().VoidPtrTy);
5819   }
5820   // Emit the initializer:
5821   // %0 = bitcast void* %arg to <type>*
5822   // store <type> <init>, <type>* %0
5823   RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5824                          [](CodeGenFunction &) { return false; });
5825   CGF.FinishFunction();
5826   return Fn;
5827 }
5828 
5829 /// Emits reduction combiner function:
5830 /// \code
5831 /// void @.red_comb(void* %arg0, void* %arg1) {
5832 /// %lhs = bitcast void* %arg0 to <type>*
5833 /// %rhs = bitcast void* %arg1 to <type>*
5834 /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5835 /// store <type> %2, <type>* %lhs
5836 /// ret void
5837 /// }
5838 /// \endcode
5839 static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5840                                            SourceLocation Loc,
5841                                            ReductionCodeGen &RCG, unsigned N,
5842                                            const Expr *ReductionOp,
5843                                            const Expr *LHS, const Expr *RHS,
5844                                            const Expr *PrivateRef) {
5845   ASTContext &C = CGM.getContext();
5846   const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5847   const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5848   FunctionArgList Args;
5849   ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5850                                C.VoidPtrTy, ImplicitParamDecl::Other);
5851   ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5852                             ImplicitParamDecl::Other);
5853   Args.emplace_back(&ParamInOut);
5854   Args.emplace_back(&ParamIn);
5855   const auto &FnInfo =
5856       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5857   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5858   std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
5859   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5860                                     Name, &CGM.getModule());
5861   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5862   Fn->setDoesNotRecurse();
5863   CodeGenFunction CGF(CGM);
5864   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5865   llvm::Value *Size = nullptr;
5866   // If the size of the reduction item is non-constant, load it from global
5867   // threadprivate variable.
5868   if (RCG.getSizes(N).second) {
5869     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5870         CGF, CGM.getContext().getSizeType(),
5871         generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5872     Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5873                                 CGM.getContext().getSizeType(), Loc);
5874   }
5875   RCG.emitAggregateType(CGF, N, Size);
5876   // Remap lhs and rhs variables to the addresses of the function arguments.
5877   // %lhs = bitcast void* %arg0 to <type>*
5878   // %rhs = bitcast void* %arg1 to <type>*
5879   CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5880   PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
5881     // Pull out the pointer to the variable.
5882     Address PtrAddr = CGF.EmitLoadOfPointer(
5883         CGF.GetAddrOfLocalVar(&ParamInOut),
5884         C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5885     return CGF.Builder.CreateElementBitCast(
5886         PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5887   });
5888   PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
5889     // Pull out the pointer to the variable.
5890     Address PtrAddr = CGF.EmitLoadOfPointer(
5891         CGF.GetAddrOfLocalVar(&ParamIn),
5892         C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5893     return CGF.Builder.CreateElementBitCast(
5894         PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5895   });
5896   PrivateScope.Privatize();
5897   // Emit the combiner body:
5898   // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5899   // store <type> %2, <type>* %lhs
5900   CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5901       CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5902       cast<DeclRefExpr>(RHS));
5903   CGF.FinishFunction();
5904   return Fn;
5905 }
5906 
5907 /// Emits reduction finalizer function:
5908 /// \code
5909 /// void @.red_fini(void* %arg) {
5910 /// %0 = bitcast void* %arg to <type>*
5911 /// <destroy>(<type>* %0)
5912 /// ret void
5913 /// }
5914 /// \endcode
5915 static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5916                                            SourceLocation Loc,
5917                                            ReductionCodeGen &RCG, unsigned N) {
5918   if (!RCG.needCleanups(N))
5919     return nullptr;
5920   ASTContext &C = CGM.getContext();
5921   FunctionArgList Args;
5922   ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5923                           ImplicitParamDecl::Other);
5924   Args.emplace_back(&Param);
5925   const auto &FnInfo =
5926       CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5927   llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5928   std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
5929   auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5930                                     Name, &CGM.getModule());
5931   CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
5932   Fn->setDoesNotRecurse();
5933   CodeGenFunction CGF(CGM);
5934   CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
5935   Address PrivateAddr = CGF.EmitLoadOfPointer(
5936       CGF.GetAddrOfLocalVar(&Param),
5937       C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5938   llvm::Value *Size = nullptr;
5939   // If the size of the reduction item is non-constant, load it from global
5940   // threadprivate variable.
5941   if (RCG.getSizes(N).second) {
5942     Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5943         CGF, CGM.getContext().getSizeType(),
5944         generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
5945     Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5946                                 CGM.getContext().getSizeType(), Loc);
5947   }
5948   RCG.emitAggregateType(CGF, N, Size);
5949   // Emit the finalizer body:
5950   // <destroy>(<type>* %0)
5951   RCG.emitCleanups(CGF, N, PrivateAddr);
5952   CGF.FinishFunction();
5953   return Fn;
5954 }
5955 
5956 llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5957     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5958     ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5959   if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5960     return nullptr;
5961 
5962   // Build typedef struct:
5963   // kmp_task_red_input {
5964   //   void *reduce_shar; // shared reduction item
5965   //   size_t reduce_size; // size of data item
5966   //   void *reduce_init; // data initialization routine
5967   //   void *reduce_fini; // data finalization routine
5968   //   void *reduce_comb; // data combiner routine
5969   //   kmp_task_red_flags_t flags; // flags for additional info from compiler
5970   // } kmp_task_red_input_t;
5971   ASTContext &C = CGM.getContext();
5972   RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5973   RD->startDefinition();
5974   const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5975   const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5976   const FieldDecl *InitFD  = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5977   const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5978   const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5979   const FieldDecl *FlagsFD = addFieldToRecordDecl(
5980       C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5981   RD->completeDefinition();
5982   QualType RDType = C.getRecordType(RD);
5983   unsigned Size = Data.ReductionVars.size();
5984   llvm::APInt ArraySize(/*numBits=*/64, Size);
5985   QualType ArrayRDType = C.getConstantArrayType(
5986       RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5987   // kmp_task_red_input_t .rd_input.[Size];
5988   Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5989   ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5990                        Data.ReductionOps);
5991   for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5992     // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5993     llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5994                            llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5995     llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5996         TaskRedInput.getPointer(), Idxs,
5997         /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5998         ".rd_input.gep.");
5999     LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6000     // ElemLVal.reduce_shar = &Shareds[Cnt];
6001     LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6002     RCG.emitSharedLValue(CGF, Cnt);
6003     llvm::Value *CastedShared =
6004         CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6005     CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6006     RCG.emitAggregateType(CGF, Cnt);
6007     llvm::Value *SizeValInChars;
6008     llvm::Value *SizeVal;
6009     std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6010     // We use delayed creation/initialization for VLAs, array sections and
6011     // custom reduction initializations. It is required because runtime does not
6012     // provide the way to pass the sizes of VLAs/array sections to
6013     // initializer/combiner/finalizer functions and does not pass the pointer to
6014     // original reduction item to the initializer. Instead threadprivate global
6015     // variables are used to store these values and use them in the functions.
6016     bool DelayedCreation = !!SizeVal;
6017     SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6018                                                /*isSigned=*/false);
6019     LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6020     CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6021     // ElemLVal.reduce_init = init;
6022     LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6023     llvm::Value *InitAddr =
6024         CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6025     CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6026     DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6027     // ElemLVal.reduce_fini = fini;
6028     LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6029     llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6030     llvm::Value *FiniAddr = Fini
6031                                 ? CGF.EmitCastToVoidPtr(Fini)
6032                                 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6033     CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6034     // ElemLVal.reduce_comb = comb;
6035     LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6036     llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6037         CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6038         RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6039     CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6040     // ElemLVal.flags = 0;
6041     LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6042     if (DelayedCreation) {
6043       CGF.EmitStoreOfScalar(
6044           llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6045           FlagsLVal);
6046     } else
6047       CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6048   }
6049   // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6050   // *data);
6051   llvm::Value *Args[] = {
6052       CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6053                                 /*isSigned=*/true),
6054       llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6055       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6056                                                       CGM.VoidPtrTy)};
6057   return CGF.EmitRuntimeCall(
6058       createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6059 }
6060 
6061 void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6062                                               SourceLocation Loc,
6063                                               ReductionCodeGen &RCG,
6064                                               unsigned N) {
6065   auto Sizes = RCG.getSizes(N);
6066   // Emit threadprivate global variable if the type is non-constant
6067   // (Sizes.second = nullptr).
6068   if (Sizes.second) {
6069     llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6070                                                      /*isSigned=*/false);
6071     Address SizeAddr = getAddrOfArtificialThreadPrivate(
6072         CGF, CGM.getContext().getSizeType(),
6073         generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
6074     CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6075   }
6076   // Store address of the original reduction item if custom initializer is used.
6077   if (RCG.usesReductionInitializer(N)) {
6078     Address SharedAddr = getAddrOfArtificialThreadPrivate(
6079         CGF, CGM.getContext().VoidPtrTy,
6080         generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
6081     CGF.Builder.CreateStore(
6082         CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6083             RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6084         SharedAddr, /*IsVolatile=*/false);
6085   }
6086 }
6087 
6088 Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6089                                               SourceLocation Loc,
6090                                               llvm::Value *ReductionsPtr,
6091                                               LValue SharedLVal) {
6092   // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6093   // *d);
6094   llvm::Value *Args[] = {
6095       CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6096                                 /*isSigned=*/true),
6097       ReductionsPtr,
6098       CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6099                                                       CGM.VoidPtrTy)};
6100   return Address(
6101       CGF.EmitRuntimeCall(
6102           createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6103       SharedLVal.getAlignment());
6104 }
6105 
6106 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6107                                        SourceLocation Loc) {
6108   if (!CGF.HaveInsertPoint())
6109     return;
6110   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6111   // global_tid);
6112   llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6113   // Ignore return result until untied tasks are supported.
6114   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
6115   if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6116     Region->emitUntiedSwitch(CGF);
6117 }
6118 
6119 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
6120                                            OpenMPDirectiveKind InnerKind,
6121                                            const RegionCodeGenTy &CodeGen,
6122                                            bool HasCancel) {
6123   if (!CGF.HaveInsertPoint())
6124     return;
6125   InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
6126   CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
6127 }
6128 
6129 namespace {
6130 enum RTCancelKind {
6131   CancelNoreq = 0,
6132   CancelParallel = 1,
6133   CancelLoop = 2,
6134   CancelSections = 3,
6135   CancelTaskgroup = 4
6136 };
6137 } // anonymous namespace
6138 
6139 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6140   RTCancelKind CancelKind = CancelNoreq;
6141   if (CancelRegion == OMPD_parallel)
6142     CancelKind = CancelParallel;
6143   else if (CancelRegion == OMPD_for)
6144     CancelKind = CancelLoop;
6145   else if (CancelRegion == OMPD_sections)
6146     CancelKind = CancelSections;
6147   else {
6148     assert(CancelRegion == OMPD_taskgroup);
6149     CancelKind = CancelTaskgroup;
6150   }
6151   return CancelKind;
6152 }
6153 
6154 void CGOpenMPRuntime::emitCancellationPointCall(
6155     CodeGenFunction &CGF, SourceLocation Loc,
6156     OpenMPDirectiveKind CancelRegion) {
6157   if (!CGF.HaveInsertPoint())
6158     return;
6159   // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6160   // global_tid, kmp_int32 cncl_kind);
6161   if (auto *OMPRegionInfo =
6162           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
6163     // For 'cancellation point taskgroup', the task region info may not have a
6164     // cancel. This may instead happen in another adjacent task.
6165     if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
6166       llvm::Value *Args[] = {
6167           emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6168           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6169       // Ignore return result until untied tasks are supported.
6170       llvm::Value *Result = CGF.EmitRuntimeCall(
6171           createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6172       // if (__kmpc_cancellationpoint()) {
6173       //   exit from construct;
6174       // }
6175       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6176       llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6177       llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
6178       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6179       CGF.EmitBlock(ExitBB);
6180       // exit from construct;
6181       CodeGenFunction::JumpDest CancelDest =
6182           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6183       CGF.EmitBranchThroughCleanup(CancelDest);
6184       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6185     }
6186   }
6187 }
6188 
6189 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
6190                                      const Expr *IfCond,
6191                                      OpenMPDirectiveKind CancelRegion) {
6192   if (!CGF.HaveInsertPoint())
6193     return;
6194   // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6195   // kmp_int32 cncl_kind);
6196   if (auto *OMPRegionInfo =
6197           dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
6198     auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6199                                                         PrePostActionTy &) {
6200       CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
6201       llvm::Value *Args[] = {
6202           RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
6203           CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6204       // Ignore return result until untied tasks are supported.
6205       llvm::Value *Result = CGF.EmitRuntimeCall(
6206           RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
6207       // if (__kmpc_cancel()) {
6208       //   exit from construct;
6209       // }
6210       llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6211       llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6212       llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
6213       CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6214       CGF.EmitBlock(ExitBB);
6215       // exit from construct;
6216       CodeGenFunction::JumpDest CancelDest =
6217           CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6218       CGF.EmitBranchThroughCleanup(CancelDest);
6219       CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6220     };
6221     if (IfCond) {
6222       emitOMPIfClause(CGF, IfCond, ThenGen,
6223                       [](CodeGenFunction &, PrePostActionTy &) {});
6224     } else {
6225       RegionCodeGenTy ThenRCG(ThenGen);
6226       ThenRCG(CGF);
6227     }
6228   }
6229 }
6230 
6231 void CGOpenMPRuntime::emitTargetOutlinedFunction(
6232     const OMPExecutableDirective &D, StringRef ParentName,
6233     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6234     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
6235   assert(!ParentName.empty() && "Invalid target region parent name!");
6236   emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6237                                    IsOffloadEntry, CodeGen);
6238 }
6239 
6240 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6241     const OMPExecutableDirective &D, StringRef ParentName,
6242     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6243     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
6244   // Create a unique name for the entry function using the source location
6245   // information of the current target region. The name will be something like:
6246   //
6247   // __omp_offloading_DD_FFFF_PP_lBB
6248   //
6249   // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
6250   // mangled name of the function that encloses the target region and BB is the
6251   // line number of the target region.
6252 
6253   unsigned DeviceID;
6254   unsigned FileID;
6255   unsigned Line;
6256   getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
6257                            Line);
6258   SmallString<64> EntryFnName;
6259   {
6260     llvm::raw_svector_ostream OS(EntryFnName);
6261     OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6262        << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
6263   }
6264 
6265   const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
6266 
6267   CodeGenFunction CGF(CGM, true);
6268   CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
6269   CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6270 
6271   OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
6272 
6273   // If this target outline function is not an offload entry, we don't need to
6274   // register it.
6275   if (!IsOffloadEntry)
6276     return;
6277 
6278   // The target region ID is used by the runtime library to identify the current
6279   // target region, so it only has to be unique and not necessarily point to
6280   // anything. It could be the pointer to the outlined function that implements
6281   // the target region, but we aren't using that so that the compiler doesn't
6282   // need to keep that, and could therefore inline the host function if proven
6283   // worthwhile during optimization. In the other hand, if emitting code for the
6284   // device, the ID has to be the function address so that it can retrieved from
6285   // the offloading entry and launched by the runtime library. We also mark the
6286   // outlined function to have external linkage in case we are emitting code for
6287   // the device, because these functions will be entry points to the device.
6288 
6289   if (CGM.getLangOpts().OpenMPIsDevice) {
6290     OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
6291     OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
6292     OutlinedFn->setDSOLocal(false);
6293   } else {
6294     std::string Name = getName({"omp_offload", "region_id"});
6295     OutlinedFnID = new llvm::GlobalVariable(
6296         CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
6297         llvm::GlobalValue::PrivateLinkage,
6298         llvm::Constant::getNullValue(CGM.Int8Ty), Name);
6299   }
6300 
6301   // Register the information for the entry associated with this target region.
6302   OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
6303       DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
6304       OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
6305 }
6306 
6307 /// discard all CompoundStmts intervening between two constructs
6308 static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
6309   while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
6310     Body = CS->body_front();
6311 
6312   return Body;
6313 }
6314 
6315 /// Emit the number of teams for a target directive.  Inspect the num_teams
6316 /// clause associated with a teams construct combined or closely nested
6317 /// with the target directive.
6318 ///
6319 /// Emit a team of size one for directives such as 'target parallel' that
6320 /// have no associated teams construct.
6321 ///
6322 /// Otherwise, return nullptr.
6323 static llvm::Value *
6324 emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6325                                CodeGenFunction &CGF,
6326                                const OMPExecutableDirective &D) {
6327   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6328                                               "teams directive expected to be "
6329                                               "emitted only for the host!");
6330 
6331   CGBuilderTy &Bld = CGF.Builder;
6332 
6333   // If the target directive is combined with a teams directive:
6334   //   Return the value in the num_teams clause, if any.
6335   //   Otherwise, return 0 to denote the runtime default.
6336   if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6337     if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6338       CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
6339       llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6340                                                  /*IgnoreResultAssign*/ true);
6341       return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6342                                /*IsSigned=*/true);
6343     }
6344 
6345     // The default value is 0.
6346     return Bld.getInt32(0);
6347   }
6348 
6349   // If the target directive is combined with a parallel directive but not a
6350   // teams directive, start one team.
6351   if (isOpenMPParallelDirective(D.getDirectiveKind()))
6352     return Bld.getInt32(1);
6353 
6354   // If the current target region has a teams region enclosed, we need to get
6355   // the number of teams to pass to the runtime function call. This is done
6356   // by generating the expression in a inlined region. This is required because
6357   // the expression is captured in the enclosing target environment when the
6358   // teams directive is not combined with target.
6359 
6360   const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
6361 
6362   if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
6363           ignoreCompoundStmts(CS.getCapturedStmt()))) {
6364     if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6365       if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
6366         CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6367         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6368         llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6369         return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6370                                  /*IsSigned=*/true);
6371       }
6372 
6373       // If we have an enclosed teams directive but no num_teams clause we use
6374       // the default value 0.
6375       return Bld.getInt32(0);
6376     }
6377   }
6378 
6379   // No teams associated with the directive.
6380   return nullptr;
6381 }
6382 
6383 /// Emit the number of threads for a target directive.  Inspect the
6384 /// thread_limit clause associated with a teams construct combined or closely
6385 /// nested with the target directive.
6386 ///
6387 /// Emit the num_threads clause for directives such as 'target parallel' that
6388 /// have no associated teams construct.
6389 ///
6390 /// Otherwise, return nullptr.
6391 static llvm::Value *
6392 emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6393                                  CodeGenFunction &CGF,
6394                                  const OMPExecutableDirective &D) {
6395   assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6396                                               "teams directive expected to be "
6397                                               "emitted only for the host!");
6398 
6399   CGBuilderTy &Bld = CGF.Builder;
6400 
6401   //
6402   // If the target directive is combined with a teams directive:
6403   //   Return the value in the thread_limit clause, if any.
6404   //
6405   // If the target directive is combined with a parallel directive:
6406   //   Return the value in the num_threads clause, if any.
6407   //
6408   // If both clauses are set, select the minimum of the two.
6409   //
6410   // If neither teams or parallel combined directives set the number of threads
6411   // in a team, return 0 to denote the runtime default.
6412   //
6413   // If this is not a teams directive return nullptr.
6414 
6415   if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6416       isOpenMPParallelDirective(D.getDirectiveKind())) {
6417     llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6418     llvm::Value *NumThreadsVal = nullptr;
6419     llvm::Value *ThreadLimitVal = nullptr;
6420 
6421     if (const auto *ThreadLimitClause =
6422             D.getSingleClause<OMPThreadLimitClause>()) {
6423       CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6424       llvm::Value *ThreadLimit =
6425           CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6426                              /*IgnoreResultAssign*/ true);
6427       ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6428                                          /*IsSigned=*/true);
6429     }
6430 
6431     if (const auto *NumThreadsClause =
6432             D.getSingleClause<OMPNumThreadsClause>()) {
6433       CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6434       llvm::Value *NumThreads =
6435           CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6436                              /*IgnoreResultAssign*/ true);
6437       NumThreadsVal =
6438           Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6439     }
6440 
6441     // Select the lesser of thread_limit and num_threads.
6442     if (NumThreadsVal)
6443       ThreadLimitVal = ThreadLimitVal
6444                            ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6445                                                                 ThreadLimitVal),
6446                                               NumThreadsVal, ThreadLimitVal)
6447                            : NumThreadsVal;
6448 
6449     // Set default value passed to the runtime if either teams or a target
6450     // parallel type directive is found but no clause is specified.
6451     if (!ThreadLimitVal)
6452       ThreadLimitVal = DefaultThreadLimitVal;
6453 
6454     return ThreadLimitVal;
6455   }
6456 
6457   // If the current target region has a teams region enclosed, we need to get
6458   // the thread limit to pass to the runtime function call. This is done
6459   // by generating the expression in a inlined region. This is required because
6460   // the expression is captured in the enclosing target environment when the
6461   // teams directive is not combined with target.
6462 
6463   const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
6464 
6465   if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
6466           ignoreCompoundStmts(CS.getCapturedStmt()))) {
6467     if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6468       if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6469         CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6470         CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6471         llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6472         return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6473                                          /*IsSigned=*/true);
6474       }
6475 
6476       // If we have an enclosed teams directive but no thread_limit clause we
6477       // use the default value 0.
6478       return CGF.Builder.getInt32(0);
6479     }
6480   }
6481 
6482   // No teams associated with the directive.
6483   return nullptr;
6484 }
6485 
6486 namespace {
6487 // \brief Utility to handle information from clauses associated with a given
6488 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6489 // It provides a convenient interface to obtain the information and generate
6490 // code for that information.
6491 class MappableExprsHandler {
6492 public:
6493   /// \brief Values for bit flags used to specify the mapping type for
6494   /// offloading.
6495   enum OpenMPOffloadMappingFlags {
6496     /// \brief Allocate memory on the device and move data from host to device.
6497     OMP_MAP_TO = 0x01,
6498     /// \brief Allocate memory on the device and move data from device to host.
6499     OMP_MAP_FROM = 0x02,
6500     /// \brief Always perform the requested mapping action on the element, even
6501     /// if it was already mapped before.
6502     OMP_MAP_ALWAYS = 0x04,
6503     /// \brief Delete the element from the device environment, ignoring the
6504     /// current reference count associated with the element.
6505     OMP_MAP_DELETE = 0x08,
6506     /// \brief The element being mapped is a pointer-pointee pair; both the
6507     /// pointer and the pointee should be mapped.
6508     OMP_MAP_PTR_AND_OBJ = 0x10,
6509     /// \brief This flags signals that the base address of an entry should be
6510     /// passed to the target kernel as an argument.
6511     OMP_MAP_TARGET_PARAM = 0x20,
6512     /// \brief Signal that the runtime library has to return the device pointer
6513     /// in the current position for the data being mapped. Used when we have the
6514     /// use_device_ptr clause.
6515     OMP_MAP_RETURN_PARAM = 0x40,
6516     /// \brief This flag signals that the reference being passed is a pointer to
6517     /// private data.
6518     OMP_MAP_PRIVATE = 0x80,
6519     /// \brief Pass the element to the device by value.
6520     OMP_MAP_LITERAL = 0x100,
6521     /// Implicit map
6522     OMP_MAP_IMPLICIT = 0x200,
6523   };
6524 
6525   /// Class that associates information with a base pointer to be passed to the
6526   /// runtime library.
6527   class BasePointerInfo {
6528     /// The base pointer.
6529     llvm::Value *Ptr = nullptr;
6530     /// The base declaration that refers to this device pointer, or null if
6531     /// there is none.
6532     const ValueDecl *DevPtrDecl = nullptr;
6533 
6534   public:
6535     BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6536         : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6537     llvm::Value *operator*() const { return Ptr; }
6538     const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6539     void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6540   };
6541 
6542   typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
6543   typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
6544   typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
6545 
6546 private:
6547   /// \brief Directive from where the map clauses were extracted.
6548   const OMPExecutableDirective &CurDir;
6549 
6550   /// \brief Function the directive is being generated for.
6551   CodeGenFunction &CGF;
6552 
6553   /// \brief Set of all first private variables in the current directive.
6554   llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6555   /// Set of all reduction variables in the current directive.
6556   llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
6557 
6558   /// Map between device pointer declarations and their expression components.
6559   /// The key value for declarations in 'this' is null.
6560   llvm::DenseMap<
6561       const ValueDecl *,
6562       SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6563       DevPointersMap;
6564 
6565   llvm::Value *getExprTypeSize(const Expr *E) const {
6566     QualType ExprTy = E->getType().getCanonicalType();
6567 
6568     // Reference types are ignored for mapping purposes.
6569     if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
6570       ExprTy = RefTy->getPointeeType().getCanonicalType();
6571 
6572     // Given that an array section is considered a built-in type, we need to
6573     // do the calculation based on the length of the section instead of relying
6574     // on CGF.getTypeSize(E->getType()).
6575     if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6576       QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6577                             OAE->getBase()->IgnoreParenImpCasts())
6578                             .getCanonicalType();
6579 
6580       // If there is no length associated with the expression, that means we
6581       // are using the whole length of the base.
6582       if (!OAE->getLength() && OAE->getColonLoc().isValid())
6583         return CGF.getTypeSize(BaseTy);
6584 
6585       llvm::Value *ElemSize;
6586       if (const auto *PTy = BaseTy->getAs<PointerType>()) {
6587         ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6588       } else {
6589         const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6590         assert(ATy && "Expecting array type if not a pointer type.");
6591         ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6592       }
6593 
6594       // If we don't have a length at this point, that is because we have an
6595       // array section with a single element.
6596       if (!OAE->getLength())
6597         return ElemSize;
6598 
6599       llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6600       LengthVal =
6601           CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6602       return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6603     }
6604     return CGF.getTypeSize(ExprTy);
6605   }
6606 
6607   /// \brief Return the corresponding bits for a given map clause modifier. Add
6608   /// a flag marking the map as a pointer if requested. Add a flag marking the
6609   /// map as the first one of a series of maps that relate to the same map
6610   /// expression.
6611   uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
6612                           OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
6613                           bool AddIsTargetParamFlag) const {
6614     uint64_t Bits = 0u;
6615     switch (MapType) {
6616     case OMPC_MAP_alloc:
6617     case OMPC_MAP_release:
6618       // alloc and release is the default behavior in the runtime library,  i.e.
6619       // if we don't pass any bits alloc/release that is what the runtime is
6620       // going to do. Therefore, we don't need to signal anything for these two
6621       // type modifiers.
6622       break;
6623     case OMPC_MAP_to:
6624       Bits = OMP_MAP_TO;
6625       break;
6626     case OMPC_MAP_from:
6627       Bits = OMP_MAP_FROM;
6628       break;
6629     case OMPC_MAP_tofrom:
6630       Bits = OMP_MAP_TO | OMP_MAP_FROM;
6631       break;
6632     case OMPC_MAP_delete:
6633       Bits = OMP_MAP_DELETE;
6634       break;
6635     default:
6636       llvm_unreachable("Unexpected map type!");
6637       break;
6638     }
6639     if (AddPtrFlag)
6640       Bits |= OMP_MAP_PTR_AND_OBJ;
6641     if (AddIsTargetParamFlag)
6642       Bits |= OMP_MAP_TARGET_PARAM;
6643     if (MapTypeModifier == OMPC_MAP_always)
6644       Bits |= OMP_MAP_ALWAYS;
6645     return Bits;
6646   }
6647 
6648   /// \brief Return true if the provided expression is a final array section. A
6649   /// final array section, is one whose length can't be proved to be one.
6650   bool isFinalArraySectionExpression(const Expr *E) const {
6651     const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6652 
6653     // It is not an array section and therefore not a unity-size one.
6654     if (!OASE)
6655       return false;
6656 
6657     // An array section with no colon always refer to a single element.
6658     if (OASE->getColonLoc().isInvalid())
6659       return false;
6660 
6661     const Expr *Length = OASE->getLength();
6662 
6663     // If we don't have a length we have to check if the array has size 1
6664     // for this dimension. Also, we should always expect a length if the
6665     // base type is pointer.
6666     if (!Length) {
6667       QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6668                              OASE->getBase()->IgnoreParenImpCasts())
6669                              .getCanonicalType();
6670       if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6671         return ATy->getSize().getSExtValue() != 1;
6672       // If we don't have a constant dimension length, we have to consider
6673       // the current section as having any size, so it is not necessarily
6674       // unitary. If it happen to be unity size, that's user fault.
6675       return true;
6676     }
6677 
6678     // Check if the length evaluates to 1.
6679     llvm::APSInt ConstLength;
6680     if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6681       return true; // Can have more that size 1.
6682 
6683     return ConstLength.getSExtValue() != 1;
6684   }
6685 
6686   /// \brief Return the adjusted map modifiers if the declaration a capture
6687   /// refers to appears in a first-private clause. This is expected to be used
6688   /// only with directives that start with 'target'.
6689   unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6690                                                unsigned CurrentModifiers) {
6691     assert(Cap.capturesVariable() && "Expected capture by reference only!");
6692 
6693     // A first private variable captured by reference will use only the
6694     // 'private ptr' and 'map to' flag. Return the right flags if the captured
6695     // declaration is known as first-private in this handler.
6696     if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6697       return MappableExprsHandler::OMP_MAP_PRIVATE |
6698              MappableExprsHandler::OMP_MAP_TO;
6699     // Reduction variable  will use only the 'private ptr' and 'map to_from'
6700     // flag.
6701     if (ReductionDecls.count(Cap.getCapturedVar())) {
6702       return MappableExprsHandler::OMP_MAP_TO |
6703              MappableExprsHandler::OMP_MAP_FROM;
6704     }
6705 
6706     // We didn't modify anything.
6707     return CurrentModifiers;
6708   }
6709 
6710 public:
6711   MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6712       : CurDir(Dir), CGF(CGF) {
6713     // Extract firstprivate clause information.
6714     for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6715       for (const Expr *D : C->varlists())
6716         FirstPrivateDecls.insert(
6717             cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6718     for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6719       for (const Expr *D : C->varlists()) {
6720         ReductionDecls.insert(
6721             cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6722       }
6723     }
6724     // Extract device pointer clause information.
6725     for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6726       for (const auto &L : C->component_lists())
6727         DevPointersMap[L.first].push_back(L.second);
6728   }
6729 
6730   /// \brief Generate the base pointers, section pointers, sizes and map type
6731   /// bits for the provided map type, map modifier, and expression components.
6732   /// \a IsFirstComponent should be set to true if the provided set of
6733   /// components is the first associated with a capture.
6734   void generateInfoForComponentList(
6735       OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6736       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6737       MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
6738       MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6739       bool IsFirstComponentList, bool IsImplicit) const {
6740 
6741     // The following summarizes what has to be generated for each map and the
6742     // types below. The generated information is expressed in this order:
6743     // base pointer, section pointer, size, flags
6744     // (to add to the ones that come from the map type and modifier).
6745     //
6746     // double d;
6747     // int i[100];
6748     // float *p;
6749     //
6750     // struct S1 {
6751     //   int i;
6752     //   float f[50];
6753     // }
6754     // struct S2 {
6755     //   int i;
6756     //   float f[50];
6757     //   S1 s;
6758     //   double *p;
6759     //   struct S2 *ps;
6760     // }
6761     // S2 s;
6762     // S2 *ps;
6763     //
6764     // map(d)
6765     // &d, &d, sizeof(double), noflags
6766     //
6767     // map(i)
6768     // &i, &i, 100*sizeof(int), noflags
6769     //
6770     // map(i[1:23])
6771     // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6772     //
6773     // map(p)
6774     // &p, &p, sizeof(float*), noflags
6775     //
6776     // map(p[1:24])
6777     // p, &p[1], 24*sizeof(float), noflags
6778     //
6779     // map(s)
6780     // &s, &s, sizeof(S2), noflags
6781     //
6782     // map(s.i)
6783     // &s, &(s.i), sizeof(int), noflags
6784     //
6785     // map(s.s.f)
6786     // &s, &(s.i.f), 50*sizeof(int), noflags
6787     //
6788     // map(s.p)
6789     // &s, &(s.p), sizeof(double*), noflags
6790     //
6791     // map(s.p[:22], s.a s.b)
6792     // &s, &(s.p), sizeof(double*), noflags
6793     // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
6794     //
6795     // map(s.ps)
6796     // &s, &(s.ps), sizeof(S2*), noflags
6797     //
6798     // map(s.ps->s.i)
6799     // &s, &(s.ps), sizeof(S2*), noflags
6800     // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
6801     //
6802     // map(s.ps->ps)
6803     // &s, &(s.ps), sizeof(S2*), noflags
6804     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6805     //
6806     // map(s.ps->ps->ps)
6807     // &s, &(s.ps), sizeof(S2*), noflags
6808     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6809     // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
6810     //
6811     // map(s.ps->ps->s.f[:22])
6812     // &s, &(s.ps), sizeof(S2*), noflags
6813     // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6814     // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
6815     //
6816     // map(ps)
6817     // &ps, &ps, sizeof(S2*), noflags
6818     //
6819     // map(ps->i)
6820     // ps, &(ps->i), sizeof(int), noflags
6821     //
6822     // map(ps->s.f)
6823     // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6824     //
6825     // map(ps->p)
6826     // ps, &(ps->p), sizeof(double*), noflags
6827     //
6828     // map(ps->p[:22])
6829     // ps, &(ps->p), sizeof(double*), noflags
6830     // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
6831     //
6832     // map(ps->ps)
6833     // ps, &(ps->ps), sizeof(S2*), noflags
6834     //
6835     // map(ps->ps->s.i)
6836     // ps, &(ps->ps), sizeof(S2*), noflags
6837     // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
6838     //
6839     // map(ps->ps->ps)
6840     // ps, &(ps->ps), sizeof(S2*), noflags
6841     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6842     //
6843     // map(ps->ps->ps->ps)
6844     // ps, &(ps->ps), sizeof(S2*), noflags
6845     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6846     // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
6847     //
6848     // map(ps->ps->ps->s.f[:22])
6849     // ps, &(ps->ps), sizeof(S2*), noflags
6850     // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6851     // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
6852 
6853     // Track if the map information being generated is the first for a capture.
6854     bool IsCaptureFirstInfo = IsFirstComponentList;
6855     bool IsLink = false; // Is this variable a "declare target link"?
6856 
6857     // Scan the components from the base to the complete expression.
6858     auto CI = Components.rbegin();
6859     auto CE = Components.rend();
6860     auto I = CI;
6861 
6862     // Track if the map information being generated is the first for a list of
6863     // components.
6864     bool IsExpressionFirstInfo = true;
6865     llvm::Value *BP = nullptr;
6866 
6867     if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6868       // The base is the 'this' pointer. The content of the pointer is going
6869       // to be the base of the field being mapped.
6870       BP = CGF.EmitScalarExpr(ME->getBase());
6871     } else {
6872       // The base is the reference to the variable.
6873       // BP = &Var.
6874       BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
6875       if (const auto *VD =
6876               dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6877         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
6878             isDeclareTargetDeclaration(VD))
6879           if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6880             IsLink = true;
6881             BP = CGF.CGM.getOpenMPRuntime()
6882                      .getAddrOfDeclareTargetLink(VD)
6883                      .getPointer();
6884           }
6885       }
6886 
6887       // If the variable is a pointer and is being dereferenced (i.e. is not
6888       // the last component), the base has to be the pointer itself, not its
6889       // reference. References are ignored for mapping purposes.
6890       QualType Ty =
6891           I->getAssociatedDeclaration()->getType().getNonReferenceType();
6892       if (Ty->isAnyPointerType() && std::next(I) != CE) {
6893         LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
6894         BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
6895                                          Ty->castAs<PointerType>())
6896                  .getPointer();
6897 
6898         // We do not need to generate individual map information for the
6899         // pointer, it can be associated with the combined storage.
6900         ++I;
6901       }
6902     }
6903 
6904     uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
6905     for (; I != CE; ++I) {
6906       auto Next = std::next(I);
6907 
6908       // We need to generate the addresses and sizes if this is the last
6909       // component, if the component is a pointer or if it is an array section
6910       // whose length can't be proved to be one. If this is a pointer, it
6911       // becomes the base address for the following components.
6912 
6913       // A final array section, is one whose length can't be proved to be one.
6914       bool IsFinalArraySection =
6915           isFinalArraySectionExpression(I->getAssociatedExpression());
6916 
6917       // Get information on whether the element is a pointer. Have to do a
6918       // special treatment for array sections given that they are built-in
6919       // types.
6920       const auto *OASE =
6921           dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6922       bool IsPointer =
6923           (OASE &&
6924            OMPArraySectionExpr::getBaseOriginalType(OASE)
6925                .getCanonicalType()
6926                ->isAnyPointerType()) ||
6927           I->getAssociatedExpression()->getType()->isAnyPointerType();
6928 
6929       if (Next == CE || IsPointer || IsFinalArraySection) {
6930         // If this is not the last component, we expect the pointer to be
6931         // associated with an array expression or member expression.
6932         assert((Next == CE ||
6933                 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6934                 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6935                 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6936                "Unexpected expression");
6937 
6938         llvm::Value *LB =
6939             CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
6940         llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
6941 
6942         // If we have a member expression and the current component is a
6943         // reference, we have to map the reference too. Whenever we have a
6944         // reference, the section that reference refers to is going to be a
6945         // load instruction from the storage assigned to the reference.
6946         if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6947             I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6948           auto *LI = cast<llvm::LoadInst>(LB);
6949           llvm::Value *RefAddr = LI->getPointerOperand();
6950 
6951           BasePointers.push_back(BP);
6952           Pointers.push_back(RefAddr);
6953           Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6954           Types.push_back(DefaultFlags |
6955                           getMapTypeBits(
6956                               /*MapType*/ OMPC_MAP_alloc,
6957                               /*MapTypeModifier=*/OMPC_MAP_unknown,
6958                               !IsExpressionFirstInfo, IsCaptureFirstInfo));
6959           IsExpressionFirstInfo = false;
6960           IsCaptureFirstInfo = false;
6961           // The reference will be the next base address.
6962           BP = RefAddr;
6963         }
6964 
6965         BasePointers.push_back(BP);
6966         Pointers.push_back(LB);
6967         Sizes.push_back(Size);
6968 
6969         // We need to add a pointer flag for each map that comes from the
6970         // same expression except for the first one. We also need to signal
6971         // this map is the first one that relates with the current capture
6972         // (there is a set of entries for each capture).
6973         Types.push_back(DefaultFlags |
6974                         getMapTypeBits(MapType, MapTypeModifier,
6975                                        !IsExpressionFirstInfo || IsLink,
6976                                        IsCaptureFirstInfo && !IsLink));
6977 
6978         // If we have a final array section, we are done with this expression.
6979         if (IsFinalArraySection)
6980           break;
6981 
6982         // The pointer becomes the base for the next element.
6983         if (Next != CE)
6984           BP = LB;
6985 
6986         IsExpressionFirstInfo = false;
6987         IsCaptureFirstInfo = false;
6988       }
6989     }
6990   }
6991 
6992   /// \brief Generate all the base pointers, section pointers, sizes and map
6993   /// types for the extracted mappable expressions. Also, for each item that
6994   /// relates with a device pointer, a pair of the relevant declaration and
6995   /// index where it occurs is appended to the device pointers info array.
6996   void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
6997                        MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6998                        MapFlagsArrayTy &Types) const {
6999     BasePointers.clear();
7000     Pointers.clear();
7001     Sizes.clear();
7002     Types.clear();
7003 
7004     struct MapInfo {
7005       /// Kind that defines how a device pointer has to be returned.
7006       enum ReturnPointerKind {
7007         // Don't have to return any pointer.
7008         RPK_None,
7009         // Pointer is the base of the declaration.
7010         RPK_Base,
7011         // Pointer is a member of the base declaration - 'this'
7012         RPK_Member,
7013         // Pointer is a reference and a member of the base declaration - 'this'
7014         RPK_MemberReference,
7015       };
7016       OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7017       OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7018       OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
7019       ReturnPointerKind ReturnDevicePointer = RPK_None;
7020       bool IsImplicit = false;
7021 
7022       MapInfo() = default;
7023       MapInfo(
7024           OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7025           OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
7026           ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
7027           : Components(Components), MapType(MapType),
7028             MapTypeModifier(MapTypeModifier),
7029             ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
7030     };
7031 
7032     // We have to process the component lists that relate with the same
7033     // declaration in a single chunk so that we can generate the map flags
7034     // correctly. Therefore, we organize all lists in a map.
7035     llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
7036 
7037     // Helper function to fill the information map for the different supported
7038     // clauses.
7039     auto &&InfoGen = [&Info](
7040         const ValueDecl *D,
7041         OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7042         OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
7043         MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
7044       const ValueDecl *VD =
7045           D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
7046       Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7047                             IsImplicit);
7048     };
7049 
7050     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
7051     for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7052       for (const auto &L : C->component_lists()) {
7053         InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
7054                 MapInfo::RPK_None, C->isImplicit());
7055       }
7056     for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7057       for (const auto &L : C->component_lists()) {
7058         InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
7059                 MapInfo::RPK_None, C->isImplicit());
7060       }
7061     for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7062       for (const auto &L : C->component_lists()) {
7063         InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
7064                 MapInfo::RPK_None, C->isImplicit());
7065       }
7066 
7067     // Look at the use_device_ptr clause information and mark the existing map
7068     // entries as such. If there is no map information for an entry in the
7069     // use_device_ptr list, we create one with map type 'alloc' and zero size
7070     // section. It is the user fault if that was not mapped before.
7071     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
7072     for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7073       for (const auto &L : C->component_lists()) {
7074         assert(!L.second.empty() && "Not expecting empty list of components!");
7075         const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7076         VD = cast<ValueDecl>(VD->getCanonicalDecl());
7077         const Expr *IE = L.second.back().getAssociatedExpression();
7078         // If the first component is a member expression, we have to look into
7079         // 'this', which maps to null in the map of map information. Otherwise
7080         // look directly for the information.
7081         auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7082 
7083         // We potentially have map information for this declaration already.
7084         // Look for the first set of components that refer to it.
7085         if (It != Info.end()) {
7086           auto CI = std::find_if(
7087               It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7088                 return MI.Components.back().getAssociatedDeclaration() == VD;
7089               });
7090           // If we found a map entry, signal that the pointer has to be returned
7091           // and move on to the next declaration.
7092           if (CI != It->second.end()) {
7093             CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7094                                           ? (VD->getType()->isReferenceType()
7095                                                  ? MapInfo::RPK_MemberReference
7096                                                  : MapInfo::RPK_Member)
7097                                           : MapInfo::RPK_Base;
7098             continue;
7099           }
7100         }
7101 
7102         // We didn't find any match in our map information - generate a zero
7103         // size array section.
7104         // FIXME: MSVC 2013 seems to require this-> to find member CGF.
7105         llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7106                                                       IE->getExprLoc());
7107         BasePointers.push_back({Ptr, VD});
7108         Pointers.push_back(Ptr);
7109         Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7110         Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7111       }
7112 
7113     for (const auto &M : Info) {
7114       // We need to know when we generate information for the first component
7115       // associated with a capture, because the mapping flags depend on it.
7116       bool IsFirstComponentList = true;
7117       for (const MapInfo &L : M.second) {
7118         assert(!L.Components.empty() &&
7119                "Not expecting declaration with no component lists.");
7120 
7121         // Remember the current base pointer index.
7122         unsigned CurrentBasePointersIdx = BasePointers.size();
7123         // FIXME: MSVC 2013 seems to require this-> to find the member method.
7124         this->generateInfoForComponentList(
7125             L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7126             Sizes, Types, IsFirstComponentList, L.IsImplicit);
7127 
7128         // If this entry relates with a device pointer, set the relevant
7129         // declaration and add the 'return pointer' flag.
7130         if (IsFirstComponentList &&
7131             L.ReturnDevicePointer != MapInfo::RPK_None) {
7132           // If the pointer is not the base of the map, we need to skip the
7133           // base. If it is a reference in a member field, we also need to skip
7134           // the map of the reference.
7135           if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7136             ++CurrentBasePointersIdx;
7137             if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7138               ++CurrentBasePointersIdx;
7139           }
7140           assert(BasePointers.size() > CurrentBasePointersIdx &&
7141                  "Unexpected number of mapped base pointers.");
7142 
7143           const ValueDecl *RelevantVD =
7144               L.Components.back().getAssociatedDeclaration();
7145           assert(RelevantVD &&
7146                  "No relevant declaration related with device pointer??");
7147 
7148           BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7149           Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
7150         }
7151         IsFirstComponentList = false;
7152       }
7153     }
7154   }
7155 
7156   /// \brief Generate the base pointers, section pointers, sizes and map types
7157   /// associated to a given capture.
7158   void generateInfoForCapture(const CapturedStmt::Capture *Cap,
7159                               llvm::Value *Arg,
7160                               MapBaseValuesArrayTy &BasePointers,
7161                               MapValuesArrayTy &Pointers,
7162                               MapValuesArrayTy &Sizes,
7163                               MapFlagsArrayTy &Types) const {
7164     assert(!Cap->capturesVariableArrayType() &&
7165            "Not expecting to generate map info for a variable array type!");
7166 
7167     BasePointers.clear();
7168     Pointers.clear();
7169     Sizes.clear();
7170     Types.clear();
7171 
7172     // We need to know when we generating information for the first component
7173     // associated with a capture, because the mapping flags depend on it.
7174     bool IsFirstComponentList = true;
7175 
7176     const ValueDecl *VD =
7177         Cap->capturesThis()
7178             ? nullptr
7179             : Cap->getCapturedVar()->getCanonicalDecl();
7180 
7181     // If this declaration appears in a is_device_ptr clause we just have to
7182     // pass the pointer by value. If it is a reference to a declaration, we just
7183     // pass its value, otherwise, if it is a member expression, we need to map
7184     // 'to' the field.
7185     if (!VD) {
7186       auto It = DevPointersMap.find(VD);
7187       if (It != DevPointersMap.end()) {
7188         for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7189              It->second) {
7190           generateInfoForComponentList(
7191               /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
7192               BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7193               /*IsImplicit=*/false);
7194           IsFirstComponentList = false;
7195         }
7196         return;
7197       }
7198     } else if (DevPointersMap.count(VD)) {
7199       BasePointers.emplace_back(Arg, VD);
7200       Pointers.push_back(Arg);
7201       Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
7202       Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
7203       return;
7204     }
7205 
7206     // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
7207     for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7208       for (const auto &L : C->decl_component_lists(VD)) {
7209         assert(L.first == VD &&
7210                "We got information for the wrong declaration??");
7211         assert(!L.second.empty() &&
7212                "Not expecting declaration with no component lists.");
7213         generateInfoForComponentList(
7214             C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7215             Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
7216         IsFirstComponentList = false;
7217       }
7218 
7219     return;
7220   }
7221 
7222   /// \brief Generate the default map information for a given capture \a CI,
7223   /// record field declaration \a RI and captured value \a CV.
7224   void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7225                               const FieldDecl &RI, llvm::Value *CV,
7226                               MapBaseValuesArrayTy &CurBasePointers,
7227                               MapValuesArrayTy &CurPointers,
7228                               MapValuesArrayTy &CurSizes,
7229                               MapFlagsArrayTy &CurMapTypes) {
7230 
7231     // Do the default mapping.
7232     if (CI.capturesThis()) {
7233       CurBasePointers.push_back(CV);
7234       CurPointers.push_back(CV);
7235       const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
7236       CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7237       // Default map type.
7238       CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
7239     } else if (CI.capturesVariableByCopy()) {
7240       CurBasePointers.push_back(CV);
7241       CurPointers.push_back(CV);
7242       if (!RI.getType()->isAnyPointerType()) {
7243         // We have to signal to the runtime captures passed by value that are
7244         // not pointers.
7245         CurMapTypes.push_back(OMP_MAP_LITERAL);
7246         CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7247       } else {
7248         // Pointers are implicitly mapped with a zero size and no flags
7249         // (other than first map that is added for all implicit maps).
7250         CurMapTypes.push_back(0u);
7251         CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7252       }
7253     } else {
7254       assert(CI.capturesVariable() && "Expected captured reference.");
7255       CurBasePointers.push_back(CV);
7256       CurPointers.push_back(CV);
7257 
7258       const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
7259       QualType ElementType = PtrTy->getPointeeType();
7260       CurSizes.push_back(CGF.getTypeSize(ElementType));
7261       // The default map type for a scalar/complex type is 'to' because by
7262       // default the value doesn't have to be retrieved. For an aggregate
7263       // type, the default is 'tofrom'.
7264       CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7265           CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7266                                              : OMP_MAP_TO));
7267     }
7268     // Every default map produces a single argument which is a target parameter.
7269     CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
7270   }
7271 };
7272 
7273 enum OpenMPOffloadingReservedDeviceIDs {
7274   /// \brief Device ID if the device was not defined, runtime should get it
7275   /// from environment variables in the spec.
7276   OMP_DEVICEID_UNDEF = -1,
7277 };
7278 } // anonymous namespace
7279 
7280 /// \brief Emit the arrays used to pass the captures and map information to the
7281 /// offloading runtime library. If there is no map or capture information,
7282 /// return nullptr by reference.
7283 static void
7284 emitOffloadingArrays(CodeGenFunction &CGF,
7285                      MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
7286                      MappableExprsHandler::MapValuesArrayTy &Pointers,
7287                      MappableExprsHandler::MapValuesArrayTy &Sizes,
7288                      MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7289                      CGOpenMPRuntime::TargetDataInfo &Info) {
7290   CodeGenModule &CGM = CGF.CGM;
7291   ASTContext &Ctx = CGF.getContext();
7292 
7293   // Reset the array information.
7294   Info.clearArrayInfo();
7295   Info.NumberOfPtrs = BasePointers.size();
7296 
7297   if (Info.NumberOfPtrs) {
7298     // Detect if we have any capture size requiring runtime evaluation of the
7299     // size so that a constant array could be eventually used.
7300     bool hasRuntimeEvaluationCaptureSize = false;
7301     for (llvm::Value *S : Sizes)
7302       if (!isa<llvm::Constant>(S)) {
7303         hasRuntimeEvaluationCaptureSize = true;
7304         break;
7305       }
7306 
7307     llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
7308     QualType PointerArrayType =
7309         Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7310                                  /*IndexTypeQuals=*/0);
7311 
7312     Info.BasePointersArray =
7313         CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
7314     Info.PointersArray =
7315         CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7316 
7317     // If we don't have any VLA types or other types that require runtime
7318     // evaluation, we can use a constant array for the map sizes, otherwise we
7319     // need to fill up the arrays as we do for the pointers.
7320     if (hasRuntimeEvaluationCaptureSize) {
7321       QualType SizeArrayType = Ctx.getConstantArrayType(
7322           Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7323           /*IndexTypeQuals=*/0);
7324       Info.SizesArray =
7325           CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7326     } else {
7327       // We expect all the sizes to be constant, so we collect them to create
7328       // a constant array.
7329       SmallVector<llvm::Constant *, 16> ConstSizes;
7330       for (llvm::Value *S : Sizes)
7331         ConstSizes.push_back(cast<llvm::Constant>(S));
7332 
7333       auto *SizesArrayInit = llvm::ConstantArray::get(
7334           llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
7335       std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
7336       auto *SizesArrayGbl = new llvm::GlobalVariable(
7337           CGM.getModule(), SizesArrayInit->getType(),
7338           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7339           SizesArrayInit, Name);
7340       SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7341       Info.SizesArray = SizesArrayGbl;
7342     }
7343 
7344     // The map types are always constant so we don't need to generate code to
7345     // fill arrays. Instead, we create an array constant.
7346     llvm::Constant *MapTypesArrayInit =
7347         llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
7348     std::string MaptypesName =
7349         CGM.getOpenMPRuntime().getName({"offload_maptypes"});
7350     auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7351         CGM.getModule(), MapTypesArrayInit->getType(),
7352         /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7353         MapTypesArrayInit, MaptypesName);
7354     MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7355     Info.MapTypesArray = MapTypesArrayGbl;
7356 
7357     for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7358       llvm::Value *BPVal = *BasePointers[I];
7359       llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
7360           llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7361           Info.BasePointersArray, 0, I);
7362       BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7363           BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
7364       Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7365       CGF.Builder.CreateStore(BPVal, BPAddr);
7366 
7367       if (Info.requiresDevicePointerInfo())
7368         if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
7369           Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
7370 
7371       llvm::Value *PVal = Pointers[I];
7372       llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
7373           llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7374           Info.PointersArray, 0, I);
7375       P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7376           P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
7377       Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7378       CGF.Builder.CreateStore(PVal, PAddr);
7379 
7380       if (hasRuntimeEvaluationCaptureSize) {
7381         llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
7382             llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7383             Info.SizesArray,
7384             /*Idx0=*/0,
7385             /*Idx1=*/I);
7386         Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7387         CGF.Builder.CreateStore(
7388             CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
7389             SAddr);
7390       }
7391     }
7392   }
7393 }
7394 /// \brief Emit the arguments to be passed to the runtime library based on the
7395 /// arrays of pointers, sizes and map types.
7396 static void emitOffloadingArraysArgument(
7397     CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7398     llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
7399     llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
7400   CodeGenModule &CGM = CGF.CGM;
7401   if (Info.NumberOfPtrs) {
7402     BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
7403         llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7404         Info.BasePointersArray,
7405         /*Idx0=*/0, /*Idx1=*/0);
7406     PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
7407         llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7408         Info.PointersArray,
7409         /*Idx0=*/0,
7410         /*Idx1=*/0);
7411     SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
7412         llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
7413         /*Idx0=*/0, /*Idx1=*/0);
7414     MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
7415         llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
7416         Info.MapTypesArray,
7417         /*Idx0=*/0,
7418         /*Idx1=*/0);
7419   } else {
7420     BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7421     PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7422     SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7423     MapTypesArrayArg =
7424         llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
7425   }
7426 }
7427 
7428 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7429                                      const OMPExecutableDirective &D,
7430                                      llvm::Value *OutlinedFn,
7431                                      llvm::Value *OutlinedFnID,
7432                                      const Expr *IfCond, const Expr *Device) {
7433   if (!CGF.HaveInsertPoint())
7434     return;
7435 
7436   assert(OutlinedFn && "Invalid outlined function!");
7437 
7438   const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7439   llvm::SmallVector<llvm::Value *, 16> CapturedVars;
7440   const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
7441   auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7442                                             PrePostActionTy &) {
7443     CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7444   };
7445   emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
7446 
7447   CodeGenFunction::OMPTargetDataInfo InputInfo;
7448   llvm::Value *MapTypesArray = nullptr;
7449   // Fill up the pointer arrays and transfer execution to the device.
7450   auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7451                     &MapTypesArray, &CS, RequiresOuterTask,
7452                     &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
7453     // On top of the arrays that were filled up, the target offloading call
7454     // takes as arguments the device id as well as the host pointer. The host
7455     // pointer is used by the runtime library to identify the current target
7456     // region, so it only has to be unique and not necessarily point to
7457     // anything. It could be the pointer to the outlined function that
7458     // implements the target region, but we aren't using that so that the
7459     // compiler doesn't need to keep that, and could therefore inline the host
7460     // function if proven worthwhile during optimization.
7461 
7462     // From this point on, we need to have an ID of the target region defined.
7463     assert(OutlinedFnID && "Invalid outlined function ID!");
7464 
7465     // Emit device ID if any.
7466     llvm::Value *DeviceID;
7467     if (Device) {
7468       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7469                                            CGF.Int64Ty, /*isSigned=*/true);
7470     } else {
7471       DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7472     }
7473 
7474     // Emit the number of elements in the offloading arrays.
7475     llvm::Value *PointerNum =
7476         CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
7477 
7478     // Return value of the runtime offloading call.
7479     llvm::Value *Return;
7480 
7481     llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7482     llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
7483 
7484     bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
7485     // The target region is an outlined function launched by the runtime
7486     // via calls __tgt_target() or __tgt_target_teams().
7487     //
7488     // __tgt_target() launches a target region with one team and one thread,
7489     // executing a serial region.  This master thread may in turn launch
7490     // more threads within its team upon encountering a parallel region,
7491     // however, no additional teams can be launched on the device.
7492     //
7493     // __tgt_target_teams() launches a target region with one or more teams,
7494     // each with one or more threads.  This call is required for target
7495     // constructs such as:
7496     //  'target teams'
7497     //  'target' / 'teams'
7498     //  'target teams distribute parallel for'
7499     //  'target parallel'
7500     // and so on.
7501     //
7502     // Note that on the host and CPU targets, the runtime implementation of
7503     // these calls simply call the outlined function without forking threads.
7504     // The outlined functions themselves have runtime calls to
7505     // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7506     // the compiler in emitTeamsCall() and emitParallelCall().
7507     //
7508     // In contrast, on the NVPTX target, the implementation of
7509     // __tgt_target_teams() launches a GPU kernel with the requested number
7510     // of teams and threads so no additional calls to the runtime are required.
7511     if (NumTeams) {
7512       // If we have NumTeams defined this means that we have an enclosed teams
7513       // region. Therefore we also expect to have NumThreads defined. These two
7514       // values should be defined in the presence of a teams directive,
7515       // regardless of having any clauses associated. If the user is using teams
7516       // but no clauses, these two values will be the default that should be
7517       // passed to the runtime library - a 32-bit integer with the value zero.
7518       assert(NumThreads && "Thread limit expression should be available along "
7519                            "with number of teams.");
7520       llvm::Value *OffloadingArgs[] = {DeviceID,
7521                                        OutlinedFnID,
7522                                        PointerNum,
7523                                        InputInfo.BasePointersArray.getPointer(),
7524                                        InputInfo.PointersArray.getPointer(),
7525                                        InputInfo.SizesArray.getPointer(),
7526                                        MapTypesArray,
7527                                        NumTeams,
7528                                        NumThreads};
7529       Return = CGF.EmitRuntimeCall(
7530           createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7531                                           : OMPRTL__tgt_target_teams),
7532           OffloadingArgs);
7533     } else {
7534       llvm::Value *OffloadingArgs[] = {DeviceID,
7535                                        OutlinedFnID,
7536                                        PointerNum,
7537                                        InputInfo.BasePointersArray.getPointer(),
7538                                        InputInfo.PointersArray.getPointer(),
7539                                        InputInfo.SizesArray.getPointer(),
7540                                        MapTypesArray};
7541       Return = CGF.EmitRuntimeCall(
7542           createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7543                                           : OMPRTL__tgt_target),
7544           OffloadingArgs);
7545     }
7546 
7547     // Check the error code and execute the host version if required.
7548     llvm::BasicBlock *OffloadFailedBlock =
7549         CGF.createBasicBlock("omp_offload.failed");
7550     llvm::BasicBlock *OffloadContBlock =
7551         CGF.createBasicBlock("omp_offload.cont");
7552     llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7553     CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7554 
7555     CGF.EmitBlock(OffloadFailedBlock);
7556     if (RequiresOuterTask) {
7557       CapturedVars.clear();
7558       CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7559     }
7560     emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7561     CGF.EmitBranch(OffloadContBlock);
7562 
7563     CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
7564   };
7565 
7566   // Notify that the host version must be executed.
7567   auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7568                     RequiresOuterTask](CodeGenFunction &CGF,
7569                                        PrePostActionTy &) {
7570     if (RequiresOuterTask) {
7571       CapturedVars.clear();
7572       CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7573     }
7574     emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7575   };
7576 
7577   auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7578                           &CapturedVars, RequiresOuterTask,
7579                           &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7580     // Fill up the arrays with all the captured variables.
7581     MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7582     MappableExprsHandler::MapValuesArrayTy Pointers;
7583     MappableExprsHandler::MapValuesArrayTy Sizes;
7584     MappableExprsHandler::MapFlagsArrayTy MapTypes;
7585 
7586     MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7587     MappableExprsHandler::MapValuesArrayTy CurPointers;
7588     MappableExprsHandler::MapValuesArrayTy CurSizes;
7589     MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7590 
7591     // Get mappable expression information.
7592     MappableExprsHandler MEHandler(D, CGF);
7593 
7594     auto RI = CS.getCapturedRecordDecl()->field_begin();
7595     auto CV = CapturedVars.begin();
7596     for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7597                                               CE = CS.capture_end();
7598          CI != CE; ++CI, ++RI, ++CV) {
7599       CurBasePointers.clear();
7600       CurPointers.clear();
7601       CurSizes.clear();
7602       CurMapTypes.clear();
7603 
7604       // VLA sizes are passed to the outlined region by copy and do not have map
7605       // information associated.
7606       if (CI->capturesVariableArrayType()) {
7607         CurBasePointers.push_back(*CV);
7608         CurPointers.push_back(*CV);
7609         CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7610         // Copy to the device as an argument. No need to retrieve it.
7611         CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7612                               MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7613       } else {
7614         // If we have any information in the map clause, we use it, otherwise we
7615         // just do a default mapping.
7616         MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7617                                          CurSizes, CurMapTypes);
7618         if (CurBasePointers.empty())
7619           MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7620                                            CurPointers, CurSizes, CurMapTypes);
7621       }
7622       // We expect to have at least an element of information for this capture.
7623       assert(!CurBasePointers.empty() &&
7624              "Non-existing map pointer for capture!");
7625       assert(CurBasePointers.size() == CurPointers.size() &&
7626              CurBasePointers.size() == CurSizes.size() &&
7627              CurBasePointers.size() == CurMapTypes.size() &&
7628              "Inconsistent map information sizes!");
7629 
7630       // We need to append the results of this capture to what we already have.
7631       BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7632       Pointers.append(CurPointers.begin(), CurPointers.end());
7633       Sizes.append(CurSizes.begin(), CurSizes.end());
7634       MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7635     }
7636     // Map other list items in the map clause which are not captured variables
7637     // but "declare target link" global variables.
7638     for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
7639       for (const auto &L : C->component_lists()) {
7640         if (!L.first)
7641           continue;
7642         const auto *VD = dyn_cast<VarDecl>(L.first);
7643         if (!VD)
7644           continue;
7645         llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7646             isDeclareTargetDeclaration(VD);
7647         if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7648           continue;
7649         MEHandler.generateInfoForComponentList(
7650             C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7651             Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7652             C->isImplicit());
7653       }
7654     }
7655 
7656     TargetDataInfo Info;
7657     // Fill up the arrays and create the arguments.
7658     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7659     emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7660                                  Info.PointersArray, Info.SizesArray,
7661                                  Info.MapTypesArray, Info);
7662     InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7663     InputInfo.BasePointersArray =
7664         Address(Info.BasePointersArray, CGM.getPointerAlign());
7665     InputInfo.PointersArray =
7666         Address(Info.PointersArray, CGM.getPointerAlign());
7667     InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7668     MapTypesArray = Info.MapTypesArray;
7669     if (RequiresOuterTask)
7670       CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7671     else
7672       emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7673   };
7674 
7675   auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7676                              CodeGenFunction &CGF, PrePostActionTy &) {
7677     if (RequiresOuterTask) {
7678       CodeGenFunction::OMPTargetDataInfo InputInfo;
7679       CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7680     } else {
7681       emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7682     }
7683   };
7684 
7685   // If we have a target function ID it means that we need to support
7686   // offloading, otherwise, just execute on the host. We need to execute on host
7687   // regardless of the conditional in the if clause if, e.g., the user do not
7688   // specify target triples.
7689   if (OutlinedFnID) {
7690     if (IfCond) {
7691       emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7692     } else {
7693       RegionCodeGenTy ThenRCG(TargetThenGen);
7694       ThenRCG(CGF);
7695     }
7696   } else {
7697     RegionCodeGenTy ElseRCG(TargetElseGen);
7698     ElseRCG(CGF);
7699   }
7700 }
7701 
7702 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7703                                                     StringRef ParentName) {
7704   if (!S)
7705     return;
7706 
7707   // Codegen OMP target directives that offload compute to the device.
7708   bool RequiresDeviceCodegen =
7709       isa<OMPExecutableDirective>(S) &&
7710       isOpenMPTargetExecutionDirective(
7711           cast<OMPExecutableDirective>(S)->getDirectiveKind());
7712 
7713   if (RequiresDeviceCodegen) {
7714     const auto &E = *cast<OMPExecutableDirective>(S);
7715     unsigned DeviceID;
7716     unsigned FileID;
7717     unsigned Line;
7718     getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
7719                              FileID, Line);
7720 
7721     // Is this a target region that should not be emitted as an entry point? If
7722     // so just signal we are done with this target region.
7723     if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7724                                                             ParentName, Line))
7725       return;
7726 
7727     switch (E.getDirectiveKind()) {
7728     case OMPD_target:
7729       CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7730                                                    cast<OMPTargetDirective>(E));
7731       break;
7732     case OMPD_target_parallel:
7733       CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7734           CGM, ParentName, cast<OMPTargetParallelDirective>(E));
7735       break;
7736     case OMPD_target_teams:
7737       CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7738           CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
7739       break;
7740     case OMPD_target_teams_distribute:
7741       CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7742           CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
7743       break;
7744     case OMPD_target_teams_distribute_simd:
7745       CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7746           CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
7747       break;
7748     case OMPD_target_parallel_for:
7749       CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7750           CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
7751       break;
7752     case OMPD_target_parallel_for_simd:
7753       CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7754           CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
7755       break;
7756     case OMPD_target_simd:
7757       CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7758           CGM, ParentName, cast<OMPTargetSimdDirective>(E));
7759       break;
7760     case OMPD_target_teams_distribute_parallel_for:
7761       CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7762           CGM, ParentName,
7763           cast<OMPTargetTeamsDistributeParallelForDirective>(E));
7764       break;
7765     case OMPD_target_teams_distribute_parallel_for_simd:
7766       CodeGenFunction::
7767           EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7768               CGM, ParentName,
7769               cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
7770       break;
7771     case OMPD_parallel:
7772     case OMPD_for:
7773     case OMPD_parallel_for:
7774     case OMPD_parallel_sections:
7775     case OMPD_for_simd:
7776     case OMPD_parallel_for_simd:
7777     case OMPD_cancel:
7778     case OMPD_cancellation_point:
7779     case OMPD_ordered:
7780     case OMPD_threadprivate:
7781     case OMPD_task:
7782     case OMPD_simd:
7783     case OMPD_sections:
7784     case OMPD_section:
7785     case OMPD_single:
7786     case OMPD_master:
7787     case OMPD_critical:
7788     case OMPD_taskyield:
7789     case OMPD_barrier:
7790     case OMPD_taskwait:
7791     case OMPD_taskgroup:
7792     case OMPD_atomic:
7793     case OMPD_flush:
7794     case OMPD_teams:
7795     case OMPD_target_data:
7796     case OMPD_target_exit_data:
7797     case OMPD_target_enter_data:
7798     case OMPD_distribute:
7799     case OMPD_distribute_simd:
7800     case OMPD_distribute_parallel_for:
7801     case OMPD_distribute_parallel_for_simd:
7802     case OMPD_teams_distribute:
7803     case OMPD_teams_distribute_simd:
7804     case OMPD_teams_distribute_parallel_for:
7805     case OMPD_teams_distribute_parallel_for_simd:
7806     case OMPD_target_update:
7807     case OMPD_declare_simd:
7808     case OMPD_declare_target:
7809     case OMPD_end_declare_target:
7810     case OMPD_declare_reduction:
7811     case OMPD_taskloop:
7812     case OMPD_taskloop_simd:
7813     case OMPD_unknown:
7814       llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7815     }
7816     return;
7817   }
7818 
7819   if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
7820     if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
7821       return;
7822 
7823     scanForTargetRegionsFunctions(
7824         E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
7825     return;
7826   }
7827 
7828   // If this is a lambda function, look into its body.
7829   if (const auto *L = dyn_cast<LambdaExpr>(S))
7830     S = L->getBody();
7831 
7832   // Keep looking for target regions recursively.
7833   for (const Stmt *II : S->children())
7834     scanForTargetRegionsFunctions(II, ParentName);
7835 }
7836 
7837 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7838   const auto *FD = cast<FunctionDecl>(GD.getDecl());
7839 
7840   // If emitting code for the host, we do not process FD here. Instead we do
7841   // the normal code generation.
7842   if (!CGM.getLangOpts().OpenMPIsDevice)
7843     return false;
7844 
7845   // Try to detect target regions in the function.
7846   scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
7847 
7848   // Do not to emit function if it is not marked as declare target.
7849   return !isDeclareTargetDeclaration(FD) &&
7850          AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
7851 }
7852 
7853 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7854   if (!CGM.getLangOpts().OpenMPIsDevice)
7855     return false;
7856 
7857   // Check if there are Ctors/Dtors in this declaration and look for target
7858   // regions in it. We use the complete variant to produce the kernel name
7859   // mangling.
7860   QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7861   if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7862     for (const CXXConstructorDecl *Ctor : RD->ctors()) {
7863       StringRef ParentName =
7864           CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7865       scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7866     }
7867     if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
7868       StringRef ParentName =
7869           CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7870       scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7871     }
7872   }
7873 
7874   // Do not to emit variable if it is not marked as declare target.
7875   llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7876       isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
7877   return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
7878 }
7879 
7880 void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7881                                                    llvm::Constant *Addr) {
7882   if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7883           isDeclareTargetDeclaration(VD)) {
7884     OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7885     StringRef VarName;
7886     CharUnits VarSize;
7887     llvm::GlobalValue::LinkageTypes Linkage;
7888     switch (*Res) {
7889     case OMPDeclareTargetDeclAttr::MT_To:
7890       Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7891       VarName = CGM.getMangledName(VD);
7892       VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7893       Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7894       break;
7895     case OMPDeclareTargetDeclAttr::MT_Link:
7896       // Map type 'to' because we do not map the original variable but the
7897       // reference.
7898       Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7899       if (!CGM.getLangOpts().OpenMPIsDevice) {
7900         Addr =
7901             cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7902       }
7903       VarName = Addr->getName();
7904       VarSize = CGM.getPointerSize();
7905       Linkage = llvm::GlobalValue::WeakAnyLinkage;
7906       break;
7907     }
7908     OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7909         VarName, Addr, VarSize, Flags, Linkage);
7910   }
7911 }
7912 
7913 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7914   if (isa<FunctionDecl>(GD.getDecl()))
7915     return emitTargetFunctions(GD);
7916 
7917   return emitTargetGlobalVariable(GD);
7918 }
7919 
7920 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7921     CodeGenModule &CGM)
7922     : CGM(CGM) {
7923   if (CGM.getLangOpts().OpenMPIsDevice) {
7924     SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7925     CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7926   }
7927 }
7928 
7929 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7930   if (CGM.getLangOpts().OpenMPIsDevice)
7931     CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7932 }
7933 
7934 bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
7935   if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7936     return true;
7937 
7938   const auto *D = cast<FunctionDecl>(GD.getDecl());
7939   const FunctionDecl *FD = D->getCanonicalDecl();
7940   // Do not to emit function if it is marked as declare target as it was already
7941   // emitted.
7942   if (isDeclareTargetDeclaration(D)) {
7943     if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7944       if (auto *F = dyn_cast_or_null<llvm::Function>(
7945               CGM.GetGlobalValue(CGM.getMangledName(GD))))
7946         return !F->isDeclaration();
7947       return false;
7948     }
7949     return true;
7950   }
7951 
7952   return !AlreadyEmittedTargetFunctions.insert(FD).second;
7953 }
7954 
7955 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7956   // If we have offloading in the current module, we need to emit the entries
7957   // now and register the offloading descriptor.
7958   createOffloadEntriesAndInfoMetadata();
7959 
7960   // Create and register the offloading binary descriptors. This is the main
7961   // entity that captures all the information about offloading in the current
7962   // compilation unit.
7963   return createOffloadingBinaryDescriptorRegistration();
7964 }
7965 
7966 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7967                                     const OMPExecutableDirective &D,
7968                                     SourceLocation Loc,
7969                                     llvm::Value *OutlinedFn,
7970                                     ArrayRef<llvm::Value *> CapturedVars) {
7971   if (!CGF.HaveInsertPoint())
7972     return;
7973 
7974   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
7975   CodeGenFunction::RunCleanupsScope Scope(CGF);
7976 
7977   // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7978   llvm::Value *Args[] = {
7979       RTLoc,
7980       CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7981       CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7982   llvm::SmallVector<llvm::Value *, 16> RealArgs;
7983   RealArgs.append(std::begin(Args), std::end(Args));
7984   RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7985 
7986   llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7987   CGF.EmitRuntimeCall(RTLFn, RealArgs);
7988 }
7989 
7990 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
7991                                          const Expr *NumTeams,
7992                                          const Expr *ThreadLimit,
7993                                          SourceLocation Loc) {
7994   if (!CGF.HaveInsertPoint())
7995     return;
7996 
7997   llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
7998 
7999   llvm::Value *NumTeamsVal =
8000       NumTeams
8001           ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8002                                       CGF.CGM.Int32Ty, /* isSigned = */ true)
8003           : CGF.Builder.getInt32(0);
8004 
8005   llvm::Value *ThreadLimitVal =
8006       ThreadLimit
8007           ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8008                                       CGF.CGM.Int32Ty, /* isSigned = */ true)
8009           : CGF.Builder.getInt32(0);
8010 
8011   // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
8012   llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8013                                      ThreadLimitVal};
8014   CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8015                       PushNumTeamsArgs);
8016 }
8017 
8018 void CGOpenMPRuntime::emitTargetDataCalls(
8019     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8020     const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8021   if (!CGF.HaveInsertPoint())
8022     return;
8023 
8024   // Action used to replace the default codegen action and turn privatization
8025   // off.
8026   PrePostActionTy NoPrivAction;
8027 
8028   // Generate the code for the opening of the data environment. Capture all the
8029   // arguments of the runtime call by reference because they are used in the
8030   // closing of the region.
8031   auto &&BeginThenGen = [this, &D, Device, &Info,
8032                          &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
8033     // Fill up the arrays with all the mapped variables.
8034     MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8035     MappableExprsHandler::MapValuesArrayTy Pointers;
8036     MappableExprsHandler::MapValuesArrayTy Sizes;
8037     MappableExprsHandler::MapFlagsArrayTy MapTypes;
8038 
8039     // Get map clause information.
8040     MappableExprsHandler MCHandler(D, CGF);
8041     MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8042 
8043     // Fill up the arrays and create the arguments.
8044     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8045 
8046     llvm::Value *BasePointersArrayArg = nullptr;
8047     llvm::Value *PointersArrayArg = nullptr;
8048     llvm::Value *SizesArrayArg = nullptr;
8049     llvm::Value *MapTypesArrayArg = nullptr;
8050     emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
8051                                  SizesArrayArg, MapTypesArrayArg, Info);
8052 
8053     // Emit device ID if any.
8054     llvm::Value *DeviceID = nullptr;
8055     if (Device) {
8056       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8057                                            CGF.Int64Ty, /*isSigned=*/true);
8058     } else {
8059       DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8060     }
8061 
8062     // Emit the number of elements in the offloading arrays.
8063     llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
8064 
8065     llvm::Value *OffloadingArgs[] = {
8066         DeviceID,         PointerNum,    BasePointersArrayArg,
8067         PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
8068     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
8069                         OffloadingArgs);
8070 
8071     // If device pointer privatization is required, emit the body of the region
8072     // here. It will have to be duplicated: with and without privatization.
8073     if (!Info.CaptureDeviceAddrMap.empty())
8074       CodeGen(CGF);
8075   };
8076 
8077   // Generate code for the closing of the data region.
8078   auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8079                                             PrePostActionTy &) {
8080     assert(Info.isValid() && "Invalid data environment closing arguments.");
8081 
8082     llvm::Value *BasePointersArrayArg = nullptr;
8083     llvm::Value *PointersArrayArg = nullptr;
8084     llvm::Value *SizesArrayArg = nullptr;
8085     llvm::Value *MapTypesArrayArg = nullptr;
8086     emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
8087                                  SizesArrayArg, MapTypesArrayArg, Info);
8088 
8089     // Emit device ID if any.
8090     llvm::Value *DeviceID = nullptr;
8091     if (Device) {
8092       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8093                                            CGF.Int64Ty, /*isSigned=*/true);
8094     } else {
8095       DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8096     }
8097 
8098     // Emit the number of elements in the offloading arrays.
8099     llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
8100 
8101     llvm::Value *OffloadingArgs[] = {
8102         DeviceID,         PointerNum,    BasePointersArrayArg,
8103         PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
8104     CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
8105                         OffloadingArgs);
8106   };
8107 
8108   // If we need device pointer privatization, we need to emit the body of the
8109   // region with no privatization in the 'else' branch of the conditional.
8110   // Otherwise, we don't have to do anything.
8111   auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8112                                                          PrePostActionTy &) {
8113     if (!Info.CaptureDeviceAddrMap.empty()) {
8114       CodeGen.setAction(NoPrivAction);
8115       CodeGen(CGF);
8116     }
8117   };
8118 
8119   // We don't have to do anything to close the region if the if clause evaluates
8120   // to false.
8121   auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
8122 
8123   if (IfCond) {
8124     emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
8125   } else {
8126     RegionCodeGenTy RCG(BeginThenGen);
8127     RCG(CGF);
8128   }
8129 
8130   // If we don't require privatization of device pointers, we emit the body in
8131   // between the runtime calls. This avoids duplicating the body code.
8132   if (Info.CaptureDeviceAddrMap.empty()) {
8133     CodeGen.setAction(NoPrivAction);
8134     CodeGen(CGF);
8135   }
8136 
8137   if (IfCond) {
8138     emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
8139   } else {
8140     RegionCodeGenTy RCG(EndThenGen);
8141     RCG(CGF);
8142   }
8143 }
8144 
8145 void CGOpenMPRuntime::emitTargetDataStandAloneCall(
8146     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8147     const Expr *Device) {
8148   if (!CGF.HaveInsertPoint())
8149     return;
8150 
8151   assert((isa<OMPTargetEnterDataDirective>(D) ||
8152           isa<OMPTargetExitDataDirective>(D) ||
8153           isa<OMPTargetUpdateDirective>(D)) &&
8154          "Expecting either target enter, exit data, or update directives.");
8155 
8156   CodeGenFunction::OMPTargetDataInfo InputInfo;
8157   llvm::Value *MapTypesArray = nullptr;
8158   // Generate the code for the opening of the data environment.
8159   auto &&ThenGen = [this, &D, Device, &InputInfo,
8160                     &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
8161     // Emit device ID if any.
8162     llvm::Value *DeviceID = nullptr;
8163     if (Device) {
8164       DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8165                                            CGF.Int64Ty, /*isSigned=*/true);
8166     } else {
8167       DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8168     }
8169 
8170     // Emit the number of elements in the offloading arrays.
8171     llvm::Constant *PointerNum =
8172         CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
8173 
8174     llvm::Value *OffloadingArgs[] = {DeviceID,
8175                                      PointerNum,
8176                                      InputInfo.BasePointersArray.getPointer(),
8177                                      InputInfo.PointersArray.getPointer(),
8178                                      InputInfo.SizesArray.getPointer(),
8179                                      MapTypesArray};
8180 
8181     // Select the right runtime function call for each expected standalone
8182     // directive.
8183     const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
8184     OpenMPRTLFunction RTLFn;
8185     switch (D.getDirectiveKind()) {
8186     case OMPD_target_enter_data:
8187       RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8188                         : OMPRTL__tgt_target_data_begin;
8189       break;
8190     case OMPD_target_exit_data:
8191       RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8192                         : OMPRTL__tgt_target_data_end;
8193       break;
8194     case OMPD_target_update:
8195       RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8196                         : OMPRTL__tgt_target_data_update;
8197       break;
8198     case OMPD_parallel:
8199     case OMPD_for:
8200     case OMPD_parallel_for:
8201     case OMPD_parallel_sections:
8202     case OMPD_for_simd:
8203     case OMPD_parallel_for_simd:
8204     case OMPD_cancel:
8205     case OMPD_cancellation_point:
8206     case OMPD_ordered:
8207     case OMPD_threadprivate:
8208     case OMPD_task:
8209     case OMPD_simd:
8210     case OMPD_sections:
8211     case OMPD_section:
8212     case OMPD_single:
8213     case OMPD_master:
8214     case OMPD_critical:
8215     case OMPD_taskyield:
8216     case OMPD_barrier:
8217     case OMPD_taskwait:
8218     case OMPD_taskgroup:
8219     case OMPD_atomic:
8220     case OMPD_flush:
8221     case OMPD_teams:
8222     case OMPD_target_data:
8223     case OMPD_distribute:
8224     case OMPD_distribute_simd:
8225     case OMPD_distribute_parallel_for:
8226     case OMPD_distribute_parallel_for_simd:
8227     case OMPD_teams_distribute:
8228     case OMPD_teams_distribute_simd:
8229     case OMPD_teams_distribute_parallel_for:
8230     case OMPD_teams_distribute_parallel_for_simd:
8231     case OMPD_declare_simd:
8232     case OMPD_declare_target:
8233     case OMPD_end_declare_target:
8234     case OMPD_declare_reduction:
8235     case OMPD_taskloop:
8236     case OMPD_taskloop_simd:
8237     case OMPD_target:
8238     case OMPD_target_simd:
8239     case OMPD_target_teams_distribute:
8240     case OMPD_target_teams_distribute_simd:
8241     case OMPD_target_teams_distribute_parallel_for:
8242     case OMPD_target_teams_distribute_parallel_for_simd:
8243     case OMPD_target_teams:
8244     case OMPD_target_parallel:
8245     case OMPD_target_parallel_for:
8246     case OMPD_target_parallel_for_simd:
8247     case OMPD_unknown:
8248       llvm_unreachable("Unexpected standalone target data directive.");
8249       break;
8250     }
8251     CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
8252   };
8253 
8254   auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8255                              CodeGenFunction &CGF, PrePostActionTy &) {
8256     // Fill up the arrays with all the mapped variables.
8257     MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8258     MappableExprsHandler::MapValuesArrayTy Pointers;
8259     MappableExprsHandler::MapValuesArrayTy Sizes;
8260     MappableExprsHandler::MapFlagsArrayTy MapTypes;
8261 
8262     // Get map clause information.
8263     MappableExprsHandler MEHandler(D, CGF);
8264     MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8265 
8266     TargetDataInfo Info;
8267     // Fill up the arrays and create the arguments.
8268     emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8269     emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8270                                  Info.PointersArray, Info.SizesArray,
8271                                  Info.MapTypesArray, Info);
8272     InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8273     InputInfo.BasePointersArray =
8274         Address(Info.BasePointersArray, CGM.getPointerAlign());
8275     InputInfo.PointersArray =
8276         Address(Info.PointersArray, CGM.getPointerAlign());
8277     InputInfo.SizesArray =
8278         Address(Info.SizesArray, CGM.getPointerAlign());
8279     MapTypesArray = Info.MapTypesArray;
8280     if (D.hasClausesOfKind<OMPDependClause>())
8281       CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8282     else
8283       emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8284   };
8285 
8286   if (IfCond) {
8287     emitOMPIfClause(CGF, IfCond, TargetThenGen,
8288                     [](CodeGenFunction &CGF, PrePostActionTy &) {});
8289   } else {
8290     RegionCodeGenTy ThenRCG(TargetThenGen);
8291     ThenRCG(CGF);
8292   }
8293 }
8294 
8295 namespace {
8296   /// Kind of parameter in a function with 'declare simd' directive.
8297   enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8298   /// Attribute set of the parameter.
8299   struct ParamAttrTy {
8300     ParamKindTy Kind = Vector;
8301     llvm::APSInt StrideOrArg;
8302     llvm::APSInt Alignment;
8303   };
8304 } // namespace
8305 
8306 static unsigned evaluateCDTSize(const FunctionDecl *FD,
8307                                 ArrayRef<ParamAttrTy> ParamAttrs) {
8308   // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8309   // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8310   // of that clause. The VLEN value must be power of 2.
8311   // In other case the notion of the function`s "characteristic data type" (CDT)
8312   // is used to compute the vector length.
8313   // CDT is defined in the following order:
8314   //   a) For non-void function, the CDT is the return type.
8315   //   b) If the function has any non-uniform, non-linear parameters, then the
8316   //   CDT is the type of the first such parameter.
8317   //   c) If the CDT determined by a) or b) above is struct, union, or class
8318   //   type which is pass-by-value (except for the type that maps to the
8319   //   built-in complex data type), the characteristic data type is int.
8320   //   d) If none of the above three cases is applicable, the CDT is int.
8321   // The VLEN is then determined based on the CDT and the size of vector
8322   // register of that ISA for which current vector version is generated. The
8323   // VLEN is computed using the formula below:
8324   //   VLEN  = sizeof(vector_register) / sizeof(CDT),
8325   // where vector register size specified in section 3.2.1 Registers and the
8326   // Stack Frame of original AMD64 ABI document.
8327   QualType RetType = FD->getReturnType();
8328   if (RetType.isNull())
8329     return 0;
8330   ASTContext &C = FD->getASTContext();
8331   QualType CDT;
8332   if (!RetType.isNull() && !RetType->isVoidType()) {
8333     CDT = RetType;
8334   } else {
8335     unsigned Offset = 0;
8336     if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8337       if (ParamAttrs[Offset].Kind == Vector)
8338         CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8339       ++Offset;
8340     }
8341     if (CDT.isNull()) {
8342       for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8343         if (ParamAttrs[I + Offset].Kind == Vector) {
8344           CDT = FD->getParamDecl(I)->getType();
8345           break;
8346         }
8347       }
8348     }
8349   }
8350   if (CDT.isNull())
8351     CDT = C.IntTy;
8352   CDT = CDT->getCanonicalTypeUnqualified();
8353   if (CDT->isRecordType() || CDT->isUnionType())
8354     CDT = C.IntTy;
8355   return C.getTypeSize(CDT);
8356 }
8357 
8358 static void
8359 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
8360                            const llvm::APSInt &VLENVal,
8361                            ArrayRef<ParamAttrTy> ParamAttrs,
8362                            OMPDeclareSimdDeclAttr::BranchStateTy State) {
8363   struct ISADataTy {
8364     char ISA;
8365     unsigned VecRegSize;
8366   };
8367   ISADataTy ISAData[] = {
8368       {
8369           'b', 128
8370       }, // SSE
8371       {
8372           'c', 256
8373       }, // AVX
8374       {
8375           'd', 256
8376       }, // AVX2
8377       {
8378           'e', 512
8379       }, // AVX512
8380   };
8381   llvm::SmallVector<char, 2> Masked;
8382   switch (State) {
8383   case OMPDeclareSimdDeclAttr::BS_Undefined:
8384     Masked.push_back('N');
8385     Masked.push_back('M');
8386     break;
8387   case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8388     Masked.push_back('N');
8389     break;
8390   case OMPDeclareSimdDeclAttr::BS_Inbranch:
8391     Masked.push_back('M');
8392     break;
8393   }
8394   for (char Mask : Masked) {
8395     for (const ISADataTy &Data : ISAData) {
8396       SmallString<256> Buffer;
8397       llvm::raw_svector_ostream Out(Buffer);
8398       Out << "_ZGV" << Data.ISA << Mask;
8399       if (!VLENVal) {
8400         Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8401                                          evaluateCDTSize(FD, ParamAttrs));
8402       } else {
8403         Out << VLENVal;
8404       }
8405       for (const ParamAttrTy &ParamAttr : ParamAttrs) {
8406         switch (ParamAttr.Kind){
8407         case LinearWithVarStride:
8408           Out << 's' << ParamAttr.StrideOrArg;
8409           break;
8410         case Linear:
8411           Out << 'l';
8412           if (!!ParamAttr.StrideOrArg)
8413             Out << ParamAttr.StrideOrArg;
8414           break;
8415         case Uniform:
8416           Out << 'u';
8417           break;
8418         case Vector:
8419           Out << 'v';
8420           break;
8421         }
8422         if (!!ParamAttr.Alignment)
8423           Out << 'a' << ParamAttr.Alignment;
8424       }
8425       Out << '_' << Fn->getName();
8426       Fn->addFnAttr(Out.str());
8427     }
8428   }
8429 }
8430 
8431 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8432                                               llvm::Function *Fn) {
8433   ASTContext &C = CGM.getContext();
8434   FD = FD->getMostRecentDecl();
8435   // Map params to their positions in function decl.
8436   llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8437   if (isa<CXXMethodDecl>(FD))
8438     ParamPositions.try_emplace(FD, 0);
8439   unsigned ParamPos = ParamPositions.size();
8440   for (const ParmVarDecl *P : FD->parameters()) {
8441     ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
8442     ++ParamPos;
8443   }
8444   while (FD) {
8445     for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
8446       llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8447       // Mark uniform parameters.
8448       for (const Expr *E : Attr->uniforms()) {
8449         E = E->IgnoreParenImpCasts();
8450         unsigned Pos;
8451         if (isa<CXXThisExpr>(E)) {
8452           Pos = ParamPositions[FD];
8453         } else {
8454           const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8455                                 ->getCanonicalDecl();
8456           Pos = ParamPositions[PVD];
8457         }
8458         ParamAttrs[Pos].Kind = Uniform;
8459       }
8460       // Get alignment info.
8461       auto NI = Attr->alignments_begin();
8462       for (const Expr *E : Attr->aligneds()) {
8463         E = E->IgnoreParenImpCasts();
8464         unsigned Pos;
8465         QualType ParmTy;
8466         if (isa<CXXThisExpr>(E)) {
8467           Pos = ParamPositions[FD];
8468           ParmTy = E->getType();
8469         } else {
8470           const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8471                                 ->getCanonicalDecl();
8472           Pos = ParamPositions[PVD];
8473           ParmTy = PVD->getType();
8474         }
8475         ParamAttrs[Pos].Alignment =
8476             (*NI)
8477                 ? (*NI)->EvaluateKnownConstInt(C)
8478                 : llvm::APSInt::getUnsigned(
8479                       C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8480                           .getQuantity());
8481         ++NI;
8482       }
8483       // Mark linear parameters.
8484       auto SI = Attr->steps_begin();
8485       auto MI = Attr->modifiers_begin();
8486       for (const Expr *E : Attr->linears()) {
8487         E = E->IgnoreParenImpCasts();
8488         unsigned Pos;
8489         if (isa<CXXThisExpr>(E)) {
8490           Pos = ParamPositions[FD];
8491         } else {
8492           const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8493                                 ->getCanonicalDecl();
8494           Pos = ParamPositions[PVD];
8495         }
8496         ParamAttrTy &ParamAttr = ParamAttrs[Pos];
8497         ParamAttr.Kind = Linear;
8498         if (*SI) {
8499           if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8500                                     Expr::SE_AllowSideEffects)) {
8501             if (const auto *DRE =
8502                     cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8503               if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
8504                 ParamAttr.Kind = LinearWithVarStride;
8505                 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8506                     ParamPositions[StridePVD->getCanonicalDecl()]);
8507               }
8508             }
8509           }
8510         }
8511         ++SI;
8512         ++MI;
8513       }
8514       llvm::APSInt VLENVal;
8515       if (const Expr *VLEN = Attr->getSimdlen())
8516         VLENVal = VLEN->EvaluateKnownConstInt(C);
8517       OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8518       if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8519           CGM.getTriple().getArch() == llvm::Triple::x86_64)
8520         emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
8521     }
8522     FD = FD->getPreviousDecl();
8523   }
8524 }
8525 
8526 namespace {
8527 /// Cleanup action for doacross support.
8528 class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8529 public:
8530   static const int DoacrossFinArgs = 2;
8531 
8532 private:
8533   llvm::Value *RTLFn;
8534   llvm::Value *Args[DoacrossFinArgs];
8535 
8536 public:
8537   DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8538       : RTLFn(RTLFn) {
8539     assert(CallArgs.size() == DoacrossFinArgs);
8540     std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8541   }
8542   void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8543     if (!CGF.HaveInsertPoint())
8544       return;
8545     CGF.EmitRuntimeCall(RTLFn, Args);
8546   }
8547 };
8548 } // namespace
8549 
8550 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8551                                        const OMPLoopDirective &D) {
8552   if (!CGF.HaveInsertPoint())
8553     return;
8554 
8555   ASTContext &C = CGM.getContext();
8556   QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8557   RecordDecl *RD;
8558   if (KmpDimTy.isNull()) {
8559     // Build struct kmp_dim {  // loop bounds info casted to kmp_int64
8560     //  kmp_int64 lo; // lower
8561     //  kmp_int64 up; // upper
8562     //  kmp_int64 st; // stride
8563     // };
8564     RD = C.buildImplicitRecord("kmp_dim");
8565     RD->startDefinition();
8566     addFieldToRecordDecl(C, RD, Int64Ty);
8567     addFieldToRecordDecl(C, RD, Int64Ty);
8568     addFieldToRecordDecl(C, RD, Int64Ty);
8569     RD->completeDefinition();
8570     KmpDimTy = C.getRecordType(RD);
8571   } else {
8572     RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
8573   }
8574 
8575   Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8576   CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8577   enum { LowerFD = 0, UpperFD, StrideFD };
8578   // Fill dims with data.
8579   LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8580   // dims.upper = num_iterations;
8581   LValue UpperLVal =
8582       CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8583   llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8584       CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8585       Int64Ty, D.getNumIterations()->getExprLoc());
8586   CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8587   // dims.stride = 1;
8588   LValue StrideLVal =
8589       CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8590   CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8591                         StrideLVal);
8592 
8593   // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8594   // kmp_int32 num_dims, struct kmp_dim * dims);
8595   llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8596                          getThreadID(CGF, D.getLocStart()),
8597                          llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8598                          CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8599                              DimsAddr.getPointer(), CGM.VoidPtrTy)};
8600 
8601   llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8602   CGF.EmitRuntimeCall(RTLFn, Args);
8603   llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8604       emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8605   llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8606   CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8607                                              llvm::makeArrayRef(FiniArgs));
8608 }
8609 
8610 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8611                                           const OMPDependClause *C) {
8612   QualType Int64Ty =
8613       CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8614   const Expr *CounterVal = C->getCounterValue();
8615   assert(CounterVal);
8616   llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8617                                                  CounterVal->getType(), Int64Ty,
8618                                                  CounterVal->getExprLoc());
8619   Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8620   CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8621   llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8622                          getThreadID(CGF, C->getLocStart()),
8623                          CntAddr.getPointer()};
8624   llvm::Value *RTLFn;
8625   if (C->getDependencyKind() == OMPC_DEPEND_source) {
8626     RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
8627   } else {
8628     assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8629     RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8630   }
8631   CGF.EmitRuntimeCall(RTLFn, Args);
8632 }
8633 
8634 void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8635                                llvm::Value *Callee,
8636                                ArrayRef<llvm::Value *> Args) const {
8637   assert(Loc.isValid() && "Outlined function call location must be valid.");
8638   auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8639 
8640   if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
8641     if (Fn->doesNotThrow()) {
8642       CGF.EmitNounwindRuntimeCall(Fn, Args);
8643       return;
8644     }
8645   }
8646   CGF.EmitRuntimeCall(Callee, Args);
8647 }
8648 
8649 void CGOpenMPRuntime::emitOutlinedFunctionCall(
8650     CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8651     ArrayRef<llvm::Value *> Args) const {
8652   emitCall(CGF, Loc, OutlinedFn, Args);
8653 }
8654 
8655 Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8656                                              const VarDecl *NativeParam,
8657                                              const VarDecl *TargetParam) const {
8658   return CGF.GetAddrOfLocalVar(NativeParam);
8659 }
8660 
8661 Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8662                                                    const VarDecl *VD) {
8663   return Address::invalid();
8664 }
8665 
8666 llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8667     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8668     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8669   llvm_unreachable("Not supported in SIMD-only mode");
8670 }
8671 
8672 llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8673     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8674     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8675   llvm_unreachable("Not supported in SIMD-only mode");
8676 }
8677 
8678 llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8679     const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8680     const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8681     OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8682     bool Tied, unsigned &NumberOfParts) {
8683   llvm_unreachable("Not supported in SIMD-only mode");
8684 }
8685 
8686 void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8687                                            SourceLocation Loc,
8688                                            llvm::Value *OutlinedFn,
8689                                            ArrayRef<llvm::Value *> CapturedVars,
8690                                            const Expr *IfCond) {
8691   llvm_unreachable("Not supported in SIMD-only mode");
8692 }
8693 
8694 void CGOpenMPSIMDRuntime::emitCriticalRegion(
8695     CodeGenFunction &CGF, StringRef CriticalName,
8696     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8697     const Expr *Hint) {
8698   llvm_unreachable("Not supported in SIMD-only mode");
8699 }
8700 
8701 void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8702                                            const RegionCodeGenTy &MasterOpGen,
8703                                            SourceLocation Loc) {
8704   llvm_unreachable("Not supported in SIMD-only mode");
8705 }
8706 
8707 void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8708                                             SourceLocation Loc) {
8709   llvm_unreachable("Not supported in SIMD-only mode");
8710 }
8711 
8712 void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8713     CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8714     SourceLocation Loc) {
8715   llvm_unreachable("Not supported in SIMD-only mode");
8716 }
8717 
8718 void CGOpenMPSIMDRuntime::emitSingleRegion(
8719     CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8720     SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8721     ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8722     ArrayRef<const Expr *> AssignmentOps) {
8723   llvm_unreachable("Not supported in SIMD-only mode");
8724 }
8725 
8726 void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8727                                             const RegionCodeGenTy &OrderedOpGen,
8728                                             SourceLocation Loc,
8729                                             bool IsThreads) {
8730   llvm_unreachable("Not supported in SIMD-only mode");
8731 }
8732 
8733 void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8734                                           SourceLocation Loc,
8735                                           OpenMPDirectiveKind Kind,
8736                                           bool EmitChecks,
8737                                           bool ForceSimpleCall) {
8738   llvm_unreachable("Not supported in SIMD-only mode");
8739 }
8740 
8741 void CGOpenMPSIMDRuntime::emitForDispatchInit(
8742     CodeGenFunction &CGF, SourceLocation Loc,
8743     const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8744     bool Ordered, const DispatchRTInput &DispatchValues) {
8745   llvm_unreachable("Not supported in SIMD-only mode");
8746 }
8747 
8748 void CGOpenMPSIMDRuntime::emitForStaticInit(
8749     CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8750     const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8751   llvm_unreachable("Not supported in SIMD-only mode");
8752 }
8753 
8754 void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8755     CodeGenFunction &CGF, SourceLocation Loc,
8756     OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8757   llvm_unreachable("Not supported in SIMD-only mode");
8758 }
8759 
8760 void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8761                                                      SourceLocation Loc,
8762                                                      unsigned IVSize,
8763                                                      bool IVSigned) {
8764   llvm_unreachable("Not supported in SIMD-only mode");
8765 }
8766 
8767 void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8768                                               SourceLocation Loc,
8769                                               OpenMPDirectiveKind DKind) {
8770   llvm_unreachable("Not supported in SIMD-only mode");
8771 }
8772 
8773 llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8774                                               SourceLocation Loc,
8775                                               unsigned IVSize, bool IVSigned,
8776                                               Address IL, Address LB,
8777                                               Address UB, Address ST) {
8778   llvm_unreachable("Not supported in SIMD-only mode");
8779 }
8780 
8781 void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8782                                                llvm::Value *NumThreads,
8783                                                SourceLocation Loc) {
8784   llvm_unreachable("Not supported in SIMD-only mode");
8785 }
8786 
8787 void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8788                                              OpenMPProcBindClauseKind ProcBind,
8789                                              SourceLocation Loc) {
8790   llvm_unreachable("Not supported in SIMD-only mode");
8791 }
8792 
8793 Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8794                                                     const VarDecl *VD,
8795                                                     Address VDAddr,
8796                                                     SourceLocation Loc) {
8797   llvm_unreachable("Not supported in SIMD-only mode");
8798 }
8799 
8800 llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8801     const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8802     CodeGenFunction *CGF) {
8803   llvm_unreachable("Not supported in SIMD-only mode");
8804 }
8805 
8806 Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8807     CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8808   llvm_unreachable("Not supported in SIMD-only mode");
8809 }
8810 
8811 void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8812                                     ArrayRef<const Expr *> Vars,
8813                                     SourceLocation Loc) {
8814   llvm_unreachable("Not supported in SIMD-only mode");
8815 }
8816 
8817 void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8818                                        const OMPExecutableDirective &D,
8819                                        llvm::Value *TaskFunction,
8820                                        QualType SharedsTy, Address Shareds,
8821                                        const Expr *IfCond,
8822                                        const OMPTaskDataTy &Data) {
8823   llvm_unreachable("Not supported in SIMD-only mode");
8824 }
8825 
8826 void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8827     CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8828     llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8829     const Expr *IfCond, const OMPTaskDataTy &Data) {
8830   llvm_unreachable("Not supported in SIMD-only mode");
8831 }
8832 
8833 void CGOpenMPSIMDRuntime::emitReduction(
8834     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8835     ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8836     ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8837   assert(Options.SimpleReduction && "Only simple reduction is expected.");
8838   CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8839                                  ReductionOps, Options);
8840 }
8841 
8842 llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8843     CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8844     ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8845   llvm_unreachable("Not supported in SIMD-only mode");
8846 }
8847 
8848 void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8849                                                   SourceLocation Loc,
8850                                                   ReductionCodeGen &RCG,
8851                                                   unsigned N) {
8852   llvm_unreachable("Not supported in SIMD-only mode");
8853 }
8854 
8855 Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8856                                                   SourceLocation Loc,
8857                                                   llvm::Value *ReductionsPtr,
8858                                                   LValue SharedLVal) {
8859   llvm_unreachable("Not supported in SIMD-only mode");
8860 }
8861 
8862 void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8863                                            SourceLocation Loc) {
8864   llvm_unreachable("Not supported in SIMD-only mode");
8865 }
8866 
8867 void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8868     CodeGenFunction &CGF, SourceLocation Loc,
8869     OpenMPDirectiveKind CancelRegion) {
8870   llvm_unreachable("Not supported in SIMD-only mode");
8871 }
8872 
8873 void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8874                                          SourceLocation Loc, const Expr *IfCond,
8875                                          OpenMPDirectiveKind CancelRegion) {
8876   llvm_unreachable("Not supported in SIMD-only mode");
8877 }
8878 
8879 void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8880     const OMPExecutableDirective &D, StringRef ParentName,
8881     llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8882     bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8883   llvm_unreachable("Not supported in SIMD-only mode");
8884 }
8885 
8886 void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8887                                          const OMPExecutableDirective &D,
8888                                          llvm::Value *OutlinedFn,
8889                                          llvm::Value *OutlinedFnID,
8890                                          const Expr *IfCond, const Expr *Device) {
8891   llvm_unreachable("Not supported in SIMD-only mode");
8892 }
8893 
8894 bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8895   llvm_unreachable("Not supported in SIMD-only mode");
8896 }
8897 
8898 bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8899   llvm_unreachable("Not supported in SIMD-only mode");
8900 }
8901 
8902 bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8903   return false;
8904 }
8905 
8906 llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8907   return nullptr;
8908 }
8909 
8910 void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8911                                         const OMPExecutableDirective &D,
8912                                         SourceLocation Loc,
8913                                         llvm::Value *OutlinedFn,
8914                                         ArrayRef<llvm::Value *> CapturedVars) {
8915   llvm_unreachable("Not supported in SIMD-only mode");
8916 }
8917 
8918 void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8919                                              const Expr *NumTeams,
8920                                              const Expr *ThreadLimit,
8921                                              SourceLocation Loc) {
8922   llvm_unreachable("Not supported in SIMD-only mode");
8923 }
8924 
8925 void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8926     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8927     const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8928   llvm_unreachable("Not supported in SIMD-only mode");
8929 }
8930 
8931 void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8932     CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8933     const Expr *Device) {
8934   llvm_unreachable("Not supported in SIMD-only mode");
8935 }
8936 
8937 void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8938                                            const OMPLoopDirective &D) {
8939   llvm_unreachable("Not supported in SIMD-only mode");
8940 }
8941 
8942 void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8943                                               const OMPDependClause *C) {
8944   llvm_unreachable("Not supported in SIMD-only mode");
8945 }
8946 
8947 const VarDecl *
8948 CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8949                                         const VarDecl *NativeParam) const {
8950   llvm_unreachable("Not supported in SIMD-only mode");
8951 }
8952 
8953 Address
8954 CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8955                                          const VarDecl *NativeParam,
8956                                          const VarDecl *TargetParam) const {
8957   llvm_unreachable("Not supported in SIMD-only mode");
8958 }
8959 
8960