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