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