1 //===- Inliner.cpp - Code common to all inliners --------------------------===//
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 // This file implements the mechanics required to implement inlining without
10 // missing any calls and updating the call graph.  The decisions of which calls
11 // are profitable to inline are implemented elsewhere.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/Inliner.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/AssumptionCache.h"
27 #include "llvm/Analysis/BasicAliasAnalysis.h"
28 #include "llvm/Analysis/BlockFrequencyInfo.h"
29 #include "llvm/Analysis/CGSCCPassManager.h"
30 #include "llvm/Analysis/CallGraph.h"
31 #include "llvm/Analysis/GlobalsModRef.h"
32 #include "llvm/Analysis/InlineAdvisor.h"
33 #include "llvm/Analysis/InlineCost.h"
34 #include "llvm/Analysis/LazyCallGraph.h"
35 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/TargetTransformInfo.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/DiagnosticInfo.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InstIterator.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/PassManager.h"
53 #include "llvm/IR/User.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
61 #include "llvm/Transforms/Utils/Cloning.h"
62 #include "llvm/Transforms/Utils/ImportedFunctionsInliningStatistics.h"
63 #include "llvm/Transforms/Utils/Local.h"
64 #include "llvm/Transforms/Utils/ModuleUtils.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <functional>
68 #include <sstream>
69 #include <tuple>
70 #include <utility>
71 #include <vector>
72 
73 using namespace llvm;
74 
75 #define DEBUG_TYPE "inline"
76 
77 STATISTIC(NumInlined, "Number of functions inlined");
78 STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
79 STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
80 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
81 
82 /// Flag to disable manual alloca merging.
83 ///
84 /// Merging of allocas was originally done as a stack-size saving technique
85 /// prior to LLVM's code generator having support for stack coloring based on
86 /// lifetime markers. It is now in the process of being removed. To experiment
87 /// with disabling it and relying fully on lifetime marker based stack
88 /// coloring, you can pass this flag to LLVM.
89 static cl::opt<bool>
90     DisableInlinedAllocaMerging("disable-inlined-alloca-merging",
91                                 cl::init(false), cl::Hidden);
92 
93 namespace {
94 
95 enum class InlinerFunctionImportStatsOpts {
96   No = 0,
97   Basic = 1,
98   Verbose = 2,
99 };
100 
101 } // end anonymous namespace
102 
103 static cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats(
104     "inliner-function-import-stats",
105     cl::init(InlinerFunctionImportStatsOpts::No),
106     cl::values(clEnumValN(InlinerFunctionImportStatsOpts::Basic, "basic",
107                           "basic statistics"),
108                clEnumValN(InlinerFunctionImportStatsOpts::Verbose, "verbose",
109                           "printing of statistics for each inlined function")),
110     cl::Hidden, cl::desc("Enable inliner stats for imported functions"));
111 
112 LegacyInlinerBase::LegacyInlinerBase(char &ID) : CallGraphSCCPass(ID) {}
113 
114 LegacyInlinerBase::LegacyInlinerBase(char &ID, bool InsertLifetime)
115     : CallGraphSCCPass(ID), InsertLifetime(InsertLifetime) {}
116 
117 /// For this class, we declare that we require and preserve the call graph.
118 /// If the derived class implements this method, it should
119 /// always explicitly call the implementation here.
120 void LegacyInlinerBase::getAnalysisUsage(AnalysisUsage &AU) const {
121   AU.addRequired<AssumptionCacheTracker>();
122   AU.addRequired<ProfileSummaryInfoWrapperPass>();
123   AU.addRequired<TargetLibraryInfoWrapperPass>();
124   getAAResultsAnalysisUsage(AU);
125   CallGraphSCCPass::getAnalysisUsage(AU);
126 }
127 
128 using InlinedArrayAllocasTy = DenseMap<ArrayType *, std::vector<AllocaInst *>>;
129 
130 /// Look at all of the allocas that we inlined through this call site.  If we
131 /// have already inlined other allocas through other calls into this function,
132 /// then we know that they have disjoint lifetimes and that we can merge them.
133 ///
134 /// There are many heuristics possible for merging these allocas, and the
135 /// different options have different tradeoffs.  One thing that we *really*
136 /// don't want to hurt is SRoA: once inlining happens, often allocas are no
137 /// longer address taken and so they can be promoted.
138 ///
139 /// Our "solution" for that is to only merge allocas whose outermost type is an
140 /// array type.  These are usually not promoted because someone is using a
141 /// variable index into them.  These are also often the most important ones to
142 /// merge.
143 ///
144 /// A better solution would be to have real memory lifetime markers in the IR
145 /// and not have the inliner do any merging of allocas at all.  This would
146 /// allow the backend to do proper stack slot coloring of all allocas that
147 /// *actually make it to the backend*, which is really what we want.
148 ///
149 /// Because we don't have this information, we do this simple and useful hack.
150 static void mergeInlinedArrayAllocas(Function *Caller, InlineFunctionInfo &IFI,
151                                      InlinedArrayAllocasTy &InlinedArrayAllocas,
152                                      int InlineHistory) {
153   SmallPtrSet<AllocaInst *, 16> UsedAllocas;
154 
155   // When processing our SCC, check to see if the call site was inlined from
156   // some other call site.  For example, if we're processing "A" in this code:
157   //   A() { B() }
158   //   B() { x = alloca ... C() }
159   //   C() { y = alloca ... }
160   // Assume that C was not inlined into B initially, and so we're processing A
161   // and decide to inline B into A.  Doing this makes an alloca available for
162   // reuse and makes a callsite (C) available for inlining.  When we process
163   // the C call site we don't want to do any alloca merging between X and Y
164   // because their scopes are not disjoint.  We could make this smarter by
165   // keeping track of the inline history for each alloca in the
166   // InlinedArrayAllocas but this isn't likely to be a significant win.
167   if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
168     return;
169 
170   // Loop over all the allocas we have so far and see if they can be merged with
171   // a previously inlined alloca.  If not, remember that we had it.
172   for (unsigned AllocaNo = 0, E = IFI.StaticAllocas.size(); AllocaNo != E;
173        ++AllocaNo) {
174     AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
175 
176     // Don't bother trying to merge array allocations (they will usually be
177     // canonicalized to be an allocation *of* an array), or allocations whose
178     // type is not itself an array (because we're afraid of pessimizing SRoA).
179     ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
180     if (!ATy || AI->isArrayAllocation())
181       continue;
182 
183     // Get the list of all available allocas for this array type.
184     std::vector<AllocaInst *> &AllocasForType = InlinedArrayAllocas[ATy];
185 
186     // Loop over the allocas in AllocasForType to see if we can reuse one.  Note
187     // that we have to be careful not to reuse the same "available" alloca for
188     // multiple different allocas that we just inlined, we use the 'UsedAllocas'
189     // set to keep track of which "available" allocas are being used by this
190     // function.  Also, AllocasForType can be empty of course!
191     bool MergedAwayAlloca = false;
192     for (AllocaInst *AvailableAlloca : AllocasForType) {
193       Align Align1 = AI->getAlign();
194       Align Align2 = AvailableAlloca->getAlign();
195 
196       // The available alloca has to be in the right function, not in some other
197       // function in this SCC.
198       if (AvailableAlloca->getParent() != AI->getParent())
199         continue;
200 
201       // If the inlined function already uses this alloca then we can't reuse
202       // it.
203       if (!UsedAllocas.insert(AvailableAlloca).second)
204         continue;
205 
206       // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
207       // success!
208       LLVM_DEBUG(dbgs() << "    ***MERGED ALLOCA: " << *AI
209                         << "\n\t\tINTO: " << *AvailableAlloca << '\n');
210 
211       // Move affected dbg.declare calls immediately after the new alloca to
212       // avoid the situation when a dbg.declare precedes its alloca.
213       if (auto *L = LocalAsMetadata::getIfExists(AI))
214         if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
215           for (User *U : MDV->users())
216             if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
217               DDI->moveBefore(AvailableAlloca->getNextNode());
218 
219       AI->replaceAllUsesWith(AvailableAlloca);
220 
221       if (Align1 > Align2)
222         AvailableAlloca->setAlignment(AI->getAlign());
223 
224       AI->eraseFromParent();
225       MergedAwayAlloca = true;
226       ++NumMergedAllocas;
227       IFI.StaticAllocas[AllocaNo] = nullptr;
228       break;
229     }
230 
231     // If we already nuked the alloca, we're done with it.
232     if (MergedAwayAlloca)
233       continue;
234 
235     // If we were unable to merge away the alloca either because there are no
236     // allocas of the right type available or because we reused them all
237     // already, remember that this alloca came from an inlined function and mark
238     // it used so we don't reuse it for other allocas from this inline
239     // operation.
240     AllocasForType.push_back(AI);
241     UsedAllocas.insert(AI);
242   }
243 }
244 
245 /// If it is possible to inline the specified call site,
246 /// do so and update the CallGraph for this operation.
247 ///
248 /// This function also does some basic book-keeping to update the IR.  The
249 /// InlinedArrayAllocas map keeps track of any allocas that are already
250 /// available from other functions inlined into the caller.  If we are able to
251 /// inline this call site we attempt to reuse already available allocas or add
252 /// any new allocas to the set if not possible.
253 static InlineResult inlineCallIfPossible(
254     CallBase &CB, InlineFunctionInfo &IFI,
255     InlinedArrayAllocasTy &InlinedArrayAllocas, int InlineHistory,
256     bool InsertLifetime, function_ref<AAResults &(Function &)> &AARGetter,
257     ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
258   Function *Callee = CB.getCalledFunction();
259   Function *Caller = CB.getCaller();
260 
261   AAResults &AAR = AARGetter(*Callee);
262 
263   // Try to inline the function.  Get the list of static allocas that were
264   // inlined.
265   InlineResult IR = InlineFunction(CB, IFI, &AAR, InsertLifetime);
266   if (!IR.isSuccess())
267     return IR;
268 
269   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
270     ImportedFunctionsStats.recordInline(*Caller, *Callee);
271 
272   AttributeFuncs::mergeAttributesForInlining(*Caller, *Callee);
273 
274   if (!DisableInlinedAllocaMerging)
275     mergeInlinedArrayAllocas(Caller, IFI, InlinedArrayAllocas, InlineHistory);
276 
277   return IR; // success
278 }
279 
280 /// Return true if the specified inline history ID
281 /// indicates an inline history that includes the specified function.
282 static bool inlineHistoryIncludes(
283     Function *F, int InlineHistoryID,
284     const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) {
285   while (InlineHistoryID != -1) {
286     assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
287            "Invalid inline history ID");
288     if (InlineHistory[InlineHistoryID].first == F)
289       return true;
290     InlineHistoryID = InlineHistory[InlineHistoryID].second;
291   }
292   return false;
293 }
294 
295 bool LegacyInlinerBase::doInitialization(CallGraph &CG) {
296   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
297     ImportedFunctionsStats.setModuleInfo(CG.getModule());
298   return false; // No changes to CallGraph.
299 }
300 
301 bool LegacyInlinerBase::runOnSCC(CallGraphSCC &SCC) {
302   if (skipSCC(SCC))
303     return false;
304   return inlineCalls(SCC);
305 }
306 
307 static bool
308 inlineCallsImpl(CallGraphSCC &SCC, CallGraph &CG,
309                 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
310                 ProfileSummaryInfo *PSI,
311                 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
312                 bool InsertLifetime,
313                 function_ref<InlineCost(CallBase &CB)> GetInlineCost,
314                 function_ref<AAResults &(Function &)> AARGetter,
315                 ImportedFunctionsInliningStatistics &ImportedFunctionsStats) {
316   SmallPtrSet<Function *, 8> SCCFunctions;
317   LLVM_DEBUG(dbgs() << "Inliner visiting SCC:");
318   for (CallGraphNode *Node : SCC) {
319     Function *F = Node->getFunction();
320     if (F)
321       SCCFunctions.insert(F);
322     LLVM_DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
323   }
324 
325   // Scan through and identify all call sites ahead of time so that we only
326   // inline call sites in the original functions, not call sites that result
327   // from inlining other functions.
328   SmallVector<std::pair<CallBase *, int>, 16> CallSites;
329 
330   // When inlining a callee produces new call sites, we want to keep track of
331   // the fact that they were inlined from the callee.  This allows us to avoid
332   // infinite inlining in some obscure cases.  To represent this, we use an
333   // index into the InlineHistory vector.
334   SmallVector<std::pair<Function *, int>, 8> InlineHistory;
335 
336   for (CallGraphNode *Node : SCC) {
337     Function *F = Node->getFunction();
338     if (!F || F->isDeclaration())
339       continue;
340 
341     OptimizationRemarkEmitter ORE(F);
342     for (BasicBlock &BB : *F)
343       for (Instruction &I : BB) {
344         auto *CB = dyn_cast<CallBase>(&I);
345         // If this isn't a call, or it is a call to an intrinsic, it can
346         // never be inlined.
347         if (!CB || isa<IntrinsicInst>(I))
348           continue;
349 
350         // If this is a direct call to an external function, we can never inline
351         // it.  If it is an indirect call, inlining may resolve it to be a
352         // direct call, so we keep it.
353         if (Function *Callee = CB->getCalledFunction())
354           if (Callee->isDeclaration()) {
355             using namespace ore;
356 
357             setInlineRemark(*CB, "unavailable definition");
358             ORE.emit([&]() {
359               return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
360                      << NV("Callee", Callee) << " will not be inlined into "
361                      << NV("Caller", CB->getCaller())
362                      << " because its definition is unavailable"
363                      << setIsVerbose();
364             });
365             continue;
366           }
367 
368         CallSites.push_back(std::make_pair(CB, -1));
369       }
370   }
371 
372   LLVM_DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
373 
374   // If there are no calls in this function, exit early.
375   if (CallSites.empty())
376     return false;
377 
378   // Now that we have all of the call sites, move the ones to functions in the
379   // current SCC to the end of the list.
380   unsigned FirstCallInSCC = CallSites.size();
381   for (unsigned I = 0; I < FirstCallInSCC; ++I)
382     if (Function *F = CallSites[I].first->getCalledFunction())
383       if (SCCFunctions.count(F))
384         std::swap(CallSites[I--], CallSites[--FirstCallInSCC]);
385 
386   InlinedArrayAllocasTy InlinedArrayAllocas;
387   InlineFunctionInfo InlineInfo(&CG, GetAssumptionCache, PSI);
388 
389   // Now that we have all of the call sites, loop over them and inline them if
390   // it looks profitable to do so.
391   bool Changed = false;
392   bool LocalChange;
393   do {
394     LocalChange = false;
395     // Iterate over the outer loop because inlining functions can cause indirect
396     // calls to become direct calls.
397     // CallSites may be modified inside so ranged for loop can not be used.
398     for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
399       auto &P = CallSites[CSi];
400       CallBase &CB = *P.first;
401       const int InlineHistoryID = P.second;
402 
403       Function *Caller = CB.getCaller();
404       Function *Callee = CB.getCalledFunction();
405 
406       // We can only inline direct calls to non-declarations.
407       if (!Callee || Callee->isDeclaration())
408         continue;
409 
410       bool IsTriviallyDead = isInstructionTriviallyDead(&CB, &GetTLI(*Caller));
411 
412       if (!IsTriviallyDead) {
413         // If this call site was obtained by inlining another function, verify
414         // that the include path for the function did not include the callee
415         // itself.  If so, we'd be recursively inlining the same function,
416         // which would provide the same callsites, which would cause us to
417         // infinitely inline.
418         if (InlineHistoryID != -1 &&
419             inlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory)) {
420           setInlineRemark(CB, "recursive");
421           continue;
422         }
423       }
424 
425       // FIXME for new PM: because of the old PM we currently generate ORE and
426       // in turn BFI on demand.  With the new PM, the ORE dependency should
427       // just become a regular analysis dependency.
428       OptimizationRemarkEmitter ORE(Caller);
429 
430       auto OIC = shouldInline(CB, GetInlineCost, ORE);
431       // If the policy determines that we should inline this function,
432       // delete the call instead.
433       if (!OIC)
434         continue;
435 
436       // If this call site is dead and it is to a readonly function, we should
437       // just delete the call instead of trying to inline it, regardless of
438       // size.  This happens because IPSCCP propagates the result out of the
439       // call and then we're left with the dead call.
440       if (IsTriviallyDead) {
441         LLVM_DEBUG(dbgs() << "    -> Deleting dead call: " << CB << "\n");
442         // Update the call graph by deleting the edge from Callee to Caller.
443         setInlineRemark(CB, "trivially dead");
444         CG[Caller]->removeCallEdgeFor(CB);
445         CB.eraseFromParent();
446         ++NumCallsDeleted;
447       } else {
448         // Get DebugLoc to report. CB will be invalid after Inliner.
449         DebugLoc DLoc = CB.getDebugLoc();
450         BasicBlock *Block = CB.getParent();
451 
452         // Attempt to inline the function.
453         using namespace ore;
454 
455         InlineResult IR = inlineCallIfPossible(
456             CB, InlineInfo, InlinedArrayAllocas, InlineHistoryID,
457             InsertLifetime, AARGetter, ImportedFunctionsStats);
458         if (!IR.isSuccess()) {
459           setInlineRemark(CB, std::string(IR.getFailureReason()) + "; " +
460                                   inlineCostStr(*OIC));
461           ORE.emit([&]() {
462             return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc,
463                                             Block)
464                    << NV("Callee", Callee) << " will not be inlined into "
465                    << NV("Caller", Caller) << ": "
466                    << NV("Reason", IR.getFailureReason());
467           });
468           continue;
469         }
470         ++NumInlined;
471 
472         emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
473 
474         // If inlining this function gave us any new call sites, throw them
475         // onto our worklist to process.  They are useful inline candidates.
476         if (!InlineInfo.InlinedCalls.empty()) {
477           // Create a new inline history entry for this, so that we remember
478           // that these new callsites came about due to inlining Callee.
479           int NewHistoryID = InlineHistory.size();
480           InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
481 
482 #ifndef NDEBUG
483           // Make sure no dupplicates in the inline candidates. This could
484           // happen when a callsite is simpilfied to reusing the return value
485           // of another callsite during function cloning, thus the other
486           // callsite will be reconsidered here.
487           DenseSet<CallBase *> DbgCallSites;
488           for (auto &II : CallSites)
489             DbgCallSites.insert(II.first);
490 #endif
491 
492           for (Value *Ptr : InlineInfo.InlinedCalls) {
493 #ifndef NDEBUG
494             assert(DbgCallSites.count(dyn_cast<CallBase>(Ptr)) == 0);
495 #endif
496             CallSites.push_back(
497                 std::make_pair(dyn_cast<CallBase>(Ptr), NewHistoryID));
498           }
499         }
500       }
501 
502       // If we inlined or deleted the last possible call site to the function,
503       // delete the function body now.
504       if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
505           // TODO: Can remove if in SCC now.
506           !SCCFunctions.count(Callee) &&
507           // The function may be apparently dead, but if there are indirect
508           // callgraph references to the node, we cannot delete it yet, this
509           // could invalidate the CGSCC iterator.
510           CG[Callee]->getNumReferences() == 0) {
511         LLVM_DEBUG(dbgs() << "    -> Deleting dead function: "
512                           << Callee->getName() << "\n");
513         CallGraphNode *CalleeNode = CG[Callee];
514 
515         // Remove any call graph edges from the callee to its callees.
516         CalleeNode->removeAllCalledFunctions();
517 
518         // Removing the node for callee from the call graph and delete it.
519         delete CG.removeFunctionFromModule(CalleeNode);
520         ++NumDeleted;
521       }
522 
523       // Remove this call site from the list.  If possible, use
524       // swap/pop_back for efficiency, but do not use it if doing so would
525       // move a call site to a function in this SCC before the
526       // 'FirstCallInSCC' barrier.
527       if (SCC.isSingular()) {
528         CallSites[CSi] = CallSites.back();
529         CallSites.pop_back();
530       } else {
531         CallSites.erase(CallSites.begin() + CSi);
532       }
533       --CSi;
534 
535       Changed = true;
536       LocalChange = true;
537     }
538   } while (LocalChange);
539 
540   return Changed;
541 }
542 
543 bool LegacyInlinerBase::inlineCalls(CallGraphSCC &SCC) {
544   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
545   ACT = &getAnalysis<AssumptionCacheTracker>();
546   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
547   GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
548     return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
549   };
550   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
551     return ACT->getAssumptionCache(F);
552   };
553   return inlineCallsImpl(
554       SCC, CG, GetAssumptionCache, PSI, GetTLI, InsertLifetime,
555       [&](CallBase &CB) { return getInlineCost(CB); }, LegacyAARGetter(*this),
556       ImportedFunctionsStats);
557 }
558 
559 /// Remove now-dead linkonce functions at the end of
560 /// processing to avoid breaking the SCC traversal.
561 bool LegacyInlinerBase::doFinalization(CallGraph &CG) {
562   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
563     ImportedFunctionsStats.dump(InlinerFunctionImportStats ==
564                                 InlinerFunctionImportStatsOpts::Verbose);
565   return removeDeadFunctions(CG);
566 }
567 
568 /// Remove dead functions that are not included in DNR (Do Not Remove) list.
569 bool LegacyInlinerBase::removeDeadFunctions(CallGraph &CG,
570                                             bool AlwaysInlineOnly) {
571   SmallVector<CallGraphNode *, 16> FunctionsToRemove;
572   SmallVector<Function *, 16> DeadFunctionsInComdats;
573 
574   auto RemoveCGN = [&](CallGraphNode *CGN) {
575     // Remove any call graph edges from the function to its callees.
576     CGN->removeAllCalledFunctions();
577 
578     // Remove any edges from the external node to the function's call graph
579     // node.  These edges might have been made irrelegant due to
580     // optimization of the program.
581     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
582 
583     // Removing the node for callee from the call graph and delete it.
584     FunctionsToRemove.push_back(CGN);
585   };
586 
587   // Scan for all of the functions, looking for ones that should now be removed
588   // from the program.  Insert the dead ones in the FunctionsToRemove set.
589   for (const auto &I : CG) {
590     CallGraphNode *CGN = I.second.get();
591     Function *F = CGN->getFunction();
592     if (!F || F->isDeclaration())
593       continue;
594 
595     // Handle the case when this function is called and we only want to care
596     // about always-inline functions. This is a bit of a hack to share code
597     // between here and the InlineAlways pass.
598     if (AlwaysInlineOnly && !F->hasFnAttribute(Attribute::AlwaysInline))
599       continue;
600 
601     // If the only remaining users of the function are dead constants, remove
602     // them.
603     F->removeDeadConstantUsers();
604 
605     if (!F->isDefTriviallyDead())
606       continue;
607 
608     // It is unsafe to drop a function with discardable linkage from a COMDAT
609     // without also dropping the other members of the COMDAT.
610     // The inliner doesn't visit non-function entities which are in COMDAT
611     // groups so it is unsafe to do so *unless* the linkage is local.
612     if (!F->hasLocalLinkage()) {
613       if (F->hasComdat()) {
614         DeadFunctionsInComdats.push_back(F);
615         continue;
616       }
617     }
618 
619     RemoveCGN(CGN);
620   }
621   if (!DeadFunctionsInComdats.empty()) {
622     // Filter out the functions whose comdats remain alive.
623     filterDeadComdatFunctions(CG.getModule(), DeadFunctionsInComdats);
624     // Remove the rest.
625     for (Function *F : DeadFunctionsInComdats)
626       RemoveCGN(CG[F]);
627   }
628 
629   if (FunctionsToRemove.empty())
630     return false;
631 
632   // Now that we know which functions to delete, do so.  We didn't want to do
633   // this inline, because that would invalidate our CallGraph::iterator
634   // objects. :(
635   //
636   // Note that it doesn't matter that we are iterating over a non-stable order
637   // here to do this, it doesn't matter which order the functions are deleted
638   // in.
639   array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
640   FunctionsToRemove.erase(
641       std::unique(FunctionsToRemove.begin(), FunctionsToRemove.end()),
642       FunctionsToRemove.end());
643   for (CallGraphNode *CGN : FunctionsToRemove) {
644     delete CG.removeFunctionFromModule(CGN);
645     ++NumDeleted;
646   }
647   return true;
648 }
649 
650 InlinerPass::~InlinerPass() {
651   if (ImportedFunctionsStats) {
652     assert(InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No);
653     ImportedFunctionsStats->dump(InlinerFunctionImportStats ==
654                                  InlinerFunctionImportStatsOpts::Verbose);
655   }
656 }
657 
658 InlineAdvisor &
659 InlinerPass::getAdvisor(const ModuleAnalysisManagerCGSCCProxy::Result &MAM,
660                         FunctionAnalysisManager &FAM, Module &M) {
661   auto *IAA = MAM.getCachedResult<InlineAdvisorAnalysis>(M);
662   if (!IAA) {
663     // It should still be possible to run the inliner as a stand-alone SCC pass,
664     // for test scenarios. In that case, we default to the
665     // DefaultInlineAdvisor, which doesn't need to keep state between SCC pass
666     // runs. It also uses just the default InlineParams.
667     // In this case, we need to use the provided FAM, which is valid for the
668     // duration of the inliner pass, and thus the lifetime of the owned advisor.
669     // The one we would get from the MAM can be invalidated as a result of the
670     // inliner's activity.
671     OwnedDefaultAdvisor.emplace(FAM, getInlineParams());
672     return *OwnedDefaultAdvisor;
673   }
674   assert(IAA->getAdvisor() &&
675          "Expected a present InlineAdvisorAnalysis also have an "
676          "InlineAdvisor initialized");
677   return *IAA->getAdvisor();
678 }
679 
680 PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC,
681                                    CGSCCAnalysisManager &AM, LazyCallGraph &CG,
682                                    CGSCCUpdateResult &UR) {
683   const auto &MAMProxy =
684       AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG);
685   bool Changed = false;
686 
687   assert(InitialC.size() > 0 && "Cannot handle an empty SCC!");
688   Module &M = *InitialC.begin()->getFunction().getParent();
689   ProfileSummaryInfo *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(M);
690 
691   FunctionAnalysisManager &FAM =
692       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)
693           .getManager();
694 
695   InlineAdvisor &Advisor = getAdvisor(MAMProxy, FAM, M);
696   Advisor.onPassEntry();
697 
698   auto AdvisorOnExit = make_scope_exit([&] { Advisor.onPassExit(); });
699 
700   if (!ImportedFunctionsStats &&
701       InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) {
702     ImportedFunctionsStats =
703         std::make_unique<ImportedFunctionsInliningStatistics>();
704     ImportedFunctionsStats->setModuleInfo(M);
705   }
706 
707   // We use a single common worklist for calls across the entire SCC. We
708   // process these in-order and append new calls introduced during inlining to
709   // the end.
710   //
711   // Note that this particular order of processing is actually critical to
712   // avoid very bad behaviors. Consider *highly connected* call graphs where
713   // each function contains a small amount of code and a couple of calls to
714   // other functions. Because the LLVM inliner is fundamentally a bottom-up
715   // inliner, it can handle gracefully the fact that these all appear to be
716   // reasonable inlining candidates as it will flatten things until they become
717   // too big to inline, and then move on and flatten another batch.
718   //
719   // However, when processing call edges *within* an SCC we cannot rely on this
720   // bottom-up behavior. As a consequence, with heavily connected *SCCs* of
721   // functions we can end up incrementally inlining N calls into each of
722   // N functions because each incremental inlining decision looks good and we
723   // don't have a topological ordering to prevent explosions.
724   //
725   // To compensate for this, we don't process transitive edges made immediate
726   // by inlining until we've done one pass of inlining across the entire SCC.
727   // Large, highly connected SCCs still lead to some amount of code bloat in
728   // this model, but it is uniformly spread across all the functions in the SCC
729   // and eventually they all become too large to inline, rather than
730   // incrementally maknig a single function grow in a super linear fashion.
731   SmallVector<std::pair<CallBase *, int>, 16> Calls;
732 
733   // Populate the initial list of calls in this SCC.
734   for (auto &N : InitialC) {
735     auto &ORE =
736         FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction());
737     // We want to generally process call sites top-down in order for
738     // simplifications stemming from replacing the call with the returned value
739     // after inlining to be visible to subsequent inlining decisions.
740     // FIXME: Using instructions sequence is a really bad way to do this.
741     // Instead we should do an actual RPO walk of the function body.
742     for (Instruction &I : instructions(N.getFunction()))
743       if (auto *CB = dyn_cast<CallBase>(&I))
744         if (Function *Callee = CB->getCalledFunction()) {
745           if (!Callee->isDeclaration())
746             Calls.push_back({CB, -1});
747           else if (!isa<IntrinsicInst>(I)) {
748             using namespace ore;
749             setInlineRemark(*CB, "unavailable definition");
750             ORE.emit([&]() {
751               return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
752                      << NV("Callee", Callee) << " will not be inlined into "
753                      << NV("Caller", CB->getCaller())
754                      << " because its definition is unavailable"
755                      << setIsVerbose();
756             });
757           }
758         }
759   }
760   if (Calls.empty())
761     return PreservedAnalyses::all();
762 
763   // Capture updatable variable for the current SCC.
764   auto *C = &InitialC;
765 
766   // When inlining a callee produces new call sites, we want to keep track of
767   // the fact that they were inlined from the callee.  This allows us to avoid
768   // infinite inlining in some obscure cases.  To represent this, we use an
769   // index into the InlineHistory vector.
770   SmallVector<std::pair<Function *, int>, 16> InlineHistory;
771 
772   // Track a set vector of inlined callees so that we can augment the caller
773   // with all of their edges in the call graph before pruning out the ones that
774   // got simplified away.
775   SmallSetVector<Function *, 4> InlinedCallees;
776 
777   // Track the dead functions to delete once finished with inlining calls. We
778   // defer deleting these to make it easier to handle the call graph updates.
779   SmallVector<Function *, 4> DeadFunctions;
780 
781   // Loop forward over all of the calls. Note that we cannot cache the size as
782   // inlining can introduce new calls that need to be processed.
783   for (int I = 0; I < (int)Calls.size(); ++I) {
784     // We expect the calls to typically be batched with sequences of calls that
785     // have the same caller, so we first set up some shared infrastructure for
786     // this caller. We also do any pruning we can at this layer on the caller
787     // alone.
788     Function &F = *Calls[I].first->getCaller();
789     LazyCallGraph::Node &N = *CG.lookup(F);
790     if (CG.lookupSCC(N) != C)
791       continue;
792     if (!Calls[I].first->getCalledFunction()->hasFnAttribute(
793             Attribute::AlwaysInline) &&
794         F.hasOptNone()) {
795       setInlineRemark(*Calls[I].first, "optnone attribute");
796       continue;
797     }
798 
799     LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n");
800 
801     auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
802       return FAM.getResult<AssumptionAnalysis>(F);
803     };
804 
805     // Now process as many calls as we have within this caller in the sequence.
806     // We bail out as soon as the caller has to change so we can update the
807     // call graph and prepare the context of that new caller.
808     bool DidInline = false;
809     for (; I < (int)Calls.size() && Calls[I].first->getCaller() == &F; ++I) {
810       auto &P = Calls[I];
811       CallBase *CB = P.first;
812       const int InlineHistoryID = P.second;
813       Function &Callee = *CB->getCalledFunction();
814 
815       if (InlineHistoryID != -1 &&
816           inlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) {
817         setInlineRemark(*CB, "recursive");
818         continue;
819       }
820 
821       // Check if this inlining may repeat breaking an SCC apart that has
822       // already been split once before. In that case, inlining here may
823       // trigger infinite inlining, much like is prevented within the inliner
824       // itself by the InlineHistory above, but spread across CGSCC iterations
825       // and thus hidden from the full inline history.
826       if (CG.lookupSCC(*CG.lookup(Callee)) == C &&
827           UR.InlinedInternalEdges.count({&N, C})) {
828         LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node "
829                              "previously split out of this SCC by inlining: "
830                           << F.getName() << " -> " << Callee.getName() << "\n");
831         setInlineRemark(*CB, "recursive SCC split");
832         continue;
833       }
834 
835       auto Advice = Advisor.getAdvice(*CB);
836       // Check whether we want to inline this callsite.
837       if (!Advice->isInliningRecommended()) {
838         Advice->recordUnattemptedInlining();
839         continue;
840       }
841 
842       // Setup the data structure used to plumb customization into the
843       // `InlineFunction` routine.
844       InlineFunctionInfo IFI(
845           /*cg=*/nullptr, GetAssumptionCache, PSI,
846           &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())),
847           &FAM.getResult<BlockFrequencyAnalysis>(Callee));
848 
849       InlineResult IR =
850           InlineFunction(*CB, IFI, &FAM.getResult<AAManager>(*CB->getCaller()));
851       if (!IR.isSuccess()) {
852         Advice->recordUnsuccessfulInlining(IR);
853         continue;
854       }
855 
856       DidInline = true;
857       InlinedCallees.insert(&Callee);
858       ++NumInlined;
859 
860       // Add any new callsites to defined functions to the worklist.
861       if (!IFI.InlinedCallSites.empty()) {
862         int NewHistoryID = InlineHistory.size();
863         InlineHistory.push_back({&Callee, InlineHistoryID});
864 
865         for (CallBase *ICB : reverse(IFI.InlinedCallSites)) {
866           Function *NewCallee = ICB->getCalledFunction();
867           if (!NewCallee) {
868             // Try to promote an indirect (virtual) call without waiting for
869             // the post-inline cleanup and the next DevirtSCCRepeatedPass
870             // iteration because the next iteration may not happen and we may
871             // miss inlining it.
872             if (tryPromoteCall(*ICB))
873               NewCallee = ICB->getCalledFunction();
874           }
875           if (NewCallee)
876             if (!NewCallee->isDeclaration())
877               Calls.push_back({ICB, NewHistoryID});
878         }
879       }
880 
881       if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
882         ImportedFunctionsStats->recordInline(F, Callee);
883 
884       // Merge the attributes based on the inlining.
885       AttributeFuncs::mergeAttributesForInlining(F, Callee);
886 
887       // For local functions, check whether this makes the callee trivially
888       // dead. In that case, we can drop the body of the function eagerly
889       // which may reduce the number of callers of other functions to one,
890       // changing inline cost thresholds.
891       bool CalleeWasDeleted = false;
892       if (Callee.hasLocalLinkage()) {
893         // To check this we also need to nuke any dead constant uses (perhaps
894         // made dead by this operation on other functions).
895         Callee.removeDeadConstantUsers();
896         if (Callee.use_empty() && !CG.isLibFunction(Callee)) {
897           Calls.erase(
898               std::remove_if(Calls.begin() + I + 1, Calls.end(),
899                              [&](const std::pair<CallBase *, int> &Call) {
900                                return Call.first->getCaller() == &Callee;
901                              }),
902               Calls.end());
903           // Clear the body and queue the function itself for deletion when we
904           // finish inlining and call graph updates.
905           // Note that after this point, it is an error to do anything other
906           // than use the callee's address or delete it.
907           Callee.dropAllReferences();
908           assert(!is_contained(DeadFunctions, &Callee) &&
909                  "Cannot put cause a function to become dead twice!");
910           DeadFunctions.push_back(&Callee);
911           CalleeWasDeleted = true;
912         }
913       }
914       if (CalleeWasDeleted)
915         Advice->recordInliningWithCalleeDeleted();
916       else
917         Advice->recordInlining();
918     }
919 
920     // Back the call index up by one to put us in a good position to go around
921     // the outer loop.
922     --I;
923 
924     if (!DidInline)
925       continue;
926     Changed = true;
927 
928     // At this point, since we have made changes we have at least removed
929     // a call instruction. However, in the process we do some incremental
930     // simplification of the surrounding code. This simplification can
931     // essentially do all of the same things as a function pass and we can
932     // re-use the exact same logic for updating the call graph to reflect the
933     // change.
934 
935     // Inside the update, we also update the FunctionAnalysisManager in the
936     // proxy for this particular SCC. We do this as the SCC may have changed and
937     // as we're going to mutate this particular function we want to make sure
938     // the proxy is in place to forward any invalidation events.
939     LazyCallGraph::SCC *OldC = C;
940     C = &updateCGAndAnalysisManagerForCGSCCPass(CG, *C, N, AM, UR, FAM);
941     LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n");
942 
943     // If this causes an SCC to split apart into multiple smaller SCCs, there
944     // is a subtle risk we need to prepare for. Other transformations may
945     // expose an "infinite inlining" opportunity later, and because of the SCC
946     // mutation, we will revisit this function and potentially re-inline. If we
947     // do, and that re-inlining also has the potentially to mutate the SCC
948     // structure, the infinite inlining problem can manifest through infinite
949     // SCC splits and merges. To avoid this, we capture the originating caller
950     // node and the SCC containing the call edge. This is a slight over
951     // approximation of the possible inlining decisions that must be avoided,
952     // but is relatively efficient to store. We use C != OldC to know when
953     // a new SCC is generated and the original SCC may be generated via merge
954     // in later iterations.
955     //
956     // It is also possible that even if no new SCC is generated
957     // (i.e., C == OldC), the original SCC could be split and then merged
958     // into the same one as itself. and the original SCC will be added into
959     // UR.CWorklist again, we want to catch such cases too.
960     //
961     // FIXME: This seems like a very heavyweight way of retaining the inline
962     // history, we should look for a more efficient way of tracking it.
963     if ((C != OldC || UR.CWorklist.count(OldC)) &&
964         llvm::any_of(InlinedCallees, [&](Function *Callee) {
965           return CG.lookupSCC(*CG.lookup(*Callee)) == OldC;
966         })) {
967       LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, "
968                            "retaining this to avoid infinite inlining.\n");
969       UR.InlinedInternalEdges.insert({&N, OldC});
970     }
971     InlinedCallees.clear();
972   }
973 
974   // Now that we've finished inlining all of the calls across this SCC, delete
975   // all of the trivially dead functions, updating the call graph and the CGSCC
976   // pass manager in the process.
977   //
978   // Note that this walks a pointer set which has non-deterministic order but
979   // that is OK as all we do is delete things and add pointers to unordered
980   // sets.
981   for (Function *DeadF : DeadFunctions) {
982     // Get the necessary information out of the call graph and nuke the
983     // function there. Also, clear out any cached analyses.
984     auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));
985     FAM.clear(*DeadF, DeadF->getName());
986     AM.clear(DeadC, DeadC.getName());
987     auto &DeadRC = DeadC.getOuterRefSCC();
988     CG.removeDeadFunction(*DeadF);
989 
990     // Mark the relevant parts of the call graph as invalid so we don't visit
991     // them.
992     UR.InvalidatedSCCs.insert(&DeadC);
993     UR.InvalidatedRefSCCs.insert(&DeadRC);
994 
995     // And delete the actual function from the module.
996     // The Advisor may use Function pointers to efficiently index various
997     // internal maps, e.g. for memoization. Function cleanup passes like
998     // argument promotion create new functions. It is possible for a new
999     // function to be allocated at the address of a deleted function. We could
1000     // index using names, but that's inefficient. Alternatively, we let the
1001     // Advisor free the functions when it sees fit.
1002     DeadF->getBasicBlockList().clear();
1003     M.getFunctionList().remove(DeadF);
1004 
1005     ++NumDeleted;
1006   }
1007 
1008   if (!Changed)
1009     return PreservedAnalyses::all();
1010 
1011   // Even if we change the IR, we update the core CGSCC data structures and so
1012   // can preserve the proxy to the function analysis manager.
1013   PreservedAnalyses PA;
1014   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1015   return PA;
1016 }
1017 
1018 ModuleInlinerWrapperPass::ModuleInlinerWrapperPass(InlineParams Params,
1019                                                    bool Debugging,
1020                                                    InliningAdvisorMode Mode,
1021                                                    unsigned MaxDevirtIterations)
1022     : Params(Params), Mode(Mode), MaxDevirtIterations(MaxDevirtIterations),
1023       PM(Debugging), MPM(Debugging) {
1024   // Run the inliner first. The theory is that we are walking bottom-up and so
1025   // the callees have already been fully optimized, and we want to inline them
1026   // into the callers so that our optimizations can reflect that.
1027   // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
1028   // because it makes profile annotation in the backend inaccurate.
1029   PM.addPass(InlinerPass());
1030 }
1031 
1032 PreservedAnalyses ModuleInlinerWrapperPass::run(Module &M,
1033                                                 ModuleAnalysisManager &MAM) {
1034   auto &IAA = MAM.getResult<InlineAdvisorAnalysis>(M);
1035   if (!IAA.tryCreate(Params, Mode)) {
1036     M.getContext().emitError(
1037         "Could not setup Inlining Advisor for the requested "
1038         "mode and/or options");
1039     return PreservedAnalyses::all();
1040   }
1041 
1042   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
1043   // to detect when we devirtualize indirect calls and iterate the SCC passes
1044   // in that case to try and catch knock-on inlining or function attrs
1045   // opportunities. Then we add it to the module pipeline by walking the SCCs
1046   // in postorder (or bottom-up).
1047   // If MaxDevirtIterations is 0, we just don't use the devirtualization
1048   // wrapper.
1049   if (MaxDevirtIterations == 0)
1050     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(PM)));
1051   else
1052     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1053         createDevirtSCCRepeatedPass(std::move(PM), MaxDevirtIterations)));
1054   auto Ret = MPM.run(M, MAM);
1055 
1056   IAA.clear();
1057   return Ret;
1058 }
1059