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