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     auto &IRBuilder = OMPInfoCache.OMPBuilder;
816     // Add "issue" runtime call declaration:
817     // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32,
818     //   i8**, i8**, i64*, i64*)
819     FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction(
820         M, OMPRTL___tgt_target_data_begin_mapper_issue);
821 
822     // Change RuntimeCall call site for its asynchronous version.
823     SmallVector<Value *, 8> Args;
824     for (auto &Arg : RuntimeCall.args())
825       Args.push_back(Arg.get());
826 
827     CallInst *IssueCallsite =
828         CallInst::Create(IssueDecl, Args, "handle", &RuntimeCall);
829     RuntimeCall.eraseFromParent();
830 
831     // Add "wait" runtime call declaration:
832     // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info)
833     FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction(
834         M, OMPRTL___tgt_target_data_begin_mapper_wait);
835 
836     // Add call site to WaitDecl.
837     Value *WaitParams[2] = {
838         IssueCallsite->getArgOperand(0), // device_id.
839         IssueCallsite // returned handle.
840     };
841     CallInst::Create(WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint);
842 
843     return true;
844   }
845 
846   static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
847                                     bool GlobalOnly, bool &SingleChoice) {
848     if (CurrentIdent == NextIdent)
849       return CurrentIdent;
850 
851     // TODO: Figure out how to actually combine multiple debug locations. For
852     //       now we just keep an existing one if there is a single choice.
853     if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
854       SingleChoice = !CurrentIdent;
855       return NextIdent;
856     }
857     return nullptr;
858   }
859 
860   /// Return an `struct ident_t*` value that represents the ones used in the
861   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
862   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
863   /// return value we create one from scratch. We also do not yet combine
864   /// information, e.g., the source locations, see combinedIdentStruct.
865   Value *
866   getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI,
867                                  Function &F, bool GlobalOnly) {
868     bool SingleChoice = true;
869     Value *Ident = nullptr;
870     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
871       CallInst *CI = getCallIfRegularCall(U, &RFI);
872       if (!CI || &F != &Caller)
873         return false;
874       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
875                                   /* GlobalOnly */ true, SingleChoice);
876       return false;
877     };
878     RFI.foreachUse(SCC, CombineIdentStruct);
879 
880     if (!Ident || !SingleChoice) {
881       // The IRBuilder uses the insertion block to get to the module, this is
882       // unfortunate but we work around it for now.
883       if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock())
884         OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
885             &F.getEntryBlock(), F.getEntryBlock().begin()));
886       // Create a fallback location if non was found.
887       // TODO: Use the debug locations of the calls instead.
888       Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr();
889       Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc);
890     }
891     return Ident;
892   }
893 
894   /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or
895   /// \p ReplVal if given.
896   bool deduplicateRuntimeCalls(Function &F,
897                                OMPInformationCache::RuntimeFunctionInfo &RFI,
898                                Value *ReplVal = nullptr) {
899     auto *UV = RFI.getUseVector(F);
900     if (!UV || UV->size() + (ReplVal != nullptr) < 2)
901       return false;
902 
903     LLVM_DEBUG(
904         dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name
905                << (ReplVal ? " with an existing value\n" : "\n") << "\n");
906 
907     assert((!ReplVal || (isa<Argument>(ReplVal) &&
908                          cast<Argument>(ReplVal)->getParent() == &F)) &&
909            "Unexpected replacement value!");
910 
911     // TODO: Use dominance to find a good position instead.
912     auto CanBeMoved = [this](CallBase &CB) {
913       unsigned NumArgs = CB.getNumArgOperands();
914       if (NumArgs == 0)
915         return true;
916       if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr)
917         return false;
918       for (unsigned u = 1; u < NumArgs; ++u)
919         if (isa<Instruction>(CB.getArgOperand(u)))
920           return false;
921       return true;
922     };
923 
924     if (!ReplVal) {
925       for (Use *U : *UV)
926         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
927           if (!CanBeMoved(*CI))
928             continue;
929 
930           auto Remark = [&](OptimizationRemark OR) {
931             auto newLoc = &*F.getEntryBlock().getFirstInsertionPt();
932             return OR << "OpenMP runtime call "
933                       << ore::NV("OpenMPOptRuntime", RFI.Name) << " moved to "
934                       << ore::NV("OpenMPRuntimeMoves", newLoc->getDebugLoc());
935           };
936           emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeCodeMotion", Remark);
937 
938           CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
939           ReplVal = CI;
940           break;
941         }
942       if (!ReplVal)
943         return false;
944     }
945 
946     // If we use a call as a replacement value we need to make sure the ident is
947     // valid at the new location. For now we just pick a global one, either
948     // existing and used by one of the calls, or created from scratch.
949     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
950       if (CI->getNumArgOperands() > 0 &&
951           CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) {
952         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
953                                                       /* GlobalOnly */ true);
954         CI->setArgOperand(0, Ident);
955       }
956     }
957 
958     bool Changed = false;
959     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
960       CallInst *CI = getCallIfRegularCall(U, &RFI);
961       if (!CI || CI == ReplVal || &F != &Caller)
962         return false;
963       assert(CI->getCaller() == &F && "Unexpected call!");
964 
965       auto Remark = [&](OptimizationRemark OR) {
966         return OR << "OpenMP runtime call "
967                   << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated";
968       };
969       emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeDeduplicated", Remark);
970 
971       CGUpdater.removeCallSite(*CI);
972       CI->replaceAllUsesWith(ReplVal);
973       CI->eraseFromParent();
974       ++NumOpenMPRuntimeCallsDeduplicated;
975       Changed = true;
976       return true;
977     };
978     RFI.foreachUse(SCC, ReplaceAndDeleteCB);
979 
980     return Changed;
981   }
982 
983   /// Collect arguments that represent the global thread id in \p GTIdArgs.
984   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
985     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
986     //       initialization. We could define an AbstractAttribute instead and
987     //       run the Attributor here once it can be run as an SCC pass.
988 
989     // Helper to check the argument \p ArgNo at all call sites of \p F for
990     // a GTId.
991     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
992       if (!F.hasLocalLinkage())
993         return false;
994       for (Use &U : F.uses()) {
995         if (CallInst *CI = getCallIfRegularCall(U)) {
996           Value *ArgOp = CI->getArgOperand(ArgNo);
997           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
998               getCallIfRegularCall(
999                   *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]))
1000             continue;
1001         }
1002         return false;
1003       }
1004       return true;
1005     };
1006 
1007     // Helper to identify uses of a GTId as GTId arguments.
1008     auto AddUserArgs = [&](Value &GTId) {
1009       for (Use &U : GTId.uses())
1010         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
1011           if (CI->isArgOperand(&U))
1012             if (Function *Callee = CI->getCalledFunction())
1013               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
1014                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
1015     };
1016 
1017     // The argument users of __kmpc_global_thread_num calls are GTIds.
1018     OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI =
1019         OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num];
1020 
1021     GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) {
1022       if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
1023         AddUserArgs(*CI);
1024       return false;
1025     });
1026 
1027     // Transitively search for more arguments by looking at the users of the
1028     // ones we know already. During the search the GTIdArgs vector is extended
1029     // so we cannot cache the size nor can we use a range based for.
1030     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
1031       AddUserArgs(*GTIdArgs[u]);
1032   }
1033 
1034   /// Kernel (=GPU) optimizations and utility functions
1035   ///
1036   ///{{
1037 
1038   /// Check if \p F is a kernel, hence entry point for target offloading.
1039   bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); }
1040 
1041   /// Cache to remember the unique kernel for a function.
1042   DenseMap<Function *, Optional<Kernel>> UniqueKernelMap;
1043 
1044   /// Find the unique kernel that will execute \p F, if any.
1045   Kernel getUniqueKernelFor(Function &F);
1046 
1047   /// Find the unique kernel that will execute \p I, if any.
1048   Kernel getUniqueKernelFor(Instruction &I) {
1049     return getUniqueKernelFor(*I.getFunction());
1050   }
1051 
1052   /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in
1053   /// the cases we can avoid taking the address of a function.
1054   bool rewriteDeviceCodeStateMachine();
1055 
1056   ///
1057   ///}}
1058 
1059   /// Emit a remark generically
1060   ///
1061   /// This template function can be used to generically emit a remark. The
1062   /// RemarkKind should be one of the following:
1063   ///   - OptimizationRemark to indicate a successful optimization attempt
1064   ///   - OptimizationRemarkMissed to report a failed optimization attempt
1065   ///   - OptimizationRemarkAnalysis to provide additional information about an
1066   ///     optimization attempt
1067   ///
1068   /// The remark is built using a callback function provided by the caller that
1069   /// takes a RemarkKind as input and returns a RemarkKind.
1070   template <typename RemarkKind,
1071             typename RemarkCallBack = function_ref<RemarkKind(RemarkKind &&)>>
1072   void emitRemark(Instruction *Inst, StringRef RemarkName,
1073                   RemarkCallBack &&RemarkCB) const {
1074     Function *F = Inst->getParent()->getParent();
1075     auto &ORE = OREGetter(F);
1076 
1077     ORE.emit(
1078         [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, Inst)); });
1079   }
1080 
1081   /// Emit a remark on a function. Since only OptimizationRemark is supporting
1082   /// this, it can't be made generic.
1083   void
1084   emitRemarkOnFunction(Function *F, StringRef RemarkName,
1085                        function_ref<OptimizationRemark(OptimizationRemark &&)>
1086                            &&RemarkCB) const {
1087     auto &ORE = OREGetter(F);
1088 
1089     ORE.emit([&]() {
1090       return RemarkCB(OptimizationRemark(DEBUG_TYPE, RemarkName, F));
1091     });
1092   }
1093 
1094   /// The underlying module.
1095   Module &M;
1096 
1097   /// The SCC we are operating on.
1098   SmallVectorImpl<Function *> &SCC;
1099 
1100   /// Callback to update the call graph, the first argument is a removed call,
1101   /// the second an optional replacement call.
1102   CallGraphUpdater &CGUpdater;
1103 
1104   /// Callback to get an OptimizationRemarkEmitter from a Function *
1105   OptimizationRemarkGetter OREGetter;
1106 
1107   /// OpenMP-specific information cache. Also Used for Attributor runs.
1108   OMPInformationCache &OMPInfoCache;
1109 
1110   /// Attributor instance.
1111   Attributor &A;
1112 
1113   /// Helper function to run Attributor on SCC.
1114   bool runAttributor() {
1115     if (SCC.empty())
1116       return false;
1117 
1118     registerAAs();
1119 
1120     ChangeStatus Changed = A.run();
1121 
1122     LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
1123                       << " functions, result: " << Changed << ".\n");
1124 
1125     return Changed == ChangeStatus::CHANGED;
1126   }
1127 
1128   /// Populate the Attributor with abstract attribute opportunities in the
1129   /// function.
1130   void registerAAs() {
1131     if (SCC.empty())
1132       return;
1133 
1134     // Create CallSite AA for all Getters.
1135     for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
1136       auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
1137 
1138       auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
1139 
1140       auto CreateAA = [&](Use &U, Function &Caller) {
1141         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
1142         if (!CI)
1143           return false;
1144 
1145         auto &CB = cast<CallBase>(*CI);
1146 
1147         IRPosition CBPos = IRPosition::callsite_function(CB);
1148         A.getOrCreateAAFor<AAICVTracker>(CBPos);
1149         return false;
1150       };
1151 
1152       GetterRFI.foreachUse(SCC, CreateAA);
1153     }
1154   }
1155 };
1156 
1157 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
1158   if (!OMPInfoCache.ModuleSlice.count(&F))
1159     return nullptr;
1160 
1161   // Use a scope to keep the lifetime of the CachedKernel short.
1162   {
1163     Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
1164     if (CachedKernel)
1165       return *CachedKernel;
1166 
1167     // TODO: We should use an AA to create an (optimistic and callback
1168     //       call-aware) call graph. For now we stick to simple patterns that
1169     //       are less powerful, basically the worst fixpoint.
1170     if (isKernel(F)) {
1171       CachedKernel = Kernel(&F);
1172       return *CachedKernel;
1173     }
1174 
1175     CachedKernel = nullptr;
1176     if (!F.hasLocalLinkage())
1177       return nullptr;
1178   }
1179 
1180   auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
1181     if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
1182       // Allow use in equality comparisons.
1183       if (Cmp->isEquality())
1184         return getUniqueKernelFor(*Cmp);
1185       return nullptr;
1186     }
1187     if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
1188       // Allow direct calls.
1189       if (CB->isCallee(&U))
1190         return getUniqueKernelFor(*CB);
1191       // Allow the use in __kmpc_kernel_prepare_parallel calls.
1192       if (Function *Callee = CB->getCalledFunction())
1193         if (Callee->getName() == "__kmpc_kernel_prepare_parallel")
1194           return getUniqueKernelFor(*CB);
1195       return nullptr;
1196     }
1197     // Disallow every other use.
1198     return nullptr;
1199   };
1200 
1201   // TODO: In the future we want to track more than just a unique kernel.
1202   SmallPtrSet<Kernel, 2> PotentialKernels;
1203   OMPInformationCache::foreachUse(F, [&](const Use &U) {
1204     PotentialKernels.insert(GetUniqueKernelForUse(U));
1205   });
1206 
1207   Kernel K = nullptr;
1208   if (PotentialKernels.size() == 1)
1209     K = *PotentialKernels.begin();
1210 
1211   // Cache the result.
1212   UniqueKernelMap[&F] = K;
1213 
1214   return K;
1215 }
1216 
1217 bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
1218   OMPInformationCache::RuntimeFunctionInfo &KernelPrepareParallelRFI =
1219       OMPInfoCache.RFIs[OMPRTL___kmpc_kernel_prepare_parallel];
1220 
1221   bool Changed = false;
1222   if (!KernelPrepareParallelRFI)
1223     return Changed;
1224 
1225   for (Function *F : SCC) {
1226 
1227     // Check if the function is uses in a __kmpc_kernel_prepare_parallel call at
1228     // all.
1229     bool UnknownUse = false;
1230     bool KernelPrepareUse = false;
1231     unsigned NumDirectCalls = 0;
1232 
1233     SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
1234     OMPInformationCache::foreachUse(*F, [&](Use &U) {
1235       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
1236         if (CB->isCallee(&U)) {
1237           ++NumDirectCalls;
1238           return;
1239         }
1240 
1241       if (isa<ICmpInst>(U.getUser())) {
1242         ToBeReplacedStateMachineUses.push_back(&U);
1243         return;
1244       }
1245       if (!KernelPrepareUse && OpenMPOpt::getCallIfRegularCall(
1246                                    *U.getUser(), &KernelPrepareParallelRFI)) {
1247         KernelPrepareUse = true;
1248         ToBeReplacedStateMachineUses.push_back(&U);
1249         return;
1250       }
1251       UnknownUse = true;
1252     });
1253 
1254     // Do not emit a remark if we haven't seen a __kmpc_kernel_prepare_parallel
1255     // use.
1256     if (!KernelPrepareUse)
1257       continue;
1258 
1259     {
1260       auto Remark = [&](OptimizationRemark OR) {
1261         return OR << "Found a parallel region that is called in a target "
1262                      "region but not part of a combined target construct nor "
1263                      "nesed inside a target construct without intermediate "
1264                      "code. This can lead to excessive register usage for "
1265                      "unrelated target regions in the same translation unit "
1266                      "due to spurious call edges assumed by ptxas.";
1267       };
1268       emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
1269     }
1270 
1271     // If this ever hits, we should investigate.
1272     // TODO: Checking the number of uses is not a necessary restriction and
1273     // should be lifted.
1274     if (UnknownUse || NumDirectCalls != 1 ||
1275         ToBeReplacedStateMachineUses.size() != 2) {
1276       {
1277         auto Remark = [&](OptimizationRemark OR) {
1278           return OR << "Parallel region is used in "
1279                     << (UnknownUse ? "unknown" : "unexpected")
1280                     << " ways; will not attempt to rewrite the state machine.";
1281         };
1282         emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
1283       }
1284       continue;
1285     }
1286 
1287     // Even if we have __kmpc_kernel_prepare_parallel calls, we (for now) give
1288     // up if the function is not called from a unique kernel.
1289     Kernel K = getUniqueKernelFor(*F);
1290     if (!K) {
1291       {
1292         auto Remark = [&](OptimizationRemark OR) {
1293           return OR << "Parallel region is not known to be called from a "
1294                        "unique single target region, maybe the surrounding "
1295                        "function has external linkage?; will not attempt to "
1296                        "rewrite the state machine use.";
1297         };
1298         emitRemarkOnFunction(F, "OpenMPParallelRegionInMultipleKernesl",
1299                              Remark);
1300       }
1301       continue;
1302     }
1303 
1304     // We now know F is a parallel body function called only from the kernel K.
1305     // We also identified the state machine uses in which we replace the
1306     // function pointer by a new global symbol for identification purposes. This
1307     // ensures only direct calls to the function are left.
1308 
1309     {
1310       auto RemarkParalleRegion = [&](OptimizationRemark OR) {
1311         return OR << "Specialize parallel region that is only reached from a "
1312                      "single target region to avoid spurious call edges and "
1313                      "excessive register usage in other target regions. "
1314                      "(parallel region ID: "
1315                   << ore::NV("OpenMPParallelRegion", F->getName())
1316                   << ", kernel ID: "
1317                   << ore::NV("OpenMPTargetRegion", K->getName()) << ")";
1318       };
1319       emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD",
1320                            RemarkParalleRegion);
1321       auto RemarkKernel = [&](OptimizationRemark OR) {
1322         return OR << "Target region containing the parallel region that is "
1323                      "specialized. (parallel region ID: "
1324                   << ore::NV("OpenMPParallelRegion", F->getName())
1325                   << ", kernel ID: "
1326                   << ore::NV("OpenMPTargetRegion", K->getName()) << ")";
1327       };
1328       emitRemarkOnFunction(K, "OpenMPParallelRegionInNonSPMD", RemarkKernel);
1329     }
1330 
1331     Module &M = *F->getParent();
1332     Type *Int8Ty = Type::getInt8Ty(M.getContext());
1333 
1334     auto *ID = new GlobalVariable(
1335         M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
1336         UndefValue::get(Int8Ty), F->getName() + ".ID");
1337 
1338     for (Use *U : ToBeReplacedStateMachineUses)
1339       U->set(ConstantExpr::getBitCast(ID, U->get()->getType()));
1340 
1341     ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
1342 
1343     Changed = true;
1344   }
1345 
1346   return Changed;
1347 }
1348 
1349 /// Abstract Attribute for tracking ICV values.
1350 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
1351   using Base = StateWrapper<BooleanState, AbstractAttribute>;
1352   AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
1353 
1354   void initialize(Attributor &A) override {
1355     Function *F = getAnchorScope();
1356     if (!F || !A.isFunctionIPOAmendable(*F))
1357       indicatePessimisticFixpoint();
1358   }
1359 
1360   /// Returns true if value is assumed to be tracked.
1361   bool isAssumedTracked() const { return getAssumed(); }
1362 
1363   /// Returns true if value is known to be tracked.
1364   bool isKnownTracked() const { return getAssumed(); }
1365 
1366   /// Create an abstract attribute biew for the position \p IRP.
1367   static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
1368 
1369   /// Return the value with which \p I can be replaced for specific \p ICV.
1370   virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
1371                                                 const Instruction *I,
1372                                                 Attributor &A) const {
1373     return None;
1374   }
1375 
1376   /// Return an assumed unique ICV value if a single candidate is found. If
1377   /// there cannot be one, return a nullptr. If it is not clear yet, return the
1378   /// Optional::NoneType.
1379   virtual Optional<Value *>
1380   getUniqueReplacementValue(InternalControlVar ICV) const = 0;
1381 
1382   // Currently only nthreads is being tracked.
1383   // this array will only grow with time.
1384   InternalControlVar TrackableICVs[1] = {ICV_nthreads};
1385 
1386   /// See AbstractAttribute::getName()
1387   const std::string getName() const override { return "AAICVTracker"; }
1388 
1389   /// See AbstractAttribute::getIdAddr()
1390   const char *getIdAddr() const override { return &ID; }
1391 
1392   /// This function should return true if the type of the \p AA is AAICVTracker
1393   static bool classof(const AbstractAttribute *AA) {
1394     return (AA->getIdAddr() == &ID);
1395   }
1396 
1397   static const char ID;
1398 };
1399 
1400 struct AAICVTrackerFunction : public AAICVTracker {
1401   AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
1402       : AAICVTracker(IRP, A) {}
1403 
1404   // FIXME: come up with better string.
1405   const std::string getAsStr() const override { return "ICVTrackerFunction"; }
1406 
1407   // FIXME: come up with some stats.
1408   void trackStatistics() const override {}
1409 
1410   /// We don't manifest anything for this AA.
1411   ChangeStatus manifest(Attributor &A) override {
1412     return ChangeStatus::UNCHANGED;
1413   }
1414 
1415   // Map of ICV to their values at specific program point.
1416   EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
1417                   InternalControlVar::ICV___last>
1418       ICVReplacementValuesMap;
1419 
1420   ChangeStatus updateImpl(Attributor &A) override {
1421     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1422 
1423     Function *F = getAnchorScope();
1424 
1425     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1426 
1427     for (InternalControlVar ICV : TrackableICVs) {
1428       auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
1429 
1430       auto &ValuesMap = ICVReplacementValuesMap[ICV];
1431       auto TrackValues = [&](Use &U, Function &) {
1432         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
1433         if (!CI)
1434           return false;
1435 
1436         // FIXME: handle setters with more that 1 arguments.
1437         /// Track new value.
1438         if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
1439           HasChanged = ChangeStatus::CHANGED;
1440 
1441         return false;
1442       };
1443 
1444       auto CallCheck = [&](Instruction &I) {
1445         Optional<Value *> ReplVal = getValueForCall(A, &I, ICV);
1446         if (ReplVal.hasValue() &&
1447             ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
1448           HasChanged = ChangeStatus::CHANGED;
1449 
1450         return true;
1451       };
1452 
1453       // Track all changes of an ICV.
1454       SetterRFI.foreachUse(TrackValues, F);
1455 
1456       A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
1457                                 /* CheckBBLivenessOnly */ true);
1458 
1459       /// TODO: Figure out a way to avoid adding entry in
1460       /// ICVReplacementValuesMap
1461       Instruction *Entry = &F->getEntryBlock().front();
1462       if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
1463         ValuesMap.insert(std::make_pair(Entry, nullptr));
1464     }
1465 
1466     return HasChanged;
1467   }
1468 
1469   /// Hepler to check if \p I is a call and get the value for it if it is
1470   /// unique.
1471   Optional<Value *> getValueForCall(Attributor &A, const Instruction *I,
1472                                     InternalControlVar &ICV) const {
1473 
1474     const auto *CB = dyn_cast<CallBase>(I);
1475     if (!CB)
1476       return None;
1477 
1478     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1479     auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
1480     auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
1481     Function *CalledFunction = CB->getCalledFunction();
1482 
1483     // Indirect call, assume ICV changes.
1484     if (CalledFunction == nullptr)
1485       return nullptr;
1486     if (CalledFunction == GetterRFI.Declaration)
1487       return None;
1488     if (CalledFunction == SetterRFI.Declaration) {
1489       if (ICVReplacementValuesMap[ICV].count(I))
1490         return ICVReplacementValuesMap[ICV].lookup(I);
1491 
1492       return nullptr;
1493     }
1494 
1495     // Since we don't know, assume it changes the ICV.
1496     if (CalledFunction->isDeclaration())
1497       return nullptr;
1498 
1499     const auto &ICVTrackingAA =
1500         A.getAAFor<AAICVTracker>(*this, IRPosition::callsite_returned(*CB));
1501 
1502     if (ICVTrackingAA.isAssumedTracked())
1503       return ICVTrackingAA.getUniqueReplacementValue(ICV);
1504 
1505     // If we don't know, assume it changes.
1506     return nullptr;
1507   }
1508 
1509   // We don't check unique value for a function, so return None.
1510   Optional<Value *>
1511   getUniqueReplacementValue(InternalControlVar ICV) const override {
1512     return None;
1513   }
1514 
1515   /// Return the value with which \p I can be replaced for specific \p ICV.
1516   Optional<Value *> getReplacementValue(InternalControlVar ICV,
1517                                         const Instruction *I,
1518                                         Attributor &A) const override {
1519     const auto &ValuesMap = ICVReplacementValuesMap[ICV];
1520     if (ValuesMap.count(I))
1521       return ValuesMap.lookup(I);
1522 
1523     SmallVector<const Instruction *, 16> Worklist;
1524     SmallPtrSet<const Instruction *, 16> Visited;
1525     Worklist.push_back(I);
1526 
1527     Optional<Value *> ReplVal;
1528 
1529     while (!Worklist.empty()) {
1530       const Instruction *CurrInst = Worklist.pop_back_val();
1531       if (!Visited.insert(CurrInst).second)
1532         continue;
1533 
1534       const BasicBlock *CurrBB = CurrInst->getParent();
1535 
1536       // Go up and look for all potential setters/calls that might change the
1537       // ICV.
1538       while ((CurrInst = CurrInst->getPrevNode())) {
1539         if (ValuesMap.count(CurrInst)) {
1540           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
1541           // Unknown value, track new.
1542           if (!ReplVal.hasValue()) {
1543             ReplVal = NewReplVal;
1544             break;
1545           }
1546 
1547           // If we found a new value, we can't know the icv value anymore.
1548           if (NewReplVal.hasValue())
1549             if (ReplVal != NewReplVal)
1550               return nullptr;
1551 
1552           break;
1553         }
1554 
1555         Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV);
1556         if (!NewReplVal.hasValue())
1557           continue;
1558 
1559         // Unknown value, track new.
1560         if (!ReplVal.hasValue()) {
1561           ReplVal = NewReplVal;
1562           break;
1563         }
1564 
1565         // if (NewReplVal.hasValue())
1566         // We found a new value, we can't know the icv value anymore.
1567         if (ReplVal != NewReplVal)
1568           return nullptr;
1569       }
1570 
1571       // If we are in the same BB and we have a value, we are done.
1572       if (CurrBB == I->getParent() && ReplVal.hasValue())
1573         return ReplVal;
1574 
1575       // Go through all predecessors and add terminators for analysis.
1576       for (const BasicBlock *Pred : predecessors(CurrBB))
1577         if (const Instruction *Terminator = Pred->getTerminator())
1578           Worklist.push_back(Terminator);
1579     }
1580 
1581     return ReplVal;
1582   }
1583 };
1584 
1585 struct AAICVTrackerFunctionReturned : AAICVTracker {
1586   AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
1587       : AAICVTracker(IRP, A) {}
1588 
1589   // FIXME: come up with better string.
1590   const std::string getAsStr() const override {
1591     return "ICVTrackerFunctionReturned";
1592   }
1593 
1594   // FIXME: come up with some stats.
1595   void trackStatistics() const override {}
1596 
1597   /// We don't manifest anything for this AA.
1598   ChangeStatus manifest(Attributor &A) override {
1599     return ChangeStatus::UNCHANGED;
1600   }
1601 
1602   // Map of ICV to their values at specific program point.
1603   EnumeratedArray<Optional<Value *>, InternalControlVar,
1604                   InternalControlVar::ICV___last>
1605       ICVReplacementValuesMap;
1606 
1607   /// Return the value with which \p I can be replaced for specific \p ICV.
1608   Optional<Value *>
1609   getUniqueReplacementValue(InternalControlVar ICV) const override {
1610     return ICVReplacementValuesMap[ICV];
1611   }
1612 
1613   ChangeStatus updateImpl(Attributor &A) override {
1614     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1615     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1616         *this, IRPosition::function(*getAnchorScope()));
1617 
1618     if (!ICVTrackingAA.isAssumedTracked())
1619       return indicatePessimisticFixpoint();
1620 
1621     for (InternalControlVar ICV : TrackableICVs) {
1622       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
1623       Optional<Value *> UniqueICVValue;
1624 
1625       auto CheckReturnInst = [&](Instruction &I) {
1626         Optional<Value *> NewReplVal =
1627             ICVTrackingAA.getReplacementValue(ICV, &I, A);
1628 
1629         // If we found a second ICV value there is no unique returned value.
1630         if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
1631           return false;
1632 
1633         UniqueICVValue = NewReplVal;
1634 
1635         return true;
1636       };
1637 
1638       if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
1639                                      /* CheckBBLivenessOnly */ true))
1640         UniqueICVValue = nullptr;
1641 
1642       if (UniqueICVValue == ReplVal)
1643         continue;
1644 
1645       ReplVal = UniqueICVValue;
1646       Changed = ChangeStatus::CHANGED;
1647     }
1648 
1649     return Changed;
1650   }
1651 };
1652 
1653 struct AAICVTrackerCallSite : AAICVTracker {
1654   AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
1655       : AAICVTracker(IRP, A) {}
1656 
1657   void initialize(Attributor &A) override {
1658     Function *F = getAnchorScope();
1659     if (!F || !A.isFunctionIPOAmendable(*F))
1660       indicatePessimisticFixpoint();
1661 
1662     // We only initialize this AA for getters, so we need to know which ICV it
1663     // gets.
1664     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
1665     for (InternalControlVar ICV : TrackableICVs) {
1666       auto ICVInfo = OMPInfoCache.ICVs[ICV];
1667       auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
1668       if (Getter.Declaration == getAssociatedFunction()) {
1669         AssociatedICV = ICVInfo.Kind;
1670         return;
1671       }
1672     }
1673 
1674     /// Unknown ICV.
1675     indicatePessimisticFixpoint();
1676   }
1677 
1678   ChangeStatus manifest(Attributor &A) override {
1679     if (!ReplVal.hasValue() || !ReplVal.getValue())
1680       return ChangeStatus::UNCHANGED;
1681 
1682     A.changeValueAfterManifest(*getCtxI(), **ReplVal);
1683     A.deleteAfterManifest(*getCtxI());
1684 
1685     return ChangeStatus::CHANGED;
1686   }
1687 
1688   // FIXME: come up with better string.
1689   const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
1690 
1691   // FIXME: come up with some stats.
1692   void trackStatistics() const override {}
1693 
1694   InternalControlVar AssociatedICV;
1695   Optional<Value *> ReplVal;
1696 
1697   ChangeStatus updateImpl(Attributor &A) override {
1698     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1699         *this, IRPosition::function(*getAnchorScope()));
1700 
1701     // We don't have any information, so we assume it changes the ICV.
1702     if (!ICVTrackingAA.isAssumedTracked())
1703       return indicatePessimisticFixpoint();
1704 
1705     Optional<Value *> NewReplVal =
1706         ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
1707 
1708     if (ReplVal == NewReplVal)
1709       return ChangeStatus::UNCHANGED;
1710 
1711     ReplVal = NewReplVal;
1712     return ChangeStatus::CHANGED;
1713   }
1714 
1715   // Return the value with which associated value can be replaced for specific
1716   // \p ICV.
1717   Optional<Value *>
1718   getUniqueReplacementValue(InternalControlVar ICV) const override {
1719     return ReplVal;
1720   }
1721 };
1722 
1723 struct AAICVTrackerCallSiteReturned : AAICVTracker {
1724   AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
1725       : AAICVTracker(IRP, A) {}
1726 
1727   // FIXME: come up with better string.
1728   const std::string getAsStr() const override {
1729     return "ICVTrackerCallSiteReturned";
1730   }
1731 
1732   // FIXME: come up with some stats.
1733   void trackStatistics() const override {}
1734 
1735   /// We don't manifest anything for this AA.
1736   ChangeStatus manifest(Attributor &A) override {
1737     return ChangeStatus::UNCHANGED;
1738   }
1739 
1740   // Map of ICV to their values at specific program point.
1741   EnumeratedArray<Optional<Value *>, InternalControlVar,
1742                   InternalControlVar::ICV___last>
1743       ICVReplacementValuesMap;
1744 
1745   /// Return the value with which associated value can be replaced for specific
1746   /// \p ICV.
1747   Optional<Value *>
1748   getUniqueReplacementValue(InternalControlVar ICV) const override {
1749     return ICVReplacementValuesMap[ICV];
1750   }
1751 
1752   ChangeStatus updateImpl(Attributor &A) override {
1753     ChangeStatus Changed = ChangeStatus::UNCHANGED;
1754     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
1755         *this, IRPosition::returned(*getAssociatedFunction()));
1756 
1757     // We don't have any information, so we assume it changes the ICV.
1758     if (!ICVTrackingAA.isAssumedTracked())
1759       return indicatePessimisticFixpoint();
1760 
1761     for (InternalControlVar ICV : TrackableICVs) {
1762       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
1763       Optional<Value *> NewReplVal =
1764           ICVTrackingAA.getUniqueReplacementValue(ICV);
1765 
1766       if (ReplVal == NewReplVal)
1767         continue;
1768 
1769       ReplVal = NewReplVal;
1770       Changed = ChangeStatus::CHANGED;
1771     }
1772     return Changed;
1773   }
1774 };
1775 } // namespace
1776 
1777 const char AAICVTracker::ID = 0;
1778 
1779 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
1780                                               Attributor &A) {
1781   AAICVTracker *AA = nullptr;
1782   switch (IRP.getPositionKind()) {
1783   case IRPosition::IRP_INVALID:
1784   case IRPosition::IRP_FLOAT:
1785   case IRPosition::IRP_ARGUMENT:
1786   case IRPosition::IRP_CALL_SITE_ARGUMENT:
1787     llvm_unreachable("ICVTracker can only be created for function position!");
1788   case IRPosition::IRP_RETURNED:
1789     AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
1790     break;
1791   case IRPosition::IRP_CALL_SITE_RETURNED:
1792     AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
1793     break;
1794   case IRPosition::IRP_CALL_SITE:
1795     AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
1796     break;
1797   case IRPosition::IRP_FUNCTION:
1798     AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
1799     break;
1800   }
1801 
1802   return *AA;
1803 }
1804 
1805 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C,
1806                                      CGSCCAnalysisManager &AM,
1807                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
1808   if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule))
1809     return PreservedAnalyses::all();
1810 
1811   if (DisableOpenMPOptimizations)
1812     return PreservedAnalyses::all();
1813 
1814   SmallVector<Function *, 16> SCC;
1815   // If there are kernels in the module, we have to run on all SCC's.
1816   bool SCCIsInteresting = !OMPInModule.getKernels().empty();
1817   for (LazyCallGraph::Node &N : C) {
1818     Function *Fn = &N.getFunction();
1819     SCC.push_back(Fn);
1820 
1821     // Do we already know that the SCC contains kernels,
1822     // or that OpenMP functions are called from this SCC?
1823     if (SCCIsInteresting)
1824       continue;
1825     // If not, let's check that.
1826     SCCIsInteresting |= OMPInModule.containsOMPRuntimeCalls(Fn);
1827   }
1828 
1829   if (!SCCIsInteresting || SCC.empty())
1830     return PreservedAnalyses::all();
1831 
1832   FunctionAnalysisManager &FAM =
1833       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1834 
1835   AnalysisGetter AG(FAM);
1836 
1837   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
1838     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
1839   };
1840 
1841   CallGraphUpdater CGUpdater;
1842   CGUpdater.initialize(CG, C, AM, UR);
1843 
1844   SetVector<Function *> Functions(SCC.begin(), SCC.end());
1845   BumpPtrAllocator Allocator;
1846   OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
1847                                 /*CGSCC*/ Functions, OMPInModule.getKernels());
1848 
1849   Attributor A(Functions, InfoCache, CGUpdater);
1850 
1851   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
1852   bool Changed = OMPOpt.run();
1853   if (Changed)
1854     return PreservedAnalyses::none();
1855 
1856   return PreservedAnalyses::all();
1857 }
1858 
1859 namespace {
1860 
1861 struct OpenMPOptLegacyPass : public CallGraphSCCPass {
1862   CallGraphUpdater CGUpdater;
1863   OpenMPInModule OMPInModule;
1864   static char ID;
1865 
1866   OpenMPOptLegacyPass() : CallGraphSCCPass(ID) {
1867     initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry());
1868   }
1869 
1870   void getAnalysisUsage(AnalysisUsage &AU) const override {
1871     CallGraphSCCPass::getAnalysisUsage(AU);
1872   }
1873 
1874   bool doInitialization(CallGraph &CG) override {
1875     // Disable the pass if there is no OpenMP (runtime call) in the module.
1876     containsOpenMP(CG.getModule(), OMPInModule);
1877     return false;
1878   }
1879 
1880   bool runOnSCC(CallGraphSCC &CGSCC) override {
1881     if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule))
1882       return false;
1883     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
1884       return false;
1885 
1886     SmallVector<Function *, 16> SCC;
1887     // If there are kernels in the module, we have to run on all SCC's.
1888     bool SCCIsInteresting = !OMPInModule.getKernels().empty();
1889     for (CallGraphNode *CGN : CGSCC) {
1890       Function *Fn = CGN->getFunction();
1891       if (!Fn || Fn->isDeclaration())
1892         continue;
1893       SCC.push_back(Fn);
1894 
1895       // Do we already know that the SCC contains kernels,
1896       // or that OpenMP functions are called from this SCC?
1897       if (SCCIsInteresting)
1898         continue;
1899       // If not, let's check that.
1900       SCCIsInteresting |= OMPInModule.containsOMPRuntimeCalls(Fn);
1901     }
1902 
1903     if (!SCCIsInteresting || SCC.empty())
1904       return false;
1905 
1906     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1907     CGUpdater.initialize(CG, CGSCC);
1908 
1909     // Maintain a map of functions to avoid rebuilding the ORE
1910     DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
1911     auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
1912       std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
1913       if (!ORE)
1914         ORE = std::make_unique<OptimizationRemarkEmitter>(F);
1915       return *ORE;
1916     };
1917 
1918     AnalysisGetter AG;
1919     SetVector<Function *> Functions(SCC.begin(), SCC.end());
1920     BumpPtrAllocator Allocator;
1921     OMPInformationCache InfoCache(
1922         *(Functions.back()->getParent()), AG, Allocator,
1923         /*CGSCC*/ Functions, OMPInModule.getKernels());
1924 
1925     Attributor A(Functions, InfoCache, CGUpdater);
1926 
1927     OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
1928     return OMPOpt.run();
1929   }
1930 
1931   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
1932 };
1933 
1934 } // end anonymous namespace
1935 
1936 void OpenMPInModule::identifyKernels(Module &M) {
1937 
1938   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
1939   if (!MD)
1940     return;
1941 
1942   for (auto *Op : MD->operands()) {
1943     if (Op->getNumOperands() < 2)
1944       continue;
1945     MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
1946     if (!KindID || KindID->getString() != "kernel")
1947       continue;
1948 
1949     Function *KernelFn =
1950         mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
1951     if (!KernelFn)
1952       continue;
1953 
1954     ++NumOpenMPTargetRegionKernels;
1955 
1956     Kernels.insert(KernelFn);
1957   }
1958 }
1959 
1960 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) {
1961   if (OMPInModule.isKnown())
1962     return OMPInModule;
1963 
1964   auto RecordFunctionsContainingUsesOf = [&](Function *F) {
1965     for (User *U : F->users())
1966       if (auto *I = dyn_cast<Instruction>(U))
1967         OMPInModule.FuncsWithOMPRuntimeCalls.insert(I->getFunction());
1968   };
1969 
1970   // MSVC doesn't like long if-else chains for some reason and instead just
1971   // issues an error. Work around it..
1972   do {
1973 #define OMP_RTL(_Enum, _Name, ...)                                             \
1974   if (Function *F = M.getFunction(_Name)) {                                    \
1975     RecordFunctionsContainingUsesOf(F);                                        \
1976     OMPInModule = true;                                                        \
1977   }
1978 #include "llvm/Frontend/OpenMP/OMPKinds.def"
1979   } while (false);
1980 
1981   // Identify kernels once. TODO: We should split the OMPInformationCache into a
1982   // module and an SCC part. The kernel information, among other things, could
1983   // go into the module part.
1984   if (OMPInModule.isKnown() && OMPInModule) {
1985     OMPInModule.identifyKernels(M);
1986     return true;
1987   }
1988 
1989   return OMPInModule = false;
1990 }
1991 
1992 char OpenMPOptLegacyPass::ID = 0;
1993 
1994 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt",
1995                       "OpenMP specific optimizations", false, false)
1996 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1997 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt",
1998                     "OpenMP specific optimizations", false, false)
1999 
2000 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); }
2001