Inliner.cpp 51 KB

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