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