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