1 //===-- IPO/OpenMPOpt.cpp - Collection of OpenMP specific optimizations ---===//
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 // OpenMP specific optimizations:
10 //
11 // - Deduplication of runtime calls, e.g., omp_get_thread_num.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/OpenMPOpt.h"
16 
17 #include "llvm/ADT/EnumeratedArray.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22 #include "llvm/Frontend/OpenMP/OMPConstants.h"
23 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Transforms/IPO/Attributor.h"
28 #include "llvm/Transforms/Utils/CallGraphUpdater.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 
31 using namespace llvm;
32 using namespace omp;
33 
34 #define DEBUG_TYPE "openmp-opt"
35 
36 static cl::opt<bool> DisableOpenMPOptimizations(
37     "openmp-opt-disable", cl::ZeroOrMore,
38     cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
39     cl::init(false));
40 
41 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false),
42                                     cl::Hidden);
43 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels",
44                                         cl::init(false), cl::Hidden);
45 
46 static cl::opt<bool> HideMemoryTransferLatency(
47     "openmp-hide-memory-transfer-latency",
48     cl::desc("[WIP] Tries to hide the latency of host to device memory"
49              " transfers"),
50     cl::Hidden, cl::init(false));
51 
52 
53 STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
54           "Number of OpenMP runtime calls deduplicated");
55 STATISTIC(NumOpenMPParallelRegionsDeleted,
56           "Number of OpenMP parallel regions deleted");
57 STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
58           "Number of OpenMP runtime functions identified");
59 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
60           "Number of OpenMP runtime function uses identified");
61 STATISTIC(NumOpenMPTargetRegionKernels,
62           "Number of OpenMP target region entry points (=kernels) identified");
63 STATISTIC(
64     NumOpenMPParallelRegionsReplacedInGPUStateMachine,
65     "Number of OpenMP parallel regions replaced with ID in GPU state machines");
66 
67 #if !defined(NDEBUG)
68 static constexpr auto TAG = "[" DEBUG_TYPE "]";
69 #endif
70 
71 namespace {
72 
73 struct AAICVTracker;
74 
75 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for
76 /// Attributor runs.
77 struct OMPInformationCache : public InformationCache {
78   OMPInformationCache(Module &M, AnalysisGetter &AG,
79                       BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC,
80                       SmallPtrSetImpl<Kernel> &Kernels)
81       : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M),
82         Kernels(Kernels) {
83 
84     OMPBuilder.initialize();
85     initializeRuntimeFunctions();
86     initializeInternalControlVars();
87   }
88 
89   /// Generic information that describes an internal control variable.
90   struct InternalControlVarInfo {
91     /// The kind, as described by InternalControlVar enum.
92     InternalControlVar Kind;
93 
94     /// The name of the ICV.
95     StringRef Name;
96 
97     /// Environment variable associated with this ICV.
98     StringRef EnvVarName;
99 
100     /// Initial value kind.
101     ICVInitValue InitKind;
102 
103     /// Initial value.
104     ConstantInt *InitValue;
105 
106     /// Setter RTL function associated with this ICV.
107     RuntimeFunction Setter;
108 
109     /// Getter RTL function associated with this ICV.
110     RuntimeFunction Getter;
111 
112     /// RTL Function corresponding to the override clause of this ICV
113     RuntimeFunction Clause;
114   };
115 
116   /// Generic information that describes a runtime function
117   struct RuntimeFunctionInfo {
118 
119     /// The kind, as described by the RuntimeFunction enum.
120     RuntimeFunction Kind;
121 
122     /// The name of the function.
123     StringRef Name;
124 
125     /// Flag to indicate a variadic function.
126     bool IsVarArg;
127 
128     /// The return type of the function.
129     Type *ReturnType;
130 
131     /// The argument types of the function.
132     SmallVector<Type *, 8> ArgumentTypes;
133 
134     /// The declaration if available.
135     Function *Declaration = nullptr;
136 
137     /// Uses of this runtime function per function containing the use.
138     using UseVector = SmallVector<Use *, 16>;
139 
140     /// Clear UsesMap for runtime function.
141     void clearUsesMap() { UsesMap.clear(); }
142 
143     /// Boolean conversion that is true if the runtime function was found.
144     operator bool() const { return Declaration; }
145 
146     /// Return the vector of uses in function \p F.
147     UseVector &getOrCreateUseVector(Function *F) {
148       std::shared_ptr<UseVector> &UV = UsesMap[F];
149       if (!UV)
150         UV = std::make_shared<UseVector>();
151       return *UV;
152     }
153 
154     /// Return the vector of uses in function \p F or `nullptr` if there are
155     /// none.
156     const UseVector *getUseVector(Function &F) const {
157       auto I = UsesMap.find(&F);
158       if (I != UsesMap.end())
159         return I->second.get();
160       return nullptr;
161     }
162 
163     /// Return how many functions contain uses of this runtime function.
164     size_t getNumFunctionsWithUses() const { return UsesMap.size(); }
165 
166     /// Return the number of arguments (or the minimal number for variadic
167     /// functions).
168     size_t getNumArgs() const { return ArgumentTypes.size(); }
169 
170     /// Run the callback \p CB on each use and forget the use if the result is
171     /// true. The callback will be fed the function in which the use was
172     /// encountered as second argument.
173     void foreachUse(SmallVectorImpl<Function *> &SCC,
174                     function_ref<bool(Use &, Function &)> CB) {
175       for (Function *F : SCC)
176         foreachUse(CB, F);
177     }
178 
179     /// Run the callback \p CB on each use within the function \p F and forget
180     /// the use if the result is true.
181     void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) {
182       SmallVector<unsigned, 8> ToBeDeleted;
183       ToBeDeleted.clear();
184 
185       unsigned Idx = 0;
186       UseVector &UV = getOrCreateUseVector(F);
187 
188       for (Use *U : UV) {
189         if (CB(*U, *F))
190           ToBeDeleted.push_back(Idx);
191         ++Idx;
192       }
193 
194       // Remove the to-be-deleted indices in reverse order as prior
195       // modifications will not modify the smaller indices.
196       while (!ToBeDeleted.empty()) {
197         unsigned Idx = ToBeDeleted.pop_back_val();
198         UV[Idx] = UV.back();
199         UV.pop_back();
200       }
201     }
202 
203   private:
204     /// Map from functions to all uses of this runtime function contained in
205     /// them.
206     DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap;
207   };
208 
209   /// An OpenMP-IR-Builder instance
210   OpenMPIRBuilder OMPBuilder;
211 
212   /// Map from runtime function kind to the runtime function description.
213   EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
214                   RuntimeFunction::OMPRTL___last>
215       RFIs;
216 
217   /// Map from ICV kind to the ICV description.
218   EnumeratedArray<InternalControlVarInfo, InternalControlVar,
219                   InternalControlVar::ICV___last>
220       ICVs;
221 
222   /// Helper to initialize all internal control variable information for those
223   /// defined in OMPKinds.def.
224   void initializeInternalControlVars() {
225 #define ICV_RT_SET(_Name, RTL)                                                 \
226   {                                                                            \
227     auto &ICV = ICVs[_Name];                                                   \
228     ICV.Setter = RTL;                                                          \
229   }
230 #define ICV_RT_GET(Name, RTL)                                                  \
231   {                                                                            \
232     auto &ICV = ICVs[Name];                                                    \
233     ICV.Getter = RTL;                                                          \
234   }
235 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init)                           \
236   {                                                                            \
237     auto &ICV = ICVs[Enum];                                                    \
238     ICV.Name = _Name;                                                          \
239     ICV.Kind = Enum;                                                           \
240     ICV.InitKind = Init;                                                       \
241     ICV.EnvVarName = _EnvVarName;                                              \
242     switch (ICV.InitKind) {                                                    \
243     case ICV_IMPLEMENTATION_DEFINED:                                           \
244       ICV.InitValue = nullptr;                                                 \
245       break;                                                                   \
246     case ICV_ZERO:                                                             \
247       ICV.InitValue = ConstantInt::get(                                        \
248           Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0);                \
249       break;                                                                   \
250     case ICV_FALSE:                                                            \
251       ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext());    \
252       break;                                                                   \
253     case ICV_LAST:                                                             \
254       break;                                                                   \
255     }                                                                          \
256   }
257 #include "llvm/Frontend/OpenMP/OMPKinds.def"
258   }
259 
260   /// Returns true if the function declaration \p F matches the runtime
261   /// function types, that is, return type \p RTFRetType, and argument types
262   /// \p RTFArgTypes.
263   static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
264                                   SmallVector<Type *, 8> &RTFArgTypes) {
265     // TODO: We should output information to the user (under debug output
266     //       and via remarks).
267 
268     if (!F)
269       return false;
270     if (F->getReturnType() != RTFRetType)
271       return false;
272     if (F->arg_size() != RTFArgTypes.size())
273       return false;
274 
275     auto RTFTyIt = RTFArgTypes.begin();
276     for (Argument &Arg : F->args()) {
277       if (Arg.getType() != *RTFTyIt)
278         return false;
279 
280       ++RTFTyIt;
281     }
282 
283     return true;
284   }
285 
286   // Helper to collect all uses of the declaration in the UsesMap.
287   unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) {
288     unsigned NumUses = 0;
289     if (!RFI.Declaration)
290       return NumUses;
291     OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
292 
293     if (CollectStats) {
294       NumOpenMPRuntimeFunctionsIdentified += 1;
295       NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
296     }
297 
298     // TODO: We directly convert uses into proper calls and unknown uses.
299     for (Use &U : RFI.Declaration->uses()) {
300       if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
301         if (ModuleSlice.count(UserI->getFunction())) {
302           RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U);
303           ++NumUses;
304         }
305       } else {
306         RFI.getOrCreateUseVector(nullptr).push_back(&U);
307         ++NumUses;
308       }
309     }
310     return NumUses;
311   }
312 
313   // Helper function to recollect uses of all runtime functions.
314   void recollectUses() {
315     for (int Idx = 0; Idx < RFIs.size(); ++Idx) {
316       auto &RFI = RFIs[static_cast<RuntimeFunction>(Idx)];
317       RFI.clearUsesMap();
318       collectUses(RFI, /*CollectStats*/ false);
319     }
320   }
321 
322   /// Helper to initialize all runtime function information for those defined
323   /// in OpenMPKinds.def.
324   void initializeRuntimeFunctions() {
325     Module &M = *((*ModuleSlice.begin())->getParent());
326 
327     // Helper macros for handling __VA_ARGS__ in OMP_RTL
328 #define OMP_TYPE(VarName, ...)                                                 \
329   Type *VarName = OMPBuilder.VarName;                                          \
330   (void)VarName;
331 
332 #define OMP_ARRAY_TYPE(VarName, ...)                                           \
333   ArrayType *VarName##Ty = OMPBuilder.VarName##Ty;                             \
334   (void)VarName##Ty;                                                           \
335   PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy;                     \
336   (void)VarName##PtrTy;
337 
338 #define OMP_FUNCTION_TYPE(VarName, ...)                                        \
339   FunctionType *VarName = OMPBuilder.VarName;                                  \
340   (void)VarName;                                                               \
341   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
342   (void)VarName##Ptr;
343 
344 #define OMP_STRUCT_TYPE(VarName, ...)                                          \
345   StructType *VarName = OMPBuilder.VarName;                                    \
346   (void)VarName;                                                               \
347   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
348   (void)VarName##Ptr;
349 
350 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...)                     \
351   {                                                                            \
352     SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__});                           \
353     Function *F = M.getFunction(_Name);                                        \
354     if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) {           \
355       auto &RFI = RFIs[_Enum];                                                 \
356       RFI.Kind = _Enum;                                                        \
357       RFI.Name = _Name;                                                        \
358       RFI.IsVarArg = _IsVarArg;                                                \
359       RFI.ReturnType = OMPBuilder._ReturnType;                                 \
360       RFI.ArgumentTypes = std::move(ArgsTypes);                                \
361       RFI.Declaration = F;                                                     \
362       unsigned NumUses = collectUses(RFI);                                     \
363       (void)NumUses;                                                           \
364       LLVM_DEBUG({                                                             \
365         dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not")           \
366                << " found\n";                                                  \
367         if (RFI.Declaration)                                                   \
368           dbgs() << TAG << "-> got " << NumUses << " uses in "                 \
369                  << RFI.getNumFunctionsWithUses()                              \
370                  << " different functions.\n";                                 \
371       });                                                                      \
372     }                                                                          \
373   }
374 #include "llvm/Frontend/OpenMP/OMPKinds.def"
375 
376     // TODO: We should attach the attributes defined in OMPKinds.def.
377   }
378 
379   /// Collection of known kernels (\see Kernel) in the module.
380   SmallPtrSetImpl<Kernel> &Kernels;
381 };
382 
383 /// Used to map the values physically (in the IR) stored in an offload
384 /// array, to a vector in memory.
385 struct OffloadArray {
386   /// Physical array (in the IR).
387   AllocaInst *Array = nullptr;
388   /// Mapped values.
389   SmallVector<Value *, 8> StoredValues;
390   /// Last stores made in the offload array.
391   SmallVector<StoreInst *, 8> LastAccesses;
392 
393   OffloadArray() = default;
394 
395   /// Initializes the OffloadArray with the values stored in \p Array before
396   /// instruction \p Before is reached. Returns false if the initialization
397   /// fails.
398   /// This MUST be used immediately after the construction of the object.
399   bool initialize(AllocaInst &Array, Instruction &Before) {
400     if (!Array.getAllocatedType()->isArrayTy())
401       return false;
402 
403     if (!getValues(Array, Before))
404       return false;
405 
406     this->Array = &Array;
407     return true;
408   }
409 
410   static const unsigned BasePtrsArgNum = 2;
411   static const unsigned PtrsArgNum = 3;
412   static const unsigned SizesArgNum = 4;
413 
414 private:
415   /// Traverses the BasicBlock where \p Array is, collecting the stores made to
416   /// \p Array, leaving StoredValues with the values stored before the
417   /// instruction \p Before is reached.
418   bool getValues(AllocaInst &Array, Instruction &Before) {
419     // Initialize container.
420     const uint64_t NumValues =
421         Array.getAllocatedType()->getArrayNumElements();
422     StoredValues.assign(NumValues, nullptr);
423     LastAccesses.assign(NumValues, nullptr);
424 
425     // TODO: This assumes the instruction \p Before is in the same
426     //  BasicBlock as Array. Make it general, for any control flow graph.
427     BasicBlock *BB = Array.getParent();
428     if (BB != Before.getParent())
429       return false;
430 
431     const DataLayout &DL = Array.getModule()->getDataLayout();
432     const unsigned int PointerSize = DL.getPointerSize();
433 
434     for (Instruction &I : *BB) {
435       if (&I == &Before)
436         break;
437 
438       if (!isa<StoreInst>(&I))
439         continue;
440 
441       auto *S = cast<StoreInst>(&I);
442       int64_t Offset = -1;
443       auto *Dst = GetPointerBaseWithConstantOffset(S->getPointerOperand(),
444                                                    Offset, DL);
445       if (Dst == &Array) {
446         int64_t Idx = Offset / PointerSize;
447         StoredValues[Idx] = getUnderlyingObject(S->getValueOperand());
448         LastAccesses[Idx] = S;
449       }
450     }
451 
452     return isFilled();
453   }
454 
455   /// Returns true if all values in StoredValues and
456   /// LastAccesses are not nullptrs.
457   bool isFilled() {
458     const unsigned NumValues = StoredValues.size();
459     for (unsigned I = 0; I < NumValues; ++I) {
460       if (!StoredValues[I] || !LastAccesses[I])
461         return false;
462     }
463 
464     return true;
465   }
466 };
467 
468 struct OpenMPOpt {
469 
470   using OptimizationRemarkGetter =
471       function_ref<OptimizationRemarkEmitter &(Function *)>;
472 
473   OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater,
474             OptimizationRemarkGetter OREGetter,
475             OMPInformationCache &OMPInfoCache, Attributor &A)
476       : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater),
477         OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {}
478 
479   /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
480   bool run() {
481     if (SCC.empty())
482       return false;
483 
484     bool Changed = false;
485 
486     LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
487                       << " functions in a slice with "
488                       << OMPInfoCache.ModuleSlice.size() << " functions\n");
489 
490     if (PrintICVValues)
491       printICVs();
492     if (PrintOpenMPKernels)
493       printKernels();
494 
495     Changed |= rewriteDeviceCodeStateMachine();
496 
497     Changed |= runAttributor();
498 
499     // Recollect uses, in case Attributor deleted any.
500     OMPInfoCache.recollectUses();
501 
502     Changed |= deduplicateRuntimeCalls();
503     Changed |= deleteParallelRegions();
504     if (HideMemoryTransferLatency)
505       Changed |= hideMemTransfersLatency();
506 
507     return Changed;
508   }
509 
510   /// Print initial ICV values for testing.
511   /// FIXME: This should be done from the Attributor once it is added.
512   void printICVs() const {
513     InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel};
514 
515     for (Function *F : OMPInfoCache.ModuleSlice) {
516       for (auto ICV : ICVs) {
517         auto ICVInfo = OMPInfoCache.ICVs[ICV];
518         auto Remark = [&](OptimizationRemark OR) {
519           return OR << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name)
520                     << " Value: "
521                     << (ICVInfo.InitValue
522                             ? ICVInfo.InitValue->getValue().toString(10, true)
523                             : "IMPLEMENTATION_DEFINED");
524         };
525 
526         emitRemarkOnFunction(F, "OpenMPICVTracker", Remark);
527       }
528     }
529   }
530 
531   /// Print OpenMP GPU kernels for testing.
532   void printKernels() const {
533     for (Function *F : SCC) {
534       if (!OMPInfoCache.Kernels.count(F))
535         continue;
536 
537       auto Remark = [&](OptimizationRemark OR) {
538         return OR << "OpenMP GPU kernel "
539                   << ore::NV("OpenMPGPUKernel", F->getName()) << "\n";
540       };
541 
542       emitRemarkOnFunction(F, "OpenMPGPU", Remark);
543     }
544   }
545 
546   /// Return the call if \p U is a callee use in a regular call. If \p RFI is
547   /// given it has to be the callee or a nullptr is returned.
548   static CallInst *getCallIfRegularCall(
549       Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
550     CallInst *CI = dyn_cast<CallInst>(U.getUser());
551     if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
552         (!RFI || CI->getCalledFunction() == RFI->Declaration))
553       return CI;
554     return nullptr;
555   }
556 
557   /// Return the call if \p V is a regular call. If \p RFI is given it has to be
558   /// the callee or a nullptr is returned.
559   static CallInst *getCallIfRegularCall(
560       Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
561     CallInst *CI = dyn_cast<CallInst>(&V);
562     if (CI && !CI->hasOperandBundles() &&
563         (!RFI || CI->getCalledFunction() == RFI->Declaration))
564       return CI;
565     return nullptr;
566   }
567 
568 private:
569   /// Try to delete parallel regions if possible.
570   bool deleteParallelRegions() {
571     const unsigned CallbackCalleeOperand = 2;
572 
573     OMPInformationCache::RuntimeFunctionInfo &RFI =
574         OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
575 
576     if (!RFI.Declaration)
577       return false;
578 
579     bool Changed = false;
580     auto DeleteCallCB = [&](Use &U, Function &) {
581       CallInst *CI = getCallIfRegularCall(U);
582       if (!CI)
583         return false;
584       auto *Fn = dyn_cast<Function>(
585           CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
586       if (!Fn)
587         return false;
588       if (!Fn->onlyReadsMemory())
589         return false;
590       if (!Fn->hasFnAttribute(Attribute::WillReturn))
591         return false;
592 
593       LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
594                         << CI->getCaller()->getName() << "\n");
595 
596       auto Remark = [&](OptimizationRemark OR) {
597         return OR << "Parallel region in "
598                   << ore::NV("OpenMPParallelDelete", CI->getCaller()->getName())
599                   << " deleted";
600       };
601       emitRemark<OptimizationRemark>(CI, "OpenMPParallelRegionDeletion",
602                                      Remark);
603 
604       CGUpdater.removeCallSite(*CI);
605       CI->eraseFromParent();
606       Changed = true;
607       ++NumOpenMPParallelRegionsDeleted;
608       return true;
609     };
610 
611     RFI.foreachUse(SCC, DeleteCallCB);
612 
613     return Changed;
614   }
615 
616   /// Try to eliminate runtime calls by reusing existing ones.
617   bool deduplicateRuntimeCalls() {
618     bool Changed = false;
619 
620     RuntimeFunction DeduplicableRuntimeCallIDs[] = {
621         OMPRTL_omp_get_num_threads,
622         OMPRTL_omp_in_parallel,
623         OMPRTL_omp_get_cancellation,
624         OMPRTL_omp_get_thread_limit,
625         OMPRTL_omp_get_supported_active_levels,
626         OMPRTL_omp_get_level,
627         OMPRTL_omp_get_ancestor_thread_num,
628         OMPRTL_omp_get_team_size,
629         OMPRTL_omp_get_active_level,
630         OMPRTL_omp_in_final,
631         OMPRTL_omp_get_proc_bind,
632         OMPRTL_omp_get_num_places,
633         OMPRTL_omp_get_num_procs,
634         OMPRTL_omp_get_place_num,
635         OMPRTL_omp_get_partition_num_places,
636         OMPRTL_omp_get_partition_place_nums};
637 
638     // Global-tid is handled separately.
639     SmallSetVector<Value *, 16> GTIdArgs;
640     collectGlobalThreadIdArguments(GTIdArgs);
641     LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
642                       << " global thread ID arguments\n");
643 
644     for (Function *F : SCC) {
645       for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
646         Changed |= deduplicateRuntimeCalls(
647             *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]);
648 
649       // __kmpc_global_thread_num is special as we can replace it with an
650       // argument in enough cases to make it worth trying.
651       Value *GTIdArg = nullptr;
652       for (Argument &Arg : F->args())
653         if (GTIdArgs.count(&Arg)) {
654           GTIdArg = &Arg;
655           break;
656         }
657       Changed |= deduplicateRuntimeCalls(
658           *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
659     }
660 
661     return Changed;
662   }
663 
664   /// Tries to hide the latency of runtime calls that involve host to
665   /// device memory transfers by splitting them into their "issue" and "wait"
666   /// versions. The "issue" is moved upwards as much as possible. The "wait" is
667   /// moved downards as much as possible. The "issue" issues the memory transfer
668   /// asynchronously, returning a handle. The "wait" waits in the returned
669   /// handle for the memory transfer to finish.
670   bool hideMemTransfersLatency() {
671     auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper];
672     bool Changed = false;
673     auto SplitMemTransfers = [&](Use &U, Function &Decl) {
674       auto *RTCall = getCallIfRegularCall(U, &RFI);
675       if (!RTCall)
676         return false;
677 
678       OffloadArray OffloadArrays[3];
679       if (!getValuesInOffloadArrays(*RTCall, OffloadArrays))
680         return false;
681 
682       LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays));
683 
684       // TODO: Check if can be moved upwards.
685       bool WasSplit = false;
686       Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall);
687       if (WaitMovementPoint)
688         WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint);
689 
690       Changed |= WasSplit;
691       return WasSplit;
692     };
693     RFI.foreachUse(SCC, SplitMemTransfers);
694 
695     return Changed;
696   }
697 
698   /// Maps the values stored in the offload arrays passed as arguments to
699   /// \p RuntimeCall into the offload arrays in \p OAs.
700   bool getValuesInOffloadArrays(CallInst &RuntimeCall,
701                                 MutableArrayRef<OffloadArray> OAs) {
702     assert(OAs.size() == 3 && "Need space for three offload arrays!");
703 
704     // A runtime call that involves memory offloading looks something like:
705     // call void @__tgt_target_data_begin_mapper(arg0, arg1,
706     //   i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes,
707     // ...)
708     // So, the idea is to access the allocas that allocate space for these
709     // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes.
710     // Therefore:
711     // i8** %offload_baseptrs.
712     Value *BasePtrsArg =
713         RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum);
714     // i8** %offload_ptrs.
715     Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum);
716     // i8** %offload_sizes.
717     Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum);
718 
719     // Get values stored in **offload_baseptrs.
720     auto *V = getUnderlyingObject(BasePtrsArg);
721     if (!isa<AllocaInst>(V))
722       return false;
723     auto *BasePtrsArray = cast<AllocaInst>(V);
724     if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall))
725       return false;
726 
727     // Get values stored in **offload_baseptrs.
728     V = getUnderlyingObject(PtrsArg);
729     if (!isa<AllocaInst>(V))
730       return false;
731     auto *PtrsArray = cast<AllocaInst>(V);
732     if (!OAs[1].initialize(*PtrsArray, RuntimeCall))
733       return false;
734 
735     // Get values stored in **offload_sizes.
736     V = getUnderlyingObject(SizesArg);
737     // If it's a [constant] global array don't analyze it.
738     if (isa<GlobalValue>(V))
739       return isa<Constant>(V);
740     if (!isa<AllocaInst>(V))
741       return false;
742 
743     auto *SizesArray = cast<AllocaInst>(V);
744     if (!OAs[2].initialize(*SizesArray, RuntimeCall))
745       return false;
746 
747     return true;
748   }
749 
750   /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG.
751   /// For now this is a way to test that the function getValuesInOffloadArrays
752   /// is working properly.
753   /// TODO: Move this to a unittest when unittests are available for OpenMPOpt.
754   void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) {
755     assert(OAs.size() == 3 && "There are three offload arrays to debug!");
756 
757     LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n");
758     std::string ValuesStr;
759     raw_string_ostream Printer(ValuesStr);
760     std::string Separator = " --- ";
761 
762     for (auto *BP : OAs[0].StoredValues) {
763       BP->print(Printer);
764       Printer << Separator;
765     }
766     LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n");
767     ValuesStr.clear();
768 
769     for (auto *P : OAs[1].StoredValues) {
770       P->print(Printer);
771       Printer << Separator;
772     }
773     LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n");
774     ValuesStr.clear();
775 
776     for (auto *S : OAs[2].StoredValues) {
777       S->print(Printer);
778       Printer << Separator;
779     }
780     LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n");
781   }
782 
783   /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be
784   /// moved. Returns nullptr if the movement is not possible, or not worth it.
785   Instruction *canBeMovedDownwards(CallInst &RuntimeCall) {
786     // FIXME: This traverses only the BasicBlock where RuntimeCall is.
787     //  Make it traverse the CFG.
788 
789     Instruction *CurrentI = &RuntimeCall;
790     bool IsWorthIt = false;
791     while ((CurrentI = CurrentI->getNextNode())) {
792 
793       // TODO: Once we detect the regions to be offloaded we should use the
794       //  alias analysis manager to check if CurrentI may modify one of
795       //  the offloaded regions.
796       if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) {
797         if (IsWorthIt)
798           return CurrentI;
799 
800         return nullptr;
801       }
802 
803       // FIXME: For now if we move it over anything without side effect
804       //  is worth it.
805       IsWorthIt = true;
806     }
807 
808     // Return end of BasicBlock.
809     return RuntimeCall.getParent()->getTerminator();
810   }
811 
812   /// Splits \p RuntimeCall into its "issue" and "wait" counterparts.
813   bool splitTargetDataBeginRTC(CallInst &RuntimeCall,
814                                Instruction &WaitMovementPoint) {
815     // Create stack allocated handle (__tgt_async_info) at the beginning of the
816     // function. Used for storing information of the async transfer, allowing to
817     // wait on it later.
818     auto &IRBuilder = OMPInfoCache.OMPBuilder;
819     auto *F = RuntimeCall.getCaller();
820     Instruction *FirstInst = &(F->getEntryBlock().front());
821     AllocaInst *Handle = new AllocaInst(
822         IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst);
823 
824     // Add "issue" runtime call declaration:
825     // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32,
826     //   i8**, i8**, i64*, i64*)
827     FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction(
828         M, OMPRTL___tgt_target_data_begin_mapper_issue);
829 
830     // Change RuntimeCall call site for its asynchronous version.
831     SmallVector<Value *, 8> Args;
832     for (auto &Arg : RuntimeCall.args())
833       Args.push_back(Arg.get());
834     Args.push_back(Handle);
835 
836     CallInst *IssueCallsite =
837         CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall);
838     RuntimeCall.eraseFromParent();
839 
840     // Add "wait" runtime call declaration:
841     // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info)
842     FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction(
843         M, OMPRTL___tgt_target_data_begin_mapper_wait);
844 
845     // Add call site to WaitDecl.
846     const unsigned DeviceIDArgNum = 0;
847     Value *WaitParams[2] = {
848         IssueCallsite->getArgOperand(DeviceIDArgNum), // device_id.
849         Handle                                        // handle to wait on.
850     };
851     CallInst::Create(WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint);
852 
853     return true;
854   }
855 
856   static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
857                                     bool GlobalOnly, bool &SingleChoice) {
858     if (CurrentIdent == NextIdent)
859       return CurrentIdent;
860 
861     // TODO: Figure out how to actually combine multiple debug locations. For
862     //       now we just keep an existing one if there is a single choice.
863     if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
864       SingleChoice = !CurrentIdent;
865       return NextIdent;
866     }
867     return nullptr;
868   }
869 
870   /// Return an `struct ident_t*` value that represents the ones used in the
871   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
872   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
873   /// return value we create one from scratch. We also do not yet combine
874   /// information, e.g., the source locations, see combinedIdentStruct.
875   Value *
876   getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI,
877                                  Function &F, bool GlobalOnly) {
878     bool SingleChoice = true;
879     Value *Ident = nullptr;
880     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
881       CallInst *CI = getCallIfRegularCall(U, &RFI);
882       if (!CI || &F != &Caller)
883         return false;
884       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
885                                   /* GlobalOnly */ true, SingleChoice);
886       return false;
887     };
888     RFI.foreachUse(SCC, CombineIdentStruct);
889 
890     if (!Ident || !SingleChoice) {
891       // The IRBuilder uses the insertion block to get to the module, this is
892       // unfortunate but we work around it for now.
893       if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock())
894         OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
895             &F.getEntryBlock(), F.getEntryBlock().begin()));
896       // Create a fallback location if non was found.
897       // TODO: Use the debug locations of the calls instead.
898       Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr();
899       Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc);
900     }
901     return Ident;
902   }
903 
904   /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or
905   /// \p ReplVal if given.
906   bool deduplicateRuntimeCalls(Function &F,
907                                OMPInformationCache::RuntimeFunctionInfo &RFI,
908                                Value *ReplVal = nullptr) {
909     auto *UV = RFI.getUseVector(F);
910     if (!UV || UV->size() + (ReplVal != nullptr) < 2)
911       return false;
912 
913     LLVM_DEBUG(
914         dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name
915                << (ReplVal ? " with an existing value\n" : "\n") << "\n");
916 
917     assert((!ReplVal || (isa<Argument>(ReplVal) &&
918                          cast<Argument>(ReplVal)->getParent() == &F)) &&
919            "Unexpected replacement value!");
920 
921     // TODO: Use dominance to find a good position instead.
922     auto CanBeMoved = [this](CallBase &CB) {
923       unsigned NumArgs = CB.getNumArgOperands();
924       if (NumArgs == 0)
925         return true;
926       if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr)
927         return false;
928       for (unsigned u = 1; u < NumArgs; ++u)
929         if (isa<Instruction>(CB.getArgOperand(u)))
930           return false;
931       return true;
932     };
933 
934     if (!ReplVal) {
935       for (Use *U : *UV)
936         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
937           if (!CanBeMoved(*CI))
938             continue;
939 
940           auto Remark = [&](OptimizationRemark OR) {
941             auto newLoc = &*F.getEntryBlock().getFirstInsertionPt();
942             return OR << "OpenMP runtime call "
943                       << ore::NV("OpenMPOptRuntime", RFI.Name) << " moved to "
944                       << ore::NV("OpenMPRuntimeMoves", newLoc->getDebugLoc());
945           };
946           emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeCodeMotion", Remark);
947 
948           CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
949           ReplVal = CI;
950           break;
951         }
952       if (!ReplVal)
953         return false;
954     }
955 
956     // If we use a call as a replacement value we need to make sure the ident is
957     // valid at the new location. For now we just pick a global one, either
958     // existing and used by one of the calls, or created from scratch.
959     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
960       if (CI->getNumArgOperands() > 0 &&
961           CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) {
962         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
963                                                       /* GlobalOnly */ true);
964         CI->setArgOperand(0, Ident);
965       }
966     }
967 
968     bool Changed = false;
969     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
970       CallInst *CI = getCallIfRegularCall(U, &RFI);
971       if (!CI || CI == ReplVal || &F != &Caller)
972         return false;
973       assert(CI->getCaller() == &F && "Unexpected call!");
974 
975       auto Remark = [&](OptimizationRemark OR) {
976         return OR << "OpenMP runtime call "
977                   << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated";
978       };
979       emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeDeduplicated", Remark);
980 
981       CGUpdater.removeCallSite(*CI);
982       CI->replaceAllUsesWith(ReplVal);
983       CI->eraseFromParent();
984       ++NumOpenMPRuntimeCallsDeduplicated;
985       Changed = true;
986       return true;
987     };
988     RFI.foreachUse(SCC, ReplaceAndDeleteCB);
989 
990     return Changed;
991   }
992 
993   /// Collect arguments that represent the global thread id in \p GTIdArgs.
994   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
995     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
996     //       initialization. We could define an AbstractAttribute instead and
997     //       run the Attributor here once it can be run as an SCC pass.
998 
999     // Helper to check the argument \p ArgNo at all call sites of \p F for
1000     // a GTId.
1001     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
1002       if (!F.hasLocalLinkage())
1003         return false;
1004       for (Use &U : F.uses()) {
1005         if (CallInst *CI = getCallIfRegularCall(U)) {
1006           Value *ArgOp = CI->getArgOperand(ArgNo);
1007           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
1008               getCallIfRegularCall(
1009                   *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]))
1010             continue;
1011         }
1012         return false;
1013       }
1014       return true;
1015     };
1016 
1017     // Helper to identify uses of a GTId as GTId arguments.
1018     auto AddUserArgs = [&](Value &GTId) {
1019       for (Use &U : GTId.uses())
1020         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
1021           if (CI->isArgOperand(&U))
1022             if (Function *Callee = CI->getCalledFunction())
1023               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
1024                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
1025     };
1026 
1027     // The argument users of __kmpc_global_thread_num calls are GTIds.
1028     OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI =
1029         OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num];
1030 
1031     GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) {
1032       if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
1033         AddUserArgs(*CI);
1034       return false;
1035     });
1036 
1037     // Transitively search for more arguments by looking at the users of the
1038     // ones we know already. During the search the GTIdArgs vector is extended
1039     // so we cannot cache the size nor can we use a range based for.
1040     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
1041       AddUserArgs(*GTIdArgs[u]);
1042   }
1043 
1044   /// Kernel (=GPU) optimizations and utility functions
1045   ///
1046   ///{{
1047 
1048   /// Check if \p F is a kernel, hence entry point for target offloading.
1049   bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); }
1050 
1051   /// Cache to remember the unique kernel for a function.
1052   DenseMap<Function *, Optional<Kernel>> UniqueKernelMap;
1053 
1054   /// Find the unique kernel that will execute \p F, if any.
1055   Kernel getUniqueKernelFor(Function &F);
1056 
1057   /// Find the unique kernel that will execute \p I, if any.
1058   Kernel getUniqueKernelFor(Instruction &I) {
1059     return getUniqueKernelFor(*I.getFunction());
1060   }
1061 
1062   /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in
1063   /// the cases we can avoid taking the address of a function.
1064   bool rewriteDeviceCodeStateMachine();
1065 
1066   ///
1067   ///}}
1068 
1069   /// Emit a remark generically
1070   ///
1071   /// This template function can be used to generically emit a remark. The
1072   /// RemarkKind should be one of the following:
1073   ///   - OptimizationRemark to indicate a successful optimization attempt
1074   ///   - OptimizationRemarkMissed to report a failed optimization attempt
1075   ///   - OptimizationRemarkAnalysis to provide additional information about an
1076   ///     optimization attempt
1077   ///
1078   /// The remark is built using a callback function provided by the caller that
1079   /// takes a RemarkKind as input and returns a RemarkKind.
1080   template <typename RemarkKind,
1081             typename RemarkCallBack = function_ref<RemarkKind(RemarkKind &&)>>
1082   void emitRemark(Instruction *Inst, StringRef RemarkName,
1083                   RemarkCallBack &&RemarkCB) const {
1084     Function *F = Inst->getParent()->getParent();
1085     auto &ORE = OREGetter(F);
1086 
1087     ORE.emit(
1088         [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, Inst)); });
1089   }
1090 
1091   /// Emit a remark on a function. Since only OptimizationRemark is supporting
1092   /// this, it can't be made generic.
1093   void
1094   emitRemarkOnFunction(Function *F, StringRef RemarkName,
1095                        function_ref<OptimizationRemark(OptimizationRemark &&)>
1096                            &&RemarkCB) const {
1097     auto &ORE = OREGetter(F);
1098 
1099     ORE.emit([&]() {
1100       return RemarkCB(OptimizationRemark(DEBUG_TYPE, RemarkName, F));
1101     });
1102   }
1103 
1104   /// The underlying module.
1105   Module &M;
1106 
1107   /// The SCC we are operating on.
1108   SmallVectorImpl<Function *> &SCC;
1109 
1110   /// Callback to update the call graph, the first argument is a removed call,
1111   /// the second an optional replacement call.
1112   CallGraphUpdater &CGUpdater;
1113 
1114   /// Callback to get an OptimizationRemarkEmitter from a Function *
1115   OptimizationRemarkGetter OREGetter;
1116 
1117   /// OpenMP-specific information cache. Also Used for Attributor runs.
1118   OMPInformationCache &OMPInfoCache;
1119 
1120   /// Attributor instance.
1121   Attributor &A;
1122 
1123   /// Helper function to run Attributor on SCC.
1124   bool runAttributor() {
1125     if (SCC.empty())
1126       return false;
1127 
1128     registerAAs();
1129 
1130     ChangeStatus Changed = A.run();
1131 
1132     LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
1133                       << " functions, result: " << Changed << ".\n");
1134 
1135     return Changed == ChangeStatus::CHANGED;
1136   }
1137 
1138   /// Populate the Attributor with abstract attribute opportunities in the
1139   /// function.
1140   void registerAAs() {
1141     if (SCC.empty())
1142       return;
1143 
1144     // Create CallSite AA for all Getters.
1145     for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
1146       auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
1147 
1148       auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
1149 
1150       auto CreateAA = [&](Use &U, Function &Caller) {
1151         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
1152         if (!CI)
1153           return false;
1154 
1155         auto &CB = cast<CallBase>(*CI);
1156 
1157         IRPosition CBPos = IRPosition::callsite_function(CB);
1158         A.getOrCreateAAFor<AAICVTracker>(CBPos);
1159         return false;
1160       };
1161 
1162       GetterRFI.foreachUse(SCC, CreateAA);
1163     }
1164   }
1165 };
1166 
1167 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
1168   if (!OMPInfoCache.ModuleSlice.count(&F))
1169     return nullptr;
1170 
1171   // Use a scope to keep the lifetime of the CachedKernel short.
1172   {
1173     Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
1174     if (CachedKernel)
1175       return *CachedKernel;
1176 
1177     // TODO: We should use an AA to create an (optimistic and callback
1178     //       call-aware) call graph. For now we stick to simple patterns that
1179     //       are less powerful, basically the worst fixpoint.
1180     if (isKernel(F)) {
1181       CachedKernel = Kernel(&F);
1182       return *CachedKernel;
1183     }
1184 
1185     CachedKernel = nullptr;
1186     if (!F.hasLocalLinkage())
1187       return nullptr;
1188   }
1189 
1190   auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
1191     if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
1192       // Allow use in equality comparisons.
1193       if (Cmp->isEquality())
1194         return getUniqueKernelFor(*Cmp);
1195       return nullptr;
1196     }
1197     if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
1198       // Allow direct calls.
1199       if (CB->isCallee(&U))
1200         return getUniqueKernelFor(*CB);
1201       // Allow the use in __kmpc_kernel_prepare_parallel calls.
1202       if (Function *Callee = CB->getCalledFunction())
1203         if (Callee->getName() == "__kmpc_kernel_prepare_parallel")
1204           return getUniqueKernelFor(*CB);
1205       return nullptr;
1206     }
1207     // Disallow every other use.
1208     return nullptr;
1209   };
1210 
1211   // TODO: In the future we want to track more than just a unique kernel.
1212   SmallPtrSet<Kernel, 2> PotentialKernels;
1213   OMPInformationCache::foreachUse(F, [&](const Use &U) {
1214     PotentialKernels.insert(GetUniqueKernelForUse(U));
1215   });
1216 
1217   Kernel K = nullptr;
1218   if (PotentialKernels.size() == 1)
1219     K = *PotentialKernels.begin();
1220 
1221   // Cache the result.
1222   UniqueKernelMap[&F] = K;
1223 
1224   return K;
1225 }
1226 
1227 bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
1228   OMPInformationCache::RuntimeFunctionInfo &KernelPrepareParallelRFI =
1229       OMPInfoCache.RFIs[OMPRTL___kmpc_kernel_prepare_parallel];
1230 
1231   bool Changed = false;
1232   if (!KernelPrepareParallelRFI)
1233     return Changed;
1234 
1235   for (Function *F : SCC) {
1236 
1237     // Check if the function is uses in a __kmpc_kernel_prepare_parallel call at
1238     // all.
1239     bool UnknownUse = false;
1240     bool KernelPrepareUse = false;
1241     unsigned NumDirectCalls = 0;
1242 
1243     SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
1244     OMPInformationCache::foreachUse(*F, [&](Use &U) {
1245       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
1246         if (CB->isCallee(&U)) {
1247           ++NumDirectCalls;
1248           return;
1249         }
1250 
1251       if (isa<ICmpInst>(U.getUser())) {
1252         ToBeReplacedStateMachineUses.push_back(&U);
1253         return;
1254       }
1255       if (!KernelPrepareUse && OpenMPOpt::getCallIfRegularCall(
1256                                    *U.getUser(), &KernelPrepareParallelRFI)) {
1257         KernelPrepareUse = true;
1258         ToBeReplacedStateMachineUses.push_back(&U);
1259         return;
1260       }
1261       UnknownUse = true;
1262     });
1263 
1264     // Do not emit a remark if we haven't seen a __kmpc_kernel_prepare_parallel
1265     // use.
1266     if (!KernelPrepareUse)
1267       continue;
1268 
1269     {
1270       auto Remark = [&](OptimizationRemark OR) {
1271         return OR << "Found a parallel region that is called in a target "
1272                      "region but not part of a combined target construct nor "
1273                      "nesed inside a target construct without intermediate "
1274                      "code. This can lead to excessive register usage for "
1275                      "unrelated target regions in the same translation unit "
1276                      "due to spurious call edges assumed by ptxas.";
1277       };
1278       emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
1279     }
1280 
1281     // If this ever hits, we should investigate.
1282     // TODO: Checking the number of uses is not a necessary restriction and
1283     // should be lifted.
1284     if (UnknownUse || NumDirectCalls != 1 ||
1285         ToBeReplacedStateMachineUses.size() != 2) {
1286       {
1287         auto Remark = [&](OptimizationRemark OR) {
1288           return OR << "Parallel region is used in "
1289                     << (UnknownUse ? "unknown" : "unexpected")
1290                     << " ways; will not attempt to rewrite the state machine.";
1291         };
1292         emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
1293       }
1294       continue;
1295     }
1296 
1297     // Even if we have __kmpc_kernel_prepare_parallel calls, we (for now) give
1298     // up if the function is not called from a unique kernel.
1299     Kernel K = getUniqueKernelFor(*F);
1300     if (!K) {
1301       {
1302         auto Remark = [&](OptimizationRemark OR) {
1303           return OR << "Parallel region is not known to be called from a "
1304                        "unique single target region, maybe the surrounding "
1305                        "function has external linkage?; will not attempt to "
1306                        "rewrite the state machine use.";
1307         };
1308         emitRemarkOnFunction(F, "OpenMPParallelRegionInMultipleKernesl",
1309                              Remark);
1310       }
1311       continue;
1312     }
1313 
1314     // We now know F is a parallel body function called only from the kernel K.
1315     // We also identified the state machine uses in which we replace the
1316     // function pointer by a new global symbol for identification purposes. This
1317     // ensures only direct calls to the function are left.
1318 
1319     {
1320       auto RemarkParalleRegion = [&](OptimizationRemark OR) {
1321         return OR << "Specialize parallel region that is only reached from a "
1322                      "single target region to avoid spurious call edges and "
1323                      "excessive register usage in other target regions. "
1324                      "(parallel region ID: "
1325                   << ore::NV("OpenMPParallelRegion", F->getName())
1326                   << ", kernel ID: "
1327                   << ore::NV("OpenMPTargetRegion", K->getName()) << ")";
1328       };
1329       emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD",
1330                            RemarkParalleRegion);
1331       auto RemarkKernel = [&](OptimizationRemark OR) {
1332         return OR << "Target region containing the parallel region that is "
1333                      "specialized. (parallel region ID: "
1334                   << ore::NV("OpenMPParallelRegion", F->getName())
1335                   << ", kernel ID: "
1336                   << ore::NV("OpenMPTargetRegion", K->getName()) << ")";
1337       };
1338       emitRemarkOnFunction(K, "OpenMPParallelRegionInNonSPMD", RemarkKernel);
1339     }
1340 
1341     Module &M = *F->getParent();
1342     Type *Int8Ty = Type::getInt8Ty(M.getContext());
1343 
1344     auto *ID = new GlobalVariable(
1345         M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
1346         UndefValue::get(Int8Ty), F->getName() + ".ID");
1347 
1348     for (Use *U : ToBeReplacedStateMachineUses)
1349       U->set(ConstantExpr::getBitCast(ID, U->get()->getType()));
1350 
1351     ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
1352 
1353     Changed = true;
1354   }
1355 
1356   return Changed;
1357 }
1358 
1359 /// Abstract Attribute for tracking ICV values.
1360 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
1361   using Base = StateWrapper<BooleanState, AbstractAttribute>;
1362   AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
1363 
1364   void initialize(Attributor &A) override {
1365     Function *F = getAnchorScope();
1366     if (!F || !A.isFunctionIPOAmendable(*F))
1367       indicatePessimisticFixpoint();
1368   }
1369 
1370   /// Returns true if value is assumed to be tracked.
1371   bool isAssumedTracked() const { return getAssumed(); }
1372 
1373   /// Returns true if value is known to be tracked.
1374   bool isKnownTracked() const { return getAssumed(); }
1375 
1376   /// Create an abstract attribute biew for the position \p IRP.
1377   static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
1378 
1379   /// Return the value with which \p I can be replaced for specific \p ICV.
1380   virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
1381                                                 const Instruction *I,
1382                                                 Attributor &A) const {
1383     return None;
1384   }
1385 
1386   /// Return an assumed unique ICV value if a single candidate is found. If
1387   /// there cannot be one, return a nullptr. If it is not clear yet, return the
1388   /// Optional::NoneType.
1389   virtual Optional<Value *>
1390   getUniqueReplacementValue(InternalControlVar ICV) const = 0;
1391 
1392   // Currently only nthreads is being tracked.
1393   // this array will only grow with time.
1394   InternalControlVar TrackableICVs[1] = {ICV_nthreads};
1395 
1396   /// See AbstractAttribute::getName()
1397   const std::string getName() const override { return "AAICVTracker"; }
1398 
1399   /// See AbstractAttribute::getIdAddr()
1400   const char *getIdAddr() const override { return &ID; }
1401 
1402   /// This function should return true if the type of the \p AA is AAICVTracker
1403   static bool classof(const AbstractAttribute *AA) {
1404     return (AA->getIdAddr() == &ID);
1405   }
1406 
1407   static const char ID;
1408 };
1409 
1410 struct AAICVTrackerFunction : public AAICVTracker {
1411   AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
1412       : AAICVTracker(IRP, A) {}
1413 
1414   // FIXME: come up with better string.
1415   const std::string getAsStr() const override { return "ICVTrackerFunction"; }
1416 
1417   // FIXME: come up with some stats.
1418   void trackStatistics() const override {}
1419 
1420   /// We don't manifest anything for this AA.
1421   ChangeStatus manifest(Attributor &A) override {
1422     return ChangeStatus::UNCHANGED;
1423   }
1424 
1425   // Map of ICV to their values at specific program point.
1426   EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
1427                   InternalControlVar::ICV___last>
1428       ICVReplacementValuesMap;
1429 
1430   ChangeStatus updateImpl(Attributor &A) override {
1431     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1432 
1433     Function *F = getAnchorScope();
1434 
1435     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1436 
1437     for (InternalControlVar ICV : TrackableICVs) {
1438       auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
1439 
1440       auto &ValuesMap = ICVReplacementValuesMap[ICV];
1441       auto TrackValues = [&](Use &U, Function &) {
1442         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
1443         if (!CI)
1444           return false;
1445 
1446         // FIXME: handle setters with more that 1 arguments.
1447         /// Track new value.
1448         if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
1449           HasChanged = ChangeStatus::CHANGED;
1450 
1451         return false;
1452       };
1453 
1454       auto CallCheck = [&](Instruction &I) {
1455         Optional<Value *> ReplVal = getValueForCall(A, &I, ICV);
1456         if (ReplVal.hasValue() &&
1457             ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
1458           HasChanged = ChangeStatus::CHANGED;
1459 
1460         return true;
1461       };
1462 
1463       // Track all changes of an ICV.
1464       SetterRFI.foreachUse(TrackValues, F);
1465 
1466       A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
1467                                 /* CheckBBLivenessOnly */ true);
1468 
1469       /// TODO: Figure out a way to avoid adding entry in
1470       /// ICVReplacementValuesMap
1471       Instruction *Entry = &F->getEntryBlock().front();
1472       if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
1473         ValuesMap.insert(std::make_pair(Entry, nullptr));
1474     }
1475 
1476     return HasChanged;
1477   }
1478 
1479   /// Hepler to check if \p I is a call and get the value for it if it is
1480   /// unique.
1481   Optional<Value *> getValueForCall(Attributor &A, const Instruction *I,
1482                                     InternalControlVar &ICV) const {
1483 
1484     const auto *CB = dyn_cast<CallBase>(I);
1485     if (!CB)
1486       return None;
1487 
1488     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1489     auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
1490     auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
1491     Function *CalledFunction = CB->getCalledFunction();
1492 
1493     // Indirect call, assume ICV changes.
1494     if (CalledFunction == nullptr)
1495       return nullptr;
1496     if (CalledFunction == GetterRFI.Declaration)
1497       return None;
1498     if (CalledFunction == SetterRFI.Declaration) {
1499       if (ICVReplacementValuesMap[ICV].count(I))
1500         return ICVReplacementValuesMap[ICV].lookup(I);
1501 
1502       return nullptr;
1503     }
1504 
1505     // Since we don't know, assume it changes the ICV.
1506     if (CalledFunction->isDeclaration())
1507       return nullptr;
1508 
1509     const auto &ICVTrackingAA =
1510         A.getAAFor<AAICVTracker>(*this, IRPosition::callsite_returned(*CB));
1511 
1512     if (ICVTrackingAA.isAssumedTracked())
1513       return ICVTrackingAA.getUniqueReplacementValue(ICV);
1514 
1515     // If we don't know, assume it changes.
1516     return nullptr;
1517   }
1518 
1519   // We don't check unique value for a function, so return None.
1520   Optional<Value *>
1521   getUniqueReplacementValue(InternalControlVar ICV) const override {
1522     return None;
1523   }
1524 
1525   /// Return the value with which \p I can be replaced for specific \p ICV.
1526   Optional<Value *> getReplacementValue(InternalControlVar ICV,
1527                                         const Instruction *I,
1528                                         Attributor &A) const override {
1529     const auto &ValuesMap = ICVReplacementValuesMap[ICV];
1530     if (ValuesMap.count(I))
1531       return ValuesMap.lookup(I);
1532 
1533     SmallVector<const Instruction *, 16> Worklist;
1534     SmallPtrSet<const Instruction *, 16> Visited;
1535     Worklist.push_back(I);
1536 
1537     Optional<Value *> ReplVal;
1538 
1539     while (!Worklist.empty()) {
1540       const Instruction *CurrInst = Worklist.pop_back_val();
1541       if (!Visited.insert(CurrInst).second)
1542         continue;
1543 
1544       const BasicBlock *CurrBB = CurrInst->getParent();
1545 
1546       // Go up and look for all potential setters/calls that might change the
1547       // ICV.
1548       while ((CurrInst = CurrInst->getPrevNode())) {
1549         if (ValuesMap.count(CurrInst)) {
1550           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
1551           // Unknown value, track new.
1552           if (!ReplVal.hasValue()) {
1553             ReplVal = NewReplVal;
1554             break;
1555           }
1556 
1557           // If we found a new value, we can't know the icv value anymore.
1558           if (NewReplVal.hasValue())
1559             if (ReplVal != NewReplVal)
1560               return nullptr;
1561 
1562           break;
1563         }
1564 
1565         Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV);
1566         if (!NewReplVal.hasValue())
1567           continue;
1568 
1569         // Unknown value, track new.
1570         if (!ReplVal.hasValue()) {
1571           ReplVal = NewReplVal;
1572           break;
1573         }
1574 
1575         // if (NewReplVal.hasValue())
1576         // We found a new value, we can't know the icv value anymore.
1577         if (ReplVal != NewReplVal)
1578           return nullptr;
1579       }
1580 
1581       // If we are in the same BB and we have a value, we are done.
1582       if (CurrBB == I->getParent() && ReplVal.hasValue())
1583         return ReplVal;
1584 
1585       // Go through all predecessors and add terminators for analysis.
1586       for (const BasicBlock *Pred : predecessors(CurrBB))
1587         if (const Instruction *Terminator = Pred->getTerminator())
1588           Worklist.push_back(Terminator);
1589     }
1590 
1591     return ReplVal;
1592   }
1593 };
1594 
1595 struct AAICVTrackerFunctionReturned : AAICVTracker {
1596   AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
1597       : AAICVTracker(IRP, A) {}
1598 
1599   // FIXME: come up with better string.
1600   const std::string getAsStr() const override {
1601     return "ICVTrackerFunctionReturned";
1602   }
1603 
1604   // FIXME: come up with some stats.
1605   void trackStatistics() const override {}
1606 
1607   /// We don't manifest anything for this AA.
1608   ChangeStatus manifest(Attributor &A) override {
1609     return ChangeStatus::UNCHANGED;
1610   }
1611 
1612   // Map of ICV to their values at specific program point.
1613   EnumeratedArray<Optional<Value *>, InternalControlVar,
1614                   InternalControlVar::ICV___last>
1615       ICVReplacementValuesMap;
1616 
1617   /// Return the value with which \p I can be replaced for specific \p ICV.
1618   Optional<Value *>
1619   getUniqueReplacementValue(InternalControlVar ICV) const override {
1620     return ICVReplacementValuesMap[ICV];
1621   }
1622 
1623   ChangeStatus updateImpl(Attributor &A) override {
1624     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1625     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1626         *this, IRPosition::function(*getAnchorScope()));
1627 
1628     if (!ICVTrackingAA.isAssumedTracked())
1629       return indicatePessimisticFixpoint();
1630 
1631     for (InternalControlVar ICV : TrackableICVs) {
1632       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
1633       Optional<Value *> UniqueICVValue;
1634 
1635       auto CheckReturnInst = [&](Instruction &I) {
1636         Optional<Value *> NewReplVal =
1637             ICVTrackingAA.getReplacementValue(ICV, &I, A);
1638 
1639         // If we found a second ICV value there is no unique returned value.
1640         if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
1641           return false;
1642 
1643         UniqueICVValue = NewReplVal;
1644 
1645         return true;
1646       };
1647 
1648       if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
1649                                      /* CheckBBLivenessOnly */ true))
1650         UniqueICVValue = nullptr;
1651 
1652       if (UniqueICVValue == ReplVal)
1653         continue;
1654 
1655       ReplVal = UniqueICVValue;
1656       Changed = ChangeStatus::CHANGED;
1657     }
1658 
1659     return Changed;
1660   }
1661 };
1662 
1663 struct AAICVTrackerCallSite : AAICVTracker {
1664   AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
1665       : AAICVTracker(IRP, A) {}
1666 
1667   void initialize(Attributor &A) override {
1668     Function *F = getAnchorScope();
1669     if (!F || !A.isFunctionIPOAmendable(*F))
1670       indicatePessimisticFixpoint();
1671 
1672     // We only initialize this AA for getters, so we need to know which ICV it
1673     // gets.
1674     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1675     for (InternalControlVar ICV : TrackableICVs) {
1676       auto ICVInfo = OMPInfoCache.ICVs[ICV];
1677       auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
1678       if (Getter.Declaration == getAssociatedFunction()) {
1679         AssociatedICV = ICVInfo.Kind;
1680         return;
1681       }
1682     }
1683 
1684     /// Unknown ICV.
1685     indicatePessimisticFixpoint();
1686   }
1687 
1688   ChangeStatus manifest(Attributor &A) override {
1689     if (!ReplVal.hasValue() || !ReplVal.getValue())
1690       return ChangeStatus::UNCHANGED;
1691 
1692     A.changeValueAfterManifest(*getCtxI(), **ReplVal);
1693     A.deleteAfterManifest(*getCtxI());
1694 
1695     return ChangeStatus::CHANGED;
1696   }
1697 
1698   // FIXME: come up with better string.
1699   const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
1700 
1701   // FIXME: come up with some stats.
1702   void trackStatistics() const override {}
1703 
1704   InternalControlVar AssociatedICV;
1705   Optional<Value *> ReplVal;
1706 
1707   ChangeStatus updateImpl(Attributor &A) override {
1708     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1709         *this, IRPosition::function(*getAnchorScope()));
1710 
1711     // We don't have any information, so we assume it changes the ICV.
1712     if (!ICVTrackingAA.isAssumedTracked())
1713       return indicatePessimisticFixpoint();
1714 
1715     Optional<Value *> NewReplVal =
1716         ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
1717 
1718     if (ReplVal == NewReplVal)
1719       return ChangeStatus::UNCHANGED;
1720 
1721     ReplVal = NewReplVal;
1722     return ChangeStatus::CHANGED;
1723   }
1724 
1725   // Return the value with which associated value can be replaced for specific
1726   // \p ICV.
1727   Optional<Value *>
1728   getUniqueReplacementValue(InternalControlVar ICV) const override {
1729     return ReplVal;
1730   }
1731 };
1732 
1733 struct AAICVTrackerCallSiteReturned : AAICVTracker {
1734   AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
1735       : AAICVTracker(IRP, A) {}
1736 
1737   // FIXME: come up with better string.
1738   const std::string getAsStr() const override {
1739     return "ICVTrackerCallSiteReturned";
1740   }
1741 
1742   // FIXME: come up with some stats.
1743   void trackStatistics() const override {}
1744 
1745   /// We don't manifest anything for this AA.
1746   ChangeStatus manifest(Attributor &A) override {
1747     return ChangeStatus::UNCHANGED;
1748   }
1749 
1750   // Map of ICV to their values at specific program point.
1751   EnumeratedArray<Optional<Value *>, InternalControlVar,
1752                   InternalControlVar::ICV___last>
1753       ICVReplacementValuesMap;
1754 
1755   /// Return the value with which associated value can be replaced for specific
1756   /// \p ICV.
1757   Optional<Value *>
1758   getUniqueReplacementValue(InternalControlVar ICV) const override {
1759     return ICVReplacementValuesMap[ICV];
1760   }
1761 
1762   ChangeStatus updateImpl(Attributor &A) override {
1763     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1764     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1765         *this, IRPosition::returned(*getAssociatedFunction()));
1766 
1767     // We don't have any information, so we assume it changes the ICV.
1768     if (!ICVTrackingAA.isAssumedTracked())
1769       return indicatePessimisticFixpoint();
1770 
1771     for (InternalControlVar ICV : TrackableICVs) {
1772       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
1773       Optional<Value *> NewReplVal =
1774           ICVTrackingAA.getUniqueReplacementValue(ICV);
1775 
1776       if (ReplVal == NewReplVal)
1777         continue;
1778 
1779       ReplVal = NewReplVal;
1780       Changed = ChangeStatus::CHANGED;
1781     }
1782     return Changed;
1783   }
1784 };
1785 } // namespace
1786 
1787 const char AAICVTracker::ID = 0;
1788 
1789 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
1790                                               Attributor &A) {
1791   AAICVTracker *AA = nullptr;
1792   switch (IRP.getPositionKind()) {
1793   case IRPosition::IRP_INVALID:
1794   case IRPosition::IRP_FLOAT:
1795   case IRPosition::IRP_ARGUMENT:
1796   case IRPosition::IRP_CALL_SITE_ARGUMENT:
1797     llvm_unreachable("ICVTracker can only be created for function position!");
1798   case IRPosition::IRP_RETURNED:
1799     AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
1800     break;
1801   case IRPosition::IRP_CALL_SITE_RETURNED:
1802     AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
1803     break;
1804   case IRPosition::IRP_CALL_SITE:
1805     AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
1806     break;
1807   case IRPosition::IRP_FUNCTION:
1808     AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
1809     break;
1810   }
1811 
1812   return *AA;
1813 }
1814 
1815 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C,
1816                                      CGSCCAnalysisManager &AM,
1817                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
1818   if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule))
1819     return PreservedAnalyses::all();
1820 
1821   if (DisableOpenMPOptimizations)
1822     return PreservedAnalyses::all();
1823 
1824   SmallVector<Function *, 16> SCC;
1825   // If there are kernels in the module, we have to run on all SCC's.
1826   bool SCCIsInteresting = !OMPInModule.getKernels().empty();
1827   for (LazyCallGraph::Node &N : C) {
1828     Function *Fn = &N.getFunction();
1829     SCC.push_back(Fn);
1830 
1831     // Do we already know that the SCC contains kernels,
1832     // or that OpenMP functions are called from this SCC?
1833     if (SCCIsInteresting)
1834       continue;
1835     // If not, let's check that.
1836     SCCIsInteresting |= OMPInModule.containsOMPRuntimeCalls(Fn);
1837   }
1838 
1839   if (!SCCIsInteresting || SCC.empty())
1840     return PreservedAnalyses::all();
1841 
1842   FunctionAnalysisManager &FAM =
1843       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1844 
1845   AnalysisGetter AG(FAM);
1846 
1847   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
1848     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
1849   };
1850 
1851   CallGraphUpdater CGUpdater;
1852   CGUpdater.initialize(CG, C, AM, UR);
1853 
1854   SetVector<Function *> Functions(SCC.begin(), SCC.end());
1855   BumpPtrAllocator Allocator;
1856   OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
1857                                 /*CGSCC*/ Functions, OMPInModule.getKernels());
1858 
1859   Attributor A(Functions, InfoCache, CGUpdater);
1860 
1861   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
1862   bool Changed = OMPOpt.run();
1863   if (Changed)
1864     return PreservedAnalyses::none();
1865 
1866   return PreservedAnalyses::all();
1867 }
1868 
1869 namespace {
1870 
1871 struct OpenMPOptLegacyPass : public CallGraphSCCPass {
1872   CallGraphUpdater CGUpdater;
1873   OpenMPInModule OMPInModule;
1874   static char ID;
1875 
1876   OpenMPOptLegacyPass() : CallGraphSCCPass(ID) {
1877     initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry());
1878   }
1879 
1880   void getAnalysisUsage(AnalysisUsage &AU) const override {
1881     CallGraphSCCPass::getAnalysisUsage(AU);
1882   }
1883 
1884   bool doInitialization(CallGraph &CG) override {
1885     // Disable the pass if there is no OpenMP (runtime call) in the module.
1886     containsOpenMP(CG.getModule(), OMPInModule);
1887     return false;
1888   }
1889 
1890   bool runOnSCC(CallGraphSCC &CGSCC) override {
1891     if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule))
1892       return false;
1893     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
1894       return false;
1895 
1896     SmallVector<Function *, 16> SCC;
1897     // If there are kernels in the module, we have to run on all SCC's.
1898     bool SCCIsInteresting = !OMPInModule.getKernels().empty();
1899     for (CallGraphNode *CGN : CGSCC) {
1900       Function *Fn = CGN->getFunction();
1901       if (!Fn || Fn->isDeclaration())
1902         continue;
1903       SCC.push_back(Fn);
1904 
1905       // Do we already know that the SCC contains kernels,
1906       // or that OpenMP functions are called from this SCC?
1907       if (SCCIsInteresting)
1908         continue;
1909       // If not, let's check that.
1910       SCCIsInteresting |= OMPInModule.containsOMPRuntimeCalls(Fn);
1911     }
1912 
1913     if (!SCCIsInteresting || SCC.empty())
1914       return false;
1915 
1916     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1917     CGUpdater.initialize(CG, CGSCC);
1918 
1919     // Maintain a map of functions to avoid rebuilding the ORE
1920     DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
1921     auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
1922       std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
1923       if (!ORE)
1924         ORE = std::make_unique<OptimizationRemarkEmitter>(F);
1925       return *ORE;
1926     };
1927 
1928     AnalysisGetter AG;
1929     SetVector<Function *> Functions(SCC.begin(), SCC.end());
1930     BumpPtrAllocator Allocator;
1931     OMPInformationCache InfoCache(
1932         *(Functions.back()->getParent()), AG, Allocator,
1933         /*CGSCC*/ Functions, OMPInModule.getKernels());
1934 
1935     Attributor A(Functions, InfoCache, CGUpdater);
1936 
1937     OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
1938     return OMPOpt.run();
1939   }
1940 
1941   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
1942 };
1943 
1944 } // end anonymous namespace
1945 
1946 void OpenMPInModule::identifyKernels(Module &M) {
1947 
1948   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1949   if (!MD)
1950     return;
1951 
1952   for (auto *Op : MD->operands()) {
1953     if (Op->getNumOperands() < 2)
1954       continue;
1955     MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
1956     if (!KindID || KindID->getString() != "kernel")
1957       continue;
1958 
1959     Function *KernelFn =
1960         mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
1961     if (!KernelFn)
1962       continue;
1963 
1964     ++NumOpenMPTargetRegionKernels;
1965 
1966     Kernels.insert(KernelFn);
1967   }
1968 }
1969 
1970 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) {
1971   if (OMPInModule.isKnown())
1972     return OMPInModule;
1973 
1974   auto RecordFunctionsContainingUsesOf = [&](Function *F) {
1975     for (User *U : F->users())
1976       if (auto *I = dyn_cast<Instruction>(U))
1977         OMPInModule.FuncsWithOMPRuntimeCalls.insert(I->getFunction());
1978   };
1979 
1980   // MSVC doesn't like long if-else chains for some reason and instead just
1981   // issues an error. Work around it..
1982   do {
1983 #define OMP_RTL(_Enum, _Name, ...)                                             \
1984   if (Function *F = M.getFunction(_Name)) {                                    \
1985     RecordFunctionsContainingUsesOf(F);                                        \
1986     OMPInModule = true;                                                        \
1987   }
1988 #include "llvm/Frontend/OpenMP/OMPKinds.def"
1989   } while (false);
1990 
1991   // Identify kernels once. TODO: We should split the OMPInformationCache into a
1992   // module and an SCC part. The kernel information, among other things, could
1993   // go into the module part.
1994   if (OMPInModule.isKnown() && OMPInModule) {
1995     OMPInModule.identifyKernels(M);
1996     return true;
1997   }
1998 
1999   return OMPInModule = false;
2000 }
2001 
2002 char OpenMPOptLegacyPass::ID = 0;
2003 
2004 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt",
2005                       "OpenMP specific optimizations", false, false)
2006 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
2007 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt",
2008                     "OpenMP specific optimizations", false, false)
2009 
2010 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); }
2011