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