xref: /src/contrib/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.h (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides a class for OpenMP runtime code generation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
14 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H
15 
16 #include "CGValue.h"
17 #include "clang/AST/DeclOpenMP.h"
18 #include "clang/AST/GlobalDecl.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Basic/OpenMPKinds.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/PointerIntPair.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Frontend/OpenMP/OMPConstants.h"
28 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/AtomicOrdering.h"
32 
33 namespace llvm {
34 class ArrayType;
35 class Constant;
36 class FunctionType;
37 class GlobalVariable;
38 class StructType;
39 class Type;
40 class Value;
41 class OpenMPIRBuilder;
42 } // namespace llvm
43 
44 namespace clang {
45 class Expr;
46 class OMPDependClause;
47 class OMPExecutableDirective;
48 class OMPLoopDirective;
49 class VarDecl;
50 class OMPDeclareReductionDecl;
51 class IdentifierInfo;
52 
53 namespace CodeGen {
54 class Address;
55 class CodeGenFunction;
56 class CodeGenModule;
57 
58 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP
59 /// region.
60 class PrePostActionTy {
61 public:
62   explicit PrePostActionTy() {}
63   virtual void Enter(CodeGenFunction &CGF) {}
64   virtual void Exit(CodeGenFunction &CGF) {}
65   virtual ~PrePostActionTy() {}
66 };
67 
68 /// Class provides a way to call simple version of codegen for OpenMP region, or
69 /// an advanced with possible pre|post-actions in codegen.
70 class RegionCodeGenTy final {
71   intptr_t CodeGen;
72   typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &);
73   CodeGenTy Callback;
74   mutable PrePostActionTy *PrePostAction;
75   RegionCodeGenTy() = delete;
76   template <typename Callable>
77   static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF,
78                          PrePostActionTy &Action) {
79     return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action);
80   }
81 
82 public:
83   template <typename Callable>
84   RegionCodeGenTy(
85       Callable &&CodeGen,
86       std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>,
87                                      RegionCodeGenTy>::value> * = nullptr)
88       : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)),
89         Callback(CallbackFn<std::remove_reference_t<Callable>>),
90         PrePostAction(nullptr) {}
91   void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; }
92   void operator()(CodeGenFunction &CGF) const;
93 };
94 
95 struct OMPTaskDataTy final {
96   SmallVector<const Expr *, 4> PrivateVars;
97   SmallVector<const Expr *, 4> PrivateCopies;
98   SmallVector<const Expr *, 4> FirstprivateVars;
99   SmallVector<const Expr *, 4> FirstprivateCopies;
100   SmallVector<const Expr *, 4> FirstprivateInits;
101   SmallVector<const Expr *, 4> LastprivateVars;
102   SmallVector<const Expr *, 4> LastprivateCopies;
103   SmallVector<const Expr *, 4> ReductionVars;
104   SmallVector<const Expr *, 4> ReductionOrigs;
105   SmallVector<const Expr *, 4> ReductionCopies;
106   SmallVector<const Expr *, 4> ReductionOps;
107   SmallVector<CanonicalDeclPtr<const VarDecl>, 4> PrivateLocals;
108   struct DependData {
109     OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
110     const Expr *IteratorExpr = nullptr;
111     SmallVector<const Expr *, 4> DepExprs;
112     explicit DependData() = default;
113     DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr)
114         : DepKind(DepKind), IteratorExpr(IteratorExpr) {}
115   };
116   SmallVector<DependData, 4> Dependences;
117   llvm::PointerIntPair<llvm::Value *, 1, bool> Final;
118   llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule;
119   llvm::PointerIntPair<llvm::Value *, 1, bool> Priority;
120   llvm::Value *Reductions = nullptr;
121   unsigned NumberOfParts = 0;
122   bool Tied = true;
123   bool Nogroup = false;
124   bool IsReductionWithTaskMod = false;
125   bool IsWorksharingReduction = false;
126 };
127 
128 /// Class intended to support codegen of all kind of the reduction clauses.
129 class ReductionCodeGen {
130 private:
131   /// Data required for codegen of reduction clauses.
132   struct ReductionData {
133     /// Reference to the item shared between tasks to reduce into.
134     const Expr *Shared = nullptr;
135     /// Reference to the original item.
136     const Expr *Ref = nullptr;
137     /// Helper expression for generation of private copy.
138     const Expr *Private = nullptr;
139     /// Helper expression for generation reduction operation.
140     const Expr *ReductionOp = nullptr;
141     ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private,
142                   const Expr *ReductionOp)
143         : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) {
144     }
145   };
146   /// List of reduction-based clauses.
147   SmallVector<ReductionData, 4> ClausesData;
148 
149   /// List of addresses of shared variables/expressions.
150   SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses;
151   /// List of addresses of original variables/expressions.
152   SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses;
153   /// Sizes of the reduction items in chars.
154   SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes;
155   /// Base declarations for the reduction items.
156   SmallVector<const VarDecl *, 4> BaseDecls;
157 
158   /// Emits lvalue for shared expression.
159   LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E);
160   /// Emits upper bound for shared expression (if array section).
161   LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E);
162   /// Performs aggregate initialization.
163   /// \param N Number of reduction item in the common list.
164   /// \param PrivateAddr Address of the corresponding private item.
165   /// \param SharedAddr Address of the original shared variable.
166   /// \param DRD Declare reduction construct used for reduction item.
167   void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N,
168                                    Address PrivateAddr, Address SharedAddr,
169                                    const OMPDeclareReductionDecl *DRD);
170 
171 public:
172   ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs,
173                    ArrayRef<const Expr *> Privates,
174                    ArrayRef<const Expr *> ReductionOps);
175   /// Emits lvalue for the shared and original reduction item.
176   /// \param N Number of the reduction item.
177   void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N);
178   /// Emits the code for the variable-modified type, if required.
179   /// \param N Number of the reduction item.
180   void emitAggregateType(CodeGenFunction &CGF, unsigned N);
181   /// Emits the code for the variable-modified type, if required.
182   /// \param N Number of the reduction item.
183   /// \param Size Size of the type in chars.
184   void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size);
185   /// Performs initialization of the private copy for the reduction item.
186   /// \param N Number of the reduction item.
187   /// \param PrivateAddr Address of the corresponding private item.
188   /// \param DefaultInit Default initialization sequence that should be
189   /// performed if no reduction specific initialization is found.
190   /// \param SharedAddr Address of the original shared variable.
191   void
192   emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr,
193                      Address SharedAddr,
194                      llvm::function_ref<bool(CodeGenFunction &)> DefaultInit);
195   /// Returns true if the private copy requires cleanups.
196   bool needCleanups(unsigned N);
197   /// Emits cleanup code for the reduction item.
198   /// \param N Number of the reduction item.
199   /// \param PrivateAddr Address of the corresponding private item.
200   void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr);
201   /// Adjusts \p PrivatedAddr for using instead of the original variable
202   /// address in normal operations.
203   /// \param N Number of the reduction item.
204   /// \param PrivateAddr Address of the corresponding private item.
205   Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
206                                Address PrivateAddr);
207   /// Returns LValue for the reduction item.
208   LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; }
209   /// Returns LValue for the original reduction item.
210   LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; }
211   /// Returns the size of the reduction item (in chars and total number of
212   /// elements in the item), or nullptr, if the size is a constant.
213   std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const {
214     return Sizes[N];
215   }
216   /// Returns the base declaration of the reduction item.
217   const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; }
218   /// Returns the base declaration of the reduction item.
219   const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; }
220   /// Returns true if the initialization of the reduction item uses initializer
221   /// from declare reduction construct.
222   bool usesReductionInitializer(unsigned N) const;
223 };
224 
225 class CGOpenMPRuntime {
226 public:
227   /// Allows to disable automatic handling of functions used in target regions
228   /// as those marked as `omp declare target`.
229   class DisableAutoDeclareTargetRAII {
230     CodeGenModule &CGM;
231     bool SavedShouldMarkAsGlobal;
232 
233   public:
234     DisableAutoDeclareTargetRAII(CodeGenModule &CGM);
235     ~DisableAutoDeclareTargetRAII();
236   };
237 
238   /// Manages list of nontemporal decls for the specified directive.
239   class NontemporalDeclsRAII {
240     CodeGenModule &CGM;
241     const bool NeedToPush;
242 
243   public:
244     NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S);
245     ~NontemporalDeclsRAII();
246   };
247 
248   /// Manages list of nontemporal decls for the specified directive.
249   class UntiedTaskLocalDeclsRAII {
250     CodeGenModule &CGM;
251     const bool NeedToPush;
252 
253   public:
254     UntiedTaskLocalDeclsRAII(
255         CodeGenFunction &CGF,
256         const llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
257                               std::pair<Address, Address>> &LocalVars);
258     ~UntiedTaskLocalDeclsRAII();
259   };
260 
261   /// Maps the expression for the lastprivate variable to the global copy used
262   /// to store new value because original variables are not mapped in inner
263   /// parallel regions. Only private copies are captured but we need also to
264   /// store private copy in shared address.
265   /// Also, stores the expression for the private loop counter and it
266   /// threaprivate name.
267   struct LastprivateConditionalData {
268     llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>>
269         DeclToUniqueName;
270     LValue IVLVal;
271     llvm::Function *Fn = nullptr;
272     bool Disabled = false;
273   };
274   /// Manages list of lastprivate conditional decls for the specified directive.
275   class LastprivateConditionalRAII {
276     enum class ActionToDo {
277       DoNotPush,
278       PushAsLastprivateConditional,
279       DisableLastprivateConditional,
280     };
281     CodeGenModule &CGM;
282     ActionToDo Action = ActionToDo::DoNotPush;
283 
284     /// Check and try to disable analysis of inner regions for changes in
285     /// lastprivate conditional.
286     void tryToDisableInnerAnalysis(const OMPExecutableDirective &S,
287                                    llvm::DenseSet<CanonicalDeclPtr<const Decl>>
288                                        &NeedToAddForLPCsAsDisabled) const;
289 
290     LastprivateConditionalRAII(CodeGenFunction &CGF,
291                                const OMPExecutableDirective &S);
292 
293   public:
294     explicit LastprivateConditionalRAII(CodeGenFunction &CGF,
295                                         const OMPExecutableDirective &S,
296                                         LValue IVLVal);
297     static LastprivateConditionalRAII disable(CodeGenFunction &CGF,
298                                               const OMPExecutableDirective &S);
299     ~LastprivateConditionalRAII();
300   };
301 
302   llvm::OpenMPIRBuilder &getOMPBuilder() { return OMPBuilder; }
303 
304 protected:
305   CodeGenModule &CGM;
306   StringRef FirstSeparator, Separator;
307 
308   /// An OpenMP-IR-Builder instance.
309   llvm::OpenMPIRBuilder OMPBuilder;
310 
311   /// Constructor allowing to redefine the name separator for the variables.
312   explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
313                            StringRef Separator);
314 
315   /// Creates offloading entry for the provided entry ID \a ID,
316   /// address \a Addr, size \a Size, and flags \a Flags.
317   virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr,
318                                   uint64_t Size, int32_t Flags,
319                                   llvm::GlobalValue::LinkageTypes Linkage);
320 
321   /// Helper to emit outlined function for 'target' directive.
322   /// \param D Directive to emit.
323   /// \param ParentName Name of the function that encloses the target region.
324   /// \param OutlinedFn Outlined function value to be defined by this call.
325   /// \param OutlinedFnID Outlined function ID value to be defined by this call.
326   /// \param IsOffloadEntry True if the outlined function is an offload entry.
327   /// \param CodeGen Lambda codegen specific to an accelerator device.
328   /// An outlined function may not be an entry if, e.g. the if clause always
329   /// evaluates to false.
330   virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D,
331                                                 StringRef ParentName,
332                                                 llvm::Function *&OutlinedFn,
333                                                 llvm::Constant *&OutlinedFnID,
334                                                 bool IsOffloadEntry,
335                                                 const RegionCodeGenTy &CodeGen);
336 
337   /// Emits object of ident_t type with info for source location.
338   /// \param Flags Flags for OpenMP location.
339   ///
340   llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc,
341                                   unsigned Flags = 0);
342 
343   /// Emit the number of teams for a target directive.  Inspect the num_teams
344   /// clause associated with a teams construct combined or closely nested
345   /// with the target directive.
346   ///
347   /// Emit a team of size one for directives such as 'target parallel' that
348   /// have no associated teams construct.
349   ///
350   /// Otherwise, return nullptr.
351   const Expr *getNumTeamsExprForTargetDirective(CodeGenFunction &CGF,
352                                                 const OMPExecutableDirective &D,
353                                                 int32_t &DefaultVal);
354   llvm::Value *emitNumTeamsForTargetDirective(CodeGenFunction &CGF,
355                                               const OMPExecutableDirective &D);
356   /// Emit the number of threads for a target directive.  Inspect the
357   /// thread_limit clause associated with a teams construct combined or closely
358   /// nested with the target directive.
359   ///
360   /// Emit the num_threads clause for directives such as 'target parallel' that
361   /// have no associated teams construct.
362   ///
363   /// Otherwise, return nullptr.
364   const Expr *
365   getNumThreadsExprForTargetDirective(CodeGenFunction &CGF,
366                                       const OMPExecutableDirective &D,
367                                       int32_t &DefaultVal);
368   llvm::Value *
369   emitNumThreadsForTargetDirective(CodeGenFunction &CGF,
370                                    const OMPExecutableDirective &D);
371 
372   /// Returns pointer to ident_t type.
373   llvm::Type *getIdentTyPointerTy();
374 
375   /// Gets thread id value for the current thread.
376   ///
377   llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc);
378 
379   /// Get the function name of an outlined region.
380   //  The name can be customized depending on the target.
381   //
382   virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; }
383 
384   /// Emits \p Callee function call with arguments \p Args with location \p Loc.
385   void emitCall(CodeGenFunction &CGF, SourceLocation Loc,
386                 llvm::FunctionCallee Callee,
387                 ArrayRef<llvm::Value *> Args = llvm::None) const;
388 
389   /// Emits address of the word in a memory where current thread id is
390   /// stored.
391   virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc);
392 
393   void setLocThreadIdInsertPt(CodeGenFunction &CGF,
394                               bool AtCurrentPoint = false);
395   void clearLocThreadIdInsertPt(CodeGenFunction &CGF);
396 
397   /// Check if the default location must be constant.
398   /// Default is false to support OMPT/OMPD.
399   virtual bool isDefaultLocationConstant() const { return false; }
400 
401   /// Returns additional flags that can be stored in reserved_2 field of the
402   /// default location.
403   virtual unsigned getDefaultLocationReserved2Flags() const { return 0; }
404 
405   /// Returns default flags for the barriers depending on the directive, for
406   /// which this barier is going to be emitted.
407   static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind);
408 
409   /// Get the LLVM type for the critical name.
410   llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;}
411 
412   /// Returns corresponding lock object for the specified critical region
413   /// name. If the lock object does not exist it is created, otherwise the
414   /// reference to the existing copy is returned.
415   /// \param CriticalName Name of the critical region.
416   ///
417   llvm::Value *getCriticalRegionLock(StringRef CriticalName);
418 
419 private:
420 
421   /// Map for SourceLocation and OpenMP runtime library debug locations.
422   typedef llvm::DenseMap<SourceLocation, llvm::Value *> OpenMPDebugLocMapTy;
423   OpenMPDebugLocMapTy OpenMPDebugLocMap;
424   /// The type for a microtask which gets passed to __kmpc_fork_call().
425   /// Original representation is:
426   /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);
427   llvm::FunctionType *Kmpc_MicroTy = nullptr;
428   /// Stores debug location and ThreadID for the function.
429   struct DebugLocThreadIdTy {
430     llvm::Value *DebugLoc;
431     llvm::Value *ThreadID;
432     /// Insert point for the service instructions.
433     llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr;
434   };
435   /// Map of local debug location, ThreadId and functions.
436   typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy>
437       OpenMPLocThreadIDMapTy;
438   OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap;
439   /// Map of UDRs and corresponding combiner/initializer.
440   typedef llvm::DenseMap<const OMPDeclareReductionDecl *,
441                          std::pair<llvm::Function *, llvm::Function *>>
442       UDRMapTy;
443   UDRMapTy UDRMap;
444   /// Map of functions and locally defined UDRs.
445   typedef llvm::DenseMap<llvm::Function *,
446                          SmallVector<const OMPDeclareReductionDecl *, 4>>
447       FunctionUDRMapTy;
448   FunctionUDRMapTy FunctionUDRMap;
449   /// Map from the user-defined mapper declaration to its corresponding
450   /// functions.
451   llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap;
452   /// Map of functions and their local user-defined mappers.
453   using FunctionUDMMapTy =
454       llvm::DenseMap<llvm::Function *,
455                      SmallVector<const OMPDeclareMapperDecl *, 4>>;
456   FunctionUDMMapTy FunctionUDMMap;
457   /// Maps local variables marked as lastprivate conditional to their internal
458   /// types.
459   llvm::DenseMap<llvm::Function *,
460                  llvm::DenseMap<CanonicalDeclPtr<const Decl>,
461                                 std::tuple<QualType, const FieldDecl *,
462                                            const FieldDecl *, LValue>>>
463       LastprivateConditionalToTypes;
464   /// Maps function to the position of the untied task locals stack.
465   llvm::DenseMap<llvm::Function *, unsigned> FunctionToUntiedTaskStackMap;
466   /// Type kmp_critical_name, originally defined as typedef kmp_int32
467   /// kmp_critical_name[8];
468   llvm::ArrayType *KmpCriticalNameTy;
469   /// An ordered map of auto-generated variables to their unique names.
470   /// It stores variables with the following names: 1) ".gomp_critical_user_" +
471   /// <critical_section_name> + ".var" for "omp critical" directives; 2)
472   /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
473   /// variables.
474   llvm::StringMap<llvm::AssertingVH<llvm::GlobalVariable>,
475                   llvm::BumpPtrAllocator> InternalVars;
476   /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *);
477   llvm::Type *KmpRoutineEntryPtrTy = nullptr;
478   QualType KmpRoutineEntryPtrQTy;
479   /// Type typedef struct kmp_task {
480   ///    void *              shareds; /**< pointer to block of pointers to
481   ///    shared vars   */
482   ///    kmp_routine_entry_t routine; /**< pointer to routine to call for
483   ///    executing task */
484   ///    kmp_int32           part_id; /**< part id for the task */
485   ///    kmp_routine_entry_t destructors; /* pointer to function to invoke
486   ///    deconstructors of firstprivate C++ objects */
487   /// } kmp_task_t;
488   QualType KmpTaskTQTy;
489   /// Saved kmp_task_t for task directive.
490   QualType SavedKmpTaskTQTy;
491   /// Saved kmp_task_t for taskloop-based directive.
492   QualType SavedKmpTaskloopTQTy;
493   /// Type typedef struct kmp_depend_info {
494   ///    kmp_intptr_t               base_addr;
495   ///    size_t                     len;
496   ///    struct {
497   ///             bool                   in:1;
498   ///             bool                   out:1;
499   ///    } flags;
500   /// } kmp_depend_info_t;
501   QualType KmpDependInfoTy;
502   /// Type typedef struct kmp_task_affinity_info {
503   ///    kmp_intptr_t base_addr;
504   ///    size_t len;
505   ///    struct {
506   ///      bool flag1 : 1;
507   ///      bool flag2 : 1;
508   ///      kmp_int32 reserved : 30;
509   ///   } flags;
510   /// } kmp_task_affinity_info_t;
511   QualType KmpTaskAffinityInfoTy;
512   /// struct kmp_dim {  // loop bounds info casted to kmp_int64
513   ///  kmp_int64 lo; // lower
514   ///  kmp_int64 up; // upper
515   ///  kmp_int64 st; // stride
516   /// };
517   QualType KmpDimTy;
518   /// Type struct __tgt_offload_entry{
519   ///   void      *addr;       // Pointer to the offload entry info.
520   ///                          // (function or global)
521   ///   char      *name;       // Name of the function or global.
522   ///   size_t     size;       // Size of the entry info (0 if it a function).
523   ///   int32_t flags;
524   ///   int32_t reserved;
525   /// };
526   QualType TgtOffloadEntryQTy;
527   /// Entity that registers the offloading constants that were emitted so
528   /// far.
529   class OffloadEntriesInfoManagerTy {
530     CodeGenModule &CGM;
531 
532     /// Number of entries registered so far.
533     unsigned OffloadingEntriesNum = 0;
534 
535   public:
536     /// Base class of the entries info.
537     class OffloadEntryInfo {
538     public:
539       /// Kind of a given entry.
540       enum OffloadingEntryInfoKinds : unsigned {
541         /// Entry is a target region.
542         OffloadingEntryInfoTargetRegion = 0,
543         /// Entry is a declare target variable.
544         OffloadingEntryInfoDeviceGlobalVar = 1,
545         /// Invalid entry info.
546         OffloadingEntryInfoInvalid = ~0u
547       };
548 
549     protected:
550       OffloadEntryInfo() = delete;
551       explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {}
552       explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order,
553                                 uint32_t Flags)
554           : Flags(Flags), Order(Order), Kind(Kind) {}
555       ~OffloadEntryInfo() = default;
556 
557     public:
558       bool isValid() const { return Order != ~0u; }
559       unsigned getOrder() const { return Order; }
560       OffloadingEntryInfoKinds getKind() const { return Kind; }
561       uint32_t getFlags() const { return Flags; }
562       void setFlags(uint32_t NewFlags) { Flags = NewFlags; }
563       llvm::Constant *getAddress() const {
564         return cast_or_null<llvm::Constant>(Addr);
565       }
566       void setAddress(llvm::Constant *V) {
567         assert(!Addr.pointsToAliveValue() && "Address has been set before!");
568         Addr = V;
569       }
570       static bool classof(const OffloadEntryInfo *Info) { return true; }
571 
572     private:
573       /// Address of the entity that has to be mapped for offloading.
574       llvm::WeakTrackingVH Addr;
575 
576       /// Flags associated with the device global.
577       uint32_t Flags = 0u;
578 
579       /// Order this entry was emitted.
580       unsigned Order = ~0u;
581 
582       OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid;
583     };
584 
585     /// Return true if a there are no entries defined.
586     bool empty() const;
587     /// Return number of entries defined so far.
588     unsigned size() const { return OffloadingEntriesNum; }
589     OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {}
590 
591     //
592     // Target region entries related.
593     //
594 
595     /// Kind of the target registry entry.
596     enum OMPTargetRegionEntryKind : uint32_t {
597       /// Mark the entry as target region.
598       OMPTargetRegionEntryTargetRegion = 0x0,
599       /// Mark the entry as a global constructor.
600       OMPTargetRegionEntryCtor = 0x02,
601       /// Mark the entry as a global destructor.
602       OMPTargetRegionEntryDtor = 0x04,
603     };
604 
605     /// Target region entries info.
606     class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo {
607       /// Address that can be used as the ID of the entry.
608       llvm::Constant *ID = nullptr;
609 
610     public:
611       OffloadEntryInfoTargetRegion()
612           : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {}
613       explicit OffloadEntryInfoTargetRegion(unsigned Order,
614                                             llvm::Constant *Addr,
615                                             llvm::Constant *ID,
616                                             OMPTargetRegionEntryKind Flags)
617           : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags),
618             ID(ID) {
619         setAddress(Addr);
620       }
621 
622       llvm::Constant *getID() const { return ID; }
623       void setID(llvm::Constant *V) {
624         assert(!ID && "ID has been set before!");
625         ID = V;
626       }
627       static bool classof(const OffloadEntryInfo *Info) {
628         return Info->getKind() == OffloadingEntryInfoTargetRegion;
629       }
630     };
631 
632     /// Initialize target region entry.
633     void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
634                                          StringRef ParentName, unsigned LineNum,
635                                          unsigned Order);
636     /// Register target region entry.
637     void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
638                                        StringRef ParentName, unsigned LineNum,
639                                        llvm::Constant *Addr, llvm::Constant *ID,
640                                        OMPTargetRegionEntryKind Flags);
641     /// Return true if a target region entry with the provided information
642     /// exists.
643     bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
644                                   StringRef ParentName, unsigned LineNum,
645                                   bool IgnoreAddressId = false) const;
646     /// brief Applies action \a Action on all registered entries.
647     typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned,
648                                     const OffloadEntryInfoTargetRegion &)>
649         OffloadTargetRegionEntryInfoActTy;
650     void actOnTargetRegionEntriesInfo(
651         const OffloadTargetRegionEntryInfoActTy &Action);
652 
653     //
654     // Device global variable entries related.
655     //
656 
657     /// Kind of the global variable entry..
658     enum OMPTargetGlobalVarEntryKind : uint32_t {
659       /// Mark the entry as a to declare target.
660       OMPTargetGlobalVarEntryTo = 0x0,
661       /// Mark the entry as a to declare target link.
662       OMPTargetGlobalVarEntryLink = 0x1,
663     };
664 
665     /// Device global variable entries info.
666     class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo {
667       /// Type of the global variable.
668      CharUnits VarSize;
669      llvm::GlobalValue::LinkageTypes Linkage;
670 
671    public:
672      OffloadEntryInfoDeviceGlobalVar()
673          : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {}
674      explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order,
675                                               OMPTargetGlobalVarEntryKind Flags)
676          : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {}
677      explicit OffloadEntryInfoDeviceGlobalVar(
678          unsigned Order, llvm::Constant *Addr, CharUnits VarSize,
679          OMPTargetGlobalVarEntryKind Flags,
680          llvm::GlobalValue::LinkageTypes Linkage)
681          : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags),
682            VarSize(VarSize), Linkage(Linkage) {
683        setAddress(Addr);
684       }
685 
686       CharUnits getVarSize() const { return VarSize; }
687       void setVarSize(CharUnits Size) { VarSize = Size; }
688       llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; }
689       void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; }
690       static bool classof(const OffloadEntryInfo *Info) {
691         return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar;
692       }
693     };
694 
695     /// Initialize device global variable entry.
696     void initializeDeviceGlobalVarEntryInfo(StringRef Name,
697                                             OMPTargetGlobalVarEntryKind Flags,
698                                             unsigned Order);
699 
700     /// Register device global variable entry.
701     void
702     registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
703                                      CharUnits VarSize,
704                                      OMPTargetGlobalVarEntryKind Flags,
705                                      llvm::GlobalValue::LinkageTypes Linkage);
706     /// Checks if the variable with the given name has been registered already.
707     bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const {
708       return OffloadEntriesDeviceGlobalVar.count(VarName) > 0;
709     }
710     /// Applies action \a Action on all registered entries.
711     typedef llvm::function_ref<void(StringRef,
712                                     const OffloadEntryInfoDeviceGlobalVar &)>
713         OffloadDeviceGlobalVarEntryInfoActTy;
714     void actOnDeviceGlobalVarEntriesInfo(
715         const OffloadDeviceGlobalVarEntryInfoActTy &Action);
716 
717   private:
718     // Storage for target region entries kind. The storage is to be indexed by
719     // file ID, device ID, parent function name and line number.
720     typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion>
721         OffloadEntriesTargetRegionPerLine;
722     typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine>
723         OffloadEntriesTargetRegionPerParentName;
724     typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName>
725         OffloadEntriesTargetRegionPerFile;
726     typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile>
727         OffloadEntriesTargetRegionPerDevice;
728     typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy;
729     OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion;
730     /// Storage for device global variable entries kind. The storage is to be
731     /// indexed by mangled name.
732     typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar>
733         OffloadEntriesDeviceGlobalVarTy;
734     OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar;
735   };
736   OffloadEntriesInfoManagerTy OffloadEntriesInfoManager;
737 
738   bool ShouldMarkAsGlobal = true;
739   /// List of the emitted declarations.
740   llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls;
741   /// List of the global variables with their addresses that should not be
742   /// emitted for the target.
743   llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables;
744 
745   /// List of variables that can become declare target implicitly and, thus,
746   /// must be emitted.
747   llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables;
748 
749   using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>;
750   /// Stack for list of declarations in current context marked as nontemporal.
751   /// The set is the union of all current stack elements.
752   llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack;
753 
754   using UntiedLocalVarsAddressesMap =
755       llvm::MapVector<CanonicalDeclPtr<const VarDecl>,
756                       std::pair<Address, Address>>;
757   llvm::SmallVector<UntiedLocalVarsAddressesMap, 4> UntiedLocalVarsStack;
758 
759   /// Stack for list of addresses of declarations in current context marked as
760   /// lastprivate conditional. The set is the union of all current stack
761   /// elements.
762   llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack;
763 
764   /// Flag for keeping track of weather a requires unified_shared_memory
765   /// directive is present.
766   bool HasRequiresUnifiedSharedMemory = false;
767 
768   /// Atomic ordering from the omp requires directive.
769   llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic;
770 
771   /// Flag for keeping track of weather a target region has been emitted.
772   bool HasEmittedTargetRegion = false;
773 
774   /// Flag for keeping track of weather a device routine has been emitted.
775   /// Device routines are specific to the
776   bool HasEmittedDeclareTargetRegion = false;
777 
778   /// Loads all the offload entries information from the host IR
779   /// metadata.
780   void loadOffloadInfoMetadata();
781 
782   /// Returns __tgt_offload_entry type.
783   QualType getTgtOffloadEntryQTy();
784 
785   /// Start scanning from statement \a S and and emit all target regions
786   /// found along the way.
787   /// \param S Starting statement.
788   /// \param ParentName Name of the function declaration that is being scanned.
789   void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName);
790 
791   /// Build type kmp_routine_entry_t (if not built yet).
792   void emitKmpRoutineEntryT(QualType KmpInt32Ty);
793 
794   /// Returns pointer to kmpc_micro type.
795   llvm::Type *getKmpc_MicroPointerTy();
796 
797   /// Returns __kmpc_for_static_init_* runtime function for the specified
798   /// size \a IVSize and sign \a IVSigned. Will create a distribute call
799   /// __kmpc_distribute_static_init* if \a IsGPUDistribute is set.
800   llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize,
801                                                    bool IVSigned,
802                                                    bool IsGPUDistribute);
803 
804   /// Returns __kmpc_dispatch_init_* runtime function for the specified
805   /// size \a IVSize and sign \a IVSigned.
806   llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize,
807                                                   bool IVSigned);
808 
809   /// Returns __kmpc_dispatch_next_* runtime function for the specified
810   /// size \a IVSize and sign \a IVSigned.
811   llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize,
812                                                   bool IVSigned);
813 
814   /// Returns __kmpc_dispatch_fini_* runtime function for the specified
815   /// size \a IVSize and sign \a IVSigned.
816   llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize,
817                                                   bool IVSigned);
818 
819   /// If the specified mangled name is not in the module, create and
820   /// return threadprivate cache object. This object is a pointer's worth of
821   /// storage that's reserved for use by the OpenMP runtime.
822   /// \param VD Threadprivate variable.
823   /// \return Cache variable for the specified threadprivate.
824   llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD);
825 
826   /// Gets (if variable with the given name already exist) or creates
827   /// internal global variable with the specified Name. The created variable has
828   /// linkage CommonLinkage by default and is initialized by null value.
829   /// \param Ty Type of the global variable. If it is exist already the type
830   /// must be the same.
831   /// \param Name Name of the variable.
832   llvm::GlobalVariable *getOrCreateInternalVariable(llvm::Type *Ty,
833                                                     const llvm::Twine &Name,
834                                                     unsigned AddressSpace = 0);
835 
836   /// Set of threadprivate variables with the generated initializer.
837   llvm::StringSet<> ThreadPrivateWithDefinition;
838 
839   /// Set of declare target variables with the generated initializer.
840   llvm::StringSet<> DeclareTargetWithDefinition;
841 
842   /// Emits initialization code for the threadprivate variables.
843   /// \param VDAddr Address of the global variable \a VD.
844   /// \param Ctor Pointer to a global init function for \a VD.
845   /// \param CopyCtor Pointer to a global copy function for \a VD.
846   /// \param Dtor Pointer to a global destructor function for \a VD.
847   /// \param Loc Location of threadprivate declaration.
848   void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr,
849                                 llvm::Value *Ctor, llvm::Value *CopyCtor,
850                                 llvm::Value *Dtor, SourceLocation Loc);
851 
852   /// Emit the array initialization or deletion portion for user-defined mapper
853   /// code generation.
854   void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF,
855                                   llvm::Value *Handle, llvm::Value *BasePtr,
856                                   llvm::Value *Ptr, llvm::Value *Size,
857                                   llvm::Value *MapType, llvm::Value *MapName,
858                                   CharUnits ElementSize,
859                                   llvm::BasicBlock *ExitBB, bool IsInit);
860 
861   struct TaskResultTy {
862     llvm::Value *NewTask = nullptr;
863     llvm::Function *TaskEntry = nullptr;
864     llvm::Value *NewTaskNewTaskTTy = nullptr;
865     LValue TDBase;
866     const RecordDecl *KmpTaskTQTyRD = nullptr;
867     llvm::Value *TaskDupFn = nullptr;
868   };
869   /// Emit task region for the task directive. The task region is emitted in
870   /// several steps:
871   /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
872   /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
873   /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
874   /// function:
875   /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
876   ///   TaskFunction(gtid, tt->part_id, tt->shareds);
877   ///   return 0;
878   /// }
879   /// 2. Copy a list of shared variables to field shareds of the resulting
880   /// structure kmp_task_t returned by the previous call (if any).
881   /// 3. Copy a pointer to destructions function to field destructions of the
882   /// resulting structure kmp_task_t.
883   /// \param D Current task directive.
884   /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
885   /// /*part_id*/, captured_struct */*__context*/);
886   /// \param SharedsTy A type which contains references the shared variables.
887   /// \param Shareds Context with the list of shared variables from the \p
888   /// TaskFunction.
889   /// \param Data Additional data for task generation like tiednsee, final
890   /// state, list of privates etc.
891   TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
892                             const OMPExecutableDirective &D,
893                             llvm::Function *TaskFunction, QualType SharedsTy,
894                             Address Shareds, const OMPTaskDataTy &Data);
895 
896   /// Emit code that pushes the trip count of loops associated with constructs
897   /// 'target teams distribute' and 'teams distribute parallel for'.
898   /// \param SizeEmitter Emits the int64 value for the number of iterations of
899   /// the associated loop.
900   void emitTargetNumIterationsCall(
901       CodeGenFunction &CGF, const OMPExecutableDirective &D,
902       llvm::Value *DeviceID,
903       llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
904                                        const OMPLoopDirective &D)>
905           SizeEmitter);
906 
907   /// Emit update for lastprivate conditional data.
908   void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal,
909                                         StringRef UniqueDeclName, LValue LVal,
910                                         SourceLocation Loc);
911 
912   /// Returns the number of the elements and the address of the depobj
913   /// dependency array.
914   /// \return Number of elements in depobj array and the pointer to the array of
915   /// dependencies.
916   std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF,
917                                                      LValue DepobjLVal,
918                                                      SourceLocation Loc);
919 
920 public:
921   explicit CGOpenMPRuntime(CodeGenModule &CGM)
922       : CGOpenMPRuntime(CGM, ".", ".") {}
923   virtual ~CGOpenMPRuntime() {}
924   virtual void clear();
925 
926   /// Emits code for OpenMP 'if' clause using specified \a CodeGen
927   /// function. Here is the logic:
928   /// if (Cond) {
929   ///   ThenGen();
930   /// } else {
931   ///   ElseGen();
932   /// }
933   void emitIfClause(CodeGenFunction &CGF, const Expr *Cond,
934                     const RegionCodeGenTy &ThenGen,
935                     const RegionCodeGenTy &ElseGen);
936 
937   /// Checks if the \p Body is the \a CompoundStmt and returns its child
938   /// statement iff there is only one that is not evaluatable at the compile
939   /// time.
940   static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body);
941 
942   /// Get the platform-specific name separator.
943   std::string getName(ArrayRef<StringRef> Parts) const;
944 
945   /// Emit code for the specified user defined reduction construct.
946   virtual void emitUserDefinedReduction(CodeGenFunction *CGF,
947                                         const OMPDeclareReductionDecl *D);
948   /// Get combiner/initializer for the specified user-defined reduction, if any.
949   virtual std::pair<llvm::Function *, llvm::Function *>
950   getUserDefinedReduction(const OMPDeclareReductionDecl *D);
951 
952   /// Emit the function for the user defined mapper construct.
953   void emitUserDefinedMapper(const OMPDeclareMapperDecl *D,
954                              CodeGenFunction *CGF = nullptr);
955   /// Get the function for the specified user-defined mapper. If it does not
956   /// exist, create one.
957   llvm::Function *
958   getOrCreateUserDefinedMapperFunc(const OMPDeclareMapperDecl *D);
959 
960   /// Emits outlined function for the specified OpenMP parallel directive
961   /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
962   /// kmp_int32 BoundID, struct context_vars*).
963   /// \param D OpenMP directive.
964   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
965   /// \param InnermostKind Kind of innermost directive (for simple directives it
966   /// is a directive itself, for combined - its innermost directive).
967   /// \param CodeGen Code generation sequence for the \a D directive.
968   virtual llvm::Function *emitParallelOutlinedFunction(
969       const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
970       OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
971 
972   /// Emits outlined function for the specified OpenMP teams directive
973   /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
974   /// kmp_int32 BoundID, struct context_vars*).
975   /// \param D OpenMP directive.
976   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
977   /// \param InnermostKind Kind of innermost directive (for simple directives it
978   /// is a directive itself, for combined - its innermost directive).
979   /// \param CodeGen Code generation sequence for the \a D directive.
980   virtual llvm::Function *emitTeamsOutlinedFunction(
981       const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
982       OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen);
983 
984   /// Emits outlined function for the OpenMP task directive \a D. This
985   /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
986   /// TaskT).
987   /// \param D OpenMP directive.
988   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
989   /// \param PartIDVar Variable for partition id in the current OpenMP untied
990   /// task region.
991   /// \param TaskTVar Variable for task_t argument.
992   /// \param InnermostKind Kind of innermost directive (for simple directives it
993   /// is a directive itself, for combined - its innermost directive).
994   /// \param CodeGen Code generation sequence for the \a D directive.
995   /// \param Tied true if task is generated for tied task, false otherwise.
996   /// \param NumberOfParts Number of parts in untied task. Ignored for tied
997   /// tasks.
998   ///
999   virtual llvm::Function *emitTaskOutlinedFunction(
1000       const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1001       const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1002       OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1003       bool Tied, unsigned &NumberOfParts);
1004 
1005   /// Cleans up references to the objects in finished function.
1006   ///
1007   virtual void functionFinished(CodeGenFunction &CGF);
1008 
1009   /// Emits code for parallel or serial call of the \a OutlinedFn with
1010   /// variables captured in a record which address is stored in \a
1011   /// CapturedStruct.
1012   /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
1013   /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
1014   /// \param CapturedVars A pointer to the record with the references to
1015   /// variables used in \a OutlinedFn function.
1016   /// \param IfCond Condition in the associated 'if' clause, if it was
1017   /// specified, nullptr otherwise.
1018   /// \param NumThreads The value corresponding to the num_threads clause, if
1019   /// any, or nullptr.
1020   ///
1021   virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1022                                 llvm::Function *OutlinedFn,
1023                                 ArrayRef<llvm::Value *> CapturedVars,
1024                                 const Expr *IfCond, llvm::Value *NumThreads);
1025 
1026   /// Emits a critical region.
1027   /// \param CriticalName Name of the critical region.
1028   /// \param CriticalOpGen Generator for the statement associated with the given
1029   /// critical region.
1030   /// \param Hint Value of the 'hint' clause (optional).
1031   virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
1032                                   const RegionCodeGenTy &CriticalOpGen,
1033                                   SourceLocation Loc,
1034                                   const Expr *Hint = nullptr);
1035 
1036   /// Emits a master region.
1037   /// \param MasterOpGen Generator for the statement associated with the given
1038   /// master region.
1039   virtual void emitMasterRegion(CodeGenFunction &CGF,
1040                                 const RegionCodeGenTy &MasterOpGen,
1041                                 SourceLocation Loc);
1042 
1043   /// Emits a masked region.
1044   /// \param MaskedOpGen Generator for the statement associated with the given
1045   /// masked region.
1046   virtual void emitMaskedRegion(CodeGenFunction &CGF,
1047                                 const RegionCodeGenTy &MaskedOpGen,
1048                                 SourceLocation Loc,
1049                                 const Expr *Filter = nullptr);
1050 
1051   /// Emits code for a taskyield directive.
1052   virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc);
1053 
1054   /// Emit a taskgroup region.
1055   /// \param TaskgroupOpGen Generator for the statement associated with the
1056   /// given taskgroup region.
1057   virtual void emitTaskgroupRegion(CodeGenFunction &CGF,
1058                                    const RegionCodeGenTy &TaskgroupOpGen,
1059                                    SourceLocation Loc);
1060 
1061   /// Emits a single region.
1062   /// \param SingleOpGen Generator for the statement associated with the given
1063   /// single region.
1064   virtual void emitSingleRegion(CodeGenFunction &CGF,
1065                                 const RegionCodeGenTy &SingleOpGen,
1066                                 SourceLocation Loc,
1067                                 ArrayRef<const Expr *> CopyprivateVars,
1068                                 ArrayRef<const Expr *> DestExprs,
1069                                 ArrayRef<const Expr *> SrcExprs,
1070                                 ArrayRef<const Expr *> AssignmentOps);
1071 
1072   /// Emit an ordered region.
1073   /// \param OrderedOpGen Generator for the statement associated with the given
1074   /// ordered region.
1075   virtual void emitOrderedRegion(CodeGenFunction &CGF,
1076                                  const RegionCodeGenTy &OrderedOpGen,
1077                                  SourceLocation Loc, bool IsThreads);
1078 
1079   /// Emit an implicit/explicit barrier for OpenMP threads.
1080   /// \param Kind Directive for which this implicit barrier call must be
1081   /// generated. Must be OMPD_barrier for explicit barrier generation.
1082   /// \param EmitChecks true if need to emit checks for cancellation barriers.
1083   /// \param ForceSimpleCall true simple barrier call must be emitted, false if
1084   /// runtime class decides which one to emit (simple or with cancellation
1085   /// checks).
1086   ///
1087   virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
1088                                OpenMPDirectiveKind Kind,
1089                                bool EmitChecks = true,
1090                                bool ForceSimpleCall = false);
1091 
1092   /// Check if the specified \a ScheduleKind is static non-chunked.
1093   /// This kind of worksharing directive is emitted without outer loop.
1094   /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
1095   /// \param Chunked True if chunk is specified in the clause.
1096   ///
1097   virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
1098                                   bool Chunked) const;
1099 
1100   /// Check if the specified \a ScheduleKind is static non-chunked.
1101   /// This kind of distribute directive is emitted without outer loop.
1102   /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
1103   /// \param Chunked True if chunk is specified in the clause.
1104   ///
1105   virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,
1106                                   bool Chunked) const;
1107 
1108   /// Check if the specified \a ScheduleKind is static chunked.
1109   /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
1110   /// \param Chunked True if chunk is specified in the clause.
1111   ///
1112   virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
1113                                bool Chunked) const;
1114 
1115   /// Check if the specified \a ScheduleKind is static non-chunked.
1116   /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
1117   /// \param Chunked True if chunk is specified in the clause.
1118   ///
1119   virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,
1120                                bool Chunked) const;
1121 
1122   /// Check if the specified \a ScheduleKind is dynamic.
1123   /// This kind of worksharing directive is emitted without outer loop.
1124   /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
1125   ///
1126   virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const;
1127 
1128   /// struct with the values to be passed to the dispatch runtime function
1129   struct DispatchRTInput {
1130     /// Loop lower bound
1131     llvm::Value *LB = nullptr;
1132     /// Loop upper bound
1133     llvm::Value *UB = nullptr;
1134     /// Chunk size specified using 'schedule' clause (nullptr if chunk
1135     /// was not specified)
1136     llvm::Value *Chunk = nullptr;
1137     DispatchRTInput() = default;
1138     DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk)
1139         : LB(LB), UB(UB), Chunk(Chunk) {}
1140   };
1141 
1142   /// Call the appropriate runtime routine to initialize it before start
1143   /// of loop.
1144 
1145   /// This is used for non static scheduled types and when the ordered
1146   /// clause is present on the loop construct.
1147   /// Depending on the loop schedule, it is necessary to call some runtime
1148   /// routine before start of the OpenMP loop to get the loop upper / lower
1149   /// bounds \a LB and \a UB and stride \a ST.
1150   ///
1151   /// \param CGF Reference to current CodeGenFunction.
1152   /// \param Loc Clang source location.
1153   /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
1154   /// \param IVSize Size of the iteration variable in bits.
1155   /// \param IVSigned Sign of the iteration variable.
1156   /// \param Ordered true if loop is ordered, false otherwise.
1157   /// \param DispatchValues struct containing llvm values for lower bound, upper
1158   /// bound, and chunk expression.
1159   /// For the default (nullptr) value, the chunk 1 will be used.
1160   ///
1161   virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
1162                                    const OpenMPScheduleTy &ScheduleKind,
1163                                    unsigned IVSize, bool IVSigned, bool Ordered,
1164                                    const DispatchRTInput &DispatchValues);
1165 
1166   /// Struct with the values to be passed to the static runtime function
1167   struct StaticRTInput {
1168     /// Size of the iteration variable in bits.
1169     unsigned IVSize = 0;
1170     /// Sign of the iteration variable.
1171     bool IVSigned = false;
1172     /// true if loop is ordered, false otherwise.
1173     bool Ordered = false;
1174     /// Address of the output variable in which the flag of the last iteration
1175     /// is returned.
1176     Address IL = Address::invalid();
1177     /// Address of the output variable in which the lower iteration number is
1178     /// returned.
1179     Address LB = Address::invalid();
1180     /// Address of the output variable in which the upper iteration number is
1181     /// returned.
1182     Address UB = Address::invalid();
1183     /// Address of the output variable in which the stride value is returned
1184     /// necessary to generated the static_chunked scheduled loop.
1185     Address ST = Address::invalid();
1186     /// Value of the chunk for the static_chunked scheduled loop. For the
1187     /// default (nullptr) value, the chunk 1 will be used.
1188     llvm::Value *Chunk = nullptr;
1189     StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL,
1190                   Address LB, Address UB, Address ST,
1191                   llvm::Value *Chunk = nullptr)
1192         : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB),
1193           UB(UB), ST(ST), Chunk(Chunk) {}
1194   };
1195   /// Call the appropriate runtime routine to initialize it before start
1196   /// of loop.
1197   ///
1198   /// This is used only in case of static schedule, when the user did not
1199   /// specify a ordered clause on the loop construct.
1200   /// Depending on the loop schedule, it is necessary to call some runtime
1201   /// routine before start of the OpenMP loop to get the loop upper / lower
1202   /// bounds LB and UB and stride ST.
1203   ///
1204   /// \param CGF Reference to current CodeGenFunction.
1205   /// \param Loc Clang source location.
1206   /// \param DKind Kind of the directive.
1207   /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
1208   /// \param Values Input arguments for the construct.
1209   ///
1210   virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
1211                                  OpenMPDirectiveKind DKind,
1212                                  const OpenMPScheduleTy &ScheduleKind,
1213                                  const StaticRTInput &Values);
1214 
1215   ///
1216   /// \param CGF Reference to current CodeGenFunction.
1217   /// \param Loc Clang source location.
1218   /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
1219   /// \param Values Input arguments for the construct.
1220   ///
1221   virtual void emitDistributeStaticInit(CodeGenFunction &CGF,
1222                                         SourceLocation Loc,
1223                                         OpenMPDistScheduleClauseKind SchedKind,
1224                                         const StaticRTInput &Values);
1225 
1226   /// Call the appropriate runtime routine to notify that we finished
1227   /// iteration of the ordered loop with the dynamic scheduling.
1228   ///
1229   /// \param CGF Reference to current CodeGenFunction.
1230   /// \param Loc Clang source location.
1231   /// \param IVSize Size of the iteration variable in bits.
1232   /// \param IVSigned Sign of the iteration variable.
1233   ///
1234   virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF,
1235                                           SourceLocation Loc, unsigned IVSize,
1236                                           bool IVSigned);
1237 
1238   /// Call the appropriate runtime routine to notify that we finished
1239   /// all the work with current loop.
1240   ///
1241   /// \param CGF Reference to current CodeGenFunction.
1242   /// \param Loc Clang source location.
1243   /// \param DKind Kind of the directive for which the static finish is emitted.
1244   ///
1245   virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,
1246                                    OpenMPDirectiveKind DKind);
1247 
1248   /// Call __kmpc_dispatch_next(
1249   ///          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
1250   ///          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
1251   ///          kmp_int[32|64] *p_stride);
1252   /// \param IVSize Size of the iteration variable in bits.
1253   /// \param IVSigned Sign of the iteration variable.
1254   /// \param IL Address of the output variable in which the flag of the
1255   /// last iteration is returned.
1256   /// \param LB Address of the output variable in which the lower iteration
1257   /// number is returned.
1258   /// \param UB Address of the output variable in which the upper iteration
1259   /// number is returned.
1260   /// \param ST Address of the output variable in which the stride value is
1261   /// returned.
1262   virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
1263                                    unsigned IVSize, bool IVSigned,
1264                                    Address IL, Address LB,
1265                                    Address UB, Address ST);
1266 
1267   /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
1268   /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
1269   /// clause.
1270   /// \param NumThreads An integer value of threads.
1271   virtual void emitNumThreadsClause(CodeGenFunction &CGF,
1272                                     llvm::Value *NumThreads,
1273                                     SourceLocation Loc);
1274 
1275   /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
1276   /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
1277   virtual void emitProcBindClause(CodeGenFunction &CGF,
1278                                   llvm::omp::ProcBindKind ProcBind,
1279                                   SourceLocation Loc);
1280 
1281   /// Returns address of the threadprivate variable for the current
1282   /// thread.
1283   /// \param VD Threadprivate variable.
1284   /// \param VDAddr Address of the global variable \a VD.
1285   /// \param Loc Location of the reference to threadprivate var.
1286   /// \return Address of the threadprivate variable for the current thread.
1287   virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF,
1288                                          const VarDecl *VD,
1289                                          Address VDAddr,
1290                                          SourceLocation Loc);
1291 
1292   /// Returns the address of the variable marked as declare target with link
1293   /// clause OR as declare target with to clause and unified memory.
1294   virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD);
1295 
1296   /// Emit a code for initialization of threadprivate variable. It emits
1297   /// a call to runtime library which adds initial value to the newly created
1298   /// threadprivate variable (if it is not constant) and registers destructor
1299   /// for the variable (if any).
1300   /// \param VD Threadprivate variable.
1301   /// \param VDAddr Address of the global variable \a VD.
1302   /// \param Loc Location of threadprivate declaration.
1303   /// \param PerformInit true if initialization expression is not constant.
1304   virtual llvm::Function *
1305   emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
1306                                  SourceLocation Loc, bool PerformInit,
1307                                  CodeGenFunction *CGF = nullptr);
1308 
1309   /// Emit a code for initialization of declare target variable.
1310   /// \param VD Declare target variable.
1311   /// \param Addr Address of the global variable \a VD.
1312   /// \param PerformInit true if initialization expression is not constant.
1313   virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD,
1314                                               llvm::GlobalVariable *Addr,
1315                                               bool PerformInit);
1316 
1317   /// Creates artificial threadprivate variable with name \p Name and type \p
1318   /// VarType.
1319   /// \param VarType Type of the artificial threadprivate variable.
1320   /// \param Name Name of the artificial threadprivate variable.
1321   virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
1322                                                    QualType VarType,
1323                                                    StringRef Name);
1324 
1325   /// Emit flush of the variables specified in 'omp flush' directive.
1326   /// \param Vars List of variables to flush.
1327   virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
1328                          SourceLocation Loc, llvm::AtomicOrdering AO);
1329 
1330   /// Emit task region for the task directive. The task region is
1331   /// emitted in several steps:
1332   /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
1333   /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1334   /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
1335   /// function:
1336   /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1337   ///   TaskFunction(gtid, tt->part_id, tt->shareds);
1338   ///   return 0;
1339   /// }
1340   /// 2. Copy a list of shared variables to field shareds of the resulting
1341   /// structure kmp_task_t returned by the previous call (if any).
1342   /// 3. Copy a pointer to destructions function to field destructions of the
1343   /// resulting structure kmp_task_t.
1344   /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
1345   /// kmp_task_t *new_task), where new_task is a resulting structure from
1346   /// previous items.
1347   /// \param D Current task directive.
1348   /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
1349   /// /*part_id*/, captured_struct */*__context*/);
1350   /// \param SharedsTy A type which contains references the shared variables.
1351   /// \param Shareds Context with the list of shared variables from the \p
1352   /// TaskFunction.
1353   /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
1354   /// otherwise.
1355   /// \param Data Additional data for task generation like tiednsee, final
1356   /// state, list of privates etc.
1357   virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
1358                             const OMPExecutableDirective &D,
1359                             llvm::Function *TaskFunction, QualType SharedsTy,
1360                             Address Shareds, const Expr *IfCond,
1361                             const OMPTaskDataTy &Data);
1362 
1363   /// Emit task region for the taskloop directive. The taskloop region is
1364   /// emitted in several steps:
1365   /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
1366   /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1367   /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
1368   /// function:
1369   /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
1370   ///   TaskFunction(gtid, tt->part_id, tt->shareds);
1371   ///   return 0;
1372   /// }
1373   /// 2. Copy a list of shared variables to field shareds of the resulting
1374   /// structure kmp_task_t returned by the previous call (if any).
1375   /// 3. Copy a pointer to destructions function to field destructions of the
1376   /// resulting structure kmp_task_t.
1377   /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
1378   /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
1379   /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
1380   /// is a resulting structure from
1381   /// previous items.
1382   /// \param D Current task directive.
1383   /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
1384   /// /*part_id*/, captured_struct */*__context*/);
1385   /// \param SharedsTy A type which contains references the shared variables.
1386   /// \param Shareds Context with the list of shared variables from the \p
1387   /// TaskFunction.
1388   /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
1389   /// otherwise.
1390   /// \param Data Additional data for task generation like tiednsee, final
1391   /// state, list of privates etc.
1392   virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
1393                                 const OMPLoopDirective &D,
1394                                 llvm::Function *TaskFunction,
1395                                 QualType SharedsTy, Address Shareds,
1396                                 const Expr *IfCond, const OMPTaskDataTy &Data);
1397 
1398   /// Emit code for the directive that does not require outlining.
1399   ///
1400   /// \param InnermostKind Kind of innermost directive (for simple directives it
1401   /// is a directive itself, for combined - its innermost directive).
1402   /// \param CodeGen Code generation sequence for the \a D directive.
1403   /// \param HasCancel true if region has inner cancel directive, false
1404   /// otherwise.
1405   virtual void emitInlinedDirective(CodeGenFunction &CGF,
1406                                     OpenMPDirectiveKind InnermostKind,
1407                                     const RegionCodeGenTy &CodeGen,
1408                                     bool HasCancel = false);
1409 
1410   /// Emits reduction function.
1411   /// \param ArgsType Array type containing pointers to reduction variables.
1412   /// \param Privates List of private copies for original reduction arguments.
1413   /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
1414   /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
1415   /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
1416   /// or 'operator binop(LHS, RHS)'.
1417   llvm::Function *emitReductionFunction(SourceLocation Loc,
1418                                         llvm::Type *ArgsType,
1419                                         ArrayRef<const Expr *> Privates,
1420                                         ArrayRef<const Expr *> LHSExprs,
1421                                         ArrayRef<const Expr *> RHSExprs,
1422                                         ArrayRef<const Expr *> ReductionOps);
1423 
1424   /// Emits single reduction combiner
1425   void emitSingleReductionCombiner(CodeGenFunction &CGF,
1426                                    const Expr *ReductionOp,
1427                                    const Expr *PrivateRef,
1428                                    const DeclRefExpr *LHS,
1429                                    const DeclRefExpr *RHS);
1430 
1431   struct ReductionOptionsTy {
1432     bool WithNowait;
1433     bool SimpleReduction;
1434     OpenMPDirectiveKind ReductionKind;
1435   };
1436   /// Emit a code for reduction clause. Next code should be emitted for
1437   /// reduction:
1438   /// \code
1439   ///
1440   /// static kmp_critical_name lock = { 0 };
1441   ///
1442   /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
1443   ///  ...
1444   ///  *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
1445   ///  ...
1446   /// }
1447   ///
1448   /// ...
1449   /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
1450   /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
1451   /// RedList, reduce_func, &<lock>)) {
1452   /// case 1:
1453   ///  ...
1454   ///  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
1455   ///  ...
1456   /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
1457   /// break;
1458   /// case 2:
1459   ///  ...
1460   ///  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
1461   ///  ...
1462   /// break;
1463   /// default:;
1464   /// }
1465   /// \endcode
1466   ///
1467   /// \param Privates List of private copies for original reduction arguments.
1468   /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
1469   /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
1470   /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
1471   /// or 'operator binop(LHS, RHS)'.
1472   /// \param Options List of options for reduction codegen:
1473   ///     WithNowait true if parent directive has also nowait clause, false
1474   ///     otherwise.
1475   ///     SimpleReduction Emit reduction operation only. Used for omp simd
1476   ///     directive on the host.
1477   ///     ReductionKind The kind of reduction to perform.
1478   virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
1479                              ArrayRef<const Expr *> Privates,
1480                              ArrayRef<const Expr *> LHSExprs,
1481                              ArrayRef<const Expr *> RHSExprs,
1482                              ArrayRef<const Expr *> ReductionOps,
1483                              ReductionOptionsTy Options);
1484 
1485   /// Emit a code for initialization of task reduction clause. Next code
1486   /// should be emitted for reduction:
1487   /// \code
1488   ///
1489   /// _taskred_item_t red_data[n];
1490   /// ...
1491   /// red_data[i].shar = &shareds[i];
1492   /// red_data[i].orig = &origs[i];
1493   /// red_data[i].size = sizeof(origs[i]);
1494   /// red_data[i].f_init = (void*)RedInit<i>;
1495   /// red_data[i].f_fini = (void*)RedDest<i>;
1496   /// red_data[i].f_comb = (void*)RedOp<i>;
1497   /// red_data[i].flags = <Flag_i>;
1498   /// ...
1499   /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);
1500   /// \endcode
1501   /// For reduction clause with task modifier it emits the next call:
1502   /// \code
1503   ///
1504   /// _taskred_item_t red_data[n];
1505   /// ...
1506   /// red_data[i].shar = &shareds[i];
1507   /// red_data[i].orig = &origs[i];
1508   /// red_data[i].size = sizeof(origs[i]);
1509   /// red_data[i].f_init = (void*)RedInit<i>;
1510   /// red_data[i].f_fini = (void*)RedDest<i>;
1511   /// red_data[i].f_comb = (void*)RedOp<i>;
1512   /// red_data[i].flags = <Flag_i>;
1513   /// ...
1514   /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,
1515   /// red_data);
1516   /// \endcode
1517   /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.
1518   /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.
1519   /// \param Data Additional data for task generation like tiedness, final
1520   /// state, list of privates, reductions etc.
1521   virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF,
1522                                              SourceLocation Loc,
1523                                              ArrayRef<const Expr *> LHSExprs,
1524                                              ArrayRef<const Expr *> RHSExprs,
1525                                              const OMPTaskDataTy &Data);
1526 
1527   /// Emits the following code for reduction clause with task modifier:
1528   /// \code
1529   /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);
1530   /// \endcode
1531   virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,
1532                                      bool IsWorksharingReduction);
1533 
1534   /// Required to resolve existing problems in the runtime. Emits threadprivate
1535   /// variables to store the size of the VLAs/array sections for
1536   /// initializer/combiner/finalizer functions.
1537   /// \param RCG Allows to reuse an existing data for the reductions.
1538   /// \param N Reduction item for which fixups must be emitted.
1539   virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,
1540                                        ReductionCodeGen &RCG, unsigned N);
1541 
1542   /// Get the address of `void *` type of the privatue copy of the reduction
1543   /// item specified by the \p SharedLVal.
1544   /// \param ReductionsPtr Pointer to the reduction data returned by the
1545   /// emitTaskReductionInit function.
1546   /// \param SharedLVal Address of the original reduction item.
1547   virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,
1548                                        llvm::Value *ReductionsPtr,
1549                                        LValue SharedLVal);
1550 
1551   /// Emit code for 'taskwait' directive.
1552   virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc,
1553                                 const OMPTaskDataTy &Data);
1554 
1555   /// Emit code for 'cancellation point' construct.
1556   /// \param CancelRegion Region kind for which the cancellation point must be
1557   /// emitted.
1558   ///
1559   virtual void emitCancellationPointCall(CodeGenFunction &CGF,
1560                                          SourceLocation Loc,
1561                                          OpenMPDirectiveKind CancelRegion);
1562 
1563   /// Emit code for 'cancel' construct.
1564   /// \param IfCond Condition in the associated 'if' clause, if it was
1565   /// specified, nullptr otherwise.
1566   /// \param CancelRegion Region kind for which the cancel must be emitted.
1567   ///
1568   virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
1569                               const Expr *IfCond,
1570                               OpenMPDirectiveKind CancelRegion);
1571 
1572   /// Emit outilined function for 'target' directive.
1573   /// \param D Directive to emit.
1574   /// \param ParentName Name of the function that encloses the target region.
1575   /// \param OutlinedFn Outlined function value to be defined by this call.
1576   /// \param OutlinedFnID Outlined function ID value to be defined by this call.
1577   /// \param IsOffloadEntry True if the outlined function is an offload entry.
1578   /// \param CodeGen Code generation sequence for the \a D directive.
1579   /// An outlined function may not be an entry if, e.g. the if clause always
1580   /// evaluates to false.
1581   virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
1582                                           StringRef ParentName,
1583                                           llvm::Function *&OutlinedFn,
1584                                           llvm::Constant *&OutlinedFnID,
1585                                           bool IsOffloadEntry,
1586                                           const RegionCodeGenTy &CodeGen);
1587 
1588   /// Emit the target offloading code associated with \a D. The emitted
1589   /// code attempts offloading the execution to the device, an the event of
1590   /// a failure it executes the host version outlined in \a OutlinedFn.
1591   /// \param D Directive to emit.
1592   /// \param OutlinedFn Host version of the code to be offloaded.
1593   /// \param OutlinedFnID ID of host version of the code to be offloaded.
1594   /// \param IfCond Expression evaluated in if clause associated with the target
1595   /// directive, or null if no if clause is used.
1596   /// \param Device Expression evaluated in device clause associated with the
1597   /// target directive, or null if no device clause is used and device modifier.
1598   /// \param SizeEmitter Callback to emit number of iterations for loop-based
1599   /// directives.
1600   virtual void emitTargetCall(
1601       CodeGenFunction &CGF, const OMPExecutableDirective &D,
1602       llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
1603       llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
1604       llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
1605                                        const OMPLoopDirective &D)>
1606           SizeEmitter);
1607 
1608   /// Emit the target regions enclosed in \a GD function definition or
1609   /// the function itself in case it is a valid device function. Returns true if
1610   /// \a GD was dealt with successfully.
1611   /// \param GD Function to scan.
1612   virtual bool emitTargetFunctions(GlobalDecl GD);
1613 
1614   /// Emit the global variable if it is a valid device global variable.
1615   /// Returns true if \a GD was dealt with successfully.
1616   /// \param GD Variable declaration to emit.
1617   virtual bool emitTargetGlobalVariable(GlobalDecl GD);
1618 
1619   /// Checks if the provided global decl \a GD is a declare target variable and
1620   /// registers it when emitting code for the host.
1621   virtual void registerTargetGlobalVariable(const VarDecl *VD,
1622                                             llvm::Constant *Addr);
1623 
1624   /// Emit the global \a GD if it is meaningful for the target. Returns
1625   /// if it was emitted successfully.
1626   /// \param GD Global to scan.
1627   virtual bool emitTargetGlobal(GlobalDecl GD);
1628 
1629   /// Creates and returns a registration function for when at least one
1630   /// requires directives was used in the current module.
1631   llvm::Function *emitRequiresDirectiveRegFun();
1632 
1633   /// Creates all the offload entries in the current compilation unit
1634   /// along with the associated metadata.
1635   void createOffloadEntriesAndInfoMetadata();
1636 
1637   /// Emits code for teams call of the \a OutlinedFn with
1638   /// variables captured in a record which address is stored in \a
1639   /// CapturedStruct.
1640   /// \param OutlinedFn Outlined function to be run by team masters. Type of
1641   /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
1642   /// \param CapturedVars A pointer to the record with the references to
1643   /// variables used in \a OutlinedFn function.
1644   ///
1645   virtual void emitTeamsCall(CodeGenFunction &CGF,
1646                              const OMPExecutableDirective &D,
1647                              SourceLocation Loc, llvm::Function *OutlinedFn,
1648                              ArrayRef<llvm::Value *> CapturedVars);
1649 
1650   /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
1651   /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
1652   /// for num_teams clause.
1653   /// \param NumTeams An integer expression of teams.
1654   /// \param ThreadLimit An integer expression of threads.
1655   virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
1656                                   const Expr *ThreadLimit, SourceLocation Loc);
1657 
1658   /// Struct that keeps all the relevant information that should be kept
1659   /// throughout a 'target data' region.
1660   class TargetDataInfo {
1661     /// Set to true if device pointer information have to be obtained.
1662     bool RequiresDevicePointerInfo = false;
1663     /// Set to true if Clang emits separate runtime calls for the beginning and
1664     /// end of the region.  These calls might have separate map type arrays.
1665     bool SeparateBeginEndCalls = false;
1666 
1667   public:
1668     /// The array of base pointer passed to the runtime library.
1669     llvm::Value *BasePointersArray = nullptr;
1670     /// The array of section pointers passed to the runtime library.
1671     llvm::Value *PointersArray = nullptr;
1672     /// The array of sizes passed to the runtime library.
1673     llvm::Value *SizesArray = nullptr;
1674     /// The array of map types passed to the runtime library for the beginning
1675     /// of the region or for the entire region if there are no separate map
1676     /// types for the region end.
1677     llvm::Value *MapTypesArray = nullptr;
1678     /// The array of map types passed to the runtime library for the end of the
1679     /// region, or nullptr if there are no separate map types for the region
1680     /// end.
1681     llvm::Value *MapTypesArrayEnd = nullptr;
1682     /// The array of user-defined mappers passed to the runtime library.
1683     llvm::Value *MappersArray = nullptr;
1684     /// The array of original declaration names of mapped pointers sent to the
1685     /// runtime library for debugging
1686     llvm::Value *MapNamesArray = nullptr;
1687     /// Indicate whether any user-defined mapper exists.
1688     bool HasMapper = false;
1689     /// The total number of pointers passed to the runtime library.
1690     unsigned NumberOfPtrs = 0u;
1691     /// Map between the a declaration of a capture and the corresponding base
1692     /// pointer address where the runtime returns the device pointers.
1693     llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap;
1694 
1695     explicit TargetDataInfo() {}
1696     explicit TargetDataInfo(bool RequiresDevicePointerInfo,
1697                             bool SeparateBeginEndCalls)
1698         : RequiresDevicePointerInfo(RequiresDevicePointerInfo),
1699           SeparateBeginEndCalls(SeparateBeginEndCalls) {}
1700     /// Clear information about the data arrays.
1701     void clearArrayInfo() {
1702       BasePointersArray = nullptr;
1703       PointersArray = nullptr;
1704       SizesArray = nullptr;
1705       MapTypesArray = nullptr;
1706       MapTypesArrayEnd = nullptr;
1707       MapNamesArray = nullptr;
1708       MappersArray = nullptr;
1709       HasMapper = false;
1710       NumberOfPtrs = 0u;
1711     }
1712     /// Return true if the current target data information has valid arrays.
1713     bool isValid() {
1714       return BasePointersArray && PointersArray && SizesArray &&
1715              MapTypesArray && (!HasMapper || MappersArray) && NumberOfPtrs;
1716     }
1717     bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; }
1718     bool separateBeginEndCalls() { return SeparateBeginEndCalls; }
1719   };
1720 
1721   /// Emit the target data mapping code associated with \a D.
1722   /// \param D Directive to emit.
1723   /// \param IfCond Expression evaluated in if clause associated with the
1724   /// target directive, or null if no device clause is used.
1725   /// \param Device Expression evaluated in device clause associated with the
1726   /// target directive, or null if no device clause is used.
1727   /// \param Info A record used to store information that needs to be preserved
1728   /// until the region is closed.
1729   virtual void emitTargetDataCalls(CodeGenFunction &CGF,
1730                                    const OMPExecutableDirective &D,
1731                                    const Expr *IfCond, const Expr *Device,
1732                                    const RegionCodeGenTy &CodeGen,
1733                                    TargetDataInfo &Info);
1734 
1735   /// Emit the data mapping/movement code associated with the directive
1736   /// \a D that should be of the form 'target [{enter|exit} data | update]'.
1737   /// \param D Directive to emit.
1738   /// \param IfCond Expression evaluated in if clause associated with the target
1739   /// directive, or null if no if clause is used.
1740   /// \param Device Expression evaluated in device clause associated with the
1741   /// target directive, or null if no device clause is used.
1742   virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF,
1743                                             const OMPExecutableDirective &D,
1744                                             const Expr *IfCond,
1745                                             const Expr *Device);
1746 
1747   /// Marks function \a Fn with properly mangled versions of vector functions.
1748   /// \param FD Function marked as 'declare simd'.
1749   /// \param Fn LLVM function that must be marked with 'declare simd'
1750   /// attributes.
1751   virtual void emitDeclareSimdFunction(const FunctionDecl *FD,
1752                                        llvm::Function *Fn);
1753 
1754   /// Emit initialization for doacross loop nesting support.
1755   /// \param D Loop-based construct used in doacross nesting construct.
1756   virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,
1757                                 ArrayRef<Expr *> NumIterations);
1758 
1759   /// Emit code for doacross ordered directive with 'depend' clause.
1760   /// \param C 'depend' clause with 'sink|source' dependency kind.
1761   virtual void emitDoacrossOrdered(CodeGenFunction &CGF,
1762                                    const OMPDependClause *C);
1763 
1764   /// Translates the native parameter of outlined function if this is required
1765   /// for target.
1766   /// \param FD Field decl from captured record for the parameter.
1767   /// \param NativeParam Parameter itself.
1768   virtual const VarDecl *translateParameter(const FieldDecl *FD,
1769                                             const VarDecl *NativeParam) const {
1770     return NativeParam;
1771   }
1772 
1773   /// Gets the address of the native argument basing on the address of the
1774   /// target-specific parameter.
1775   /// \param NativeParam Parameter itself.
1776   /// \param TargetParam Corresponding target-specific parameter.
1777   virtual Address getParameterAddress(CodeGenFunction &CGF,
1778                                       const VarDecl *NativeParam,
1779                                       const VarDecl *TargetParam) const;
1780 
1781   /// Choose default schedule type and chunk value for the
1782   /// dist_schedule clause.
1783   virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF,
1784       const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind,
1785       llvm::Value *&Chunk) const {}
1786 
1787   /// Choose default schedule type and chunk value for the
1788   /// schedule clause.
1789   virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
1790       const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
1791       const Expr *&ChunkExpr) const;
1792 
1793   /// Emits call of the outlined function with the provided arguments,
1794   /// translating these arguments to correct target-specific arguments.
1795   virtual void
1796   emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc,
1797                            llvm::FunctionCallee OutlinedFn,
1798                            ArrayRef<llvm::Value *> Args = llvm::None) const;
1799 
1800   /// Emits OpenMP-specific function prolog.
1801   /// Required for device constructs.
1802   virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D);
1803 
1804   /// Gets the OpenMP-specific address of the local variable.
1805   virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF,
1806                                             const VarDecl *VD);
1807 
1808   /// Marks the declaration as already emitted for the device code and returns
1809   /// true, if it was marked already, and false, otherwise.
1810   bool markAsGlobalTarget(GlobalDecl GD);
1811 
1812   /// Emit deferred declare target variables marked for deferred emission.
1813   void emitDeferredTargetDecls() const;
1814 
1815   /// Adjust some parameters for the target-based directives, like addresses of
1816   /// the variables captured by reference in lambdas.
1817   virtual void
1818   adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF,
1819                                      const OMPExecutableDirective &D) const;
1820 
1821   /// Perform check on requires decl to ensure that target architecture
1822   /// supports unified addressing
1823   virtual void processRequiresDirective(const OMPRequiresDecl *D);
1824 
1825   /// Gets default memory ordering as specified in requires directive.
1826   llvm::AtomicOrdering getDefaultMemoryOrdering() const;
1827 
1828   /// Checks if the variable has associated OMPAllocateDeclAttr attribute with
1829   /// the predefined allocator and translates it into the corresponding address
1830   /// space.
1831   virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS);
1832 
1833   /// Return whether the unified_shared_memory has been specified.
1834   bool hasRequiresUnifiedSharedMemory() const;
1835 
1836   /// Checks if the \p VD variable is marked as nontemporal declaration in
1837   /// current context.
1838   bool isNontemporalDecl(const ValueDecl *VD) const;
1839 
1840   /// Create specialized alloca to handle lastprivate conditionals.
1841   Address emitLastprivateConditionalInit(CodeGenFunction &CGF,
1842                                          const VarDecl *VD);
1843 
1844   /// Checks if the provided \p LVal is lastprivate conditional and emits the
1845   /// code to update the value of the original variable.
1846   /// \code
1847   /// lastprivate(conditional: a)
1848   /// ...
1849   /// <type> a;
1850   /// lp_a = ...;
1851   /// #pragma omp critical(a)
1852   /// if (last_iv_a <= iv) {
1853   ///   last_iv_a = iv;
1854   ///   global_a = lp_a;
1855   /// }
1856   /// \endcode
1857   virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF,
1858                                                   const Expr *LHS);
1859 
1860   /// Checks if the lastprivate conditional was updated in inner region and
1861   /// writes the value.
1862   /// \code
1863   /// lastprivate(conditional: a)
1864   /// ...
1865   /// <type> a;bool Fired = false;
1866   /// #pragma omp ... shared(a)
1867   /// {
1868   ///   lp_a = ...;
1869   ///   Fired = true;
1870   /// }
1871   /// if (Fired) {
1872   ///   #pragma omp critical(a)
1873   ///   if (last_iv_a <= iv) {
1874   ///     last_iv_a = iv;
1875   ///     global_a = lp_a;
1876   ///   }
1877   ///   Fired = false;
1878   /// }
1879   /// \endcode
1880   virtual void checkAndEmitSharedLastprivateConditional(
1881       CodeGenFunction &CGF, const OMPExecutableDirective &D,
1882       const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls);
1883 
1884   /// Gets the address of the global copy used for lastprivate conditional
1885   /// update, if any.
1886   /// \param PrivLVal LValue for the private copy.
1887   /// \param VD Original lastprivate declaration.
1888   virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF,
1889                                                      LValue PrivLVal,
1890                                                      const VarDecl *VD,
1891                                                      SourceLocation Loc);
1892 
1893   /// Emits list of dependecies based on the provided data (array of
1894   /// dependence/expression pairs).
1895   /// \returns Pointer to the first element of the array casted to VoidPtr type.
1896   std::pair<llvm::Value *, Address>
1897   emitDependClause(CodeGenFunction &CGF,
1898                    ArrayRef<OMPTaskDataTy::DependData> Dependencies,
1899                    SourceLocation Loc);
1900 
1901   /// Emits list of dependecies based on the provided data (array of
1902   /// dependence/expression pairs) for depobj construct. In this case, the
1903   /// variable is allocated in dynamically. \returns Pointer to the first
1904   /// element of the array casted to VoidPtr type.
1905   Address emitDepobjDependClause(CodeGenFunction &CGF,
1906                                  const OMPTaskDataTy::DependData &Dependencies,
1907                                  SourceLocation Loc);
1908 
1909   /// Emits the code to destroy the dependency object provided in depobj
1910   /// directive.
1911   void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal,
1912                          SourceLocation Loc);
1913 
1914   /// Updates the dependency kind in the specified depobj object.
1915   /// \param DepobjLVal LValue for the main depobj object.
1916   /// \param NewDepKind New dependency kind.
1917   void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal,
1918                         OpenMPDependClauseKind NewDepKind, SourceLocation Loc);
1919 
1920   /// Initializes user defined allocators specified in the uses_allocators
1921   /// clauses.
1922   void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator,
1923                               const Expr *AllocatorTraits);
1924 
1925   /// Destroys user defined allocators specified in the uses_allocators clause.
1926   void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator);
1927 
1928   /// Returns true if the variable is a local variable in untied task.
1929   bool isLocalVarInUntiedTask(CodeGenFunction &CGF, const VarDecl *VD) const;
1930 };
1931 
1932 /// Class supports emissionof SIMD-only code.
1933 class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime {
1934 public:
1935   explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {}
1936   ~CGOpenMPSIMDRuntime() override {}
1937 
1938   /// Emits outlined function for the specified OpenMP parallel directive
1939   /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
1940   /// kmp_int32 BoundID, struct context_vars*).
1941   /// \param D OpenMP directive.
1942   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
1943   /// \param InnermostKind Kind of innermost directive (for simple directives it
1944   /// is a directive itself, for combined - its innermost directive).
1945   /// \param CodeGen Code generation sequence for the \a D directive.
1946   llvm::Function *
1947   emitParallelOutlinedFunction(const OMPExecutableDirective &D,
1948                                const VarDecl *ThreadIDVar,
1949                                OpenMPDirectiveKind InnermostKind,
1950                                const RegionCodeGenTy &CodeGen) override;
1951 
1952   /// Emits outlined function for the specified OpenMP teams directive
1953   /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
1954   /// kmp_int32 BoundID, struct context_vars*).
1955   /// \param D OpenMP directive.
1956   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
1957   /// \param InnermostKind Kind of innermost directive (for simple directives it
1958   /// is a directive itself, for combined - its innermost directive).
1959   /// \param CodeGen Code generation sequence for the \a D directive.
1960   llvm::Function *
1961   emitTeamsOutlinedFunction(const OMPExecutableDirective &D,
1962                             const VarDecl *ThreadIDVar,
1963                             OpenMPDirectiveKind InnermostKind,
1964                             const RegionCodeGenTy &CodeGen) override;
1965 
1966   /// Emits outlined function for the OpenMP task directive \a D. This
1967   /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t*
1968   /// TaskT).
1969   /// \param D OpenMP directive.
1970   /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
1971   /// \param PartIDVar Variable for partition id in the current OpenMP untied
1972   /// task region.
1973   /// \param TaskTVar Variable for task_t argument.
1974   /// \param InnermostKind Kind of innermost directive (for simple directives it
1975   /// is a directive itself, for combined - its innermost directive).
1976   /// \param CodeGen Code generation sequence for the \a D directive.
1977   /// \param Tied true if task is generated for tied task, false otherwise.
1978   /// \param NumberOfParts Number of parts in untied task. Ignored for tied
1979   /// tasks.
1980   ///
1981   llvm::Function *emitTaskOutlinedFunction(
1982       const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1983       const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1984       OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1985       bool Tied, unsigned &NumberOfParts) override;
1986 
1987   /// Emits code for parallel or serial call of the \a OutlinedFn with
1988   /// variables captured in a record which address is stored in \a
1989   /// CapturedStruct.
1990   /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
1991   /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
1992   /// \param CapturedVars A pointer to the record with the references to
1993   /// variables used in \a OutlinedFn function.
1994   /// \param IfCond Condition in the associated 'if' clause, if it was
1995   /// specified, nullptr otherwise.
1996   /// \param NumThreads The value corresponding to the num_threads clause, if
1997   /// any, or nullptr.
1998   ///
1999   void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2000                         llvm::Function *OutlinedFn,
2001                         ArrayRef<llvm::Value *> CapturedVars,
2002                         const Expr *IfCond, llvm::Value *NumThreads) override;
2003 
2004   /// Emits a critical region.
2005   /// \param CriticalName Name of the critical region.
2006   /// \param CriticalOpGen Generator for the statement associated with the given
2007   /// critical region.
2008   /// \param Hint Value of the 'hint' clause (optional).
2009   void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
2010                           const RegionCodeGenTy &CriticalOpGen,
2011                           SourceLocation Loc,
2012                           const Expr *Hint = nullptr) override;
2013 
2014   /// Emits a master region.
2015   /// \param MasterOpGen Generator for the statement associated with the given
2016   /// master region.
2017   void emitMasterRegion(CodeGenFunction &CGF,
2018                         const RegionCodeGenTy &MasterOpGen,
2019                         SourceLocation Loc) override;
2020 
2021   /// Emits a masked region.
2022   /// \param MaskedOpGen Generator for the statement associated with the given
2023   /// masked region.
2024   void emitMaskedRegion(CodeGenFunction &CGF,
2025                         const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc,
2026                         const Expr *Filter = nullptr) override;
2027 
2028   /// Emits a masked region.
2029   /// \param MaskedOpGen Generator for the statement associated with the given
2030   /// masked region.
2031 
2032   /// Emits code for a taskyield directive.
2033   void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override;
2034 
2035   /// Emit a taskgroup region.
2036   /// \param TaskgroupOpGen Generator for the statement associated with the
2037   /// given taskgroup region.
2038   void emitTaskgroupRegion(CodeGenFunction &CGF,
2039                            const RegionCodeGenTy &TaskgroupOpGen,
2040                            SourceLocation Loc) override;
2041 
2042   /// Emits a single region.
2043   /// \param SingleOpGen Generator for the statement associated with the given
2044   /// single region.
2045   void emitSingleRegion(CodeGenFunction &CGF,
2046                         const RegionCodeGenTy &SingleOpGen, SourceLocation Loc,
2047                         ArrayRef<const Expr *> CopyprivateVars,
2048                         ArrayRef<const Expr *> DestExprs,
2049                         ArrayRef<const Expr *> SrcExprs,
2050                         ArrayRef<const Expr *> AssignmentOps) override;
2051 
2052   /// Emit an ordered region.
2053   /// \param OrderedOpGen Generator for the statement associated with the given
2054   /// ordered region.
2055   void emitOrderedRegion(CodeGenFunction &CGF,
2056                          const RegionCodeGenTy &OrderedOpGen,
2057                          SourceLocation Loc, bool IsThreads) override;
2058 
2059   /// Emit an implicit/explicit barrier for OpenMP threads.
2060   /// \param Kind Directive for which this implicit barrier call must be
2061   /// generated. Must be OMPD_barrier for explicit barrier generation.
2062   /// \param EmitChecks true if need to emit checks for cancellation barriers.
2063   /// \param ForceSimpleCall true simple barrier call must be emitted, false if
2064   /// runtime class decides which one to emit (simple or with cancellation
2065   /// checks).
2066   ///
2067   void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2068                        OpenMPDirectiveKind Kind, bool EmitChecks = true,
2069                        bool ForceSimpleCall = false) override;
2070 
2071   /// This is used for non static scheduled types and when the ordered
2072   /// clause is present on the loop construct.
2073   /// Depending on the loop schedule, it is necessary to call some runtime
2074   /// routine before start of the OpenMP loop to get the loop upper / lower
2075   /// bounds \a LB and \a UB and stride \a ST.
2076   ///
2077   /// \param CGF Reference to current CodeGenFunction.
2078   /// \param Loc Clang source location.
2079   /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
2080   /// \param IVSize Size of the iteration variable in bits.
2081   /// \param IVSigned Sign of the iteration variable.
2082   /// \param Ordered true if loop is ordered, false otherwise.
2083   /// \param DispatchValues struct containing llvm values for lower bound, upper
2084   /// bound, and chunk expression.
2085   /// For the default (nullptr) value, the chunk 1 will be used.
2086   ///
2087   void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc,
2088                            const OpenMPScheduleTy &ScheduleKind,
2089                            unsigned IVSize, bool IVSigned, bool Ordered,
2090                            const DispatchRTInput &DispatchValues) override;
2091 
2092   /// Call the appropriate runtime routine to initialize it before start
2093   /// of loop.
2094   ///
2095   /// This is used only in case of static schedule, when the user did not
2096   /// specify a ordered clause on the loop construct.
2097   /// Depending on the loop schedule, it is necessary to call some runtime
2098   /// routine before start of the OpenMP loop to get the loop upper / lower
2099   /// bounds LB and UB and stride ST.
2100   ///
2101   /// \param CGF Reference to current CodeGenFunction.
2102   /// \param Loc Clang source location.
2103   /// \param DKind Kind of the directive.
2104   /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause.
2105   /// \param Values Input arguments for the construct.
2106   ///
2107   void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
2108                          OpenMPDirectiveKind DKind,
2109                          const OpenMPScheduleTy &ScheduleKind,
2110                          const StaticRTInput &Values) override;
2111 
2112   ///
2113   /// \param CGF Reference to current CodeGenFunction.
2114   /// \param Loc Clang source location.
2115   /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause.
2116   /// \param Values Input arguments for the construct.
2117   ///
2118   void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc,
2119                                 OpenMPDistScheduleClauseKind SchedKind,
2120                                 const StaticRTInput &Values) override;
2121 
2122   /// Call the appropriate runtime routine to notify that we finished
2123   /// iteration of the ordered loop with the dynamic scheduling.
2124   ///
2125   /// \param CGF Reference to current CodeGenFunction.
2126   /// \param Loc Clang source location.
2127   /// \param IVSize Size of the iteration variable in bits.
2128   /// \param IVSigned Sign of the iteration variable.
2129   ///
2130   void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc,
2131                                   unsigned IVSize, bool IVSigned) override;
2132 
2133   /// Call the appropriate runtime routine to notify that we finished
2134   /// all the work with current loop.
2135   ///
2136   /// \param CGF Reference to current CodeGenFunction.
2137   /// \param Loc Clang source location.
2138   /// \param DKind Kind of the directive for which the static finish is emitted.
2139   ///
2140   void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc,
2141                            OpenMPDirectiveKind DKind) override;
2142 
2143   /// Call __kmpc_dispatch_next(
2144   ///          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2145   ///          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2146   ///          kmp_int[32|64] *p_stride);
2147   /// \param IVSize Size of the iteration variable in bits.
2148   /// \param IVSigned Sign of the iteration variable.
2149   /// \param IL Address of the output variable in which the flag of the
2150   /// last iteration is returned.
2151   /// \param LB Address of the output variable in which the lower iteration
2152   /// number is returned.
2153   /// \param UB Address of the output variable in which the upper iteration
2154   /// number is returned.
2155   /// \param ST Address of the output variable in which the stride value is
2156   /// returned.
2157   llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc,
2158                            unsigned IVSize, bool IVSigned, Address IL,
2159                            Address LB, Address UB, Address ST) override;
2160 
2161   /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
2162   /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
2163   /// clause.
2164   /// \param NumThreads An integer value of threads.
2165   void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads,
2166                             SourceLocation Loc) override;
2167 
2168   /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
2169   /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
2170   void emitProcBindClause(CodeGenFunction &CGF,
2171                           llvm::omp::ProcBindKind ProcBind,
2172                           SourceLocation Loc) override;
2173 
2174   /// Returns address of the threadprivate variable for the current
2175   /// thread.
2176   /// \param VD Threadprivate variable.
2177   /// \param VDAddr Address of the global variable \a VD.
2178   /// \param Loc Location of the reference to threadprivate var.
2179   /// \return Address of the threadprivate variable for the current thread.
2180   Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD,
2181                                  Address VDAddr, SourceLocation Loc) override;
2182 
2183   /// Emit a code for initialization of threadprivate variable. It emits
2184   /// a call to runtime library which adds initial value to the newly created
2185   /// threadprivate variable (if it is not constant) and registers destructor
2186   /// for the variable (if any).
2187   /// \param VD Threadprivate variable.
2188   /// \param VDAddr Address of the global variable \a VD.
2189   /// \param Loc Location of threadprivate declaration.
2190   /// \param PerformInit true if initialization expression is not constant.
2191   llvm::Function *
2192   emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr,
2193                                  SourceLocation Loc, bool PerformInit,
2194                                  CodeGenFunction *CGF = nullptr) override;
2195 
2196   /// Creates artificial threadprivate variable with name \p Name and type \p
2197   /// VarType.
2198   /// \param VarType Type of the artificial threadprivate variable.
2199   /// \param Name Name of the artificial threadprivate variable.
2200   Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2201                                            QualType VarType,
2202                                            StringRef Name) override;
2203 
2204   /// Emit flush of the variables specified in 'omp flush' directive.
2205   /// \param Vars List of variables to flush.
2206   void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars,
2207                  SourceLocation Loc, llvm::AtomicOrdering AO) override;
2208 
2209   /// Emit task region for the task directive. The task region is
2210   /// emitted in several steps:
2211   /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
2212   /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2213   /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
2214   /// function:
2215   /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
2216   ///   TaskFunction(gtid, tt->part_id, tt->shareds);
2217   ///   return 0;
2218   /// }
2219   /// 2. Copy a list of shared variables to field shareds of the resulting
2220   /// structure kmp_task_t returned by the previous call (if any).
2221   /// 3. Copy a pointer to destructions function to field destructions of the
2222   /// resulting structure kmp_task_t.
2223   /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid,
2224   /// kmp_task_t *new_task), where new_task is a resulting structure from
2225   /// previous items.
2226   /// \param D Current task directive.
2227   /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
2228   /// /*part_id*/, captured_struct */*__context*/);
2229   /// \param SharedsTy A type which contains references the shared variables.
2230   /// \param Shareds Context with the list of shared variables from the \p
2231   /// TaskFunction.
2232   /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
2233   /// otherwise.
2234   /// \param Data Additional data for task generation like tiednsee, final
2235   /// state, list of privates etc.
2236   void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
2237                     const OMPExecutableDirective &D,
2238                     llvm::Function *TaskFunction, QualType SharedsTy,
2239                     Address Shareds, const Expr *IfCond,
2240                     const OMPTaskDataTy &Data) override;
2241 
2242   /// Emit task region for the taskloop directive. The taskloop region is
2243   /// emitted in several steps:
2244   /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32
2245   /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
2246   /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the
2247   /// function:
2248   /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
2249   ///   TaskFunction(gtid, tt->part_id, tt->shareds);
2250   ///   return 0;
2251   /// }
2252   /// 2. Copy a list of shared variables to field shareds of the resulting
2253   /// structure kmp_task_t returned by the previous call (if any).
2254   /// 3. Copy a pointer to destructions function to field destructions of the
2255   /// resulting structure kmp_task_t.
2256   /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t
2257   /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int
2258   /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task
2259   /// is a resulting structure from
2260   /// previous items.
2261   /// \param D Current task directive.
2262   /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32
2263   /// /*part_id*/, captured_struct */*__context*/);
2264   /// \param SharedsTy A type which contains references the shared variables.
2265   /// \param Shareds Context with the list of shared variables from the \p
2266   /// TaskFunction.
2267   /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr
2268   /// otherwise.
2269   /// \param Data Additional data for task generation like tiednsee, final
2270   /// state, list of privates etc.
2271   void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
2272                         const OMPLoopDirective &D, llvm::Function *TaskFunction,
2273                         QualType SharedsTy, Address Shareds, const Expr *IfCond,
2274                         const OMPTaskDataTy &Data) override;
2275 
2276   /// Emit a code for reduction clause. Next code should be emitted for
2277   /// reduction:
2278   /// \code
2279   ///
2280   /// static kmp_critical_name lock = { 0 };
2281   ///
2282   /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
2283   ///  ...
2284   ///  *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
2285   ///  ...
2286   /// }
2287   ///
2288   /// ...
2289   /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
2290   /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
2291   /// RedList, reduce_func, &<lock>)) {
2292   /// case 1:
2293   ///  ...
2294   ///  <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
2295   ///  ...
2296   /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
2297   /// break;
2298   /// case 2:
2299   ///  ...
2300   ///  Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
2301   ///  ...
2302   /// break;
2303   /// default:;
2304   /// }
2305   /// \endcode
2306   ///
2307   /// \param Privates List of private copies for original reduction arguments.
2308   /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
2309   /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
2310   /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
2311   /// or 'operator binop(LHS, RHS)'.
2312   /// \param Options List of options for reduction codegen:
2313   ///     WithNowait true if parent directive has also nowait clause, false
2314   ///     otherwise.
2315   ///     SimpleReduction Emit reduction operation only. Used for omp simd
2316   ///     directive on the host.
2317   ///     ReductionKind The kind of reduction to perform.
2318   void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
2319                      ArrayRef<const Expr *> Privates,
2320                      ArrayRef<const Expr *> LHSExprs,
2321                      ArrayRef<const Expr *> RHSExprs,
2322                      ArrayRef<const Expr *> ReductionOps,
2323                      ReductionOptionsTy Options) override;
2324 
2325   /// Emit a code for initialization of task reduction clause. Next code
2326   /// should be emitted for reduction:
2327   /// \code
2328   ///
2329   /// _taskred_item_t red_data[n];
2330   /// ...
2331   /// red_data[i].shar = &shareds[i];
2332   /// red_data[i].orig = &origs[i];
2333   /// red_data[i].size = sizeof(origs[i]);
2334   /// red_data[i].f_init = (void*)RedInit<i>;
2335   /// red_data[i].f_fini = (void*)RedDest<i>;
2336   /// red_data[i].f_comb = (void*)RedOp<i>;
2337   /// red_data[i].flags = <Flag_i>;
2338   /// ...
2339   /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data);
2340   /// \endcode
2341   /// For reduction clause with task modifier it emits the next call:
2342   /// \code
2343   ///
2344   /// _taskred_item_t red_data[n];
2345   /// ...
2346   /// red_data[i].shar = &shareds[i];
2347   /// red_data[i].orig = &origs[i];
2348   /// red_data[i].size = sizeof(origs[i]);
2349   /// red_data[i].f_init = (void*)RedInit<i>;
2350   /// red_data[i].f_fini = (void*)RedDest<i>;
2351   /// red_data[i].f_comb = (void*)RedOp<i>;
2352   /// red_data[i].flags = <Flag_i>;
2353   /// ...
2354   /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n,
2355   /// red_data);
2356   /// \endcode
2357   /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations.
2358   /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations.
2359   /// \param Data Additional data for task generation like tiedness, final
2360   /// state, list of privates, reductions etc.
2361   llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc,
2362                                      ArrayRef<const Expr *> LHSExprs,
2363                                      ArrayRef<const Expr *> RHSExprs,
2364                                      const OMPTaskDataTy &Data) override;
2365 
2366   /// Emits the following code for reduction clause with task modifier:
2367   /// \code
2368   /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing);
2369   /// \endcode
2370   void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc,
2371                              bool IsWorksharingReduction) override;
2372 
2373   /// Required to resolve existing problems in the runtime. Emits threadprivate
2374   /// variables to store the size of the VLAs/array sections for
2375   /// initializer/combiner/finalizer functions + emits threadprivate variable to
2376   /// store the pointer to the original reduction item for the custom
2377   /// initializer defined by declare reduction construct.
2378   /// \param RCG Allows to reuse an existing data for the reductions.
2379   /// \param N Reduction item for which fixups must be emitted.
2380   void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc,
2381                                ReductionCodeGen &RCG, unsigned N) override;
2382 
2383   /// Get the address of `void *` type of the privatue copy of the reduction
2384   /// item specified by the \p SharedLVal.
2385   /// \param ReductionsPtr Pointer to the reduction data returned by the
2386   /// emitTaskReductionInit function.
2387   /// \param SharedLVal Address of the original reduction item.
2388   Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc,
2389                                llvm::Value *ReductionsPtr,
2390                                LValue SharedLVal) override;
2391 
2392   /// Emit code for 'taskwait' directive.
2393   void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc,
2394                         const OMPTaskDataTy &Data) override;
2395 
2396   /// Emit code for 'cancellation point' construct.
2397   /// \param CancelRegion Region kind for which the cancellation point must be
2398   /// emitted.
2399   ///
2400   void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc,
2401                                  OpenMPDirectiveKind CancelRegion) override;
2402 
2403   /// Emit code for 'cancel' construct.
2404   /// \param IfCond Condition in the associated 'if' clause, if it was
2405   /// specified, nullptr otherwise.
2406   /// \param CancelRegion Region kind for which the cancel must be emitted.
2407   ///
2408   void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
2409                       const Expr *IfCond,
2410                       OpenMPDirectiveKind CancelRegion) override;
2411 
2412   /// Emit outilined function for 'target' directive.
2413   /// \param D Directive to emit.
2414   /// \param ParentName Name of the function that encloses the target region.
2415   /// \param OutlinedFn Outlined function value to be defined by this call.
2416   /// \param OutlinedFnID Outlined function ID value to be defined by this call.
2417   /// \param IsOffloadEntry True if the outlined function is an offload entry.
2418   /// \param CodeGen Code generation sequence for the \a D directive.
2419   /// An outlined function may not be an entry if, e.g. the if clause always
2420   /// evaluates to false.
2421   void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
2422                                   StringRef ParentName,
2423                                   llvm::Function *&OutlinedFn,
2424                                   llvm::Constant *&OutlinedFnID,
2425                                   bool IsOffloadEntry,
2426                                   const RegionCodeGenTy &CodeGen) override;
2427 
2428   /// Emit the target offloading code associated with \a D. The emitted
2429   /// code attempts offloading the execution to the device, an the event of
2430   /// a failure it executes the host version outlined in \a OutlinedFn.
2431   /// \param D Directive to emit.
2432   /// \param OutlinedFn Host version of the code to be offloaded.
2433   /// \param OutlinedFnID ID of host version of the code to be offloaded.
2434   /// \param IfCond Expression evaluated in if clause associated with the target
2435   /// directive, or null if no if clause is used.
2436   /// \param Device Expression evaluated in device clause associated with the
2437   /// target directive, or null if no device clause is used and device modifier.
2438   void emitTargetCall(
2439       CodeGenFunction &CGF, const OMPExecutableDirective &D,
2440       llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond,
2441       llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device,
2442       llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2443                                        const OMPLoopDirective &D)>
2444           SizeEmitter) override;
2445 
2446   /// Emit the target regions enclosed in \a GD function definition or
2447   /// the function itself in case it is a valid device function. Returns true if
2448   /// \a GD was dealt with successfully.
2449   /// \param GD Function to scan.
2450   bool emitTargetFunctions(GlobalDecl GD) override;
2451 
2452   /// Emit the global variable if it is a valid device global variable.
2453   /// Returns true if \a GD was dealt with successfully.
2454   /// \param GD Variable declaration to emit.
2455   bool emitTargetGlobalVariable(GlobalDecl GD) override;
2456 
2457   /// Emit the global \a GD if it is meaningful for the target. Returns
2458   /// if it was emitted successfully.
2459   /// \param GD Global to scan.
2460   bool emitTargetGlobal(GlobalDecl GD) override;
2461 
2462   /// Emits code for teams call of the \a OutlinedFn with
2463   /// variables captured in a record which address is stored in \a
2464   /// CapturedStruct.
2465   /// \param OutlinedFn Outlined function to be run by team masters. Type of
2466   /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
2467   /// \param CapturedVars A pointer to the record with the references to
2468   /// variables used in \a OutlinedFn function.
2469   ///
2470   void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,
2471                      SourceLocation Loc, llvm::Function *OutlinedFn,
2472                      ArrayRef<llvm::Value *> CapturedVars) override;
2473 
2474   /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32
2475   /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code
2476   /// for num_teams clause.
2477   /// \param NumTeams An integer expression of teams.
2478   /// \param ThreadLimit An integer expression of threads.
2479   void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
2480                           const Expr *ThreadLimit, SourceLocation Loc) override;
2481 
2482   /// Emit the target data mapping code associated with \a D.
2483   /// \param D Directive to emit.
2484   /// \param IfCond Expression evaluated in if clause associated with the
2485   /// target directive, or null if no device clause is used.
2486   /// \param Device Expression evaluated in device clause associated with the
2487   /// target directive, or null if no device clause is used.
2488   /// \param Info A record used to store information that needs to be preserved
2489   /// until the region is closed.
2490   void emitTargetDataCalls(CodeGenFunction &CGF,
2491                            const OMPExecutableDirective &D, const Expr *IfCond,
2492                            const Expr *Device, const RegionCodeGenTy &CodeGen,
2493                            TargetDataInfo &Info) override;
2494 
2495   /// Emit the data mapping/movement code associated with the directive
2496   /// \a D that should be of the form 'target [{enter|exit} data | update]'.
2497   /// \param D Directive to emit.
2498   /// \param IfCond Expression evaluated in if clause associated with the target
2499   /// directive, or null if no if clause is used.
2500   /// \param Device Expression evaluated in device clause associated with the
2501   /// target directive, or null if no device clause is used.
2502   void emitTargetDataStandAloneCall(CodeGenFunction &CGF,
2503                                     const OMPExecutableDirective &D,
2504                                     const Expr *IfCond,
2505                                     const Expr *Device) override;
2506 
2507   /// Emit initialization for doacross loop nesting support.
2508   /// \param D Loop-based construct used in doacross nesting construct.
2509   void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D,
2510                         ArrayRef<Expr *> NumIterations) override;
2511 
2512   /// Emit code for doacross ordered directive with 'depend' clause.
2513   /// \param C 'depend' clause with 'sink|source' dependency kind.
2514   void emitDoacrossOrdered(CodeGenFunction &CGF,
2515                            const OMPDependClause *C) override;
2516 
2517   /// Translates the native parameter of outlined function if this is required
2518   /// for target.
2519   /// \param FD Field decl from captured record for the parameter.
2520   /// \param NativeParam Parameter itself.
2521   const VarDecl *translateParameter(const FieldDecl *FD,
2522                                     const VarDecl *NativeParam) const override;
2523 
2524   /// Gets the address of the native argument basing on the address of the
2525   /// target-specific parameter.
2526   /// \param NativeParam Parameter itself.
2527   /// \param TargetParam Corresponding target-specific parameter.
2528   Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,
2529                               const VarDecl *TargetParam) const override;
2530 
2531   /// Gets the OpenMP-specific address of the local variable.
2532   Address getAddressOfLocalVariable(CodeGenFunction &CGF,
2533                                     const VarDecl *VD) override {
2534     return Address::invalid();
2535   }
2536 };
2537 
2538 } // namespace CodeGen
2539 } // namespace clang
2540 
2541 #endif
2542