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