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 // - Replacing globalized device memory with stack memory.
13 // - Replacing globalized device memory with shared memory.
14 // - Parallel region merging.
15 // - Transforming generic-mode device kernels to SPMD mode.
16 // - Specializing the state machine for generic-mode device kernels.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "llvm/Transforms/IPO/OpenMPOpt.h"
21 
22 #include "llvm/ADT/EnumeratedArray.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Analysis/CallGraphSCCPass.h"
27 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Frontend/OpenMP/OMPConstants.h"
30 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
31 #include "llvm/IR/Assumptions.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/Attributor.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/CallGraphUpdater.h"
42 #include "llvm/Transforms/Utils/CodeExtractor.h"
43 
44 using namespace llvm;
45 using namespace omp;
46 
47 #define DEBUG_TYPE "openmp-opt"
48 
49 static cl::opt<bool> DisableOpenMPOptimizations(
50     "openmp-opt-disable", cl::ZeroOrMore,
51     cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
52     cl::init(false));
53 
54 static cl::opt<bool> EnableParallelRegionMerging(
55     "openmp-opt-enable-merging", cl::ZeroOrMore,
56     cl::desc("Enable the OpenMP region merging optimization."), cl::Hidden,
57     cl::init(false));
58 
59 static cl::opt<bool>
60     DisableInternalization("openmp-opt-disable-internalization", cl::ZeroOrMore,
61                            cl::desc("Disable function internalization."),
62                            cl::Hidden, cl::init(false));
63 
64 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false),
65                                     cl::Hidden);
66 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels",
67                                         cl::init(false), cl::Hidden);
68 
69 static cl::opt<bool> HideMemoryTransferLatency(
70     "openmp-hide-memory-transfer-latency",
71     cl::desc("[WIP] Tries to hide the latency of host to device memory"
72              " transfers"),
73     cl::Hidden, cl::init(false));
74 
75 STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
76           "Number of OpenMP runtime calls deduplicated");
77 STATISTIC(NumOpenMPParallelRegionsDeleted,
78           "Number of OpenMP parallel regions deleted");
79 STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
80           "Number of OpenMP runtime functions identified");
81 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
82           "Number of OpenMP runtime function uses identified");
83 STATISTIC(NumOpenMPTargetRegionKernels,
84           "Number of OpenMP target region entry points (=kernels) identified");
85 STATISTIC(NumOpenMPTargetRegionKernelsSPMD,
86           "Number of OpenMP target region entry points (=kernels) executed in "
87           "SPMD-mode instead of generic-mode");
88 STATISTIC(NumOpenMPTargetRegionKernelsWithoutStateMachine,
89           "Number of OpenMP target region entry points (=kernels) executed in "
90           "generic-mode without a state machines");
91 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback,
92           "Number of OpenMP target region entry points (=kernels) executed in "
93           "generic-mode with customized state machines with fallback");
94 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback,
95           "Number of OpenMP target region entry points (=kernels) executed in "
96           "generic-mode with customized state machines without fallback");
97 STATISTIC(
98     NumOpenMPParallelRegionsReplacedInGPUStateMachine,
99     "Number of OpenMP parallel regions replaced with ID in GPU state machines");
100 STATISTIC(NumOpenMPParallelRegionsMerged,
101           "Number of OpenMP parallel regions merged");
102 STATISTIC(NumBytesMovedToSharedMemory,
103           "Amount of memory pushed to shared memory");
104 
105 #if !defined(NDEBUG)
106 static constexpr auto TAG = "[" DEBUG_TYPE "]";
107 #endif
108 
109 namespace {
110 
111 enum class AddressSpace : unsigned {
112   Generic = 0,
113   Global = 1,
114   Shared = 3,
115   Constant = 4,
116   Local = 5,
117 };
118 
119 struct AAHeapToShared;
120 
121 struct AAICVTracker;
122 
123 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for
124 /// Attributor runs.
125 struct OMPInformationCache : public InformationCache {
126   OMPInformationCache(Module &M, AnalysisGetter &AG,
127                       BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC,
128                       SmallPtrSetImpl<Kernel> &Kernels)
129       : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M),
130         Kernels(Kernels) {
131 
132     OMPBuilder.initialize();
133     initializeRuntimeFunctions();
134     initializeInternalControlVars();
135   }
136 
137   /// Generic information that describes an internal control variable.
138   struct InternalControlVarInfo {
139     /// The kind, as described by InternalControlVar enum.
140     InternalControlVar Kind;
141 
142     /// The name of the ICV.
143     StringRef Name;
144 
145     /// Environment variable associated with this ICV.
146     StringRef EnvVarName;
147 
148     /// Initial value kind.
149     ICVInitValue InitKind;
150 
151     /// Initial value.
152     ConstantInt *InitValue;
153 
154     /// Setter RTL function associated with this ICV.
155     RuntimeFunction Setter;
156 
157     /// Getter RTL function associated with this ICV.
158     RuntimeFunction Getter;
159 
160     /// RTL Function corresponding to the override clause of this ICV
161     RuntimeFunction Clause;
162   };
163 
164   /// Generic information that describes a runtime function
165   struct RuntimeFunctionInfo {
166 
167     /// The kind, as described by the RuntimeFunction enum.
168     RuntimeFunction Kind;
169 
170     /// The name of the function.
171     StringRef Name;
172 
173     /// Flag to indicate a variadic function.
174     bool IsVarArg;
175 
176     /// The return type of the function.
177     Type *ReturnType;
178 
179     /// The argument types of the function.
180     SmallVector<Type *, 8> ArgumentTypes;
181 
182     /// The declaration if available.
183     Function *Declaration = nullptr;
184 
185     /// Uses of this runtime function per function containing the use.
186     using UseVector = SmallVector<Use *, 16>;
187 
188     /// Clear UsesMap for runtime function.
189     void clearUsesMap() { UsesMap.clear(); }
190 
191     /// Boolean conversion that is true if the runtime function was found.
192     operator bool() const { return Declaration; }
193 
194     /// Return the vector of uses in function \p F.
195     UseVector &getOrCreateUseVector(Function *F) {
196       std::shared_ptr<UseVector> &UV = UsesMap[F];
197       if (!UV)
198         UV = std::make_shared<UseVector>();
199       return *UV;
200     }
201 
202     /// Return the vector of uses in function \p F or `nullptr` if there are
203     /// none.
204     const UseVector *getUseVector(Function &F) const {
205       auto I = UsesMap.find(&F);
206       if (I != UsesMap.end())
207         return I->second.get();
208       return nullptr;
209     }
210 
211     /// Return how many functions contain uses of this runtime function.
212     size_t getNumFunctionsWithUses() const { return UsesMap.size(); }
213 
214     /// Return the number of arguments (or the minimal number for variadic
215     /// functions).
216     size_t getNumArgs() const { return ArgumentTypes.size(); }
217 
218     /// Run the callback \p CB on each use and forget the use if the result is
219     /// true. The callback will be fed the function in which the use was
220     /// encountered as second argument.
221     void foreachUse(SmallVectorImpl<Function *> &SCC,
222                     function_ref<bool(Use &, Function &)> CB) {
223       for (Function *F : SCC)
224         foreachUse(CB, F);
225     }
226 
227     /// Run the callback \p CB on each use within the function \p F and forget
228     /// the use if the result is true.
229     void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) {
230       SmallVector<unsigned, 8> ToBeDeleted;
231       ToBeDeleted.clear();
232 
233       unsigned Idx = 0;
234       UseVector &UV = getOrCreateUseVector(F);
235 
236       for (Use *U : UV) {
237         if (CB(*U, *F))
238           ToBeDeleted.push_back(Idx);
239         ++Idx;
240       }
241 
242       // Remove the to-be-deleted indices in reverse order as prior
243       // modifications will not modify the smaller indices.
244       while (!ToBeDeleted.empty()) {
245         unsigned Idx = ToBeDeleted.pop_back_val();
246         UV[Idx] = UV.back();
247         UV.pop_back();
248       }
249     }
250 
251   private:
252     /// Map from functions to all uses of this runtime function contained in
253     /// them.
254     DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap;
255 
256   public:
257     /// Iterators for the uses of this runtime function.
258     decltype(UsesMap)::iterator begin() { return UsesMap.begin(); }
259     decltype(UsesMap)::iterator end() { return UsesMap.end(); }
260   };
261 
262   /// An OpenMP-IR-Builder instance
263   OpenMPIRBuilder OMPBuilder;
264 
265   /// Map from runtime function kind to the runtime function description.
266   EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
267                   RuntimeFunction::OMPRTL___last>
268       RFIs;
269 
270   /// Map from function declarations/definitions to their runtime enum type.
271   DenseMap<Function *, RuntimeFunction> RuntimeFunctionIDMap;
272 
273   /// Map from ICV kind to the ICV description.
274   EnumeratedArray<InternalControlVarInfo, InternalControlVar,
275                   InternalControlVar::ICV___last>
276       ICVs;
277 
278   /// Helper to initialize all internal control variable information for those
279   /// defined in OMPKinds.def.
280   void initializeInternalControlVars() {
281 #define ICV_RT_SET(_Name, RTL)                                                 \
282   {                                                                            \
283     auto &ICV = ICVs[_Name];                                                   \
284     ICV.Setter = RTL;                                                          \
285   }
286 #define ICV_RT_GET(Name, RTL)                                                  \
287   {                                                                            \
288     auto &ICV = ICVs[Name];                                                    \
289     ICV.Getter = RTL;                                                          \
290   }
291 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init)                           \
292   {                                                                            \
293     auto &ICV = ICVs[Enum];                                                    \
294     ICV.Name = _Name;                                                          \
295     ICV.Kind = Enum;                                                           \
296     ICV.InitKind = Init;                                                       \
297     ICV.EnvVarName = _EnvVarName;                                              \
298     switch (ICV.InitKind) {                                                    \
299     case ICV_IMPLEMENTATION_DEFINED:                                           \
300       ICV.InitValue = nullptr;                                                 \
301       break;                                                                   \
302     case ICV_ZERO:                                                             \
303       ICV.InitValue = ConstantInt::get(                                        \
304           Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0);                \
305       break;                                                                   \
306     case ICV_FALSE:                                                            \
307       ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext());    \
308       break;                                                                   \
309     case ICV_LAST:                                                             \
310       break;                                                                   \
311     }                                                                          \
312   }
313 #include "llvm/Frontend/OpenMP/OMPKinds.def"
314   }
315 
316   /// Returns true if the function declaration \p F matches the runtime
317   /// function types, that is, return type \p RTFRetType, and argument types
318   /// \p RTFArgTypes.
319   static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
320                                   SmallVector<Type *, 8> &RTFArgTypes) {
321     // TODO: We should output information to the user (under debug output
322     //       and via remarks).
323 
324     if (!F)
325       return false;
326     if (F->getReturnType() != RTFRetType)
327       return false;
328     if (F->arg_size() != RTFArgTypes.size())
329       return false;
330 
331     auto RTFTyIt = RTFArgTypes.begin();
332     for (Argument &Arg : F->args()) {
333       if (Arg.getType() != *RTFTyIt)
334         return false;
335 
336       ++RTFTyIt;
337     }
338 
339     return true;
340   }
341 
342   // Helper to collect all uses of the declaration in the UsesMap.
343   unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) {
344     unsigned NumUses = 0;
345     if (!RFI.Declaration)
346       return NumUses;
347     OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
348 
349     if (CollectStats) {
350       NumOpenMPRuntimeFunctionsIdentified += 1;
351       NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
352     }
353 
354     // TODO: We directly convert uses into proper calls and unknown uses.
355     for (Use &U : RFI.Declaration->uses()) {
356       if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
357         if (ModuleSlice.count(UserI->getFunction())) {
358           RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U);
359           ++NumUses;
360         }
361       } else {
362         RFI.getOrCreateUseVector(nullptr).push_back(&U);
363         ++NumUses;
364       }
365     }
366     return NumUses;
367   }
368 
369   // Helper function to recollect uses of a runtime function.
370   void recollectUsesForFunction(RuntimeFunction RTF) {
371     auto &RFI = RFIs[RTF];
372     RFI.clearUsesMap();
373     collectUses(RFI, /*CollectStats*/ false);
374   }
375 
376   // Helper function to recollect uses of all runtime functions.
377   void recollectUses() {
378     for (int Idx = 0; Idx < RFIs.size(); ++Idx)
379       recollectUsesForFunction(static_cast<RuntimeFunction>(Idx));
380   }
381 
382   /// Helper to initialize all runtime function information for those defined
383   /// in OpenMPKinds.def.
384   void initializeRuntimeFunctions() {
385     Module &M = *((*ModuleSlice.begin())->getParent());
386 
387     // Helper macros for handling __VA_ARGS__ in OMP_RTL
388 #define OMP_TYPE(VarName, ...)                                                 \
389   Type *VarName = OMPBuilder.VarName;                                          \
390   (void)VarName;
391 
392 #define OMP_ARRAY_TYPE(VarName, ...)                                           \
393   ArrayType *VarName##Ty = OMPBuilder.VarName##Ty;                             \
394   (void)VarName##Ty;                                                           \
395   PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy;                     \
396   (void)VarName##PtrTy;
397 
398 #define OMP_FUNCTION_TYPE(VarName, ...)                                        \
399   FunctionType *VarName = OMPBuilder.VarName;                                  \
400   (void)VarName;                                                               \
401   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
402   (void)VarName##Ptr;
403 
404 #define OMP_STRUCT_TYPE(VarName, ...)                                          \
405   StructType *VarName = OMPBuilder.VarName;                                    \
406   (void)VarName;                                                               \
407   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
408   (void)VarName##Ptr;
409 
410 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...)                     \
411   {                                                                            \
412     SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__});                           \
413     Function *F = M.getFunction(_Name);                                        \
414     RTLFunctions.insert(F);                                                    \
415     if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) {           \
416       RuntimeFunctionIDMap[F] = _Enum;                                         \
417       F->removeFnAttr(Attribute::NoInline);                                    \
418       auto &RFI = RFIs[_Enum];                                                 \
419       RFI.Kind = _Enum;                                                        \
420       RFI.Name = _Name;                                                        \
421       RFI.IsVarArg = _IsVarArg;                                                \
422       RFI.ReturnType = OMPBuilder._ReturnType;                                 \
423       RFI.ArgumentTypes = std::move(ArgsTypes);                                \
424       RFI.Declaration = F;                                                     \
425       unsigned NumUses = collectUses(RFI);                                     \
426       (void)NumUses;                                                           \
427       LLVM_DEBUG({                                                             \
428         dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not")           \
429                << " found\n";                                                  \
430         if (RFI.Declaration)                                                   \
431           dbgs() << TAG << "-> got " << NumUses << " uses in "                 \
432                  << RFI.getNumFunctionsWithUses()                              \
433                  << " different functions.\n";                                 \
434       });                                                                      \
435     }                                                                          \
436   }
437 #include "llvm/Frontend/OpenMP/OMPKinds.def"
438 
439     // TODO: We should attach the attributes defined in OMPKinds.def.
440   }
441 
442   /// Collection of known kernels (\see Kernel) in the module.
443   SmallPtrSetImpl<Kernel> &Kernels;
444 
445   /// Collection of known OpenMP runtime functions..
446   DenseSet<const Function *> RTLFunctions;
447 };
448 
449 template <typename Ty, bool InsertInvalidates = true>
450 struct BooleanStateWithSetVector : public BooleanState {
451   bool contains(const Ty &Elem) const { return Set.contains(Elem); }
452   bool insert(const Ty &Elem) {
453     if (InsertInvalidates)
454       BooleanState::indicatePessimisticFixpoint();
455     return Set.insert(Elem);
456   }
457 
458   const Ty &operator[](int Idx) const { return Set[Idx]; }
459   bool operator==(const BooleanStateWithSetVector &RHS) const {
460     return BooleanState::operator==(RHS) && Set == RHS.Set;
461   }
462   bool operator!=(const BooleanStateWithSetVector &RHS) const {
463     return !(*this == RHS);
464   }
465 
466   bool empty() const { return Set.empty(); }
467   size_t size() const { return Set.size(); }
468 
469   /// "Clamp" this state with \p RHS.
470   BooleanStateWithSetVector &operator^=(const BooleanStateWithSetVector &RHS) {
471     BooleanState::operator^=(RHS);
472     Set.insert(RHS.Set.begin(), RHS.Set.end());
473     return *this;
474   }
475 
476 private:
477   /// A set to keep track of elements.
478   SetVector<Ty> Set;
479 
480 public:
481   typename decltype(Set)::iterator begin() { return Set.begin(); }
482   typename decltype(Set)::iterator end() { return Set.end(); }
483   typename decltype(Set)::const_iterator begin() const { return Set.begin(); }
484   typename decltype(Set)::const_iterator end() const { return Set.end(); }
485 };
486 
487 template <typename Ty, bool InsertInvalidates = true>
488 using BooleanStateWithPtrSetVector =
489     BooleanStateWithSetVector<Ty *, InsertInvalidates>;
490 
491 struct KernelInfoState : AbstractState {
492   /// Flag to track if we reached a fixpoint.
493   bool IsAtFixpoint = false;
494 
495   /// The parallel regions (identified by the outlined parallel functions) that
496   /// can be reached from the associated function.
497   BooleanStateWithPtrSetVector<Function, /* InsertInvalidates */ false>
498       ReachedKnownParallelRegions;
499 
500   /// State to track what parallel region we might reach.
501   BooleanStateWithPtrSetVector<CallBase> ReachedUnknownParallelRegions;
502 
503   /// State to track if we are in SPMD-mode, assumed or know, and why we decided
504   /// we cannot be. If it is assumed, then RequiresFullRuntime should also be
505   /// false.
506   BooleanStateWithPtrSetVector<Instruction> SPMDCompatibilityTracker;
507 
508   /// The __kmpc_target_init call in this kernel, if any. If we find more than
509   /// one we abort as the kernel is malformed.
510   CallBase *KernelInitCB = nullptr;
511 
512   /// The __kmpc_target_deinit call in this kernel, if any. If we find more than
513   /// one we abort as the kernel is malformed.
514   CallBase *KernelDeinitCB = nullptr;
515 
516   /// Flag to indicate if the associated function is a kernel entry.
517   bool IsKernelEntry = false;
518 
519   /// State to track what kernel entries can reach the associated function.
520   BooleanStateWithPtrSetVector<Function, false> ReachingKernelEntries;
521 
522   /// Abstract State interface
523   ///{
524 
525   KernelInfoState() {}
526   KernelInfoState(bool BestState) {
527     if (!BestState)
528       indicatePessimisticFixpoint();
529   }
530 
531   /// See AbstractState::isValidState(...)
532   bool isValidState() const override { return true; }
533 
534   /// See AbstractState::isAtFixpoint(...)
535   bool isAtFixpoint() const override { return IsAtFixpoint; }
536 
537   /// See AbstractState::indicatePessimisticFixpoint(...)
538   ChangeStatus indicatePessimisticFixpoint() override {
539     IsAtFixpoint = true;
540     SPMDCompatibilityTracker.indicatePessimisticFixpoint();
541     ReachedUnknownParallelRegions.indicatePessimisticFixpoint();
542     return ChangeStatus::CHANGED;
543   }
544 
545   /// See AbstractState::indicateOptimisticFixpoint(...)
546   ChangeStatus indicateOptimisticFixpoint() override {
547     IsAtFixpoint = true;
548     return ChangeStatus::UNCHANGED;
549   }
550 
551   /// Return the assumed state
552   KernelInfoState &getAssumed() { return *this; }
553   const KernelInfoState &getAssumed() const { return *this; }
554 
555   bool operator==(const KernelInfoState &RHS) const {
556     if (SPMDCompatibilityTracker != RHS.SPMDCompatibilityTracker)
557       return false;
558     if (ReachedKnownParallelRegions != RHS.ReachedKnownParallelRegions)
559       return false;
560     if (ReachedUnknownParallelRegions != RHS.ReachedUnknownParallelRegions)
561       return false;
562     if (ReachingKernelEntries != RHS.ReachingKernelEntries)
563       return false;
564     return true;
565   }
566 
567   /// Return empty set as the best state of potential values.
568   static KernelInfoState getBestState() { return KernelInfoState(true); }
569 
570   static KernelInfoState getBestState(KernelInfoState &KIS) {
571     return getBestState();
572   }
573 
574   /// Return full set as the worst state of potential values.
575   static KernelInfoState getWorstState() { return KernelInfoState(false); }
576 
577   /// "Clamp" this state with \p KIS.
578   KernelInfoState operator^=(const KernelInfoState &KIS) {
579     // Do not merge two different _init and _deinit call sites.
580     if (KIS.KernelInitCB) {
581       if (KernelInitCB && KernelInitCB != KIS.KernelInitCB)
582         indicatePessimisticFixpoint();
583       KernelInitCB = KIS.KernelInitCB;
584     }
585     if (KIS.KernelDeinitCB) {
586       if (KernelDeinitCB && KernelDeinitCB != KIS.KernelDeinitCB)
587         indicatePessimisticFixpoint();
588       KernelDeinitCB = KIS.KernelDeinitCB;
589     }
590     SPMDCompatibilityTracker ^= KIS.SPMDCompatibilityTracker;
591     ReachedKnownParallelRegions ^= KIS.ReachedKnownParallelRegions;
592     ReachedUnknownParallelRegions ^= KIS.ReachedUnknownParallelRegions;
593     return *this;
594   }
595 
596   KernelInfoState operator&=(const KernelInfoState &KIS) {
597     return (*this ^= KIS);
598   }
599 
600   ///}
601 };
602 
603 /// Used to map the values physically (in the IR) stored in an offload
604 /// array, to a vector in memory.
605 struct OffloadArray {
606   /// Physical array (in the IR).
607   AllocaInst *Array = nullptr;
608   /// Mapped values.
609   SmallVector<Value *, 8> StoredValues;
610   /// Last stores made in the offload array.
611   SmallVector<StoreInst *, 8> LastAccesses;
612 
613   OffloadArray() = default;
614 
615   /// Initializes the OffloadArray with the values stored in \p Array before
616   /// instruction \p Before is reached. Returns false if the initialization
617   /// fails.
618   /// This MUST be used immediately after the construction of the object.
619   bool initialize(AllocaInst &Array, Instruction &Before) {
620     if (!Array.getAllocatedType()->isArrayTy())
621       return false;
622 
623     if (!getValues(Array, Before))
624       return false;
625 
626     this->Array = &Array;
627     return true;
628   }
629 
630   static const unsigned DeviceIDArgNum = 1;
631   static const unsigned BasePtrsArgNum = 3;
632   static const unsigned PtrsArgNum = 4;
633   static const unsigned SizesArgNum = 5;
634 
635 private:
636   /// Traverses the BasicBlock where \p Array is, collecting the stores made to
637   /// \p Array, leaving StoredValues with the values stored before the
638   /// instruction \p Before is reached.
639   bool getValues(AllocaInst &Array, Instruction &Before) {
640     // Initialize container.
641     const uint64_t NumValues = Array.getAllocatedType()->getArrayNumElements();
642     StoredValues.assign(NumValues, nullptr);
643     LastAccesses.assign(NumValues, nullptr);
644 
645     // TODO: This assumes the instruction \p Before is in the same
646     //  BasicBlock as Array. Make it general, for any control flow graph.
647     BasicBlock *BB = Array.getParent();
648     if (BB != Before.getParent())
649       return false;
650 
651     const DataLayout &DL = Array.getModule()->getDataLayout();
652     const unsigned int PointerSize = DL.getPointerSize();
653 
654     for (Instruction &I : *BB) {
655       if (&I == &Before)
656         break;
657 
658       if (!isa<StoreInst>(&I))
659         continue;
660 
661       auto *S = cast<StoreInst>(&I);
662       int64_t Offset = -1;
663       auto *Dst =
664           GetPointerBaseWithConstantOffset(S->getPointerOperand(), Offset, DL);
665       if (Dst == &Array) {
666         int64_t Idx = Offset / PointerSize;
667         StoredValues[Idx] = getUnderlyingObject(S->getValueOperand());
668         LastAccesses[Idx] = S;
669       }
670     }
671 
672     return isFilled();
673   }
674 
675   /// Returns true if all values in StoredValues and
676   /// LastAccesses are not nullptrs.
677   bool isFilled() {
678     const unsigned NumValues = StoredValues.size();
679     for (unsigned I = 0; I < NumValues; ++I) {
680       if (!StoredValues[I] || !LastAccesses[I])
681         return false;
682     }
683 
684     return true;
685   }
686 };
687 
688 struct OpenMPOpt {
689 
690   using OptimizationRemarkGetter =
691       function_ref<OptimizationRemarkEmitter &(Function *)>;
692 
693   OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater,
694             OptimizationRemarkGetter OREGetter,
695             OMPInformationCache &OMPInfoCache, Attributor &A)
696       : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater),
697         OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {}
698 
699   /// Check if any remarks are enabled for openmp-opt
700   bool remarksEnabled() {
701     auto &Ctx = M.getContext();
702     return Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(DEBUG_TYPE);
703   }
704 
705   /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
706   bool run(bool IsModulePass) {
707     if (SCC.empty())
708       return false;
709 
710     bool Changed = false;
711 
712     LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
713                       << " functions in a slice with "
714                       << OMPInfoCache.ModuleSlice.size() << " functions\n");
715 
716     if (IsModulePass) {
717       Changed |= runAttributor(IsModulePass);
718 
719       // Recollect uses, in case Attributor deleted any.
720       OMPInfoCache.recollectUses();
721 
722       if (remarksEnabled())
723         analysisGlobalization();
724     } else {
725       if (PrintICVValues)
726         printICVs();
727       if (PrintOpenMPKernels)
728         printKernels();
729 
730       Changed |= runAttributor(IsModulePass);
731 
732       // Recollect uses, in case Attributor deleted any.
733       OMPInfoCache.recollectUses();
734 
735       Changed |= deleteParallelRegions();
736       Changed |= rewriteDeviceCodeStateMachine();
737 
738       if (HideMemoryTransferLatency)
739         Changed |= hideMemTransfersLatency();
740       Changed |= deduplicateRuntimeCalls();
741       if (EnableParallelRegionMerging) {
742         if (mergeParallelRegions()) {
743           deduplicateRuntimeCalls();
744           Changed = true;
745         }
746       }
747     }
748 
749     return Changed;
750   }
751 
752   /// Print initial ICV values for testing.
753   /// FIXME: This should be done from the Attributor once it is added.
754   void printICVs() const {
755     InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel,
756                                  ICV_proc_bind};
757 
758     for (Function *F : OMPInfoCache.ModuleSlice) {
759       for (auto ICV : ICVs) {
760         auto ICVInfo = OMPInfoCache.ICVs[ICV];
761         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
762           return ORA << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name)
763                      << " Value: "
764                      << (ICVInfo.InitValue
765                              ? toString(ICVInfo.InitValue->getValue(), 10, true)
766                              : "IMPLEMENTATION_DEFINED");
767         };
768 
769         emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPICVTracker", Remark);
770       }
771     }
772   }
773 
774   /// Print OpenMP GPU kernels for testing.
775   void printKernels() const {
776     for (Function *F : SCC) {
777       if (!OMPInfoCache.Kernels.count(F))
778         continue;
779 
780       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
781         return ORA << "OpenMP GPU kernel "
782                    << ore::NV("OpenMPGPUKernel", F->getName()) << "\n";
783       };
784 
785       emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPGPU", Remark);
786     }
787   }
788 
789   /// Return the call if \p U is a callee use in a regular call. If \p RFI is
790   /// given it has to be the callee or a nullptr is returned.
791   static CallInst *getCallIfRegularCall(
792       Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
793     CallInst *CI = dyn_cast<CallInst>(U.getUser());
794     if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
795         (!RFI ||
796          (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
797       return CI;
798     return nullptr;
799   }
800 
801   /// Return the call if \p V is a regular call. If \p RFI is given it has to be
802   /// the callee or a nullptr is returned.
803   static CallInst *getCallIfRegularCall(
804       Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
805     CallInst *CI = dyn_cast<CallInst>(&V);
806     if (CI && !CI->hasOperandBundles() &&
807         (!RFI ||
808          (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
809       return CI;
810     return nullptr;
811   }
812 
813 private:
814   /// Merge parallel regions when it is safe.
815   bool mergeParallelRegions() {
816     const unsigned CallbackCalleeOperand = 2;
817     const unsigned CallbackFirstArgOperand = 3;
818     using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
819 
820     // Check if there are any __kmpc_fork_call calls to merge.
821     OMPInformationCache::RuntimeFunctionInfo &RFI =
822         OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
823 
824     if (!RFI.Declaration)
825       return false;
826 
827     // Unmergable calls that prevent merging a parallel region.
828     OMPInformationCache::RuntimeFunctionInfo UnmergableCallsInfo[] = {
829         OMPInfoCache.RFIs[OMPRTL___kmpc_push_proc_bind],
830         OMPInfoCache.RFIs[OMPRTL___kmpc_push_num_threads],
831     };
832 
833     bool Changed = false;
834     LoopInfo *LI = nullptr;
835     DominatorTree *DT = nullptr;
836 
837     SmallDenseMap<BasicBlock *, SmallPtrSet<Instruction *, 4>> BB2PRMap;
838 
839     BasicBlock *StartBB = nullptr, *EndBB = nullptr;
840     auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
841                          BasicBlock &ContinuationIP) {
842       BasicBlock *CGStartBB = CodeGenIP.getBlock();
843       BasicBlock *CGEndBB =
844           SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
845       assert(StartBB != nullptr && "StartBB should not be null");
846       CGStartBB->getTerminator()->setSuccessor(0, StartBB);
847       assert(EndBB != nullptr && "EndBB should not be null");
848       EndBB->getTerminator()->setSuccessor(0, CGEndBB);
849     };
850 
851     auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &,
852                       Value &Inner, Value *&ReplacementValue) -> InsertPointTy {
853       ReplacementValue = &Inner;
854       return CodeGenIP;
855     };
856 
857     auto FiniCB = [&](InsertPointTy CodeGenIP) {};
858 
859     /// Create a sequential execution region within a merged parallel region,
860     /// encapsulated in a master construct with a barrier for synchronization.
861     auto CreateSequentialRegion = [&](Function *OuterFn,
862                                       BasicBlock *OuterPredBB,
863                                       Instruction *SeqStartI,
864                                       Instruction *SeqEndI) {
865       // Isolate the instructions of the sequential region to a separate
866       // block.
867       BasicBlock *ParentBB = SeqStartI->getParent();
868       BasicBlock *SeqEndBB =
869           SplitBlock(ParentBB, SeqEndI->getNextNode(), DT, LI);
870       BasicBlock *SeqAfterBB =
871           SplitBlock(SeqEndBB, &*SeqEndBB->getFirstInsertionPt(), DT, LI);
872       BasicBlock *SeqStartBB =
873           SplitBlock(ParentBB, SeqStartI, DT, LI, nullptr, "seq.par.merged");
874 
875       assert(ParentBB->getUniqueSuccessor() == SeqStartBB &&
876              "Expected a different CFG");
877       const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc();
878       ParentBB->getTerminator()->eraseFromParent();
879 
880       auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
881                            BasicBlock &ContinuationIP) {
882         BasicBlock *CGStartBB = CodeGenIP.getBlock();
883         BasicBlock *CGEndBB =
884             SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
885         assert(SeqStartBB != nullptr && "SeqStartBB should not be null");
886         CGStartBB->getTerminator()->setSuccessor(0, SeqStartBB);
887         assert(SeqEndBB != nullptr && "SeqEndBB should not be null");
888         SeqEndBB->getTerminator()->setSuccessor(0, CGEndBB);
889       };
890       auto FiniCB = [&](InsertPointTy CodeGenIP) {};
891 
892       // Find outputs from the sequential region to outside users and
893       // broadcast their values to them.
894       for (Instruction &I : *SeqStartBB) {
895         SmallPtrSet<Instruction *, 4> OutsideUsers;
896         for (User *Usr : I.users()) {
897           Instruction &UsrI = *cast<Instruction>(Usr);
898           // Ignore outputs to LT intrinsics, code extraction for the merged
899           // parallel region will fix them.
900           if (UsrI.isLifetimeStartOrEnd())
901             continue;
902 
903           if (UsrI.getParent() != SeqStartBB)
904             OutsideUsers.insert(&UsrI);
905         }
906 
907         if (OutsideUsers.empty())
908           continue;
909 
910         // Emit an alloca in the outer region to store the broadcasted
911         // value.
912         const DataLayout &DL = M.getDataLayout();
913         AllocaInst *AllocaI = new AllocaInst(
914             I.getType(), DL.getAllocaAddrSpace(), nullptr,
915             I.getName() + ".seq.output.alloc", &OuterFn->front().front());
916 
917         // Emit a store instruction in the sequential BB to update the
918         // value.
919         new StoreInst(&I, AllocaI, SeqStartBB->getTerminator());
920 
921         // Emit a load instruction and replace the use of the output value
922         // with it.
923         for (Instruction *UsrI : OutsideUsers) {
924           LoadInst *LoadI = new LoadInst(
925               I.getType(), AllocaI, I.getName() + ".seq.output.load", UsrI);
926           UsrI->replaceUsesOfWith(&I, LoadI);
927         }
928       }
929 
930       OpenMPIRBuilder::LocationDescription Loc(
931           InsertPointTy(ParentBB, ParentBB->end()), DL);
932       InsertPointTy SeqAfterIP =
933           OMPInfoCache.OMPBuilder.createMaster(Loc, BodyGenCB, FiniCB);
934 
935       OMPInfoCache.OMPBuilder.createBarrier(SeqAfterIP, OMPD_parallel);
936 
937       BranchInst::Create(SeqAfterBB, SeqAfterIP.getBlock());
938 
939       LLVM_DEBUG(dbgs() << TAG << "After sequential inlining " << *OuterFn
940                         << "\n");
941     };
942 
943     // Helper to merge the __kmpc_fork_call calls in MergableCIs. They are all
944     // contained in BB and only separated by instructions that can be
945     // redundantly executed in parallel. The block BB is split before the first
946     // call (in MergableCIs) and after the last so the entire region we merge
947     // into a single parallel region is contained in a single basic block
948     // without any other instructions. We use the OpenMPIRBuilder to outline
949     // that block and call the resulting function via __kmpc_fork_call.
950     auto Merge = [&](SmallVectorImpl<CallInst *> &MergableCIs, BasicBlock *BB) {
951       // TODO: Change the interface to allow single CIs expanded, e.g, to
952       // include an outer loop.
953       assert(MergableCIs.size() > 1 && "Assumed multiple mergable CIs");
954 
955       auto Remark = [&](OptimizationRemark OR) {
956         OR << "Parallel region merged with parallel region"
957            << (MergableCIs.size() > 2 ? "s" : "") << " at ";
958         for (auto *CI : llvm::drop_begin(MergableCIs)) {
959           OR << ore::NV("OpenMPParallelMerge", CI->getDebugLoc());
960           if (CI != MergableCIs.back())
961             OR << ", ";
962         }
963         return OR << ".";
964       };
965 
966       emitRemark<OptimizationRemark>(MergableCIs.front(), "OMP150", Remark);
967 
968       Function *OriginalFn = BB->getParent();
969       LLVM_DEBUG(dbgs() << TAG << "Merge " << MergableCIs.size()
970                         << " parallel regions in " << OriginalFn->getName()
971                         << "\n");
972 
973       // Isolate the calls to merge in a separate block.
974       EndBB = SplitBlock(BB, MergableCIs.back()->getNextNode(), DT, LI);
975       BasicBlock *AfterBB =
976           SplitBlock(EndBB, &*EndBB->getFirstInsertionPt(), DT, LI);
977       StartBB = SplitBlock(BB, MergableCIs.front(), DT, LI, nullptr,
978                            "omp.par.merged");
979 
980       assert(BB->getUniqueSuccessor() == StartBB && "Expected a different CFG");
981       const DebugLoc DL = BB->getTerminator()->getDebugLoc();
982       BB->getTerminator()->eraseFromParent();
983 
984       // Create sequential regions for sequential instructions that are
985       // in-between mergable parallel regions.
986       for (auto *It = MergableCIs.begin(), *End = MergableCIs.end() - 1;
987            It != End; ++It) {
988         Instruction *ForkCI = *It;
989         Instruction *NextForkCI = *(It + 1);
990 
991         // Continue if there are not in-between instructions.
992         if (ForkCI->getNextNode() == NextForkCI)
993           continue;
994 
995         CreateSequentialRegion(OriginalFn, BB, ForkCI->getNextNode(),
996                                NextForkCI->getPrevNode());
997       }
998 
999       OpenMPIRBuilder::LocationDescription Loc(InsertPointTy(BB, BB->end()),
1000                                                DL);
1001       IRBuilder<>::InsertPoint AllocaIP(
1002           &OriginalFn->getEntryBlock(),
1003           OriginalFn->getEntryBlock().getFirstInsertionPt());
1004       // Create the merged parallel region with default proc binding, to
1005       // avoid overriding binding settings, and without explicit cancellation.
1006       InsertPointTy AfterIP = OMPInfoCache.OMPBuilder.createParallel(
1007           Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB, nullptr, nullptr,
1008           OMP_PROC_BIND_default, /* IsCancellable */ false);
1009       BranchInst::Create(AfterBB, AfterIP.getBlock());
1010 
1011       // Perform the actual outlining.
1012       OMPInfoCache.OMPBuilder.finalize(OriginalFn,
1013                                        /* AllowExtractorSinking */ true);
1014 
1015       Function *OutlinedFn = MergableCIs.front()->getCaller();
1016 
1017       // Replace the __kmpc_fork_call calls with direct calls to the outlined
1018       // callbacks.
1019       SmallVector<Value *, 8> Args;
1020       for (auto *CI : MergableCIs) {
1021         Value *Callee =
1022             CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts();
1023         FunctionType *FT =
1024             cast<FunctionType>(Callee->getType()->getPointerElementType());
1025         Args.clear();
1026         Args.push_back(OutlinedFn->getArg(0));
1027         Args.push_back(OutlinedFn->getArg(1));
1028         for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands();
1029              U < E; ++U)
1030           Args.push_back(CI->getArgOperand(U));
1031 
1032         CallInst *NewCI = CallInst::Create(FT, Callee, Args, "", CI);
1033         if (CI->getDebugLoc())
1034           NewCI->setDebugLoc(CI->getDebugLoc());
1035 
1036         // Forward parameter attributes from the callback to the callee.
1037         for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands();
1038              U < E; ++U)
1039           for (const Attribute &A : CI->getAttributes().getParamAttributes(U))
1040             NewCI->addParamAttr(
1041                 U - (CallbackFirstArgOperand - CallbackCalleeOperand), A);
1042 
1043         // Emit an explicit barrier to replace the implicit fork-join barrier.
1044         if (CI != MergableCIs.back()) {
1045           // TODO: Remove barrier if the merged parallel region includes the
1046           // 'nowait' clause.
1047           OMPInfoCache.OMPBuilder.createBarrier(
1048               InsertPointTy(NewCI->getParent(),
1049                             NewCI->getNextNode()->getIterator()),
1050               OMPD_parallel);
1051         }
1052 
1053         CI->eraseFromParent();
1054       }
1055 
1056       assert(OutlinedFn != OriginalFn && "Outlining failed");
1057       CGUpdater.registerOutlinedFunction(*OriginalFn, *OutlinedFn);
1058       CGUpdater.reanalyzeFunction(*OriginalFn);
1059 
1060       NumOpenMPParallelRegionsMerged += MergableCIs.size();
1061 
1062       return true;
1063     };
1064 
1065     // Helper function that identifes sequences of
1066     // __kmpc_fork_call uses in a basic block.
1067     auto DetectPRsCB = [&](Use &U, Function &F) {
1068       CallInst *CI = getCallIfRegularCall(U, &RFI);
1069       BB2PRMap[CI->getParent()].insert(CI);
1070 
1071       return false;
1072     };
1073 
1074     BB2PRMap.clear();
1075     RFI.foreachUse(SCC, DetectPRsCB);
1076     SmallVector<SmallVector<CallInst *, 4>, 4> MergableCIsVector;
1077     // Find mergable parallel regions within a basic block that are
1078     // safe to merge, that is any in-between instructions can safely
1079     // execute in parallel after merging.
1080     // TODO: support merging across basic-blocks.
1081     for (auto &It : BB2PRMap) {
1082       auto &CIs = It.getSecond();
1083       if (CIs.size() < 2)
1084         continue;
1085 
1086       BasicBlock *BB = It.getFirst();
1087       SmallVector<CallInst *, 4> MergableCIs;
1088 
1089       /// Returns true if the instruction is mergable, false otherwise.
1090       /// A terminator instruction is unmergable by definition since merging
1091       /// works within a BB. Instructions before the mergable region are
1092       /// mergable if they are not calls to OpenMP runtime functions that may
1093       /// set different execution parameters for subsequent parallel regions.
1094       /// Instructions in-between parallel regions are mergable if they are not
1095       /// calls to any non-intrinsic function since that may call a non-mergable
1096       /// OpenMP runtime function.
1097       auto IsMergable = [&](Instruction &I, bool IsBeforeMergableRegion) {
1098         // We do not merge across BBs, hence return false (unmergable) if the
1099         // instruction is a terminator.
1100         if (I.isTerminator())
1101           return false;
1102 
1103         if (!isa<CallInst>(&I))
1104           return true;
1105 
1106         CallInst *CI = cast<CallInst>(&I);
1107         if (IsBeforeMergableRegion) {
1108           Function *CalledFunction = CI->getCalledFunction();
1109           if (!CalledFunction)
1110             return false;
1111           // Return false (unmergable) if the call before the parallel
1112           // region calls an explicit affinity (proc_bind) or number of
1113           // threads (num_threads) compiler-generated function. Those settings
1114           // may be incompatible with following parallel regions.
1115           // TODO: ICV tracking to detect compatibility.
1116           for (const auto &RFI : UnmergableCallsInfo) {
1117             if (CalledFunction == RFI.Declaration)
1118               return false;
1119           }
1120         } else {
1121           // Return false (unmergable) if there is a call instruction
1122           // in-between parallel regions when it is not an intrinsic. It
1123           // may call an unmergable OpenMP runtime function in its callpath.
1124           // TODO: Keep track of possible OpenMP calls in the callpath.
1125           if (!isa<IntrinsicInst>(CI))
1126             return false;
1127         }
1128 
1129         return true;
1130       };
1131       // Find maximal number of parallel region CIs that are safe to merge.
1132       for (auto It = BB->begin(), End = BB->end(); It != End;) {
1133         Instruction &I = *It;
1134         ++It;
1135 
1136         if (CIs.count(&I)) {
1137           MergableCIs.push_back(cast<CallInst>(&I));
1138           continue;
1139         }
1140 
1141         // Continue expanding if the instruction is mergable.
1142         if (IsMergable(I, MergableCIs.empty()))
1143           continue;
1144 
1145         // Forward the instruction iterator to skip the next parallel region
1146         // since there is an unmergable instruction which can affect it.
1147         for (; It != End; ++It) {
1148           Instruction &SkipI = *It;
1149           if (CIs.count(&SkipI)) {
1150             LLVM_DEBUG(dbgs() << TAG << "Skip parallel region " << SkipI
1151                               << " due to " << I << "\n");
1152             ++It;
1153             break;
1154           }
1155         }
1156 
1157         // Store mergable regions found.
1158         if (MergableCIs.size() > 1) {
1159           MergableCIsVector.push_back(MergableCIs);
1160           LLVM_DEBUG(dbgs() << TAG << "Found " << MergableCIs.size()
1161                             << " parallel regions in block " << BB->getName()
1162                             << " of function " << BB->getParent()->getName()
1163                             << "\n";);
1164         }
1165 
1166         MergableCIs.clear();
1167       }
1168 
1169       if (!MergableCIsVector.empty()) {
1170         Changed = true;
1171 
1172         for (auto &MergableCIs : MergableCIsVector)
1173           Merge(MergableCIs, BB);
1174         MergableCIsVector.clear();
1175       }
1176     }
1177 
1178     if (Changed) {
1179       /// Re-collect use for fork calls, emitted barrier calls, and
1180       /// any emitted master/end_master calls.
1181       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_fork_call);
1182       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_barrier);
1183       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_master);
1184       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_end_master);
1185     }
1186 
1187     return Changed;
1188   }
1189 
1190   /// Try to delete parallel regions if possible.
1191   bool deleteParallelRegions() {
1192     const unsigned CallbackCalleeOperand = 2;
1193 
1194     OMPInformationCache::RuntimeFunctionInfo &RFI =
1195         OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
1196 
1197     if (!RFI.Declaration)
1198       return false;
1199 
1200     bool Changed = false;
1201     auto DeleteCallCB = [&](Use &U, Function &) {
1202       CallInst *CI = getCallIfRegularCall(U);
1203       if (!CI)
1204         return false;
1205       auto *Fn = dyn_cast<Function>(
1206           CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
1207       if (!Fn)
1208         return false;
1209       if (!Fn->onlyReadsMemory())
1210         return false;
1211       if (!Fn->hasFnAttribute(Attribute::WillReturn))
1212         return false;
1213 
1214       LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
1215                         << CI->getCaller()->getName() << "\n");
1216 
1217       auto Remark = [&](OptimizationRemark OR) {
1218         return OR << "Removing parallel region with no side-effects.";
1219       };
1220       emitRemark<OptimizationRemark>(CI, "OMP160", Remark);
1221 
1222       CGUpdater.removeCallSite(*CI);
1223       CI->eraseFromParent();
1224       Changed = true;
1225       ++NumOpenMPParallelRegionsDeleted;
1226       return true;
1227     };
1228 
1229     RFI.foreachUse(SCC, DeleteCallCB);
1230 
1231     return Changed;
1232   }
1233 
1234   /// Try to eliminate runtime calls by reusing existing ones.
1235   bool deduplicateRuntimeCalls() {
1236     bool Changed = false;
1237 
1238     RuntimeFunction DeduplicableRuntimeCallIDs[] = {
1239         OMPRTL_omp_get_num_threads,
1240         OMPRTL_omp_in_parallel,
1241         OMPRTL_omp_get_cancellation,
1242         OMPRTL_omp_get_thread_limit,
1243         OMPRTL_omp_get_supported_active_levels,
1244         OMPRTL_omp_get_level,
1245         OMPRTL_omp_get_ancestor_thread_num,
1246         OMPRTL_omp_get_team_size,
1247         OMPRTL_omp_get_active_level,
1248         OMPRTL_omp_in_final,
1249         OMPRTL_omp_get_proc_bind,
1250         OMPRTL_omp_get_num_places,
1251         OMPRTL_omp_get_num_procs,
1252         OMPRTL_omp_get_place_num,
1253         OMPRTL_omp_get_partition_num_places,
1254         OMPRTL_omp_get_partition_place_nums};
1255 
1256     // Global-tid is handled separately.
1257     SmallSetVector<Value *, 16> GTIdArgs;
1258     collectGlobalThreadIdArguments(GTIdArgs);
1259     LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
1260                       << " global thread ID arguments\n");
1261 
1262     for (Function *F : SCC) {
1263       for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
1264         Changed |= deduplicateRuntimeCalls(
1265             *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]);
1266 
1267       // __kmpc_global_thread_num is special as we can replace it with an
1268       // argument in enough cases to make it worth trying.
1269       Value *GTIdArg = nullptr;
1270       for (Argument &Arg : F->args())
1271         if (GTIdArgs.count(&Arg)) {
1272           GTIdArg = &Arg;
1273           break;
1274         }
1275       Changed |= deduplicateRuntimeCalls(
1276           *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
1277     }
1278 
1279     return Changed;
1280   }
1281 
1282   /// Tries to hide the latency of runtime calls that involve host to
1283   /// device memory transfers by splitting them into their "issue" and "wait"
1284   /// versions. The "issue" is moved upwards as much as possible. The "wait" is
1285   /// moved downards as much as possible. The "issue" issues the memory transfer
1286   /// asynchronously, returning a handle. The "wait" waits in the returned
1287   /// handle for the memory transfer to finish.
1288   bool hideMemTransfersLatency() {
1289     auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper];
1290     bool Changed = false;
1291     auto SplitMemTransfers = [&](Use &U, Function &Decl) {
1292       auto *RTCall = getCallIfRegularCall(U, &RFI);
1293       if (!RTCall)
1294         return false;
1295 
1296       OffloadArray OffloadArrays[3];
1297       if (!getValuesInOffloadArrays(*RTCall, OffloadArrays))
1298         return false;
1299 
1300       LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays));
1301 
1302       // TODO: Check if can be moved upwards.
1303       bool WasSplit = false;
1304       Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall);
1305       if (WaitMovementPoint)
1306         WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint);
1307 
1308       Changed |= WasSplit;
1309       return WasSplit;
1310     };
1311     RFI.foreachUse(SCC, SplitMemTransfers);
1312 
1313     return Changed;
1314   }
1315 
1316   void analysisGlobalization() {
1317     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
1318 
1319     auto CheckGlobalization = [&](Use &U, Function &Decl) {
1320       if (CallInst *CI = getCallIfRegularCall(U, &RFI)) {
1321         auto Remark = [&](OptimizationRemarkMissed ORM) {
1322           return ORM
1323                  << "Found thread data sharing on the GPU. "
1324                  << "Expect degraded performance due to data globalization.";
1325         };
1326         emitRemark<OptimizationRemarkMissed>(CI, "OMP112", Remark);
1327       }
1328 
1329       return false;
1330     };
1331 
1332     RFI.foreachUse(SCC, CheckGlobalization);
1333   }
1334 
1335   /// Maps the values stored in the offload arrays passed as arguments to
1336   /// \p RuntimeCall into the offload arrays in \p OAs.
1337   bool getValuesInOffloadArrays(CallInst &RuntimeCall,
1338                                 MutableArrayRef<OffloadArray> OAs) {
1339     assert(OAs.size() == 3 && "Need space for three offload arrays!");
1340 
1341     // A runtime call that involves memory offloading looks something like:
1342     // call void @__tgt_target_data_begin_mapper(arg0, arg1,
1343     //   i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes,
1344     // ...)
1345     // So, the idea is to access the allocas that allocate space for these
1346     // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes.
1347     // Therefore:
1348     // i8** %offload_baseptrs.
1349     Value *BasePtrsArg =
1350         RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum);
1351     // i8** %offload_ptrs.
1352     Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum);
1353     // i8** %offload_sizes.
1354     Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum);
1355 
1356     // Get values stored in **offload_baseptrs.
1357     auto *V = getUnderlyingObject(BasePtrsArg);
1358     if (!isa<AllocaInst>(V))
1359       return false;
1360     auto *BasePtrsArray = cast<AllocaInst>(V);
1361     if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall))
1362       return false;
1363 
1364     // Get values stored in **offload_baseptrs.
1365     V = getUnderlyingObject(PtrsArg);
1366     if (!isa<AllocaInst>(V))
1367       return false;
1368     auto *PtrsArray = cast<AllocaInst>(V);
1369     if (!OAs[1].initialize(*PtrsArray, RuntimeCall))
1370       return false;
1371 
1372     // Get values stored in **offload_sizes.
1373     V = getUnderlyingObject(SizesArg);
1374     // If it's a [constant] global array don't analyze it.
1375     if (isa<GlobalValue>(V))
1376       return isa<Constant>(V);
1377     if (!isa<AllocaInst>(V))
1378       return false;
1379 
1380     auto *SizesArray = cast<AllocaInst>(V);
1381     if (!OAs[2].initialize(*SizesArray, RuntimeCall))
1382       return false;
1383 
1384     return true;
1385   }
1386 
1387   /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG.
1388   /// For now this is a way to test that the function getValuesInOffloadArrays
1389   /// is working properly.
1390   /// TODO: Move this to a unittest when unittests are available for OpenMPOpt.
1391   void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) {
1392     assert(OAs.size() == 3 && "There are three offload arrays to debug!");
1393 
1394     LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n");
1395     std::string ValuesStr;
1396     raw_string_ostream Printer(ValuesStr);
1397     std::string Separator = " --- ";
1398 
1399     for (auto *BP : OAs[0].StoredValues) {
1400       BP->print(Printer);
1401       Printer << Separator;
1402     }
1403     LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n");
1404     ValuesStr.clear();
1405 
1406     for (auto *P : OAs[1].StoredValues) {
1407       P->print(Printer);
1408       Printer << Separator;
1409     }
1410     LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n");
1411     ValuesStr.clear();
1412 
1413     for (auto *S : OAs[2].StoredValues) {
1414       S->print(Printer);
1415       Printer << Separator;
1416     }
1417     LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n");
1418   }
1419 
1420   /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be
1421   /// moved. Returns nullptr if the movement is not possible, or not worth it.
1422   Instruction *canBeMovedDownwards(CallInst &RuntimeCall) {
1423     // FIXME: This traverses only the BasicBlock where RuntimeCall is.
1424     //  Make it traverse the CFG.
1425 
1426     Instruction *CurrentI = &RuntimeCall;
1427     bool IsWorthIt = false;
1428     while ((CurrentI = CurrentI->getNextNode())) {
1429 
1430       // TODO: Once we detect the regions to be offloaded we should use the
1431       //  alias analysis manager to check if CurrentI may modify one of
1432       //  the offloaded regions.
1433       if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) {
1434         if (IsWorthIt)
1435           return CurrentI;
1436 
1437         return nullptr;
1438       }
1439 
1440       // FIXME: For now if we move it over anything without side effect
1441       //  is worth it.
1442       IsWorthIt = true;
1443     }
1444 
1445     // Return end of BasicBlock.
1446     return RuntimeCall.getParent()->getTerminator();
1447   }
1448 
1449   /// Splits \p RuntimeCall into its "issue" and "wait" counterparts.
1450   bool splitTargetDataBeginRTC(CallInst &RuntimeCall,
1451                                Instruction &WaitMovementPoint) {
1452     // Create stack allocated handle (__tgt_async_info) at the beginning of the
1453     // function. Used for storing information of the async transfer, allowing to
1454     // wait on it later.
1455     auto &IRBuilder = OMPInfoCache.OMPBuilder;
1456     auto *F = RuntimeCall.getCaller();
1457     Instruction *FirstInst = &(F->getEntryBlock().front());
1458     AllocaInst *Handle = new AllocaInst(
1459         IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst);
1460 
1461     // Add "issue" runtime call declaration:
1462     // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32,
1463     //   i8**, i8**, i64*, i64*)
1464     FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction(
1465         M, OMPRTL___tgt_target_data_begin_mapper_issue);
1466 
1467     // Change RuntimeCall call site for its asynchronous version.
1468     SmallVector<Value *, 16> Args;
1469     for (auto &Arg : RuntimeCall.args())
1470       Args.push_back(Arg.get());
1471     Args.push_back(Handle);
1472 
1473     CallInst *IssueCallsite =
1474         CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall);
1475     RuntimeCall.eraseFromParent();
1476 
1477     // Add "wait" runtime call declaration:
1478     // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info)
1479     FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction(
1480         M, OMPRTL___tgt_target_data_begin_mapper_wait);
1481 
1482     Value *WaitParams[2] = {
1483         IssueCallsite->getArgOperand(
1484             OffloadArray::DeviceIDArgNum), // device_id.
1485         Handle                             // handle to wait on.
1486     };
1487     CallInst::Create(WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint);
1488 
1489     return true;
1490   }
1491 
1492   static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
1493                                     bool GlobalOnly, bool &SingleChoice) {
1494     if (CurrentIdent == NextIdent)
1495       return CurrentIdent;
1496 
1497     // TODO: Figure out how to actually combine multiple debug locations. For
1498     //       now we just keep an existing one if there is a single choice.
1499     if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
1500       SingleChoice = !CurrentIdent;
1501       return NextIdent;
1502     }
1503     return nullptr;
1504   }
1505 
1506   /// Return an `struct ident_t*` value that represents the ones used in the
1507   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
1508   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
1509   /// return value we create one from scratch. We also do not yet combine
1510   /// information, e.g., the source locations, see combinedIdentStruct.
1511   Value *
1512   getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI,
1513                                  Function &F, bool GlobalOnly) {
1514     bool SingleChoice = true;
1515     Value *Ident = nullptr;
1516     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
1517       CallInst *CI = getCallIfRegularCall(U, &RFI);
1518       if (!CI || &F != &Caller)
1519         return false;
1520       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
1521                                   /* GlobalOnly */ true, SingleChoice);
1522       return false;
1523     };
1524     RFI.foreachUse(SCC, CombineIdentStruct);
1525 
1526     if (!Ident || !SingleChoice) {
1527       // The IRBuilder uses the insertion block to get to the module, this is
1528       // unfortunate but we work around it for now.
1529       if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock())
1530         OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
1531             &F.getEntryBlock(), F.getEntryBlock().begin()));
1532       // Create a fallback location if non was found.
1533       // TODO: Use the debug locations of the calls instead.
1534       Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr();
1535       Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc);
1536     }
1537     return Ident;
1538   }
1539 
1540   /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or
1541   /// \p ReplVal if given.
1542   bool deduplicateRuntimeCalls(Function &F,
1543                                OMPInformationCache::RuntimeFunctionInfo &RFI,
1544                                Value *ReplVal = nullptr) {
1545     auto *UV = RFI.getUseVector(F);
1546     if (!UV || UV->size() + (ReplVal != nullptr) < 2)
1547       return false;
1548 
1549     LLVM_DEBUG(
1550         dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name
1551                << (ReplVal ? " with an existing value\n" : "\n") << "\n");
1552 
1553     assert((!ReplVal || (isa<Argument>(ReplVal) &&
1554                          cast<Argument>(ReplVal)->getParent() == &F)) &&
1555            "Unexpected replacement value!");
1556 
1557     // TODO: Use dominance to find a good position instead.
1558     auto CanBeMoved = [this](CallBase &CB) {
1559       unsigned NumArgs = CB.getNumArgOperands();
1560       if (NumArgs == 0)
1561         return true;
1562       if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr)
1563         return false;
1564       for (unsigned u = 1; u < NumArgs; ++u)
1565         if (isa<Instruction>(CB.getArgOperand(u)))
1566           return false;
1567       return true;
1568     };
1569 
1570     if (!ReplVal) {
1571       for (Use *U : *UV)
1572         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
1573           if (!CanBeMoved(*CI))
1574             continue;
1575 
1576           CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
1577           ReplVal = CI;
1578           break;
1579         }
1580       if (!ReplVal)
1581         return false;
1582     }
1583 
1584     // If we use a call as a replacement value we need to make sure the ident is
1585     // valid at the new location. For now we just pick a global one, either
1586     // existing and used by one of the calls, or created from scratch.
1587     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
1588       if (CI->getNumArgOperands() > 0 &&
1589           CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) {
1590         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
1591                                                       /* GlobalOnly */ true);
1592         CI->setArgOperand(0, Ident);
1593       }
1594     }
1595 
1596     bool Changed = false;
1597     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
1598       CallInst *CI = getCallIfRegularCall(U, &RFI);
1599       if (!CI || CI == ReplVal || &F != &Caller)
1600         return false;
1601       assert(CI->getCaller() == &F && "Unexpected call!");
1602 
1603       auto Remark = [&](OptimizationRemark OR) {
1604         return OR << "OpenMP runtime call "
1605                   << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated.";
1606       };
1607       if (CI->getDebugLoc())
1608         emitRemark<OptimizationRemark>(CI, "OMP170", Remark);
1609       else
1610         emitRemark<OptimizationRemark>(&F, "OMP170", Remark);
1611 
1612       CGUpdater.removeCallSite(*CI);
1613       CI->replaceAllUsesWith(ReplVal);
1614       CI->eraseFromParent();
1615       ++NumOpenMPRuntimeCallsDeduplicated;
1616       Changed = true;
1617       return true;
1618     };
1619     RFI.foreachUse(SCC, ReplaceAndDeleteCB);
1620 
1621     return Changed;
1622   }
1623 
1624   /// Collect arguments that represent the global thread id in \p GTIdArgs.
1625   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
1626     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
1627     //       initialization. We could define an AbstractAttribute instead and
1628     //       run the Attributor here once it can be run as an SCC pass.
1629 
1630     // Helper to check the argument \p ArgNo at all call sites of \p F for
1631     // a GTId.
1632     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
1633       if (!F.hasLocalLinkage())
1634         return false;
1635       for (Use &U : F.uses()) {
1636         if (CallInst *CI = getCallIfRegularCall(U)) {
1637           Value *ArgOp = CI->getArgOperand(ArgNo);
1638           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
1639               getCallIfRegularCall(
1640                   *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]))
1641             continue;
1642         }
1643         return false;
1644       }
1645       return true;
1646     };
1647 
1648     // Helper to identify uses of a GTId as GTId arguments.
1649     auto AddUserArgs = [&](Value &GTId) {
1650       for (Use &U : GTId.uses())
1651         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
1652           if (CI->isArgOperand(&U))
1653             if (Function *Callee = CI->getCalledFunction())
1654               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
1655                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
1656     };
1657 
1658     // The argument users of __kmpc_global_thread_num calls are GTIds.
1659     OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI =
1660         OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num];
1661 
1662     GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) {
1663       if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
1664         AddUserArgs(*CI);
1665       return false;
1666     });
1667 
1668     // Transitively search for more arguments by looking at the users of the
1669     // ones we know already. During the search the GTIdArgs vector is extended
1670     // so we cannot cache the size nor can we use a range based for.
1671     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
1672       AddUserArgs(*GTIdArgs[u]);
1673   }
1674 
1675   /// Kernel (=GPU) optimizations and utility functions
1676   ///
1677   ///{{
1678 
1679   /// Check if \p F is a kernel, hence entry point for target offloading.
1680   bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); }
1681 
1682   /// Cache to remember the unique kernel for a function.
1683   DenseMap<Function *, Optional<Kernel>> UniqueKernelMap;
1684 
1685   /// Find the unique kernel that will execute \p F, if any.
1686   Kernel getUniqueKernelFor(Function &F);
1687 
1688   /// Find the unique kernel that will execute \p I, if any.
1689   Kernel getUniqueKernelFor(Instruction &I) {
1690     return getUniqueKernelFor(*I.getFunction());
1691   }
1692 
1693   /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in
1694   /// the cases we can avoid taking the address of a function.
1695   bool rewriteDeviceCodeStateMachine();
1696 
1697   ///
1698   ///}}
1699 
1700   /// Emit a remark generically
1701   ///
1702   /// This template function can be used to generically emit a remark. The
1703   /// RemarkKind should be one of the following:
1704   ///   - OptimizationRemark to indicate a successful optimization attempt
1705   ///   - OptimizationRemarkMissed to report a failed optimization attempt
1706   ///   - OptimizationRemarkAnalysis to provide additional information about an
1707   ///     optimization attempt
1708   ///
1709   /// The remark is built using a callback function provided by the caller that
1710   /// takes a RemarkKind as input and returns a RemarkKind.
1711   template <typename RemarkKind, typename RemarkCallBack>
1712   void emitRemark(Instruction *I, StringRef RemarkName,
1713                   RemarkCallBack &&RemarkCB) const {
1714     Function *F = I->getParent()->getParent();
1715     auto &ORE = OREGetter(F);
1716 
1717     if (RemarkName.startswith("OMP"))
1718       ORE.emit([&]() {
1719         return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I))
1720                << " [" << RemarkName << "]";
1721       });
1722     else
1723       ORE.emit(
1724           [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)); });
1725   }
1726 
1727   /// Emit a remark on a function.
1728   template <typename RemarkKind, typename RemarkCallBack>
1729   void emitRemark(Function *F, StringRef RemarkName,
1730                   RemarkCallBack &&RemarkCB) const {
1731     auto &ORE = OREGetter(F);
1732 
1733     if (RemarkName.startswith("OMP"))
1734       ORE.emit([&]() {
1735         return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F))
1736                << " [" << RemarkName << "]";
1737       });
1738     else
1739       ORE.emit(
1740           [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)); });
1741   }
1742 
1743   /// The underlying module.
1744   Module &M;
1745 
1746   /// The SCC we are operating on.
1747   SmallVectorImpl<Function *> &SCC;
1748 
1749   /// Callback to update the call graph, the first argument is a removed call,
1750   /// the second an optional replacement call.
1751   CallGraphUpdater &CGUpdater;
1752 
1753   /// Callback to get an OptimizationRemarkEmitter from a Function *
1754   OptimizationRemarkGetter OREGetter;
1755 
1756   /// OpenMP-specific information cache. Also Used for Attributor runs.
1757   OMPInformationCache &OMPInfoCache;
1758 
1759   /// Attributor instance.
1760   Attributor &A;
1761 
1762   /// Helper function to run Attributor on SCC.
1763   bool runAttributor(bool IsModulePass) {
1764     if (SCC.empty())
1765       return false;
1766 
1767     registerAAs(IsModulePass);
1768 
1769     ChangeStatus Changed = A.run();
1770 
1771     LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
1772                       << " functions, result: " << Changed << ".\n");
1773 
1774     return Changed == ChangeStatus::CHANGED;
1775   }
1776 
1777   /// Populate the Attributor with abstract attribute opportunities in the
1778   /// function.
1779   void registerAAs(bool IsModulePass);
1780 };
1781 
1782 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
1783   if (!OMPInfoCache.ModuleSlice.count(&F))
1784     return nullptr;
1785 
1786   // Use a scope to keep the lifetime of the CachedKernel short.
1787   {
1788     Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
1789     if (CachedKernel)
1790       return *CachedKernel;
1791 
1792     // TODO: We should use an AA to create an (optimistic and callback
1793     //       call-aware) call graph. For now we stick to simple patterns that
1794     //       are less powerful, basically the worst fixpoint.
1795     if (isKernel(F)) {
1796       CachedKernel = Kernel(&F);
1797       return *CachedKernel;
1798     }
1799 
1800     CachedKernel = nullptr;
1801     if (!F.hasLocalLinkage()) {
1802 
1803       // See https://openmp.llvm.org/remarks/OptimizationRemarks.html
1804       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1805         return ORA << "Potentially unknown OpenMP target region caller.";
1806       };
1807       emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark);
1808 
1809       return nullptr;
1810     }
1811   }
1812 
1813   auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
1814     if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
1815       // Allow use in equality comparisons.
1816       if (Cmp->isEquality())
1817         return getUniqueKernelFor(*Cmp);
1818       return nullptr;
1819     }
1820     if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
1821       // Allow direct calls.
1822       if (CB->isCallee(&U))
1823         return getUniqueKernelFor(*CB);
1824 
1825       OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1826           OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1827       // Allow the use in __kmpc_parallel_51 calls.
1828       if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI))
1829         return getUniqueKernelFor(*CB);
1830       return nullptr;
1831     }
1832     // Disallow every other use.
1833     return nullptr;
1834   };
1835 
1836   // TODO: In the future we want to track more than just a unique kernel.
1837   SmallPtrSet<Kernel, 2> PotentialKernels;
1838   OMPInformationCache::foreachUse(F, [&](const Use &U) {
1839     PotentialKernels.insert(GetUniqueKernelForUse(U));
1840   });
1841 
1842   Kernel K = nullptr;
1843   if (PotentialKernels.size() == 1)
1844     K = *PotentialKernels.begin();
1845 
1846   // Cache the result.
1847   UniqueKernelMap[&F] = K;
1848 
1849   return K;
1850 }
1851 
1852 bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
1853   OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1854       OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1855 
1856   bool Changed = false;
1857   if (!KernelParallelRFI)
1858     return Changed;
1859 
1860   for (Function *F : SCC) {
1861 
1862     // Check if the function is a use in a __kmpc_parallel_51 call at
1863     // all.
1864     bool UnknownUse = false;
1865     bool KernelParallelUse = false;
1866     unsigned NumDirectCalls = 0;
1867 
1868     SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
1869     OMPInformationCache::foreachUse(*F, [&](Use &U) {
1870       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
1871         if (CB->isCallee(&U)) {
1872           ++NumDirectCalls;
1873           return;
1874         }
1875 
1876       if (isa<ICmpInst>(U.getUser())) {
1877         ToBeReplacedStateMachineUses.push_back(&U);
1878         return;
1879       }
1880 
1881       // Find wrapper functions that represent parallel kernels.
1882       CallInst *CI =
1883           OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI);
1884       const unsigned int WrapperFunctionArgNo = 6;
1885       if (!KernelParallelUse && CI &&
1886           CI->getArgOperandNo(&U) == WrapperFunctionArgNo) {
1887         KernelParallelUse = true;
1888         ToBeReplacedStateMachineUses.push_back(&U);
1889         return;
1890       }
1891       UnknownUse = true;
1892     });
1893 
1894     // Do not emit a remark if we haven't seen a __kmpc_parallel_51
1895     // use.
1896     if (!KernelParallelUse)
1897       continue;
1898 
1899     // If this ever hits, we should investigate.
1900     // TODO: Checking the number of uses is not a necessary restriction and
1901     // should be lifted.
1902     if (UnknownUse || NumDirectCalls != 1 ||
1903         ToBeReplacedStateMachineUses.size() > 2) {
1904       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1905         return ORA << "Parallel region is used in "
1906                    << (UnknownUse ? "unknown" : "unexpected")
1907                    << " ways. Will not attempt to rewrite the state machine.";
1908       };
1909       emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark);
1910       continue;
1911     }
1912 
1913     // Even if we have __kmpc_parallel_51 calls, we (for now) give
1914     // up if the function is not called from a unique kernel.
1915     Kernel K = getUniqueKernelFor(*F);
1916     if (!K) {
1917       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1918         return ORA << "Parallel region is not called from a unique kernel. "
1919                       "Will not attempt to rewrite the state machine.";
1920       };
1921       emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark);
1922       continue;
1923     }
1924 
1925     // We now know F is a parallel body function called only from the kernel K.
1926     // We also identified the state machine uses in which we replace the
1927     // function pointer by a new global symbol for identification purposes. This
1928     // ensures only direct calls to the function are left.
1929 
1930     Module &M = *F->getParent();
1931     Type *Int8Ty = Type::getInt8Ty(M.getContext());
1932 
1933     auto *ID = new GlobalVariable(
1934         M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
1935         UndefValue::get(Int8Ty), F->getName() + ".ID");
1936 
1937     for (Use *U : ToBeReplacedStateMachineUses)
1938       U->set(ConstantExpr::getBitCast(ID, U->get()->getType()));
1939 
1940     ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
1941 
1942     Changed = true;
1943   }
1944 
1945   return Changed;
1946 }
1947 
1948 /// Abstract Attribute for tracking ICV values.
1949 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
1950   using Base = StateWrapper<BooleanState, AbstractAttribute>;
1951   AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
1952 
1953   void initialize(Attributor &A) override {
1954     Function *F = getAnchorScope();
1955     if (!F || !A.isFunctionIPOAmendable(*F))
1956       indicatePessimisticFixpoint();
1957   }
1958 
1959   /// Returns true if value is assumed to be tracked.
1960   bool isAssumedTracked() const { return getAssumed(); }
1961 
1962   /// Returns true if value is known to be tracked.
1963   bool isKnownTracked() const { return getAssumed(); }
1964 
1965   /// Create an abstract attribute biew for the position \p IRP.
1966   static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
1967 
1968   /// Return the value with which \p I can be replaced for specific \p ICV.
1969   virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
1970                                                 const Instruction *I,
1971                                                 Attributor &A) const {
1972     return None;
1973   }
1974 
1975   /// Return an assumed unique ICV value if a single candidate is found. If
1976   /// there cannot be one, return a nullptr. If it is not clear yet, return the
1977   /// Optional::NoneType.
1978   virtual Optional<Value *>
1979   getUniqueReplacementValue(InternalControlVar ICV) const = 0;
1980 
1981   // Currently only nthreads is being tracked.
1982   // this array will only grow with time.
1983   InternalControlVar TrackableICVs[1] = {ICV_nthreads};
1984 
1985   /// See AbstractAttribute::getName()
1986   const std::string getName() const override { return "AAICVTracker"; }
1987 
1988   /// See AbstractAttribute::getIdAddr()
1989   const char *getIdAddr() const override { return &ID; }
1990 
1991   /// This function should return true if the type of the \p AA is AAICVTracker
1992   static bool classof(const AbstractAttribute *AA) {
1993     return (AA->getIdAddr() == &ID);
1994   }
1995 
1996   static const char ID;
1997 };
1998 
1999 struct AAICVTrackerFunction : public AAICVTracker {
2000   AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
2001       : AAICVTracker(IRP, A) {}
2002 
2003   // FIXME: come up with better string.
2004   const std::string getAsStr() const override { return "ICVTrackerFunction"; }
2005 
2006   // FIXME: come up with some stats.
2007   void trackStatistics() const override {}
2008 
2009   /// We don't manifest anything for this AA.
2010   ChangeStatus manifest(Attributor &A) override {
2011     return ChangeStatus::UNCHANGED;
2012   }
2013 
2014   // Map of ICV to their values at specific program point.
2015   EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
2016                   InternalControlVar::ICV___last>
2017       ICVReplacementValuesMap;
2018 
2019   ChangeStatus updateImpl(Attributor &A) override {
2020     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
2021 
2022     Function *F = getAnchorScope();
2023 
2024     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2025 
2026     for (InternalControlVar ICV : TrackableICVs) {
2027       auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2028 
2029       auto &ValuesMap = ICVReplacementValuesMap[ICV];
2030       auto TrackValues = [&](Use &U, Function &) {
2031         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
2032         if (!CI)
2033           return false;
2034 
2035         // FIXME: handle setters with more that 1 arguments.
2036         /// Track new value.
2037         if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
2038           HasChanged = ChangeStatus::CHANGED;
2039 
2040         return false;
2041       };
2042 
2043       auto CallCheck = [&](Instruction &I) {
2044         Optional<Value *> ReplVal = getValueForCall(A, &I, ICV);
2045         if (ReplVal.hasValue() &&
2046             ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
2047           HasChanged = ChangeStatus::CHANGED;
2048 
2049         return true;
2050       };
2051 
2052       // Track all changes of an ICV.
2053       SetterRFI.foreachUse(TrackValues, F);
2054 
2055       bool UsedAssumedInformation = false;
2056       A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
2057                                 UsedAssumedInformation,
2058                                 /* CheckBBLivenessOnly */ true);
2059 
2060       /// TODO: Figure out a way to avoid adding entry in
2061       /// ICVReplacementValuesMap
2062       Instruction *Entry = &F->getEntryBlock().front();
2063       if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
2064         ValuesMap.insert(std::make_pair(Entry, nullptr));
2065     }
2066 
2067     return HasChanged;
2068   }
2069 
2070   /// Hepler to check if \p I is a call and get the value for it if it is
2071   /// unique.
2072   Optional<Value *> getValueForCall(Attributor &A, const Instruction *I,
2073                                     InternalControlVar &ICV) const {
2074 
2075     const auto *CB = dyn_cast<CallBase>(I);
2076     if (!CB || CB->hasFnAttr("no_openmp") ||
2077         CB->hasFnAttr("no_openmp_routines"))
2078       return None;
2079 
2080     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2081     auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
2082     auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2083     Function *CalledFunction = CB->getCalledFunction();
2084 
2085     // Indirect call, assume ICV changes.
2086     if (CalledFunction == nullptr)
2087       return nullptr;
2088     if (CalledFunction == GetterRFI.Declaration)
2089       return None;
2090     if (CalledFunction == SetterRFI.Declaration) {
2091       if (ICVReplacementValuesMap[ICV].count(I))
2092         return ICVReplacementValuesMap[ICV].lookup(I);
2093 
2094       return nullptr;
2095     }
2096 
2097     // Since we don't know, assume it changes the ICV.
2098     if (CalledFunction->isDeclaration())
2099       return nullptr;
2100 
2101     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2102         *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED);
2103 
2104     if (ICVTrackingAA.isAssumedTracked())
2105       return ICVTrackingAA.getUniqueReplacementValue(ICV);
2106 
2107     // If we don't know, assume it changes.
2108     return nullptr;
2109   }
2110 
2111   // We don't check unique value for a function, so return None.
2112   Optional<Value *>
2113   getUniqueReplacementValue(InternalControlVar ICV) const override {
2114     return None;
2115   }
2116 
2117   /// Return the value with which \p I can be replaced for specific \p ICV.
2118   Optional<Value *> getReplacementValue(InternalControlVar ICV,
2119                                         const Instruction *I,
2120                                         Attributor &A) const override {
2121     const auto &ValuesMap = ICVReplacementValuesMap[ICV];
2122     if (ValuesMap.count(I))
2123       return ValuesMap.lookup(I);
2124 
2125     SmallVector<const Instruction *, 16> Worklist;
2126     SmallPtrSet<const Instruction *, 16> Visited;
2127     Worklist.push_back(I);
2128 
2129     Optional<Value *> ReplVal;
2130 
2131     while (!Worklist.empty()) {
2132       const Instruction *CurrInst = Worklist.pop_back_val();
2133       if (!Visited.insert(CurrInst).second)
2134         continue;
2135 
2136       const BasicBlock *CurrBB = CurrInst->getParent();
2137 
2138       // Go up and look for all potential setters/calls that might change the
2139       // ICV.
2140       while ((CurrInst = CurrInst->getPrevNode())) {
2141         if (ValuesMap.count(CurrInst)) {
2142           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
2143           // Unknown value, track new.
2144           if (!ReplVal.hasValue()) {
2145             ReplVal = NewReplVal;
2146             break;
2147           }
2148 
2149           // If we found a new value, we can't know the icv value anymore.
2150           if (NewReplVal.hasValue())
2151             if (ReplVal != NewReplVal)
2152               return nullptr;
2153 
2154           break;
2155         }
2156 
2157         Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV);
2158         if (!NewReplVal.hasValue())
2159           continue;
2160 
2161         // Unknown value, track new.
2162         if (!ReplVal.hasValue()) {
2163           ReplVal = NewReplVal;
2164           break;
2165         }
2166 
2167         // if (NewReplVal.hasValue())
2168         // We found a new value, we can't know the icv value anymore.
2169         if (ReplVal != NewReplVal)
2170           return nullptr;
2171       }
2172 
2173       // If we are in the same BB and we have a value, we are done.
2174       if (CurrBB == I->getParent() && ReplVal.hasValue())
2175         return ReplVal;
2176 
2177       // Go through all predecessors and add terminators for analysis.
2178       for (const BasicBlock *Pred : predecessors(CurrBB))
2179         if (const Instruction *Terminator = Pred->getTerminator())
2180           Worklist.push_back(Terminator);
2181     }
2182 
2183     return ReplVal;
2184   }
2185 };
2186 
2187 struct AAICVTrackerFunctionReturned : AAICVTracker {
2188   AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
2189       : AAICVTracker(IRP, A) {}
2190 
2191   // FIXME: come up with better string.
2192   const std::string getAsStr() const override {
2193     return "ICVTrackerFunctionReturned";
2194   }
2195 
2196   // FIXME: come up with some stats.
2197   void trackStatistics() const override {}
2198 
2199   /// We don't manifest anything for this AA.
2200   ChangeStatus manifest(Attributor &A) override {
2201     return ChangeStatus::UNCHANGED;
2202   }
2203 
2204   // Map of ICV to their values at specific program point.
2205   EnumeratedArray<Optional<Value *>, InternalControlVar,
2206                   InternalControlVar::ICV___last>
2207       ICVReplacementValuesMap;
2208 
2209   /// Return the value with which \p I can be replaced for specific \p ICV.
2210   Optional<Value *>
2211   getUniqueReplacementValue(InternalControlVar ICV) const override {
2212     return ICVReplacementValuesMap[ICV];
2213   }
2214 
2215   ChangeStatus updateImpl(Attributor &A) override {
2216     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2217     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2218         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2219 
2220     if (!ICVTrackingAA.isAssumedTracked())
2221       return indicatePessimisticFixpoint();
2222 
2223     for (InternalControlVar ICV : TrackableICVs) {
2224       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2225       Optional<Value *> UniqueICVValue;
2226 
2227       auto CheckReturnInst = [&](Instruction &I) {
2228         Optional<Value *> NewReplVal =
2229             ICVTrackingAA.getReplacementValue(ICV, &I, A);
2230 
2231         // If we found a second ICV value there is no unique returned value.
2232         if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
2233           return false;
2234 
2235         UniqueICVValue = NewReplVal;
2236 
2237         return true;
2238       };
2239 
2240       bool UsedAssumedInformation = false;
2241       if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
2242                                      UsedAssumedInformation,
2243                                      /* CheckBBLivenessOnly */ true))
2244         UniqueICVValue = nullptr;
2245 
2246       if (UniqueICVValue == ReplVal)
2247         continue;
2248 
2249       ReplVal = UniqueICVValue;
2250       Changed = ChangeStatus::CHANGED;
2251     }
2252 
2253     return Changed;
2254   }
2255 };
2256 
2257 struct AAICVTrackerCallSite : AAICVTracker {
2258   AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
2259       : AAICVTracker(IRP, A) {}
2260 
2261   void initialize(Attributor &A) override {
2262     Function *F = getAnchorScope();
2263     if (!F || !A.isFunctionIPOAmendable(*F))
2264       indicatePessimisticFixpoint();
2265 
2266     // We only initialize this AA for getters, so we need to know which ICV it
2267     // gets.
2268     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2269     for (InternalControlVar ICV : TrackableICVs) {
2270       auto ICVInfo = OMPInfoCache.ICVs[ICV];
2271       auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
2272       if (Getter.Declaration == getAssociatedFunction()) {
2273         AssociatedICV = ICVInfo.Kind;
2274         return;
2275       }
2276     }
2277 
2278     /// Unknown ICV.
2279     indicatePessimisticFixpoint();
2280   }
2281 
2282   ChangeStatus manifest(Attributor &A) override {
2283     if (!ReplVal.hasValue() || !ReplVal.getValue())
2284       return ChangeStatus::UNCHANGED;
2285 
2286     A.changeValueAfterManifest(*getCtxI(), **ReplVal);
2287     A.deleteAfterManifest(*getCtxI());
2288 
2289     return ChangeStatus::CHANGED;
2290   }
2291 
2292   // FIXME: come up with better string.
2293   const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
2294 
2295   // FIXME: come up with some stats.
2296   void trackStatistics() const override {}
2297 
2298   InternalControlVar AssociatedICV;
2299   Optional<Value *> ReplVal;
2300 
2301   ChangeStatus updateImpl(Attributor &A) override {
2302     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2303         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2304 
2305     // We don't have any information, so we assume it changes the ICV.
2306     if (!ICVTrackingAA.isAssumedTracked())
2307       return indicatePessimisticFixpoint();
2308 
2309     Optional<Value *> NewReplVal =
2310         ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
2311 
2312     if (ReplVal == NewReplVal)
2313       return ChangeStatus::UNCHANGED;
2314 
2315     ReplVal = NewReplVal;
2316     return ChangeStatus::CHANGED;
2317   }
2318 
2319   // Return the value with which associated value can be replaced for specific
2320   // \p ICV.
2321   Optional<Value *>
2322   getUniqueReplacementValue(InternalControlVar ICV) const override {
2323     return ReplVal;
2324   }
2325 };
2326 
2327 struct AAICVTrackerCallSiteReturned : AAICVTracker {
2328   AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
2329       : AAICVTracker(IRP, A) {}
2330 
2331   // FIXME: come up with better string.
2332   const std::string getAsStr() const override {
2333     return "ICVTrackerCallSiteReturned";
2334   }
2335 
2336   // FIXME: come up with some stats.
2337   void trackStatistics() const override {}
2338 
2339   /// We don't manifest anything for this AA.
2340   ChangeStatus manifest(Attributor &A) override {
2341     return ChangeStatus::UNCHANGED;
2342   }
2343 
2344   // Map of ICV to their values at specific program point.
2345   EnumeratedArray<Optional<Value *>, InternalControlVar,
2346                   InternalControlVar::ICV___last>
2347       ICVReplacementValuesMap;
2348 
2349   /// Return the value with which associated value can be replaced for specific
2350   /// \p ICV.
2351   Optional<Value *>
2352   getUniqueReplacementValue(InternalControlVar ICV) const override {
2353     return ICVReplacementValuesMap[ICV];
2354   }
2355 
2356   ChangeStatus updateImpl(Attributor &A) override {
2357     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2358     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2359         *this, IRPosition::returned(*getAssociatedFunction()),
2360         DepClassTy::REQUIRED);
2361 
2362     // We don't have any information, so we assume it changes the ICV.
2363     if (!ICVTrackingAA.isAssumedTracked())
2364       return indicatePessimisticFixpoint();
2365 
2366     for (InternalControlVar ICV : TrackableICVs) {
2367       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2368       Optional<Value *> NewReplVal =
2369           ICVTrackingAA.getUniqueReplacementValue(ICV);
2370 
2371       if (ReplVal == NewReplVal)
2372         continue;
2373 
2374       ReplVal = NewReplVal;
2375       Changed = ChangeStatus::CHANGED;
2376     }
2377     return Changed;
2378   }
2379 };
2380 
2381 struct AAExecutionDomainFunction : public AAExecutionDomain {
2382   AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A)
2383       : AAExecutionDomain(IRP, A) {}
2384 
2385   const std::string getAsStr() const override {
2386     return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) +
2387            "/" + std::to_string(NumBBs) + " BBs thread 0 only.";
2388   }
2389 
2390   /// See AbstractAttribute::trackStatistics().
2391   void trackStatistics() const override {}
2392 
2393   void initialize(Attributor &A) override {
2394     Function *F = getAnchorScope();
2395     for (const auto &BB : *F)
2396       SingleThreadedBBs.insert(&BB);
2397     NumBBs = SingleThreadedBBs.size();
2398   }
2399 
2400   ChangeStatus manifest(Attributor &A) override {
2401     LLVM_DEBUG({
2402       for (const BasicBlock *BB : SingleThreadedBBs)
2403         dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " "
2404                << BB->getName() << " is executed by a single thread.\n";
2405     });
2406     return ChangeStatus::UNCHANGED;
2407   }
2408 
2409   ChangeStatus updateImpl(Attributor &A) override;
2410 
2411   /// Check if an instruction is executed by a single thread.
2412   bool isExecutedByInitialThreadOnly(const Instruction &I) const override {
2413     return isExecutedByInitialThreadOnly(*I.getParent());
2414   }
2415 
2416   bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override {
2417     return isValidState() && SingleThreadedBBs.contains(&BB);
2418   }
2419 
2420   /// Set of basic blocks that are executed by a single thread.
2421   DenseSet<const BasicBlock *> SingleThreadedBBs;
2422 
2423   /// Total number of basic blocks in this function.
2424   long unsigned NumBBs;
2425 };
2426 
2427 ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) {
2428   Function *F = getAnchorScope();
2429   ReversePostOrderTraversal<Function *> RPOT(F);
2430   auto NumSingleThreadedBBs = SingleThreadedBBs.size();
2431 
2432   bool AllCallSitesKnown;
2433   auto PredForCallSite = [&](AbstractCallSite ACS) {
2434     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
2435         *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
2436         DepClassTy::REQUIRED);
2437     return ACS.isDirectCall() &&
2438            ExecutionDomainAA.isExecutedByInitialThreadOnly(
2439                *ACS.getInstruction());
2440   };
2441 
2442   if (!A.checkForAllCallSites(PredForCallSite, *this,
2443                               /* RequiresAllCallSites */ true,
2444                               AllCallSitesKnown))
2445     SingleThreadedBBs.erase(&F->getEntryBlock());
2446 
2447   auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2448   auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2449 
2450   // Check if the edge into the successor block compares the __kmpc_target_init
2451   // result with -1. If we are in non-SPMD-mode that signals only the main
2452   // thread will execute the edge.
2453   auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) {
2454     if (!Edge || !Edge->isConditional())
2455       return false;
2456     if (Edge->getSuccessor(0) != SuccessorBB)
2457       return false;
2458 
2459     auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition());
2460     if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality())
2461       return false;
2462 
2463     ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2464     if (!C)
2465       return false;
2466 
2467     // Match:  -1 == __kmpc_target_init (for non-SPMD kernels only!)
2468     if (C->isAllOnesValue()) {
2469       auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0));
2470       CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr;
2471       if (!CB)
2472         return false;
2473       const int InitIsSPMDArgNo = 1;
2474       auto *IsSPMDModeCI =
2475           dyn_cast<ConstantInt>(CB->getOperand(InitIsSPMDArgNo));
2476       return IsSPMDModeCI && IsSPMDModeCI->isZero();
2477     }
2478 
2479     return false;
2480   };
2481 
2482   // Merge all the predecessor states into the current basic block. A basic
2483   // block is executed by a single thread if all of its predecessors are.
2484   auto MergePredecessorStates = [&](BasicBlock *BB) {
2485     if (pred_begin(BB) == pred_end(BB))
2486       return SingleThreadedBBs.contains(BB);
2487 
2488     bool IsInitialThread = true;
2489     for (auto PredBB = pred_begin(BB), PredEndBB = pred_end(BB);
2490          PredBB != PredEndBB; ++PredBB) {
2491       if (!IsInitialThreadOnly(dyn_cast<BranchInst>((*PredBB)->getTerminator()),
2492                                BB))
2493         IsInitialThread &= SingleThreadedBBs.contains(*PredBB);
2494     }
2495 
2496     return IsInitialThread;
2497   };
2498 
2499   for (auto *BB : RPOT) {
2500     if (!MergePredecessorStates(BB))
2501       SingleThreadedBBs.erase(BB);
2502   }
2503 
2504   return (NumSingleThreadedBBs == SingleThreadedBBs.size())
2505              ? ChangeStatus::UNCHANGED
2506              : ChangeStatus::CHANGED;
2507 }
2508 
2509 /// Try to replace memory allocation calls called by a single thread with a
2510 /// static buffer of shared memory.
2511 struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> {
2512   using Base = StateWrapper<BooleanState, AbstractAttribute>;
2513   AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2514 
2515   /// Create an abstract attribute view for the position \p IRP.
2516   static AAHeapToShared &createForPosition(const IRPosition &IRP,
2517                                            Attributor &A);
2518 
2519   /// Returns true if HeapToShared conversion is assumed to be possible.
2520   virtual bool isAssumedHeapToShared(CallBase &CB) const = 0;
2521 
2522   /// Returns true if HeapToShared conversion is assumed and the CB is a
2523   /// callsite to a free operation to be removed.
2524   virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0;
2525 
2526   /// See AbstractAttribute::getName().
2527   const std::string getName() const override { return "AAHeapToShared"; }
2528 
2529   /// See AbstractAttribute::getIdAddr().
2530   const char *getIdAddr() const override { return &ID; }
2531 
2532   /// This function should return true if the type of the \p AA is
2533   /// AAHeapToShared.
2534   static bool classof(const AbstractAttribute *AA) {
2535     return (AA->getIdAddr() == &ID);
2536   }
2537 
2538   /// Unique ID (due to the unique address)
2539   static const char ID;
2540 };
2541 
2542 struct AAHeapToSharedFunction : public AAHeapToShared {
2543   AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A)
2544       : AAHeapToShared(IRP, A) {}
2545 
2546   const std::string getAsStr() const override {
2547     return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) +
2548            " malloc calls eligible.";
2549   }
2550 
2551   /// See AbstractAttribute::trackStatistics().
2552   void trackStatistics() const override {}
2553 
2554   /// This functions finds free calls that will be removed by the
2555   /// HeapToShared transformation.
2556   void findPotentialRemovedFreeCalls(Attributor &A) {
2557     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2558     auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2559 
2560     PotentialRemovedFreeCalls.clear();
2561     // Update free call users of found malloc calls.
2562     for (CallBase *CB : MallocCalls) {
2563       SmallVector<CallBase *, 4> FreeCalls;
2564       for (auto *U : CB->users()) {
2565         CallBase *C = dyn_cast<CallBase>(U);
2566         if (C && C->getCalledFunction() == FreeRFI.Declaration)
2567           FreeCalls.push_back(C);
2568       }
2569 
2570       if (FreeCalls.size() != 1)
2571         continue;
2572 
2573       PotentialRemovedFreeCalls.insert(FreeCalls.front());
2574     }
2575   }
2576 
2577   void initialize(Attributor &A) override {
2578     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2579     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2580 
2581     for (User *U : RFI.Declaration->users())
2582       if (CallBase *CB = dyn_cast<CallBase>(U))
2583         MallocCalls.insert(CB);
2584 
2585     findPotentialRemovedFreeCalls(A);
2586   }
2587 
2588   bool isAssumedHeapToShared(CallBase &CB) const override {
2589     return isValidState() && MallocCalls.count(&CB);
2590   }
2591 
2592   bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override {
2593     return isValidState() && PotentialRemovedFreeCalls.count(&CB);
2594   }
2595 
2596   ChangeStatus manifest(Attributor &A) override {
2597     if (MallocCalls.empty())
2598       return ChangeStatus::UNCHANGED;
2599 
2600     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2601     auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2602 
2603     Function *F = getAnchorScope();
2604     auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this,
2605                                             DepClassTy::OPTIONAL);
2606 
2607     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2608     for (CallBase *CB : MallocCalls) {
2609       // Skip replacing this if HeapToStack has already claimed it.
2610       if (HS && HS->isAssumedHeapToStack(*CB))
2611         continue;
2612 
2613       // Find the unique free call to remove it.
2614       SmallVector<CallBase *, 4> FreeCalls;
2615       for (auto *U : CB->users()) {
2616         CallBase *C = dyn_cast<CallBase>(U);
2617         if (C && C->getCalledFunction() == FreeCall.Declaration)
2618           FreeCalls.push_back(C);
2619       }
2620       if (FreeCalls.size() != 1)
2621         continue;
2622 
2623       ConstantInt *AllocSize = dyn_cast<ConstantInt>(CB->getArgOperand(0));
2624 
2625       LLVM_DEBUG(dbgs() << TAG << "Replace globalization call in "
2626                         << CB->getCaller()->getName() << " with "
2627                         << AllocSize->getZExtValue()
2628                         << " bytes of shared memory\n");
2629 
2630       // Create a new shared memory buffer of the same size as the allocation
2631       // and replace all the uses of the original allocation with it.
2632       Module *M = CB->getModule();
2633       Type *Int8Ty = Type::getInt8Ty(M->getContext());
2634       Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue());
2635       auto *SharedMem = new GlobalVariable(
2636           *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage,
2637           UndefValue::get(Int8ArrTy), CB->getName(), nullptr,
2638           GlobalValue::NotThreadLocal,
2639           static_cast<unsigned>(AddressSpace::Shared));
2640       auto *NewBuffer =
2641           ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo());
2642 
2643       auto Remark = [&](OptimizationRemark OR) {
2644         return OR << "Replaced globalized variable with "
2645                   << ore::NV("SharedMemory", AllocSize->getZExtValue())
2646                   << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ")
2647                   << "of shared memory.";
2648       };
2649       A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark);
2650 
2651       SharedMem->setAlignment(MaybeAlign(32));
2652 
2653       A.changeValueAfterManifest(*CB, *NewBuffer);
2654       A.deleteAfterManifest(*CB);
2655       A.deleteAfterManifest(*FreeCalls.front());
2656 
2657       NumBytesMovedToSharedMemory += AllocSize->getZExtValue();
2658       Changed = ChangeStatus::CHANGED;
2659     }
2660 
2661     return Changed;
2662   }
2663 
2664   ChangeStatus updateImpl(Attributor &A) override {
2665     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2666     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2667     Function *F = getAnchorScope();
2668 
2669     auto NumMallocCalls = MallocCalls.size();
2670 
2671     // Only consider malloc calls executed by a single thread with a constant.
2672     for (User *U : RFI.Declaration->users()) {
2673       const auto &ED = A.getAAFor<AAExecutionDomain>(
2674           *this, IRPosition::function(*F), DepClassTy::REQUIRED);
2675       if (CallBase *CB = dyn_cast<CallBase>(U))
2676         if (!dyn_cast<ConstantInt>(CB->getArgOperand(0)) ||
2677             !ED.isExecutedByInitialThreadOnly(*CB))
2678           MallocCalls.erase(CB);
2679     }
2680 
2681     findPotentialRemovedFreeCalls(A);
2682 
2683     if (NumMallocCalls != MallocCalls.size())
2684       return ChangeStatus::CHANGED;
2685 
2686     return ChangeStatus::UNCHANGED;
2687   }
2688 
2689   /// Collection of all malloc calls in a function.
2690   SmallPtrSet<CallBase *, 4> MallocCalls;
2691   /// Collection of potentially removed free calls in a function.
2692   SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls;
2693 };
2694 
2695 struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> {
2696   using Base = StateWrapper<KernelInfoState, AbstractAttribute>;
2697   AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2698 
2699   /// Statistics are tracked as part of manifest for now.
2700   void trackStatistics() const override {}
2701 
2702   /// See AbstractAttribute::getAsStr()
2703   const std::string getAsStr() const override {
2704     if (!isValidState())
2705       return "<invalid>";
2706     return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD"
2707                                                             : "generic") +
2708            std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]"
2709                                                                : "") +
2710            std::string(" #PRs: ") +
2711            std::to_string(ReachedKnownParallelRegions.size()) +
2712            ", #Unknown PRs: " +
2713            std::to_string(ReachedUnknownParallelRegions.size());
2714   }
2715 
2716   /// Create an abstract attribute biew for the position \p IRP.
2717   static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A);
2718 
2719   /// See AbstractAttribute::getName()
2720   const std::string getName() const override { return "AAKernelInfo"; }
2721 
2722   /// See AbstractAttribute::getIdAddr()
2723   const char *getIdAddr() const override { return &ID; }
2724 
2725   /// This function should return true if the type of the \p AA is AAKernelInfo
2726   static bool classof(const AbstractAttribute *AA) {
2727     return (AA->getIdAddr() == &ID);
2728   }
2729 
2730   static const char ID;
2731 };
2732 
2733 /// The function kernel info abstract attribute, basically, what can we say
2734 /// about a function with regards to the KernelInfoState.
2735 struct AAKernelInfoFunction : AAKernelInfo {
2736   AAKernelInfoFunction(const IRPosition &IRP, Attributor &A)
2737       : AAKernelInfo(IRP, A) {}
2738 
2739   /// See AbstractAttribute::initialize(...).
2740   void initialize(Attributor &A) override {
2741     // This is a high-level transform that might change the constant arguments
2742     // of the init and dinit calls. We need to tell the Attributor about this
2743     // to avoid other parts using the current constant value for simpliication.
2744     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2745 
2746     Function *Fn = getAnchorScope();
2747     if (!OMPInfoCache.Kernels.count(Fn))
2748       return;
2749 
2750     // Add itself to the reaching kernel and set IsKernelEntry.
2751     ReachingKernelEntries.insert(Fn);
2752     IsKernelEntry = true;
2753 
2754     OMPInformationCache::RuntimeFunctionInfo &InitRFI =
2755         OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2756     OMPInformationCache::RuntimeFunctionInfo &DeinitRFI =
2757         OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit];
2758 
2759     // For kernels we perform more initialization work, first we find the init
2760     // and deinit calls.
2761     auto StoreCallBase = [](Use &U,
2762                             OMPInformationCache::RuntimeFunctionInfo &RFI,
2763                             CallBase *&Storage) {
2764       CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI);
2765       assert(CB &&
2766              "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!");
2767       assert(!Storage &&
2768              "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!");
2769       Storage = CB;
2770       return false;
2771     };
2772     InitRFI.foreachUse(
2773         [&](Use &U, Function &) {
2774           StoreCallBase(U, InitRFI, KernelInitCB);
2775           return false;
2776         },
2777         Fn);
2778     DeinitRFI.foreachUse(
2779         [&](Use &U, Function &) {
2780           StoreCallBase(U, DeinitRFI, KernelDeinitCB);
2781           return false;
2782         },
2783         Fn);
2784 
2785     assert((KernelInitCB && KernelDeinitCB) &&
2786            "Kernel without __kmpc_target_init or __kmpc_target_deinit!");
2787 
2788     // For kernels we might need to initialize/finalize the IsSPMD state and
2789     // we need to register a simplification callback so that the Attributor
2790     // knows the constant arguments to __kmpc_target_init and
2791     // __kmpc_target_deinit might actually change.
2792 
2793     Attributor::SimplifictionCallbackTy StateMachineSimplifyCB =
2794         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2795             bool &UsedAssumedInformation) -> Optional<Value *> {
2796       // IRP represents the "use generic state machine" argument of an
2797       // __kmpc_target_init call. We will answer this one with the internal
2798       // state. As long as we are not in an invalid state, we will create a
2799       // custom state machine so the value should be a `i1 false`. If we are
2800       // in an invalid state, we won't change the value that is in the IR.
2801       if (!isValidState())
2802         return nullptr;
2803       if (AA)
2804         A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2805       UsedAssumedInformation = !isAtFixpoint();
2806       auto *FalseVal =
2807           ConstantInt::getBool(IRP.getAnchorValue().getContext(), 0);
2808       return FalseVal;
2809     };
2810 
2811     Attributor::SimplifictionCallbackTy IsSPMDModeSimplifyCB =
2812         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2813             bool &UsedAssumedInformation) -> Optional<Value *> {
2814       // IRP represents the "SPMDCompatibilityTracker" argument of an
2815       // __kmpc_target_init or
2816       // __kmpc_target_deinit call. We will answer this one with the internal
2817       // state.
2818       if (!SPMDCompatibilityTracker.isValidState())
2819         return nullptr;
2820       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2821         if (AA)
2822           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2823         UsedAssumedInformation = true;
2824       } else {
2825         UsedAssumedInformation = false;
2826       }
2827       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2828                                        SPMDCompatibilityTracker.isAssumed());
2829       return Val;
2830     };
2831 
2832     Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB =
2833         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2834             bool &UsedAssumedInformation) -> Optional<Value *> {
2835       // IRP represents the "RequiresFullRuntime" argument of an
2836       // __kmpc_target_init or __kmpc_target_deinit call. We will answer this
2837       // one with the internal state of the SPMDCompatibilityTracker, so if
2838       // generic then true, if SPMD then false.
2839       if (!SPMDCompatibilityTracker.isValidState())
2840         return nullptr;
2841       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2842         if (AA)
2843           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2844         UsedAssumedInformation = true;
2845       } else {
2846         UsedAssumedInformation = false;
2847       }
2848       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2849                                        !SPMDCompatibilityTracker.isAssumed());
2850       return Val;
2851     };
2852 
2853     constexpr const int InitIsSPMDArgNo = 1;
2854     constexpr const int DeinitIsSPMDArgNo = 1;
2855     constexpr const int InitUseStateMachineArgNo = 2;
2856     constexpr const int InitRequiresFullRuntimeArgNo = 3;
2857     constexpr const int DeinitRequiresFullRuntimeArgNo = 2;
2858     A.registerSimplificationCallback(
2859         IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo),
2860         StateMachineSimplifyCB);
2861     A.registerSimplificationCallback(
2862         IRPosition::callsite_argument(*KernelInitCB, InitIsSPMDArgNo),
2863         IsSPMDModeSimplifyCB);
2864     A.registerSimplificationCallback(
2865         IRPosition::callsite_argument(*KernelDeinitCB, DeinitIsSPMDArgNo),
2866         IsSPMDModeSimplifyCB);
2867     A.registerSimplificationCallback(
2868         IRPosition::callsite_argument(*KernelInitCB,
2869                                       InitRequiresFullRuntimeArgNo),
2870         IsGenericModeSimplifyCB);
2871     A.registerSimplificationCallback(
2872         IRPosition::callsite_argument(*KernelDeinitCB,
2873                                       DeinitRequiresFullRuntimeArgNo),
2874         IsGenericModeSimplifyCB);
2875 
2876     // Check if we know we are in SPMD-mode already.
2877     ConstantInt *IsSPMDArg =
2878         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
2879     if (IsSPMDArg && !IsSPMDArg->isZero())
2880       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
2881   }
2882 
2883   /// Modify the IR based on the KernelInfoState as the fixpoint iteration is
2884   /// finished now.
2885   ChangeStatus manifest(Attributor &A) override {
2886     // If we are not looking at a kernel with __kmpc_target_init and
2887     // __kmpc_target_deinit call we cannot actually manifest the information.
2888     if (!KernelInitCB || !KernelDeinitCB)
2889       return ChangeStatus::UNCHANGED;
2890 
2891     // Known SPMD-mode kernels need no manifest changes.
2892     if (SPMDCompatibilityTracker.isKnown())
2893       return ChangeStatus::UNCHANGED;
2894 
2895     // If we can we change the execution mode to SPMD-mode otherwise we build a
2896     // custom state machine.
2897     if (!changeToSPMDMode(A))
2898       buildCustomStateMachine(A);
2899 
2900     return ChangeStatus::CHANGED;
2901   }
2902 
2903   bool changeToSPMDMode(Attributor &A) {
2904     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2905 
2906     if (!SPMDCompatibilityTracker.isAssumed()) {
2907       for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) {
2908         if (!NonCompatibleI)
2909           continue;
2910 
2911         // Skip diagnostics on calls to known OpenMP runtime functions for now.
2912         if (auto *CB = dyn_cast<CallBase>(NonCompatibleI))
2913           if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction()))
2914             continue;
2915 
2916         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
2917           ORA << "Value has potential side effects preventing SPMD-mode "
2918                  "execution";
2919           if (isa<CallBase>(NonCompatibleI)) {
2920             ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to "
2921                    "the called function to override";
2922           }
2923           return ORA << ".";
2924         };
2925         A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121",
2926                                                  Remark);
2927 
2928         LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: "
2929                           << *NonCompatibleI << "\n");
2930       }
2931 
2932       return false;
2933     }
2934 
2935     // Adjust the global exec mode flag that tells the runtime what mode this
2936     // kernel is executed in.
2937     Function *Kernel = getAnchorScope();
2938     GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable(
2939         (Kernel->getName() + "_exec_mode").str());
2940     assert(ExecMode && "Kernel without exec mode?");
2941     assert(ExecMode->getInitializer() &&
2942            ExecMode->getInitializer()->isOneValue() &&
2943            "Initially non-SPMD kernel has SPMD exec mode!");
2944 
2945     // Set the global exec mode flag to indicate SPMD-Generic mode.
2946     constexpr int SPMDGeneric = 2;
2947     if (!ExecMode->getInitializer()->isZeroValue())
2948       ExecMode->setInitializer(
2949           ConstantInt::get(ExecMode->getInitializer()->getType(), SPMDGeneric));
2950 
2951     // Next rewrite the init and deinit calls to indicate we use SPMD-mode now.
2952     const int InitIsSPMDArgNo = 1;
2953     const int DeinitIsSPMDArgNo = 1;
2954     const int InitUseStateMachineArgNo = 2;
2955     const int InitRequiresFullRuntimeArgNo = 3;
2956     const int DeinitRequiresFullRuntimeArgNo = 2;
2957 
2958     auto &Ctx = getAnchorValue().getContext();
2959     A.changeUseAfterManifest(KernelInitCB->getArgOperandUse(InitIsSPMDArgNo),
2960                              *ConstantInt::getBool(Ctx, 1));
2961     A.changeUseAfterManifest(
2962         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo),
2963         *ConstantInt::getBool(Ctx, 0));
2964     A.changeUseAfterManifest(
2965         KernelDeinitCB->getArgOperandUse(DeinitIsSPMDArgNo),
2966         *ConstantInt::getBool(Ctx, 1));
2967     A.changeUseAfterManifest(
2968         KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo),
2969         *ConstantInt::getBool(Ctx, 0));
2970     A.changeUseAfterManifest(
2971         KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo),
2972         *ConstantInt::getBool(Ctx, 0));
2973 
2974     ++NumOpenMPTargetRegionKernelsSPMD;
2975 
2976     auto Remark = [&](OptimizationRemark OR) {
2977       return OR << "Transformed generic-mode kernel to SPMD-mode.";
2978     };
2979     A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark);
2980     return true;
2981   };
2982 
2983   ChangeStatus buildCustomStateMachine(Attributor &A) {
2984     assert(ReachedKnownParallelRegions.isValidState() &&
2985            "Custom state machine with invalid parallel region states?");
2986 
2987     const int InitIsSPMDArgNo = 1;
2988     const int InitUseStateMachineArgNo = 2;
2989 
2990     // Check if the current configuration is non-SPMD and generic state machine.
2991     // If we already have SPMD mode or a custom state machine we do not need to
2992     // go any further. If it is anything but a constant something is weird and
2993     // we give up.
2994     ConstantInt *UseStateMachine = dyn_cast<ConstantInt>(
2995         KernelInitCB->getArgOperand(InitUseStateMachineArgNo));
2996     ConstantInt *IsSPMD =
2997         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
2998 
2999     // If we are stuck with generic mode, try to create a custom device (=GPU)
3000     // state machine which is specialized for the parallel regions that are
3001     // reachable by the kernel.
3002     if (!UseStateMachine || UseStateMachine->isZero() || !IsSPMD ||
3003         !IsSPMD->isZero())
3004       return ChangeStatus::UNCHANGED;
3005 
3006     // If not SPMD mode, indicate we use a custom state machine now.
3007     auto &Ctx = getAnchorValue().getContext();
3008     auto *FalseVal = ConstantInt::getBool(Ctx, 0);
3009     A.changeUseAfterManifest(
3010         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal);
3011 
3012     // If we don't actually need a state machine we are done here. This can
3013     // happen if there simply are no parallel regions. In the resulting kernel
3014     // all worker threads will simply exit right away, leaving the main thread
3015     // to do the work alone.
3016     if (ReachedKnownParallelRegions.empty() &&
3017         ReachedUnknownParallelRegions.empty()) {
3018       ++NumOpenMPTargetRegionKernelsWithoutStateMachine;
3019 
3020       auto Remark = [&](OptimizationRemark OR) {
3021         return OR << "Removing unused state machine from generic-mode kernel.";
3022       };
3023       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark);
3024 
3025       return ChangeStatus::CHANGED;
3026     }
3027 
3028     // Keep track in the statistics of our new shiny custom state machine.
3029     if (ReachedUnknownParallelRegions.empty()) {
3030       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback;
3031 
3032       auto Remark = [&](OptimizationRemark OR) {
3033         return OR << "Rewriting generic-mode kernel with a customized state "
3034                      "machine.";
3035       };
3036       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark);
3037     } else {
3038       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback;
3039 
3040       auto Remark = [&](OptimizationRemarkAnalysis OR) {
3041         return OR << "Generic-mode kernel is executed with a customized state "
3042                      "machine that requires a fallback.";
3043       };
3044       A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark);
3045 
3046       // Tell the user why we ended up with a fallback.
3047       for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) {
3048         if (!UnknownParallelRegionCB)
3049           continue;
3050         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
3051           return ORA << "Call may contain unknown parallel regions. Use "
3052                      << "`__attribute__((assume(\"omp_no_parallelism\")))` to "
3053                         "override.";
3054         };
3055         A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB,
3056                                                  "OMP133", Remark);
3057       }
3058     }
3059 
3060     // Create all the blocks:
3061     //
3062     //                       InitCB = __kmpc_target_init(...)
3063     //                       bool IsWorker = InitCB >= 0;
3064     //                       if (IsWorker) {
3065     // SMBeginBB:               __kmpc_barrier_simple_spmd(...);
3066     //                         void *WorkFn;
3067     //                         bool Active = __kmpc_kernel_parallel(&WorkFn);
3068     //                         if (!WorkFn) return;
3069     // SMIsActiveCheckBB:       if (Active) {
3070     // SMIfCascadeCurrentBB:      if      (WorkFn == <ParFn0>)
3071     //                              ParFn0(...);
3072     // SMIfCascadeCurrentBB:      else if (WorkFn == <ParFn1>)
3073     //                              ParFn1(...);
3074     //                            ...
3075     // SMIfCascadeCurrentBB:      else
3076     //                              ((WorkFnTy*)WorkFn)(...);
3077     // SMEndParallelBB:           __kmpc_kernel_end_parallel(...);
3078     //                          }
3079     // SMDoneBB:                __kmpc_barrier_simple_spmd(...);
3080     //                          goto SMBeginBB;
3081     //                       }
3082     // UserCodeEntryBB:      // user code
3083     //                       __kmpc_target_deinit(...)
3084     //
3085     Function *Kernel = getAssociatedFunction();
3086     assert(Kernel && "Expected an associated function!");
3087 
3088     BasicBlock *InitBB = KernelInitCB->getParent();
3089     BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock(
3090         KernelInitCB->getNextNode(), "thread.user_code.check");
3091     BasicBlock *StateMachineBeginBB = BasicBlock::Create(
3092         Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB);
3093     BasicBlock *StateMachineFinishedBB = BasicBlock::Create(
3094         Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB);
3095     BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create(
3096         Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB);
3097     BasicBlock *StateMachineIfCascadeCurrentBB =
3098         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3099                            Kernel, UserCodeEntryBB);
3100     BasicBlock *StateMachineEndParallelBB =
3101         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end",
3102                            Kernel, UserCodeEntryBB);
3103     BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create(
3104         Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB);
3105     A.registerManifestAddedBasicBlock(*InitBB);
3106     A.registerManifestAddedBasicBlock(*UserCodeEntryBB);
3107     A.registerManifestAddedBasicBlock(*StateMachineBeginBB);
3108     A.registerManifestAddedBasicBlock(*StateMachineFinishedBB);
3109     A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB);
3110     A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB);
3111     A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB);
3112     A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB);
3113 
3114     const DebugLoc &DLoc = KernelInitCB->getDebugLoc();
3115     ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc);
3116 
3117     InitBB->getTerminator()->eraseFromParent();
3118     Instruction *IsWorker =
3119         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB,
3120                          ConstantInt::get(KernelInitCB->getType(), -1),
3121                          "thread.is_worker", InitBB);
3122     IsWorker->setDebugLoc(DLoc);
3123     BranchInst::Create(StateMachineBeginBB, UserCodeEntryBB, IsWorker, InitBB);
3124 
3125     // Create local storage for the work function pointer.
3126     Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
3127     AllocaInst *WorkFnAI = new AllocaInst(VoidPtrTy, 0, "worker.work_fn.addr",
3128                                           &Kernel->getEntryBlock().front());
3129     WorkFnAI->setDebugLoc(DLoc);
3130 
3131     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3132     OMPInfoCache.OMPBuilder.updateToLocation(
3133         OpenMPIRBuilder::LocationDescription(
3134             IRBuilder<>::InsertPoint(StateMachineBeginBB,
3135                                      StateMachineBeginBB->end()),
3136             DLoc));
3137 
3138     Value *Ident = KernelInitCB->getArgOperand(0);
3139     Value *GTid = KernelInitCB;
3140 
3141     Module &M = *Kernel->getParent();
3142     FunctionCallee BarrierFn =
3143         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3144             M, OMPRTL___kmpc_barrier_simple_spmd);
3145     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB)
3146         ->setDebugLoc(DLoc);
3147 
3148     FunctionCallee KernelParallelFn =
3149         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3150             M, OMPRTL___kmpc_kernel_parallel);
3151     Instruction *IsActiveWorker = CallInst::Create(
3152         KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB);
3153     IsActiveWorker->setDebugLoc(DLoc);
3154     Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn",
3155                                        StateMachineBeginBB);
3156     WorkFn->setDebugLoc(DLoc);
3157 
3158     FunctionType *ParallelRegionFnTy = FunctionType::get(
3159         Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)},
3160         false);
3161     Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
3162         WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast",
3163         StateMachineBeginBB);
3164 
3165     Instruction *IsDone =
3166         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn,
3167                          Constant::getNullValue(VoidPtrTy), "worker.is_done",
3168                          StateMachineBeginBB);
3169     IsDone->setDebugLoc(DLoc);
3170     BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB,
3171                        IsDone, StateMachineBeginBB)
3172         ->setDebugLoc(DLoc);
3173 
3174     BranchInst::Create(StateMachineIfCascadeCurrentBB,
3175                        StateMachineDoneBarrierBB, IsActiveWorker,
3176                        StateMachineIsActiveCheckBB)
3177         ->setDebugLoc(DLoc);
3178 
3179     Value *ZeroArg =
3180         Constant::getNullValue(ParallelRegionFnTy->getParamType(0));
3181 
3182     // Now that we have most of the CFG skeleton it is time for the if-cascade
3183     // that checks the function pointer we got from the runtime against the
3184     // parallel regions we expect, if there are any.
3185     for (int i = 0, e = ReachedKnownParallelRegions.size(); i < e; ++i) {
3186       auto *ParallelRegion = ReachedKnownParallelRegions[i];
3187       BasicBlock *PRExecuteBB = BasicBlock::Create(
3188           Ctx, "worker_state_machine.parallel_region.execute", Kernel,
3189           StateMachineEndParallelBB);
3190       CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB)
3191           ->setDebugLoc(DLoc);
3192       BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB)
3193           ->setDebugLoc(DLoc);
3194 
3195       BasicBlock *PRNextBB =
3196           BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3197                              Kernel, StateMachineEndParallelBB);
3198 
3199       // Check if we need to compare the pointer at all or if we can just
3200       // call the parallel region function.
3201       Value *IsPR;
3202       if (i + 1 < e || !ReachedUnknownParallelRegions.empty()) {
3203         Instruction *CmpI = ICmpInst::Create(
3204             ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion,
3205             "worker.check_parallel_region", StateMachineIfCascadeCurrentBB);
3206         CmpI->setDebugLoc(DLoc);
3207         IsPR = CmpI;
3208       } else {
3209         IsPR = ConstantInt::getTrue(Ctx);
3210       }
3211 
3212       BranchInst::Create(PRExecuteBB, PRNextBB, IsPR,
3213                          StateMachineIfCascadeCurrentBB)
3214           ->setDebugLoc(DLoc);
3215       StateMachineIfCascadeCurrentBB = PRNextBB;
3216     }
3217 
3218     // At the end of the if-cascade we place the indirect function pointer call
3219     // in case we might need it, that is if there can be parallel regions we
3220     // have not handled in the if-cascade above.
3221     if (!ReachedUnknownParallelRegions.empty()) {
3222       StateMachineIfCascadeCurrentBB->setName(
3223           "worker_state_machine.parallel_region.fallback.execute");
3224       CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "",
3225                        StateMachineIfCascadeCurrentBB)
3226           ->setDebugLoc(DLoc);
3227     }
3228     BranchInst::Create(StateMachineEndParallelBB,
3229                        StateMachineIfCascadeCurrentBB)
3230         ->setDebugLoc(DLoc);
3231 
3232     CallInst::Create(OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3233                          M, OMPRTL___kmpc_kernel_end_parallel),
3234                      {}, "", StateMachineEndParallelBB)
3235         ->setDebugLoc(DLoc);
3236     BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB)
3237         ->setDebugLoc(DLoc);
3238 
3239     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB)
3240         ->setDebugLoc(DLoc);
3241     BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB)
3242         ->setDebugLoc(DLoc);
3243 
3244     return ChangeStatus::CHANGED;
3245   }
3246 
3247   /// Fixpoint iteration update function. Will be called every time a dependence
3248   /// changed its state (and in the beginning).
3249   ChangeStatus updateImpl(Attributor &A) override {
3250     KernelInfoState StateBefore = getState();
3251 
3252     // Callback to check a read/write instruction.
3253     auto CheckRWInst = [&](Instruction &I) {
3254       // We handle calls later.
3255       if (isa<CallBase>(I))
3256         return true;
3257       // We only care about write effects.
3258       if (!I.mayWriteToMemory())
3259         return true;
3260       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3261         SmallVector<const Value *> Objects;
3262         getUnderlyingObjects(SI->getPointerOperand(), Objects);
3263         if (llvm::all_of(Objects,
3264                          [](const Value *Obj) { return isa<AllocaInst>(Obj); }))
3265           return true;
3266       }
3267       // For now we give up on everything but stores.
3268       SPMDCompatibilityTracker.insert(&I);
3269       return true;
3270     };
3271 
3272     bool UsedAssumedInformationInCheckRWInst = false;
3273     if (!SPMDCompatibilityTracker.isAtFixpoint())
3274       if (!A.checkForAllReadWriteInstructions(
3275               CheckRWInst, *this, UsedAssumedInformationInCheckRWInst))
3276         SPMDCompatibilityTracker.indicatePessimisticFixpoint();
3277 
3278     if (!IsKernelEntry)
3279       updateReachingKernelEntries(A);
3280 
3281     // Callback to check a call instruction.
3282     bool AllSPMDStatesWereFixed = true;
3283     auto CheckCallInst = [&](Instruction &I) {
3284       auto &CB = cast<CallBase>(I);
3285       auto &CBAA = A.getAAFor<AAKernelInfo>(
3286           *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL);
3287       getState() ^= CBAA.getState();
3288       AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint();
3289       return true;
3290     };
3291 
3292     bool UsedAssumedInformationInCheckCallInst = false;
3293     if (!A.checkForAllCallLikeInstructions(
3294             CheckCallInst, *this, UsedAssumedInformationInCheckCallInst))
3295       return indicatePessimisticFixpoint();
3296 
3297     // If we haven't used any assumed information for the SPMD state we can fix
3298     // it.
3299     if (!UsedAssumedInformationInCheckRWInst &&
3300         !UsedAssumedInformationInCheckCallInst && AllSPMDStatesWereFixed)
3301       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3302 
3303     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3304                                      : ChangeStatus::CHANGED;
3305   }
3306 
3307 private:
3308   /// Update info regarding reaching kernels.
3309   void updateReachingKernelEntries(Attributor &A) {
3310     auto PredCallSite = [&](AbstractCallSite ACS) {
3311       Function *Caller = ACS.getInstruction()->getFunction();
3312 
3313       assert(Caller && "Caller is nullptr");
3314 
3315       auto &CAA = A.getOrCreateAAFor<AAKernelInfo>(
3316           IRPosition::function(*Caller), this, DepClassTy::REQUIRED);
3317       if (CAA.ReachingKernelEntries.isValidState()) {
3318         ReachingKernelEntries ^= CAA.ReachingKernelEntries;
3319         return true;
3320       }
3321 
3322       // We lost track of the caller of the associated function, any kernel
3323       // could reach now.
3324       ReachingKernelEntries.indicatePessimisticFixpoint();
3325 
3326       return true;
3327     };
3328 
3329     bool AllCallSitesKnown;
3330     if (!A.checkForAllCallSites(PredCallSite, *this,
3331                                 true /* RequireAllCallSites */,
3332                                 AllCallSitesKnown))
3333       ReachingKernelEntries.indicatePessimisticFixpoint();
3334   }
3335 };
3336 
3337 /// The call site kernel info abstract attribute, basically, what can we say
3338 /// about a call site with regards to the KernelInfoState. For now this simply
3339 /// forwards the information from the callee.
3340 struct AAKernelInfoCallSite : AAKernelInfo {
3341   AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A)
3342       : AAKernelInfo(IRP, A) {}
3343 
3344   /// See AbstractAttribute::initialize(...).
3345   void initialize(Attributor &A) override {
3346     AAKernelInfo::initialize(A);
3347 
3348     CallBase &CB = cast<CallBase>(getAssociatedValue());
3349     Function *Callee = getAssociatedFunction();
3350 
3351     // Helper to lookup an assumption string.
3352     auto HasAssumption = [](Function *Fn, StringRef AssumptionStr) {
3353       return Fn && hasAssumption(*Fn, AssumptionStr);
3354     };
3355 
3356     // Check for SPMD-mode assumptions.
3357     if (HasAssumption(Callee, "ompx_spmd_amenable"))
3358       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3359 
3360     // First weed out calls we do not care about, that is readonly/readnone
3361     // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a
3362     // parallel region or anything else we are looking for.
3363     if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) {
3364       indicateOptimisticFixpoint();
3365       return;
3366     }
3367 
3368     // Next we check if we know the callee. If it is a known OpenMP function
3369     // we will handle them explicitly in the switch below. If it is not, we
3370     // will use an AAKernelInfo object on the callee to gather information and
3371     // merge that into the current state. The latter happens in the updateImpl.
3372     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3373     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3374     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3375       // Unknown caller or declarations are not analyzable, we give up.
3376       if (!Callee || !A.isFunctionIPOAmendable(*Callee)) {
3377 
3378         // Unknown callees might contain parallel regions, except if they have
3379         // an appropriate assumption attached.
3380         if (!(HasAssumption(Callee, "omp_no_openmp") ||
3381               HasAssumption(Callee, "omp_no_parallelism")))
3382           ReachedUnknownParallelRegions.insert(&CB);
3383 
3384         // If SPMDCompatibilityTracker is not fixed, we need to give up on the
3385         // idea we can run something unknown in SPMD-mode.
3386         if (!SPMDCompatibilityTracker.isAtFixpoint())
3387           SPMDCompatibilityTracker.insert(&CB);
3388 
3389         // We have updated the state for this unknown call properly, there won't
3390         // be any change so we indicate a fixpoint.
3391         indicateOptimisticFixpoint();
3392       }
3393       // If the callee is known and can be used in IPO, we will update the state
3394       // based on the callee state in updateImpl.
3395       return;
3396     }
3397 
3398     const unsigned int WrapperFunctionArgNo = 6;
3399     RuntimeFunction RF = It->getSecond();
3400     switch (RF) {
3401     // All the functions we know are compatible with SPMD mode.
3402     case OMPRTL___kmpc_is_spmd_exec_mode:
3403     case OMPRTL___kmpc_for_static_fini:
3404     case OMPRTL___kmpc_global_thread_num:
3405     case OMPRTL___kmpc_single:
3406     case OMPRTL___kmpc_end_single:
3407     case OMPRTL___kmpc_master:
3408     case OMPRTL___kmpc_end_master:
3409     case OMPRTL___kmpc_barrier:
3410       break;
3411     case OMPRTL___kmpc_for_static_init_4:
3412     case OMPRTL___kmpc_for_static_init_4u:
3413     case OMPRTL___kmpc_for_static_init_8:
3414     case OMPRTL___kmpc_for_static_init_8u: {
3415       // Check the schedule and allow static schedule in SPMD mode.
3416       unsigned ScheduleArgOpNo = 2;
3417       auto *ScheduleTypeCI =
3418           dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo));
3419       unsigned ScheduleTypeVal =
3420           ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0;
3421       switch (OMPScheduleType(ScheduleTypeVal)) {
3422       case OMPScheduleType::Static:
3423       case OMPScheduleType::StaticChunked:
3424       case OMPScheduleType::Distribute:
3425       case OMPScheduleType::DistributeChunked:
3426         break;
3427       default:
3428         SPMDCompatibilityTracker.insert(&CB);
3429         break;
3430       };
3431     } break;
3432     case OMPRTL___kmpc_target_init:
3433       KernelInitCB = &CB;
3434       break;
3435     case OMPRTL___kmpc_target_deinit:
3436       KernelDeinitCB = &CB;
3437       break;
3438     case OMPRTL___kmpc_parallel_51:
3439       if (auto *ParallelRegion = dyn_cast<Function>(
3440               CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) {
3441         ReachedKnownParallelRegions.insert(ParallelRegion);
3442         break;
3443       }
3444       // The condition above should usually get the parallel region function
3445       // pointer and record it. In the off chance it doesn't we assume the
3446       // worst.
3447       ReachedUnknownParallelRegions.insert(&CB);
3448       break;
3449     case OMPRTL___kmpc_omp_task:
3450       // We do not look into tasks right now, just give up.
3451       SPMDCompatibilityTracker.insert(&CB);
3452       ReachedUnknownParallelRegions.insert(&CB);
3453       break;
3454     case OMPRTL___kmpc_alloc_shared:
3455     case OMPRTL___kmpc_free_shared:
3456       // Return without setting a fixpoint, to be resolved in updateImpl.
3457       return;
3458     default:
3459       // Unknown OpenMP runtime calls cannot be executed in SPMD-mode,
3460       // generally.
3461       SPMDCompatibilityTracker.insert(&CB);
3462       break;
3463     }
3464     // All other OpenMP runtime calls will not reach parallel regions so they
3465     // can be safely ignored for now. Since it is a known OpenMP runtime call we
3466     // have now modeled all effects and there is no need for any update.
3467     indicateOptimisticFixpoint();
3468   }
3469 
3470   ChangeStatus updateImpl(Attributor &A) override {
3471     // TODO: Once we have call site specific value information we can provide
3472     //       call site specific liveness information and then it makes
3473     //       sense to specialize attributes for call sites arguments instead of
3474     //       redirecting requests to the callee argument.
3475     Function *F = getAssociatedFunction();
3476 
3477     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3478     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F);
3479 
3480     // If F is not a runtime function, propagate the AAKernelInfo of the callee.
3481     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3482       const IRPosition &FnPos = IRPosition::function(*F);
3483       auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED);
3484       if (getState() == FnAA.getState())
3485         return ChangeStatus::UNCHANGED;
3486       getState() = FnAA.getState();
3487       return ChangeStatus::CHANGED;
3488     }
3489 
3490     // F is a runtime function that allocates or frees memory, check
3491     // AAHeapToStack and AAHeapToShared.
3492     KernelInfoState StateBefore = getState();
3493     assert((It->getSecond() == OMPRTL___kmpc_alloc_shared ||
3494             It->getSecond() == OMPRTL___kmpc_free_shared) &&
3495            "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call");
3496 
3497     CallBase &CB = cast<CallBase>(getAssociatedValue());
3498 
3499     auto &HeapToStackAA = A.getAAFor<AAHeapToStack>(
3500         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3501     auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>(
3502         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3503 
3504     RuntimeFunction RF = It->getSecond();
3505 
3506     switch (RF) {
3507     // If neither HeapToStack nor HeapToShared assume the call is removed,
3508     // assume SPMD incompatibility.
3509     case OMPRTL___kmpc_alloc_shared:
3510       if (!HeapToStackAA.isAssumedHeapToStack(CB) &&
3511           !HeapToSharedAA.isAssumedHeapToShared(CB))
3512         SPMDCompatibilityTracker.insert(&CB);
3513       break;
3514     case OMPRTL___kmpc_free_shared:
3515       if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) &&
3516           !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB))
3517         SPMDCompatibilityTracker.insert(&CB);
3518       break;
3519     default:
3520       SPMDCompatibilityTracker.insert(&CB);
3521     }
3522 
3523     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3524                                      : ChangeStatus::CHANGED;
3525   }
3526 };
3527 
3528 struct AAFoldRuntimeCall
3529     : public StateWrapper<BooleanState, AbstractAttribute> {
3530   using Base = StateWrapper<BooleanState, AbstractAttribute>;
3531 
3532   AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
3533 
3534   /// Statistics are tracked as part of manifest for now.
3535   void trackStatistics() const override {}
3536 
3537   /// Create an abstract attribute biew for the position \p IRP.
3538   static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP,
3539                                               Attributor &A);
3540 
3541   /// See AbstractAttribute::getName()
3542   const std::string getName() const override { return "AAFoldRuntimeCall"; }
3543 
3544   /// See AbstractAttribute::getIdAddr()
3545   const char *getIdAddr() const override { return &ID; }
3546 
3547   /// This function should return true if the type of the \p AA is
3548   /// AAFoldRuntimeCall
3549   static bool classof(const AbstractAttribute *AA) {
3550     return (AA->getIdAddr() == &ID);
3551   }
3552 
3553   static const char ID;
3554 };
3555 
3556 struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
3557   AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A)
3558       : AAFoldRuntimeCall(IRP, A) {}
3559 
3560   /// See AbstractAttribute::getAsStr()
3561   const std::string getAsStr() const override {
3562     if (!isValidState())
3563       return "<invalid>";
3564 
3565     std::string Str("simplified value: ");
3566 
3567     if (!SimplifiedValue.hasValue())
3568       return Str + std::string("none");
3569 
3570     if (!SimplifiedValue.getValue())
3571       return Str + std::string("nullptr");
3572 
3573     if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue()))
3574       return Str + std::to_string(CI->getSExtValue());
3575 
3576     return Str + std::string("unknown");
3577   }
3578 
3579   void initialize(Attributor &A) override {
3580     Function *Callee = getAssociatedFunction();
3581 
3582     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3583     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3584     assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() &&
3585            "Expected a known OpenMP runtime function");
3586 
3587     RFKind = It->getSecond();
3588 
3589     CallBase &CB = cast<CallBase>(getAssociatedValue());
3590     A.registerSimplificationCallback(
3591         IRPosition::callsite_returned(CB),
3592         [&](const IRPosition &IRP, const AbstractAttribute *AA,
3593             bool &UsedAssumedInformation) -> Optional<Value *> {
3594           assert((isValidState() || (SimplifiedValue.hasValue() &&
3595                                      SimplifiedValue.getValue() == nullptr)) &&
3596                  "Unexpected invalid state!");
3597 
3598           if (!isAtFixpoint()) {
3599             UsedAssumedInformation = true;
3600             if (AA)
3601               A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
3602           }
3603           return SimplifiedValue;
3604         });
3605   }
3606 
3607   ChangeStatus updateImpl(Attributor &A) override {
3608     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3609 
3610     switch (RFKind) {
3611     case OMPRTL___kmpc_is_spmd_exec_mode:
3612       Changed |= foldIsSPMDExecMode(A);
3613       break;
3614     case OMPRTL___kmpc_is_generic_main_thread_id:
3615       Changed |= foldIsGenericMainThread(A);
3616       break;
3617     default:
3618       llvm_unreachable("Unhandled OpenMP runtime function!");
3619     }
3620 
3621     return Changed;
3622   }
3623 
3624   ChangeStatus manifest(Attributor &A) override {
3625     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3626 
3627     if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) {
3628       Instruction &CB = *getCtxI();
3629       A.changeValueAfterManifest(CB, **SimplifiedValue);
3630       A.deleteAfterManifest(CB);
3631 
3632       LLVM_DEBUG(dbgs() << TAG << "Folding runtime call: " << CB << " with "
3633                         << **SimplifiedValue << "\n");
3634 
3635       Changed = ChangeStatus::CHANGED;
3636     }
3637 
3638     return Changed;
3639   }
3640 
3641   ChangeStatus indicatePessimisticFixpoint() override {
3642     SimplifiedValue = nullptr;
3643     return AAFoldRuntimeCall::indicatePessimisticFixpoint();
3644   }
3645 
3646 private:
3647   /// Fold __kmpc_is_spmd_exec_mode into a constant if possible.
3648   ChangeStatus foldIsSPMDExecMode(Attributor &A) {
3649     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3650 
3651     unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
3652     unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
3653     auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
3654         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
3655 
3656     if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
3657       return indicatePessimisticFixpoint();
3658 
3659     for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
3660       auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
3661                                           DepClassTy::REQUIRED);
3662 
3663       if (!AA.isValidState()) {
3664         SimplifiedValue = nullptr;
3665         return indicatePessimisticFixpoint();
3666       }
3667 
3668       if (AA.SPMDCompatibilityTracker.isAssumed()) {
3669         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3670           ++KnownSPMDCount;
3671         else
3672           ++AssumedSPMDCount;
3673       } else {
3674         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3675           ++KnownNonSPMDCount;
3676         else
3677           ++AssumedNonSPMDCount;
3678       }
3679     }
3680 
3681     if (KnownSPMDCount && KnownNonSPMDCount)
3682       return indicatePessimisticFixpoint();
3683 
3684     if (AssumedSPMDCount && AssumedNonSPMDCount)
3685       return indicatePessimisticFixpoint();
3686 
3687     auto &Ctx = getAnchorValue().getContext();
3688     if (KnownSPMDCount || AssumedSPMDCount) {
3689       assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
3690              "Expected only SPMD kernels!");
3691       // All reaching kernels are in SPMD mode. Update all function calls to
3692       // __kmpc_is_spmd_exec_mode to 1.
3693       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3694     } else if (KnownNonSPMDCount || AssumedNonSPMDCount) {
3695       assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
3696              "Expected only non-SPMD kernels!");
3697       // All reaching kernels are in non-SPMD mode. Update all function
3698       // calls to __kmpc_is_spmd_exec_mode to 0.
3699       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false);
3700     } else {
3701       // We have empty reaching kernels, therefore we cannot tell if the
3702       // associated call site can be folded. At this moment, SimplifiedValue
3703       // must be none.
3704       assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none");
3705     }
3706 
3707     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3708                                                     : ChangeStatus::CHANGED;
3709   }
3710 
3711   /// Fold __kmpc_is_generic_main_thread_id into a constant if possible.
3712   ChangeStatus foldIsGenericMainThread(Attributor &A) {
3713     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3714 
3715     CallBase &CB = cast<CallBase>(getAssociatedValue());
3716     Function *F = CB.getFunction();
3717     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
3718         *this, IRPosition::function(*F), DepClassTy::REQUIRED);
3719 
3720     if (!ExecutionDomainAA.isValidState())
3721       return indicatePessimisticFixpoint();
3722 
3723     auto &Ctx = getAnchorValue().getContext();
3724     if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB))
3725       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3726     else
3727       return indicatePessimisticFixpoint();
3728 
3729     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3730                                                     : ChangeStatus::CHANGED;
3731   }
3732 
3733   /// An optional value the associated value is assumed to fold to. That is, we
3734   /// assume the associated value (which is a call) can be replaced by this
3735   /// simplified value.
3736   Optional<Value *> SimplifiedValue;
3737 
3738   /// The runtime function kind of the callee of the associated call site.
3739   RuntimeFunction RFKind;
3740 };
3741 
3742 } // namespace
3743 
3744 void OpenMPOpt::registerAAs(bool IsModulePass) {
3745   if (SCC.empty())
3746 
3747     return;
3748   if (IsModulePass) {
3749     // Ensure we create the AAKernelInfo AAs first and without triggering an
3750     // update. This will make sure we register all value simplification
3751     // callbacks before any other AA has the chance to create an AAValueSimplify
3752     // or similar.
3753     for (Function *Kernel : OMPInfoCache.Kernels)
3754       A.getOrCreateAAFor<AAKernelInfo>(
3755           IRPosition::function(*Kernel), /* QueryingAA */ nullptr,
3756           DepClassTy::NONE, /* ForceUpdate */ false,
3757           /* UpdateAfterInit */ false);
3758 
3759     auto &IsMainRFI =
3760         OMPInfoCache.RFIs[OMPRTL___kmpc_is_generic_main_thread_id];
3761     IsMainRFI.foreachUse(SCC, [&](Use &U, Function &F) {
3762       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &IsMainRFI);
3763       if (!CI)
3764         return false;
3765       A.getOrCreateAAFor<AAFoldRuntimeCall>(
3766           IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
3767           DepClassTy::NONE, /* ForceUpdate */ false,
3768           /* UpdateAfterInit */ false);
3769       return false;
3770     });
3771 
3772     auto &IsSPMDRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_is_spmd_exec_mode];
3773     IsSPMDRFI.foreachUse(SCC, [&](Use &U, Function &) {
3774       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &IsSPMDRFI);
3775       if (!CI)
3776         return false;
3777       A.getOrCreateAAFor<AAFoldRuntimeCall>(
3778           IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
3779           DepClassTy::NONE, /* ForceUpdate */ false,
3780           /* UpdateAfterInit */ false);
3781       return false;
3782     });
3783   }
3784 
3785   // Create CallSite AA for all Getters.
3786   for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
3787     auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
3788 
3789     auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
3790 
3791     auto CreateAA = [&](Use &U, Function &Caller) {
3792       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
3793       if (!CI)
3794         return false;
3795 
3796       auto &CB = cast<CallBase>(*CI);
3797 
3798       IRPosition CBPos = IRPosition::callsite_function(CB);
3799       A.getOrCreateAAFor<AAICVTracker>(CBPos);
3800       return false;
3801     };
3802 
3803     GetterRFI.foreachUse(SCC, CreateAA);
3804   }
3805   auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
3806   auto CreateAA = [&](Use &U, Function &F) {
3807     A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F));
3808     return false;
3809   };
3810   GlobalizationRFI.foreachUse(SCC, CreateAA);
3811 
3812   // Create an ExecutionDomain AA for every function and a HeapToStack AA for
3813   // every function if there is a device kernel.
3814   for (auto *F : SCC) {
3815     if (!F->isDeclaration())
3816       A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F));
3817     if (isOpenMPDevice(M))
3818       A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F));
3819   }
3820 }
3821 
3822 const char AAICVTracker::ID = 0;
3823 const char AAKernelInfo::ID = 0;
3824 const char AAExecutionDomain::ID = 0;
3825 const char AAHeapToShared::ID = 0;
3826 const char AAFoldRuntimeCall::ID = 0;
3827 
3828 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
3829                                               Attributor &A) {
3830   AAICVTracker *AA = nullptr;
3831   switch (IRP.getPositionKind()) {
3832   case IRPosition::IRP_INVALID:
3833   case IRPosition::IRP_FLOAT:
3834   case IRPosition::IRP_ARGUMENT:
3835   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3836     llvm_unreachable("ICVTracker can only be created for function position!");
3837   case IRPosition::IRP_RETURNED:
3838     AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
3839     break;
3840   case IRPosition::IRP_CALL_SITE_RETURNED:
3841     AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
3842     break;
3843   case IRPosition::IRP_CALL_SITE:
3844     AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
3845     break;
3846   case IRPosition::IRP_FUNCTION:
3847     AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
3848     break;
3849   }
3850 
3851   return *AA;
3852 }
3853 
3854 AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP,
3855                                                         Attributor &A) {
3856   AAExecutionDomainFunction *AA = nullptr;
3857   switch (IRP.getPositionKind()) {
3858   case IRPosition::IRP_INVALID:
3859   case IRPosition::IRP_FLOAT:
3860   case IRPosition::IRP_ARGUMENT:
3861   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3862   case IRPosition::IRP_RETURNED:
3863   case IRPosition::IRP_CALL_SITE_RETURNED:
3864   case IRPosition::IRP_CALL_SITE:
3865     llvm_unreachable(
3866         "AAExecutionDomain can only be created for function position!");
3867   case IRPosition::IRP_FUNCTION:
3868     AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A);
3869     break;
3870   }
3871 
3872   return *AA;
3873 }
3874 
3875 AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP,
3876                                                   Attributor &A) {
3877   AAHeapToSharedFunction *AA = nullptr;
3878   switch (IRP.getPositionKind()) {
3879   case IRPosition::IRP_INVALID:
3880   case IRPosition::IRP_FLOAT:
3881   case IRPosition::IRP_ARGUMENT:
3882   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3883   case IRPosition::IRP_RETURNED:
3884   case IRPosition::IRP_CALL_SITE_RETURNED:
3885   case IRPosition::IRP_CALL_SITE:
3886     llvm_unreachable(
3887         "AAHeapToShared can only be created for function position!");
3888   case IRPosition::IRP_FUNCTION:
3889     AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A);
3890     break;
3891   }
3892 
3893   return *AA;
3894 }
3895 
3896 AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP,
3897                                               Attributor &A) {
3898   AAKernelInfo *AA = nullptr;
3899   switch (IRP.getPositionKind()) {
3900   case IRPosition::IRP_INVALID:
3901   case IRPosition::IRP_FLOAT:
3902   case IRPosition::IRP_ARGUMENT:
3903   case IRPosition::IRP_RETURNED:
3904   case IRPosition::IRP_CALL_SITE_RETURNED:
3905   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3906     llvm_unreachable("KernelInfo can only be created for function position!");
3907   case IRPosition::IRP_CALL_SITE:
3908     AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A);
3909     break;
3910   case IRPosition::IRP_FUNCTION:
3911     AA = new (A.Allocator) AAKernelInfoFunction(IRP, A);
3912     break;
3913   }
3914 
3915   return *AA;
3916 }
3917 
3918 AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP,
3919                                                         Attributor &A) {
3920   AAFoldRuntimeCall *AA = nullptr;
3921   switch (IRP.getPositionKind()) {
3922   case IRPosition::IRP_INVALID:
3923   case IRPosition::IRP_FLOAT:
3924   case IRPosition::IRP_ARGUMENT:
3925   case IRPosition::IRP_RETURNED:
3926   case IRPosition::IRP_FUNCTION:
3927   case IRPosition::IRP_CALL_SITE:
3928   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3929     llvm_unreachable("KernelInfo can only be created for call site position!");
3930   case IRPosition::IRP_CALL_SITE_RETURNED:
3931     AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A);
3932     break;
3933   }
3934 
3935   return *AA;
3936 }
3937 
3938 PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) {
3939   if (!containsOpenMP(M))
3940     return PreservedAnalyses::all();
3941   if (DisableOpenMPOptimizations)
3942     return PreservedAnalyses::all();
3943 
3944   FunctionAnalysisManager &FAM =
3945       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3946   KernelSet Kernels = getDeviceKernels(M);
3947 
3948   auto IsCalled = [&](Function &F) {
3949     if (Kernels.contains(&F))
3950       return true;
3951     for (const User *U : F.users())
3952       if (!isa<BlockAddress>(U))
3953         return true;
3954     return false;
3955   };
3956 
3957   auto EmitRemark = [&](Function &F) {
3958     auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3959     ORE.emit([&]() {
3960       OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F);
3961       return ORA << "Could not internalize function. "
3962                  << "Some optimizations may not be possible.";
3963     });
3964   };
3965 
3966   // Create internal copies of each function if this is a kernel Module. This
3967   // allows iterprocedural passes to see every call edge.
3968   DenseSet<const Function *> InternalizedFuncs;
3969   if (isOpenMPDevice(M))
3970     for (Function &F : M)
3971       if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) &&
3972           !DisableInternalization) {
3973         if (Attributor::internalizeFunction(F, /* Force */ true)) {
3974           InternalizedFuncs.insert(&F);
3975         } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) {
3976           EmitRemark(F);
3977         }
3978       }
3979 
3980   // Look at every function in the Module unless it was internalized.
3981   SmallVector<Function *, 16> SCC;
3982   for (Function &F : M)
3983     if (!F.isDeclaration() && !InternalizedFuncs.contains(&F))
3984       SCC.push_back(&F);
3985 
3986   if (SCC.empty())
3987     return PreservedAnalyses::all();
3988 
3989   AnalysisGetter AG(FAM);
3990 
3991   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
3992     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
3993   };
3994 
3995   BumpPtrAllocator Allocator;
3996   CallGraphUpdater CGUpdater;
3997 
3998   SetVector<Function *> Functions(SCC.begin(), SCC.end());
3999   OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels);
4000 
4001   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4002   Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false,
4003                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4004 
4005   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4006   bool Changed = OMPOpt.run(true);
4007   if (Changed)
4008     return PreservedAnalyses::none();
4009 
4010   return PreservedAnalyses::all();
4011 }
4012 
4013 PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C,
4014                                           CGSCCAnalysisManager &AM,
4015                                           LazyCallGraph &CG,
4016                                           CGSCCUpdateResult &UR) {
4017   if (!containsOpenMP(*C.begin()->getFunction().getParent()))
4018     return PreservedAnalyses::all();
4019   if (DisableOpenMPOptimizations)
4020     return PreservedAnalyses::all();
4021 
4022   SmallVector<Function *, 16> SCC;
4023   // If there are kernels in the module, we have to run on all SCC's.
4024   for (LazyCallGraph::Node &N : C) {
4025     Function *Fn = &N.getFunction();
4026     SCC.push_back(Fn);
4027   }
4028 
4029   if (SCC.empty())
4030     return PreservedAnalyses::all();
4031 
4032   Module &M = *C.begin()->getFunction().getParent();
4033 
4034   KernelSet Kernels = getDeviceKernels(M);
4035 
4036   FunctionAnalysisManager &FAM =
4037       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
4038 
4039   AnalysisGetter AG(FAM);
4040 
4041   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
4042     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
4043   };
4044 
4045   BumpPtrAllocator Allocator;
4046   CallGraphUpdater CGUpdater;
4047   CGUpdater.initialize(CG, C, AM, UR);
4048 
4049   SetVector<Function *> Functions(SCC.begin(), SCC.end());
4050   OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
4051                                 /*CGSCC*/ Functions, Kernels);
4052 
4053   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4054   Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4055                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4056 
4057   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4058   bool Changed = OMPOpt.run(false);
4059   if (Changed)
4060     return PreservedAnalyses::none();
4061 
4062   return PreservedAnalyses::all();
4063 }
4064 
4065 namespace {
4066 
4067 struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass {
4068   CallGraphUpdater CGUpdater;
4069   static char ID;
4070 
4071   OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) {
4072     initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
4073   }
4074 
4075   void getAnalysisUsage(AnalysisUsage &AU) const override {
4076     CallGraphSCCPass::getAnalysisUsage(AU);
4077   }
4078 
4079   bool runOnSCC(CallGraphSCC &CGSCC) override {
4080     if (!containsOpenMP(CGSCC.getCallGraph().getModule()))
4081       return false;
4082     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
4083       return false;
4084 
4085     SmallVector<Function *, 16> SCC;
4086     // If there are kernels in the module, we have to run on all SCC's.
4087     for (CallGraphNode *CGN : CGSCC) {
4088       Function *Fn = CGN->getFunction();
4089       if (!Fn || Fn->isDeclaration())
4090         continue;
4091       SCC.push_back(Fn);
4092     }
4093 
4094     if (SCC.empty())
4095       return false;
4096 
4097     Module &M = CGSCC.getCallGraph().getModule();
4098     KernelSet Kernels = getDeviceKernels(M);
4099 
4100     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
4101     CGUpdater.initialize(CG, CGSCC);
4102 
4103     // Maintain a map of functions to avoid rebuilding the ORE
4104     DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
4105     auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
4106       std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
4107       if (!ORE)
4108         ORE = std::make_unique<OptimizationRemarkEmitter>(F);
4109       return *ORE;
4110     };
4111 
4112     AnalysisGetter AG;
4113     SetVector<Function *> Functions(SCC.begin(), SCC.end());
4114     BumpPtrAllocator Allocator;
4115     OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG,
4116                                   Allocator,
4117                                   /*CGSCC*/ Functions, Kernels);
4118 
4119     unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4120     Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4121                  MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4122 
4123     OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4124     return OMPOpt.run(false);
4125   }
4126 
4127   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
4128 };
4129 
4130 } // end anonymous namespace
4131 
4132 KernelSet llvm::omp::getDeviceKernels(Module &M) {
4133   // TODO: Create a more cross-platform way of determining device kernels.
4134   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
4135   KernelSet Kernels;
4136 
4137   if (!MD)
4138     return Kernels;
4139 
4140   for (auto *Op : MD->operands()) {
4141     if (Op->getNumOperands() < 2)
4142       continue;
4143     MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
4144     if (!KindID || KindID->getString() != "kernel")
4145       continue;
4146 
4147     Function *KernelFn =
4148         mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
4149     if (!KernelFn)
4150       continue;
4151 
4152     ++NumOpenMPTargetRegionKernels;
4153 
4154     Kernels.insert(KernelFn);
4155   }
4156 
4157   return Kernels;
4158 }
4159 
4160 bool llvm::omp::containsOpenMP(Module &M) {
4161   Metadata *MD = M.getModuleFlag("openmp");
4162   if (!MD)
4163     return false;
4164 
4165   return true;
4166 }
4167 
4168 bool llvm::omp::isOpenMPDevice(Module &M) {
4169   Metadata *MD = M.getModuleFlag("openmp-device");
4170   if (!MD)
4171     return false;
4172 
4173   return true;
4174 }
4175 
4176 char OpenMPOptCGSCCLegacyPass::ID = 0;
4177 
4178 INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4179                       "OpenMP specific optimizations", false, false)
4180 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
4181 INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4182                     "OpenMP specific optimizations", false, false)
4183 
4184 Pass *llvm::createOpenMPOptCGSCCLegacyPass() {
4185   return new OpenMPOptCGSCCLegacyPass();
4186 }
4187