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 =
672         std::make_unique<DefaultInlineAdvisor>(FAM, getInlineParams());
673     return *OwnedDefaultAdvisor;
674   }
675   assert(IAA->getAdvisor() &&
676          "Expected a present InlineAdvisorAnalysis also have an "
677          "InlineAdvisor initialized");
678   return *IAA->getAdvisor();
679 }
680 
681 PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC,
682                                    CGSCCAnalysisManager &AM, LazyCallGraph &CG,
683                                    CGSCCUpdateResult &UR) {
684   const auto &MAMProxy =
685       AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG);
686   bool Changed = false;
687 
688   assert(InitialC.size() > 0 && "Cannot handle an empty SCC!");
689   Module &M = *InitialC.begin()->getFunction().getParent();
690   ProfileSummaryInfo *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(M);
691 
692   FunctionAnalysisManager &FAM =
693       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)
694           .getManager();
695 
696   InlineAdvisor &Advisor = getAdvisor(MAMProxy, FAM, M);
697   Advisor.onPassEntry();
698 
699   auto AdvisorOnExit = make_scope_exit([&] { Advisor.onPassExit(); });
700 
701   if (!ImportedFunctionsStats &&
702       InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) {
703     ImportedFunctionsStats =
704         std::make_unique<ImportedFunctionsInliningStatistics>();
705     ImportedFunctionsStats->setModuleInfo(M);
706   }
707 
708   // We use a single common worklist for calls across the entire SCC. We
709   // process these in-order and append new calls introduced during inlining to
710   // the end.
711   //
712   // Note that this particular order of processing is actually critical to
713   // avoid very bad behaviors. Consider *highly connected* call graphs where
714   // each function contains a small amount of code and a couple of calls to
715   // other functions. Because the LLVM inliner is fundamentally a bottom-up
716   // inliner, it can handle gracefully the fact that these all appear to be
717   // reasonable inlining candidates as it will flatten things until they become
718   // too big to inline, and then move on and flatten another batch.
719   //
720   // However, when processing call edges *within* an SCC we cannot rely on this
721   // bottom-up behavior. As a consequence, with heavily connected *SCCs* of
722   // functions we can end up incrementally inlining N calls into each of
723   // N functions because each incremental inlining decision looks good and we
724   // don't have a topological ordering to prevent explosions.
725   //
726   // To compensate for this, we don't process transitive edges made immediate
727   // by inlining until we've done one pass of inlining across the entire SCC.
728   // Large, highly connected SCCs still lead to some amount of code bloat in
729   // this model, but it is uniformly spread across all the functions in the SCC
730   // and eventually they all become too large to inline, rather than
731   // incrementally maknig a single function grow in a super linear fashion.
732   SmallVector<std::pair<CallBase *, int>, 16> Calls;
733 
734   // Populate the initial list of calls in this SCC.
735   for (auto &N : InitialC) {
736     auto &ORE =
737         FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction());
738     // We want to generally process call sites top-down in order for
739     // simplifications stemming from replacing the call with the returned value
740     // after inlining to be visible to subsequent inlining decisions.
741     // FIXME: Using instructions sequence is a really bad way to do this.
742     // Instead we should do an actual RPO walk of the function body.
743     for (Instruction &I : instructions(N.getFunction()))
744       if (auto *CB = dyn_cast<CallBase>(&I))
745         if (Function *Callee = CB->getCalledFunction()) {
746           if (!Callee->isDeclaration())
747             Calls.push_back({CB, -1});
748           else if (!isa<IntrinsicInst>(I)) {
749             using namespace ore;
750             setInlineRemark(*CB, "unavailable definition");
751             ORE.emit([&]() {
752               return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)
753                      << NV("Callee", Callee) << " will not be inlined into "
754                      << NV("Caller", CB->getCaller())
755                      << " because its definition is unavailable"
756                      << setIsVerbose();
757             });
758           }
759         }
760   }
761   if (Calls.empty())
762     return PreservedAnalyses::all();
763 
764   // Capture updatable variable for the current SCC.
765   auto *C = &InitialC;
766 
767   // When inlining a callee produces new call sites, we want to keep track of
768   // the fact that they were inlined from the callee.  This allows us to avoid
769   // infinite inlining in some obscure cases.  To represent this, we use an
770   // index into the InlineHistory vector.
771   SmallVector<std::pair<Function *, int>, 16> InlineHistory;
772 
773   // Track a set vector of inlined callees so that we can augment the caller
774   // with all of their edges in the call graph before pruning out the ones that
775   // got simplified away.
776   SmallSetVector<Function *, 4> InlinedCallees;
777 
778   // Track the dead functions to delete once finished with inlining calls. We
779   // defer deleting these to make it easier to handle the call graph updates.
780   SmallVector<Function *, 4> DeadFunctions;
781 
782   // Loop forward over all of the calls. Note that we cannot cache the size as
783   // inlining can introduce new calls that need to be processed.
784   for (int I = 0; I < (int)Calls.size(); ++I) {
785     // We expect the calls to typically be batched with sequences of calls that
786     // have the same caller, so we first set up some shared infrastructure for
787     // this caller. We also do any pruning we can at this layer on the caller
788     // alone.
789     Function &F = *Calls[I].first->getCaller();
790     LazyCallGraph::Node &N = *CG.lookup(F);
791     if (CG.lookupSCC(N) != C)
792       continue;
793     if (!Calls[I].first->getCalledFunction()->hasFnAttribute(
794             Attribute::AlwaysInline) &&
795         F.hasOptNone()) {
796       setInlineRemark(*Calls[I].first, "optnone attribute");
797       continue;
798     }
799 
800     LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n");
801 
802     auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
803       return FAM.getResult<AssumptionAnalysis>(F);
804     };
805 
806     // Now process as many calls as we have within this caller in the sequence.
807     // We bail out as soon as the caller has to change so we can update the
808     // call graph and prepare the context of that new caller.
809     bool DidInline = false;
810     for (; I < (int)Calls.size() && Calls[I].first->getCaller() == &F; ++I) {
811       auto &P = Calls[I];
812       CallBase *CB = P.first;
813       const int InlineHistoryID = P.second;
814       Function &Callee = *CB->getCalledFunction();
815 
816       if (InlineHistoryID != -1 &&
817           inlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) {
818         setInlineRemark(*CB, "recursive");
819         continue;
820       }
821 
822       // Check if this inlining may repeat breaking an SCC apart that has
823       // already been split once before. In that case, inlining here may
824       // trigger infinite inlining, much like is prevented within the inliner
825       // itself by the InlineHistory above, but spread across CGSCC iterations
826       // and thus hidden from the full inline history.
827       if (CG.lookupSCC(*CG.lookup(Callee)) == C &&
828           UR.InlinedInternalEdges.count({&N, C})) {
829         LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node "
830                              "previously split out of this SCC by inlining: "
831                           << F.getName() << " -> " << Callee.getName() << "\n");
832         setInlineRemark(*CB, "recursive SCC split");
833         continue;
834       }
835 
836       auto Advice = Advisor.getAdvice(*CB, OnlyMandatory);
837       // Check whether we want to inline this callsite.
838       if (!Advice->isInliningRecommended()) {
839         Advice->recordUnattemptedInlining();
840         continue;
841       }
842 
843       // Setup the data structure used to plumb customization into the
844       // `InlineFunction` routine.
845       InlineFunctionInfo IFI(
846           /*cg=*/nullptr, GetAssumptionCache, PSI,
847           &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())),
848           &FAM.getResult<BlockFrequencyAnalysis>(Callee));
849 
850       InlineResult IR =
851           InlineFunction(*CB, IFI, &FAM.getResult<AAManager>(*CB->getCaller()));
852       if (!IR.isSuccess()) {
853         Advice->recordUnsuccessfulInlining(IR);
854         continue;
855       }
856 
857       DidInline = true;
858       InlinedCallees.insert(&Callee);
859       ++NumInlined;
860 
861       // Add any new callsites to defined functions to the worklist.
862       if (!IFI.InlinedCallSites.empty()) {
863         int NewHistoryID = InlineHistory.size();
864         InlineHistory.push_back({&Callee, InlineHistoryID});
865 
866         for (CallBase *ICB : reverse(IFI.InlinedCallSites)) {
867           Function *NewCallee = ICB->getCalledFunction();
868           if (!NewCallee) {
869             // Try to promote an indirect (virtual) call without waiting for
870             // the post-inline cleanup and the next DevirtSCCRepeatedPass
871             // iteration because the next iteration may not happen and we may
872             // miss inlining it.
873             if (tryPromoteCall(*ICB))
874               NewCallee = ICB->getCalledFunction();
875           }
876           if (NewCallee)
877             if (!NewCallee->isDeclaration())
878               Calls.push_back({ICB, NewHistoryID});
879         }
880       }
881 
882       if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No)
883         ImportedFunctionsStats->recordInline(F, Callee);
884 
885       // Merge the attributes based on the inlining.
886       AttributeFuncs::mergeAttributesForInlining(F, Callee);
887 
888       // For local functions, check whether this makes the callee trivially
889       // dead. In that case, we can drop the body of the function eagerly
890       // which may reduce the number of callers of other functions to one,
891       // changing inline cost thresholds.
892       bool CalleeWasDeleted = false;
893       if (Callee.hasLocalLinkage()) {
894         // To check this we also need to nuke any dead constant uses (perhaps
895         // made dead by this operation on other functions).
896         Callee.removeDeadConstantUsers();
897         if (Callee.use_empty() && !CG.isLibFunction(Callee)) {
898           Calls.erase(
899               std::remove_if(Calls.begin() + I + 1, Calls.end(),
900                              [&](const std::pair<CallBase *, int> &Call) {
901                                return Call.first->getCaller() == &Callee;
902                              }),
903               Calls.end());
904           // Clear the body and queue the function itself for deletion when we
905           // finish inlining and call graph updates.
906           // Note that after this point, it is an error to do anything other
907           // than use the callee's address or delete it.
908           Callee.dropAllReferences();
909           assert(!is_contained(DeadFunctions, &Callee) &&
910                  "Cannot put cause a function to become dead twice!");
911           DeadFunctions.push_back(&Callee);
912           CalleeWasDeleted = true;
913         }
914       }
915       if (CalleeWasDeleted)
916         Advice->recordInliningWithCalleeDeleted();
917       else
918         Advice->recordInlining();
919     }
920 
921     // Back the call index up by one to put us in a good position to go around
922     // the outer loop.
923     --I;
924 
925     if (!DidInline)
926       continue;
927     Changed = true;
928 
929     // At this point, since we have made changes we have at least removed
930     // a call instruction. However, in the process we do some incremental
931     // simplification of the surrounding code. This simplification can
932     // essentially do all of the same things as a function pass and we can
933     // re-use the exact same logic for updating the call graph to reflect the
934     // change.
935 
936     // Inside the update, we also update the FunctionAnalysisManager in the
937     // proxy for this particular SCC. We do this as the SCC may have changed and
938     // as we're going to mutate this particular function we want to make sure
939     // the proxy is in place to forward any invalidation events.
940     LazyCallGraph::SCC *OldC = C;
941     C = &updateCGAndAnalysisManagerForCGSCCPass(CG, *C, N, AM, UR, FAM);
942     LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n");
943 
944     // If this causes an SCC to split apart into multiple smaller SCCs, there
945     // is a subtle risk we need to prepare for. Other transformations may
946     // expose an "infinite inlining" opportunity later, and because of the SCC
947     // mutation, we will revisit this function and potentially re-inline. If we
948     // do, and that re-inlining also has the potentially to mutate the SCC
949     // structure, the infinite inlining problem can manifest through infinite
950     // SCC splits and merges. To avoid this, we capture the originating caller
951     // node and the SCC containing the call edge. This is a slight over
952     // approximation of the possible inlining decisions that must be avoided,
953     // but is relatively efficient to store. We use C != OldC to know when
954     // a new SCC is generated and the original SCC may be generated via merge
955     // in later iterations.
956     //
957     // It is also possible that even if no new SCC is generated
958     // (i.e., C == OldC), the original SCC could be split and then merged
959     // into the same one as itself. and the original SCC will be added into
960     // UR.CWorklist again, we want to catch such cases too.
961     //
962     // FIXME: This seems like a very heavyweight way of retaining the inline
963     // history, we should look for a more efficient way of tracking it.
964     if ((C != OldC || UR.CWorklist.count(OldC)) &&
965         llvm::any_of(InlinedCallees, [&](Function *Callee) {
966           return CG.lookupSCC(*CG.lookup(*Callee)) == OldC;
967         })) {
968       LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, "
969                            "retaining this to avoid infinite inlining.\n");
970       UR.InlinedInternalEdges.insert({&N, OldC});
971     }
972     InlinedCallees.clear();
973   }
974 
975   // Now that we've finished inlining all of the calls across this SCC, delete
976   // all of the trivially dead functions, updating the call graph and the CGSCC
977   // pass manager in the process.
978   //
979   // Note that this walks a pointer set which has non-deterministic order but
980   // that is OK as all we do is delete things and add pointers to unordered
981   // sets.
982   for (Function *DeadF : DeadFunctions) {
983     // Get the necessary information out of the call graph and nuke the
984     // function there. Also, clear out any cached analyses.
985     auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));
986     FAM.clear(*DeadF, DeadF->getName());
987     AM.clear(DeadC, DeadC.getName());
988     auto &DeadRC = DeadC.getOuterRefSCC();
989     CG.removeDeadFunction(*DeadF);
990 
991     // Mark the relevant parts of the call graph as invalid so we don't visit
992     // them.
993     UR.InvalidatedSCCs.insert(&DeadC);
994     UR.InvalidatedRefSCCs.insert(&DeadRC);
995 
996     // And delete the actual function from the module.
997     // The Advisor may use Function pointers to efficiently index various
998     // internal maps, e.g. for memoization. Function cleanup passes like
999     // argument promotion create new functions. It is possible for a new
1000     // function to be allocated at the address of a deleted function. We could
1001     // index using names, but that's inefficient. Alternatively, we let the
1002     // Advisor free the functions when it sees fit.
1003     DeadF->getBasicBlockList().clear();
1004     M.getFunctionList().remove(DeadF);
1005 
1006     ++NumDeleted;
1007   }
1008 
1009   if (!Changed)
1010     return PreservedAnalyses::all();
1011 
1012   // Even if we change the IR, we update the core CGSCC data structures and so
1013   // can preserve the proxy to the function analysis manager.
1014   PreservedAnalyses PA;
1015   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1016   return PA;
1017 }
1018 
1019 ModuleInlinerWrapperPass::ModuleInlinerWrapperPass(InlineParams Params,
1020                                                    bool Debugging,
1021                                                    bool MandatoryFirst,
1022                                                    InliningAdvisorMode Mode,
1023                                                    unsigned MaxDevirtIterations)
1024     : Params(Params), Mode(Mode), MaxDevirtIterations(MaxDevirtIterations),
1025       PM(Debugging), MPM(Debugging) {
1026   // Run the inliner first. The theory is that we are walking bottom-up and so
1027   // the callees have already been fully optimized, and we want to inline them
1028   // into the callers so that our optimizations can reflect that.
1029   // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
1030   // because it makes profile annotation in the backend inaccurate.
1031   if (MandatoryFirst)
1032     PM.addPass(InlinerPass(/*OnlyMandatory*/ true));
1033   PM.addPass(InlinerPass());
1034 }
1035 
1036 PreservedAnalyses ModuleInlinerWrapperPass::run(Module &M,
1037                                                 ModuleAnalysisManager &MAM) {
1038   auto &IAA = MAM.getResult<InlineAdvisorAnalysis>(M);
1039   if (!IAA.tryCreate(Params, Mode)) {
1040     M.getContext().emitError(
1041         "Could not setup Inlining Advisor for the requested "
1042         "mode and/or options");
1043     return PreservedAnalyses::all();
1044   }
1045 
1046   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
1047   // to detect when we devirtualize indirect calls and iterate the SCC passes
1048   // in that case to try and catch knock-on inlining or function attrs
1049   // opportunities. Then we add it to the module pipeline by walking the SCCs
1050   // in postorder (or bottom-up).
1051   // If MaxDevirtIterations is 0, we just don't use the devirtualization
1052   // wrapper.
1053   if (MaxDevirtIterations == 0)
1054     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(PM)));
1055   else
1056     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1057         createDevirtSCCRepeatedPass(std::move(PM), MaxDevirtIterations)));
1058   auto Ret = MPM.run(M, MAM);
1059 
1060   IAA.clear();
1061   return Ret;
1062 }
1063