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 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/OpenMPOpt.h"
16 
17 #include "llvm/ADT/EnumeratedArray.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Frontend/OpenMP/OMPConstants.h"
22 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Transforms/Utils/CallGraphUpdater.h"
28 
29 using namespace llvm;
30 using namespace omp;
31 using namespace types;
32 
33 #define DEBUG_TYPE "openmp-opt"
34 
35 static cl::opt<bool> DisableOpenMPOptimizations(
36     "openmp-opt-disable", cl::ZeroOrMore,
37     cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
38     cl::init(false));
39 
40 STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
41           "Number of OpenMP runtime calls deduplicated");
42 STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
43           "Number of OpenMP runtime functions identified");
44 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
45           "Number of OpenMP runtime function uses identified");
46 
47 #if !defined(NDEBUG)
48 static constexpr auto TAG = "[" DEBUG_TYPE "]";
49 #endif
50 
51 namespace {
52 struct OpenMPOpt {
53 
54   OpenMPOpt(SmallPtrSetImpl<Function *> &SCC,
55             SmallPtrSetImpl<Function *> &ModuleSlice,
56             CallGraphUpdater &CGUpdater)
57       : M(*(*SCC.begin())->getParent()), SCC(SCC), ModuleSlice(ModuleSlice),
58         OMPBuilder(M), CGUpdater(CGUpdater) {
59     initializeTypes(M);
60     initializeRuntimeFunctions();
61     OMPBuilder.initialize();
62   }
63 
64   /// Generic information that describes a runtime function
65   struct RuntimeFunctionInfo {
66     /// The kind, as described by the RuntimeFunction enum.
67     RuntimeFunction Kind;
68 
69     /// The name of the function.
70     StringRef Name;
71 
72     /// Flag to indicate a variadic function.
73     bool IsVarArg;
74 
75     /// The return type of the function.
76     Type *ReturnType;
77 
78     /// The argument types of the function.
79     SmallVector<Type *, 8> ArgumentTypes;
80 
81     /// The declaration if available.
82     Function *Declaration = nullptr;
83 
84     /// Uses of this runtime function per function containing the use.
85     DenseMap<Function *, SmallPtrSet<Use *, 16>> UsesMap;
86 
87     /// Return the number of arguments (or the minimal number for variadic
88     /// functions).
89     size_t getNumArgs() const { return ArgumentTypes.size(); }
90 
91     /// Run the callback \p CB on each use and forget the use if the result is
92     /// true. The callback will be fed the function in which the use was
93     /// encountered as second argument.
94     void foreachUse(function_ref<bool(Use &, Function &)> CB) {
95       SmallVector<Use *, 8> ToBeDeleted;
96       for (auto &It : UsesMap) {
97         ToBeDeleted.clear();
98         for (Use *U : It.second)
99           if (CB(*U, *It.first))
100             ToBeDeleted.push_back(U);
101         for (Use *U : ToBeDeleted)
102           It.second.erase(U);
103       }
104     }
105   };
106 
107   /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
108   bool run() {
109     bool Changed = false;
110 
111     LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
112                       << " functions in a slice with " << ModuleSlice.size()
113                       << " functions\n");
114 
115     Changed |= deduplicateRuntimeCalls();
116     Changed |= deleteParallelRegions();
117 
118     return Changed;
119   }
120 
121 private:
122   /// Try to delete parallel regions if possible.
123   bool deleteParallelRegions() {
124     const unsigned CallbackCalleeOperand = 2;
125 
126     RuntimeFunctionInfo &RFI = RFIs[OMPRTL___kmpc_fork_call];
127     if (!RFI.Declaration)
128       return false;
129 
130     bool Changed = false;
131     auto DeleteCallCB = [&](Use &U, Function &) {
132       CallInst *CI = getCallIfRegularCall(U);
133       if (!CI)
134         return false;
135       auto *Fn = dyn_cast<Function>(
136           CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
137       if (!Fn)
138         return false;
139       if (!Fn->onlyReadsMemory())
140         return false;
141       if (!Fn->hasFnAttribute(Attribute::WillReturn))
142         return false;
143 
144       LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
145                         << CI->getCaller()->getName() << "\n");
146       CGUpdater.removeCallSite(*CI);
147       CI->eraseFromParent();
148       Changed = true;
149       return true;
150     };
151 
152     RFI.foreachUse(DeleteCallCB);
153 
154     return Changed;
155   }
156 
157   /// Try to eliminiate runtime calls by reusing existing ones.
158   bool deduplicateRuntimeCalls() {
159     bool Changed = false;
160 
161     RuntimeFunction DeduplicableRuntimeCallIDs[] = {
162         OMPRTL_omp_get_num_threads,
163         OMPRTL_omp_in_parallel,
164         OMPRTL_omp_get_cancellation,
165         OMPRTL_omp_get_thread_limit,
166         OMPRTL_omp_get_supported_active_levels,
167         OMPRTL_omp_get_level,
168         OMPRTL_omp_get_ancestor_thread_num,
169         OMPRTL_omp_get_team_size,
170         OMPRTL_omp_get_active_level,
171         OMPRTL_omp_in_final,
172         OMPRTL_omp_get_proc_bind,
173         OMPRTL_omp_get_num_places,
174         OMPRTL_omp_get_num_procs,
175         OMPRTL_omp_get_place_num,
176         OMPRTL_omp_get_partition_num_places,
177         OMPRTL_omp_get_partition_place_nums};
178 
179     // Global-tid is handled separatly.
180     SmallSetVector<Value *, 16> GTIdArgs;
181     collectGlobalThreadIdArguments(GTIdArgs);
182     LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
183                       << " global thread ID arguments\n");
184 
185     for (Function *F : SCC) {
186       for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
187         deduplicateRuntimeCalls(*F, RFIs[DeduplicableRuntimeCallID]);
188 
189       // __kmpc_global_thread_num is special as we can replace it with an
190       // argument in enough cases to make it worth trying.
191       Value *GTIdArg = nullptr;
192       for (Argument &Arg : F->args())
193         if (GTIdArgs.count(&Arg)) {
194           GTIdArg = &Arg;
195           break;
196         }
197       Changed |= deduplicateRuntimeCalls(
198           *F, RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
199     }
200 
201     return Changed;
202   }
203 
204   static Value *combinedIdentStruct(Value *Ident0, Value *Ident1,
205                                     bool GlobalOnly) {
206     // TODO: Figure out how to actually combine multiple debug locations. For
207     //       now we just keep the first we find.
208     if (Ident0)
209       return Ident0;
210     if (!GlobalOnly || isa<GlobalValue>(Ident1))
211       return Ident1;
212     return nullptr;
213   }
214 
215   /// Return an `struct ident_t*` value that represents the ones used in the
216   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
217   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
218   /// return value we create one from scratch. We also do not yet combine
219   /// information, e.g., the source locations, see combinedIdentStruct.
220   Value *getCombinedIdentFromCallUsesIn(RuntimeFunctionInfo &RFI, Function &F,
221                                         bool GlobalOnly) {
222     Value *Ident = nullptr;
223     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
224       CallInst *CI = getCallIfRegularCall(U, &RFI);
225       if (!CI || &F != &Caller)
226         return false;
227       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
228                                   /* GlobalOnly */ true);
229       return false;
230     };
231     RFI.foreachUse(CombineIdentStruct);
232 
233     if (!Ident) {
234       // The IRBuilder uses the insertion block to get to the module, this is
235       // unfortunate but we work around it for now.
236       if (!OMPBuilder.getInsertionPoint().getBlock())
237         OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
238             &F.getEntryBlock(), F.getEntryBlock().begin()));
239       // Create a fallback location if non was found.
240       // TODO: Use the debug locations of the calls instead.
241       Constant *Loc = OMPBuilder.getOrCreateDefaultSrcLocStr();
242       Ident = OMPBuilder.getOrCreateIdent(Loc);
243     }
244     return Ident;
245   }
246 
247   /// Try to eliminiate calls of \p RFI in \p F by reusing an existing one or
248   /// \p ReplVal if given.
249   bool deduplicateRuntimeCalls(Function &F, RuntimeFunctionInfo &RFI,
250                                Value *ReplVal = nullptr) {
251     auto &Uses = RFI.UsesMap[&F];
252     if (Uses.size() + (ReplVal != nullptr) < 2)
253       return false;
254 
255     LLVM_DEBUG(dbgs() << TAG << "Deduplicate " << Uses.size() << " uses of "
256                       << RFI.Name
257                       << (ReplVal ? " with an existing value\n" : "\n")
258                       << "\n");
259     assert((!ReplVal || (isa<Argument>(ReplVal) &&
260                          cast<Argument>(ReplVal)->getParent() == &F)) &&
261            "Unexpected replacement value!");
262 
263     // TODO: Use dominance to find a good position instead.
264     auto CanBeMoved = [](CallBase &CB) {
265       unsigned NumArgs = CB.getNumArgOperands();
266       if (NumArgs == 0)
267         return true;
268       if (CB.getArgOperand(0)->getType() != IdentPtr)
269         return false;
270       for (unsigned u = 1; u < NumArgs; ++u)
271         if (isa<Instruction>(CB.getArgOperand(u)))
272           return false;
273       return true;
274     };
275 
276     if (!ReplVal) {
277       for (Use *U : Uses)
278         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
279           if (!CanBeMoved(*CI))
280             continue;
281           CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
282           ReplVal = CI;
283           break;
284         }
285       if (!ReplVal)
286         return false;
287     }
288 
289     // If we use a call as a replacement value we need to make sure the ident is
290     // valid at the new location. For now we just pick a global one, either
291     // existing and used by one of the calls, or created from scratch.
292     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
293       if (CI->getNumArgOperands() > 0 &&
294           CI->getArgOperand(0)->getType() == IdentPtr) {
295         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
296                                                       /* GlobalOnly */ true);
297         CI->setArgOperand(0, Ident);
298       }
299     }
300 
301     bool Changed = false;
302     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
303       CallInst *CI = getCallIfRegularCall(U, &RFI);
304       if (!CI || CI == ReplVal || &F != &Caller)
305         return false;
306       assert(CI->getCaller() == &F && "Unexpected call!");
307       CGUpdater.removeCallSite(*CI);
308       CI->replaceAllUsesWith(ReplVal);
309       CI->eraseFromParent();
310       ++NumOpenMPRuntimeCallsDeduplicated;
311       Changed = true;
312       return true;
313     };
314     RFI.foreachUse(ReplaceAndDeleteCB);
315 
316     return Changed;
317   }
318 
319   /// Collect arguments that represent the global thread id in \p GTIdArgs.
320   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
321     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
322     //       initialization. We could define an AbstractAttribute instead and
323     //       run the Attributor here once it can be run as an SCC pass.
324 
325     // Helper to check the argument \p ArgNo at all call sites of \p F for
326     // a GTId.
327     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
328       if (!F.hasLocalLinkage())
329         return false;
330       for (Use &U : F.uses()) {
331         if (CallInst *CI = getCallIfRegularCall(U)) {
332           Value *ArgOp = CI->getArgOperand(ArgNo);
333           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
334               getCallIfRegularCall(*ArgOp,
335                                    &RFIs[OMPRTL___kmpc_global_thread_num]))
336             continue;
337         }
338         return false;
339       }
340       return true;
341     };
342 
343     // Helper to identify uses of a GTId as GTId arguments.
344     auto AddUserArgs = [&](Value &GTId) {
345       for (Use &U : GTId.uses())
346         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
347           if (CI->isArgOperand(&U))
348             if (Function *Callee = CI->getCalledFunction())
349               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
350                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
351     };
352 
353     // The argument users of __kmpc_global_thread_num calls are GTIds.
354     RuntimeFunctionInfo &GlobThreadNumRFI =
355         RFIs[OMPRTL___kmpc_global_thread_num];
356     for (auto &It : GlobThreadNumRFI.UsesMap)
357       for (Use *U : It.second)
358         if (CallInst *CI = getCallIfRegularCall(*U, &GlobThreadNumRFI))
359           AddUserArgs(*CI);
360 
361     // Transitively search for more arguments by looking at the users of the
362     // ones we know already. During the search the GTIdArgs vector is extended
363     // so we cannot cache the size nor can we use a range based for.
364     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
365       AddUserArgs(*GTIdArgs[u]);
366   }
367 
368   /// Return the call if \p U is a callee use in a regular call. If \p RFI is
369   /// given it has to be the callee or a nullptr is returned.
370   CallInst *getCallIfRegularCall(Use &U, RuntimeFunctionInfo *RFI = nullptr) {
371     CallInst *CI = dyn_cast<CallInst>(U.getUser());
372     if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
373         (!RFI || CI->getCalledFunction() == RFI->Declaration))
374       return CI;
375     return nullptr;
376   }
377 
378   /// Return the call if \p V is a regular call. If \p RFI is given it has to be
379   /// the callee or a nullptr is returned.
380   CallInst *getCallIfRegularCall(Value &V, RuntimeFunctionInfo *RFI = nullptr) {
381     CallInst *CI = dyn_cast<CallInst>(&V);
382     if (CI && !CI->hasOperandBundles() &&
383         (!RFI || CI->getCalledFunction() == RFI->Declaration))
384       return CI;
385     return nullptr;
386   }
387 
388   /// Returns true if the function declaration \p F matches the runtime
389   /// function types, that is, return type \p RTFRetType, and argument types
390   /// \p RTFArgTypes.
391   static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
392                                   SmallVector<Type *, 8> &RTFArgTypes) {
393     // TODO: We should output information to the user (under debug output
394     //       and via remarks).
395 
396     if (!F)
397       return false;
398     if (F->getReturnType() != RTFRetType)
399       return false;
400     if (F->arg_size() != RTFArgTypes.size())
401       return false;
402 
403     auto RTFTyIt = RTFArgTypes.begin();
404     for (Argument &Arg : F->args()) {
405       if (Arg.getType() != *RTFTyIt)
406         return false;
407 
408       ++RTFTyIt;
409     }
410 
411     return true;
412   }
413 
414   /// Helper to initialize all runtime function information for those defined in
415   /// OpenMPKinds.def.
416   void initializeRuntimeFunctions() {
417     // Helper to collect all uses of the decleration in the UsesMap.
418     auto CollectUses = [&](RuntimeFunctionInfo &RFI) {
419       unsigned NumUses = 0;
420       if (!RFI.Declaration)
421         return NumUses;
422       OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
423 
424       NumOpenMPRuntimeFunctionsIdentified += 1;
425       NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
426 
427       // TODO: We directly convert uses into proper calls and unknown uses.
428       for (Use &U : RFI.Declaration->uses()) {
429         if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
430           if (ModuleSlice.count(UserI->getFunction())) {
431             RFI.UsesMap[UserI->getFunction()].insert(&U);
432             ++NumUses;
433           }
434         } else {
435           RFI.UsesMap[nullptr].insert(&U);
436           ++NumUses;
437         }
438       }
439       return NumUses;
440     };
441 
442 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...)                     \
443   {                                                                            \
444     SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__});                           \
445     Function *F = M.getFunction(_Name);                                        \
446     if (declMatchesRTFTypes(F, _ReturnType , ArgsTypes)) {                     \
447       auto &RFI = RFIs[_Enum];                                                 \
448       RFI.Kind = _Enum;                                                        \
449       RFI.Name = _Name;                                                        \
450       RFI.IsVarArg = _IsVarArg;                                                \
451       RFI.ReturnType = _ReturnType;                                            \
452       RFI.ArgumentTypes = std::move(ArgsTypes);                                \
453       RFI.Declaration = F;                                                     \
454       unsigned NumUses = CollectUses(RFI);                                     \
455       (void)NumUses;                                                           \
456       LLVM_DEBUG({                                                             \
457         dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not")           \
458               << " found\n";                                                   \
459         if (RFI.Declaration)                                                   \
460           dbgs() << TAG << "-> got " << NumUses << " uses in "                 \
461                 << RFI.UsesMap.size() << " different functions.\n";            \
462       });                                                                      \
463     }                                                                          \
464   }
465 #include "llvm/Frontend/OpenMP/OMPKinds.def"
466 
467     // TODO: We should attach the attributes defined in OMPKinds.def.
468   }
469 
470   /// The underyling module.
471   Module &M;
472 
473   /// The SCC we are operating on.
474   SmallPtrSetImpl<Function *> &SCC;
475 
476   /// The slice of the module we are allowed to look at.
477   SmallPtrSetImpl<Function *> &ModuleSlice;
478 
479   /// An OpenMP-IR-Builder instance
480   OpenMPIRBuilder OMPBuilder;
481 
482   /// Callback to update the call graph, the first argument is a removed call,
483   /// the second an optional replacement call.
484   CallGraphUpdater &CGUpdater;
485 
486   /// Map from runtime function kind to the runtime function description.
487   EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
488                   RuntimeFunction::OMPRTL___last>
489       RFIs;
490 };
491 } // namespace
492 
493 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C,
494                                      CGSCCAnalysisManager &AM,
495                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
496   if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule))
497     return PreservedAnalyses::all();
498 
499   if (DisableOpenMPOptimizations)
500     return PreservedAnalyses::all();
501 
502   SmallPtrSet<Function *, 16> SCC;
503   for (LazyCallGraph::Node &N : C)
504     SCC.insert(&N.getFunction());
505 
506   if (SCC.empty())
507     return PreservedAnalyses::all();
508 
509   CallGraphUpdater CGUpdater;
510   CGUpdater.initialize(CG, C, AM, UR);
511   // TODO: Compute the module slice we are allowed to look at.
512   OpenMPOpt OMPOpt(SCC, SCC, CGUpdater);
513   bool Changed = OMPOpt.run();
514   (void)Changed;
515   return PreservedAnalyses::all();
516 }
517 
518 namespace {
519 
520 struct OpenMPOptLegacyPass : public CallGraphSCCPass {
521   CallGraphUpdater CGUpdater;
522   OpenMPInModule OMPInModule;
523   static char ID;
524 
525   OpenMPOptLegacyPass() : CallGraphSCCPass(ID) {
526     initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry());
527   }
528 
529   void getAnalysisUsage(AnalysisUsage &AU) const override {
530     CallGraphSCCPass::getAnalysisUsage(AU);
531   }
532 
533   bool doInitialization(CallGraph &CG) override {
534     // Disable the pass if there is no OpenMP (runtime call) in the module.
535     containsOpenMP(CG.getModule(), OMPInModule);
536     return false;
537   }
538 
539   bool runOnSCC(CallGraphSCC &CGSCC) override {
540     if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule))
541       return false;
542     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
543       return false;
544 
545     SmallPtrSet<Function *, 16> SCC;
546     for (CallGraphNode *CGN : CGSCC)
547       if (Function *Fn = CGN->getFunction())
548         if (!Fn->isDeclaration())
549           SCC.insert(Fn);
550 
551     if (SCC.empty())
552       return false;
553 
554     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
555     CGUpdater.initialize(CG, CGSCC);
556 
557     // TODO: Compute the module slice we are allowed to look at.
558     OpenMPOpt OMPOpt(SCC, SCC, CGUpdater);
559     return OMPOpt.run();
560   }
561 
562   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
563 };
564 
565 } // end anonymous namespace
566 
567 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) {
568   if (OMPInModule.isKnown())
569     return OMPInModule;
570 
571 #define OMP_RTL(_Enum, _Name, ...)                                             \
572   if (M.getFunction(_Name))                                                    \
573     return OMPInModule = true;
574 #include "llvm/Frontend/OpenMP/OMPKinds.def"
575   return OMPInModule = false;
576 }
577 
578 char OpenMPOptLegacyPass::ID = 0;
579 
580 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt",
581                       "OpenMP specific optimizations", false, false)
582 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
583 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt",
584                     "OpenMP specific optimizations", false, false)
585 
586 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); }
587