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