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