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