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