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