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