blob: 10b20cfc917f7b2c3281cfad296487f950ddafc4 [file] [log] [blame]
Chris Lattner7d30a6c2004-06-20 04:11:48 +00001//===- Inliner.cpp - Code common to all inliners --------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerd075cc22003-08-31 19:10:30 +00009//
Chris Lattner6754b822004-05-23 21:22:17 +000010// This file implements the mechanics required to implement inlining without
11// missing any calls and updating the call graph. The decisions of which calls
12// are profitable to inline are implemented elsewhere.
Chris Lattnerd075cc22003-08-31 19:10:30 +000013//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/IPO/InlinerPass.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/Statistic.h"
Chris Lattnerd075cc22003-08-31 19:10:30 +000019#include "llvm/Analysis/CallGraph.h"
Dan Gohman4552e3c2009-10-13 18:30:07 +000020#include "llvm/Analysis/InlineCost.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Diego Novilloa9298b22014-04-08 16:42:34 +000023#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instructions.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Module.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000029#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetLibraryInfo.h"
31#include "llvm/Transforms/Utils/Cloning.h"
32#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera82f1312003-11-21 21:45:31 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "inline"
36
Chris Lattner1631bcb2006-12-19 22:09:18 +000037STATISTIC(NumInlined, "Number of functions inlined");
Chris Lattnerb49a6222010-05-01 17:19:38 +000038STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
Chris Lattner1631bcb2006-12-19 22:09:18 +000039STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
Chris Lattnerd3374e82009-08-27 06:29:33 +000040STATISTIC(NumMergedAllocas, "Number of allocas merged together");
Chris Lattner1631bcb2006-12-19 22:09:18 +000041
Benjamin Kramerbde91762012-06-02 10:20:22 +000042// This weirdly named statistic tracks the number of times that, when attempting
Chandler Carruth7ae90d42012-04-11 10:15:10 +000043// to inline a function A into B, we analyze the callers of B in order to see
44// if those would be more profitable and blocked inline steps.
45STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
46
Dan Gohmand78c4002008-05-13 00:00:25 +000047static cl::opt<int>
Jakob Stoklund Olesen113fb542010-02-04 18:48:20 +000048InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
49 cl::desc("Control the amount of inlining to perform (default = 225)"));
Chris Lattnerd075cc22003-08-31 19:10:30 +000050
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +000051static cl::opt<int>
52HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
53 cl::desc("Threshold for inlining functions with inline hint"));
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000054
Manman Rend4612442014-02-06 01:59:22 +000055// We instroduce this threshold to help performance of instrumentation based
56// PGO before we actually hook up inliner with analysis passes such as BPI and
57// BFI.
Manman Rene8781b12014-02-05 22:53:44 +000058static cl::opt<int>
Manman Rend4612442014-02-06 01:59:22 +000059ColdThreshold("inlinecold-threshold", cl::Hidden, cl::init(225),
Manman Rene8781b12014-02-05 22:53:44 +000060 cl::desc("Threshold for inlining functions with cold attribute"));
61
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000062// Threshold to use when optsize is specified (and there is no -inline-limit).
63const int OptSizeThreshold = 75;
64
Owen Andersona7aed182010-08-06 18:33:48 +000065Inliner::Inliner(char &ID)
Chad Rosier07d37bc2012-02-25 02:56:01 +000066 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
Chris Lattnerd075cc22003-08-31 19:10:30 +000067
Chad Rosier07d37bc2012-02-25 02:56:01 +000068Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
Jakob Stoklund Olesen31a7eb42010-11-02 23:40:26 +000069 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
Chad Rosier07d37bc2012-02-25 02:56:01 +000070 InlineLimit : Threshold),
71 InsertLifetime(InsertLifetime) {}
Chris Lattner22ad7ab2008-01-12 06:49:13 +000072
Chris Lattnerf94bed32007-01-30 23:28:39 +000073/// getAnalysisUsage - For this class, we declare that we require and preserve
74/// the call graph. If the derived class implements this method, it should
75/// always explicitly call the implementation here.
Chandler Carruthe40e60e2012-12-27 11:17:15 +000076void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
77 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnerf94bed32007-01-30 23:28:39 +000078}
79
Chris Lattnerd3374e82009-08-27 06:29:33 +000080
Chris Lattner229907c2011-07-18 04:54:35 +000081typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
Chris Lattnerd3374e82009-08-27 06:29:33 +000082InlinedArrayAllocasTy;
83
Bill Wendlingd154e2832013-01-23 06:41:41 +000084/// \brief If the inlined function had a higher stack protection level than the
85/// calling function, then bump up the caller's stack protection level.
86static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
87 // If upgrading the SSP attribute, clear out the old SSP Attributes first.
88 // Having multiple SSP attributes doesn't actually hurt, but it adds useless
89 // clutter to the IR.
90 AttrBuilder B;
91 B.addAttribute(Attribute::StackProtect)
92 .addAttribute(Attribute::StackProtectStrong);
93 AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
94 AttributeSet::FunctionIndex,
95 B);
96 AttributeSet CallerAttr = Caller->getAttributes(),
97 CalleeAttr = Callee->getAttributes();
98
99 if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
100 Attribute::StackProtectReq)) {
101 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
102 Caller->addFnAttr(Attribute::StackProtectReq);
103 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
104 Attribute::StackProtectStrong) &&
105 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
106 Attribute::StackProtectReq)) {
107 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
108 Caller->addFnAttr(Attribute::StackProtectStrong);
109 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
110 Attribute::StackProtect) &&
111 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
112 Attribute::StackProtectReq) &&
113 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
114 Attribute::StackProtectStrong))
115 Caller->addFnAttr(Attribute::StackProtect);
116}
117
Chris Lattnerd3374e82009-08-27 06:29:33 +0000118/// InlineCallIfPossible - If it is possible to inline the specified call site,
119/// do so and update the CallGraph for this operation.
120///
121/// This function also does some basic book-keeping to update the IR. The
Chris Lattner0e890182009-08-28 04:48:54 +0000122/// InlinedArrayAllocas map keeps track of any allocas that are already
123/// available from other functions inlined into the caller. If we are able to
124/// inline this call site we attempt to reuse already available allocas or add
125/// any new allocas to the set if not possible.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000126static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
Chris Lattnerfb212de2010-12-06 07:52:42 +0000127 InlinedArrayAllocasTy &InlinedArrayAllocas,
Hal Finkel9caa8f72013-07-16 17:10:55 +0000128 int InlineHistory, bool InsertLifetime,
Rafael Espindola612886f2014-02-21 01:53:35 +0000129 const DataLayout *DL) {
Chris Lattner6754b822004-05-23 21:22:17 +0000130 Function *Callee = CS.getCalledFunction();
Bill Wendlingf5260d22008-11-21 00:09:21 +0000131 Function *Caller = CS.getCaller();
132
Chris Lattnerd3374e82009-08-27 06:29:33 +0000133 // Try to inline the function. Get the list of static allocas that were
134 // inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +0000135 if (!InlineFunction(CS, IFI, InsertLifetime))
Chris Lattnerb9d0a962009-08-27 04:32:07 +0000136 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000137
Bill Wendlingd154e2832013-01-23 06:41:41 +0000138 AdjustCallerSSPLevel(Caller, Callee);
Bill Wendling26c6a3e2008-11-21 00:06:32 +0000139
Chris Lattnerd3374e82009-08-27 06:29:33 +0000140 // Look at all of the allocas that we inlined through this call site. If we
141 // have already inlined other allocas through other calls into this function,
142 // then we know that they have disjoint lifetimes and that we can merge them.
143 //
144 // There are many heuristics possible for merging these allocas, and the
145 // different options have different tradeoffs. One thing that we *really*
146 // don't want to hurt is SRoA: once inlining happens, often allocas are no
147 // longer address taken and so they can be promoted.
148 //
149 // Our "solution" for that is to only merge allocas whose outermost type is an
150 // array type. These are usually not promoted because someone is using a
151 // variable index into them. These are also often the most important ones to
152 // merge.
153 //
154 // A better solution would be to have real memory lifetime markers in the IR
155 // and not have the inliner do any merging of allocas at all. This would
156 // allow the backend to do proper stack slot coloring of all allocas that
157 // *actually make it to the backend*, which is really what we want.
158 //
159 // Because we don't have this information, we do this simple and useful hack.
160 //
161 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
162
Chris Lattnerfb212de2010-12-06 07:52:42 +0000163 // When processing our SCC, check to see if CS was inlined from some other
164 // call site. For example, if we're processing "A" in this code:
165 // A() { B() }
166 // B() { x = alloca ... C() }
167 // C() { y = alloca ... }
168 // Assume that C was not inlined into B initially, and so we're processing A
169 // and decide to inline B into A. Doing this makes an alloca available for
170 // reuse and makes a callsite (C) available for inlining. When we process
171 // the C call site we don't want to do any alloca merging between X and Y
172 // because their scopes are not disjoint. We could make this smarter by
173 // keeping track of the inline history for each alloca in the
174 // InlinedArrayAllocas but this isn't likely to be a significant win.
175 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
176 return true;
177
Chris Lattnerd3374e82009-08-27 06:29:33 +0000178 // Loop over all the allocas we have so far and see if they can be merged with
179 // a previously inlined alloca. If not, remember that we had it.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000180 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
Chris Lattnerd3374e82009-08-27 06:29:33 +0000181 AllocaNo != e; ++AllocaNo) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000182 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chris Lattnerd3374e82009-08-27 06:29:33 +0000183
184 // Don't bother trying to merge array allocations (they will usually be
185 // canonicalized to be an allocation *of* an array), or allocations whose
186 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattner229907c2011-07-18 04:54:35 +0000187 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Craig Topperf40110f2014-04-25 05:29:35 +0000188 if (!ATy || AI->isArrayAllocation())
Chris Lattnerd3374e82009-08-27 06:29:33 +0000189 continue;
190
191 // Get the list of all available allocas for this array type.
192 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
193
194 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
195 // that we have to be careful not to reuse the same "available" alloca for
196 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
197 // set to keep track of which "available" allocas are being used by this
198 // function. Also, AllocasForType can be empty of course!
199 bool MergedAwayAlloca = false;
200 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
201 AllocaInst *AvailableAlloca = AllocasForType[i];
Hal Finkel9caa8f72013-07-16 17:10:55 +0000202
203 unsigned Align1 = AI->getAlignment(),
204 Align2 = AvailableAlloca->getAlignment();
205 // If we don't have data layout information, and only one alloca is using
206 // the target default, then we can't safely merge them because we can't
207 // pick the greater alignment.
Rafael Espindola612886f2014-02-21 01:53:35 +0000208 if (!DL && (!Align1 || !Align2) && Align1 != Align2)
Hal Finkel9caa8f72013-07-16 17:10:55 +0000209 continue;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000210
211 // The available alloca has to be in the right function, not in some other
212 // function in this SCC.
213 if (AvailableAlloca->getParent() != AI->getParent())
214 continue;
215
216 // If the inlined function already uses this alloca then we can't reuse
217 // it.
218 if (!UsedAllocas.insert(AvailableAlloca))
219 continue;
220
221 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
222 // success!
Chris Lattner5b6a8652010-12-06 07:38:40 +0000223 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
224 << *AvailableAlloca << '\n');
Chris Lattnerd3374e82009-08-27 06:29:33 +0000225
226 AI->replaceAllUsesWith(AvailableAlloca);
Hal Finkel9caa8f72013-07-16 17:10:55 +0000227
Hal Finkelec7cd262013-07-17 14:32:41 +0000228 if (Align1 != Align2) {
229 if (!Align1 || !Align2) {
Rafael Espindola612886f2014-02-21 01:53:35 +0000230 assert(DL && "DataLayout required to compare default alignments");
231 unsigned TypeAlign = DL->getABITypeAlignment(AI->getAllocatedType());
Hal Finkelec7cd262013-07-17 14:32:41 +0000232
233 Align1 = Align1 ? Align1 : TypeAlign;
234 Align2 = Align2 ? Align2 : TypeAlign;
235 }
236
237 if (Align1 > Align2)
238 AvailableAlloca->setAlignment(AI->getAlignment());
239 }
Hal Finkel9caa8f72013-07-16 17:10:55 +0000240
Chris Lattnerd3374e82009-08-27 06:29:33 +0000241 AI->eraseFromParent();
242 MergedAwayAlloca = true;
243 ++NumMergedAllocas;
Craig Topperf40110f2014-04-25 05:29:35 +0000244 IFI.StaticAllocas[AllocaNo] = nullptr;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000245 break;
246 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000247
Chris Lattnerd3374e82009-08-27 06:29:33 +0000248 // If we already nuked the alloca, we're done with it.
249 if (MergedAwayAlloca)
250 continue;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000251
Chris Lattnerd3374e82009-08-27 06:29:33 +0000252 // If we were unable to merge away the alloca either because there are no
253 // allocas of the right type available or because we reused them all
254 // already, remember that this alloca came from an inlined function and mark
255 // it used so we don't reuse it for other allocas from this inline
256 // operation.
257 AllocasForType.push_back(AI);
258 UsedAllocas.insert(AI);
Chris Lattner6754b822004-05-23 21:22:17 +0000259 }
Chris Lattnerd3374e82009-08-27 06:29:33 +0000260
Chris Lattner6754b822004-05-23 21:22:17 +0000261 return true;
Chris Lattnerd075cc22003-08-31 19:10:30 +0000262}
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000263
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000264unsigned Inliner::getInlineThreshold(CallSite CS) const {
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000265 int thres = InlineThreshold; // -inline-threshold or else selected by
266 // overall opt level
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000267
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000268 // If -inline-threshold is not given, listen to the optsize attribute when it
269 // would decrease the threshold.
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000270 Function *Caller = CS.getCaller();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000271 bool OptSize = Caller && !Caller->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000272 Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
273 Attribute::OptimizeForSize);
Nadav Rotem97d44342012-09-13 16:27:32 +0000274 if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
275 OptSizeThreshold < thres)
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000276 thres = OptSizeThreshold;
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000277
Quentin Colombetc0dba202012-12-13 01:05:25 +0000278 // Listen to the inlinehint attribute when it would increase the threshold
279 // and the caller does not need to minimize its size.
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000280 Function *Callee = CS.getCalledFunction();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000281 bool InlineHint = Callee && !Callee->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000282 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
283 Attribute::InlineHint);
Quentin Colombetc0dba202012-12-13 01:05:25 +0000284 if (InlineHint && HintThreshold > thres
Bill Wendling698e84f2012-12-30 10:32:01 +0000285 && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
286 Attribute::MinSize))
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000287 thres = HintThreshold;
288
Manman Rene8781b12014-02-05 22:53:44 +0000289 // Listen to the cold attribute when it would decrease the threshold.
290 bool ColdCallee = Callee && !Callee->isDeclaration() &&
291 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
292 Attribute::Cold);
Manman Ren3c440672014-04-25 17:34:55 +0000293 // Command line argument for InlineLimit will override the default
294 // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
295 // do not use the default cold threshold even if it is smaller.
296 if ((InlineLimit.getNumOccurrences() == 0 ||
297 ColdThreshold.getNumOccurrences() > 0) && ColdCallee &&
298 ColdThreshold < thres)
Manman Rene8781b12014-02-05 22:53:44 +0000299 thres = ColdThreshold;
300
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000301 return thres;
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000302}
303
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000304/// shouldInline - Return true if the inliner should attempt to inline
305/// at the given CallSite.
306bool Inliner::shouldInline(CallSite CS) {
Daniel Dunbar3933e662008-10-30 19:26:59 +0000307 InlineCost IC = getInlineCost(CS);
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000308
Daniel Dunbar3933e662008-10-30 19:26:59 +0000309 if (IC.isAlways()) {
David Greene0122fc42010-01-05 01:27:51 +0000310 DEBUG(dbgs() << " Inlining: cost=always"
Bill Wendling2602bb42009-07-31 19:52:24 +0000311 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000312 return true;
313 }
314
315 if (IC.isNever()) {
David Greene0122fc42010-01-05 01:27:51 +0000316 DEBUG(dbgs() << " NOT Inlining: cost=never"
Bill Wendling2602bb42009-07-31 19:52:24 +0000317 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000318 return false;
319 }
320
Dale Johannesen30599242009-10-09 00:11:32 +0000321 Function *Caller = CS.getCaller();
Chandler Carruth0539c072012-03-31 12:42:41 +0000322 if (!IC) {
323 DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
324 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Bill Wendling2602bb42009-07-31 19:52:24 +0000325 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000326 return false;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000327 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000328
Chandler Carruth30b84162012-03-14 20:16:41 +0000329 // Try to detect the case where the current inlining candidate caller (call
330 // it B) is a static or linkonce-ODR function and is an inlining candidate
331 // elsewhere, and the current candidate callee (call it C) is large enough
332 // that inlining it into B would make B too big to inline later. In these
333 // circumstances it may be best not to inline C into B, but to inline B into
334 // its callers.
335 //
336 // This only applies to static and linkonce-ODR functions because those are
337 // expected to be available for inlining in the translation units where they
338 // are used. Thus we will always have the opportunity to make local inlining
339 // decisions. Importantly the linkonce-ODR linkage covers inline functions
340 // and templates in C++.
Chandler Carruth0539c072012-03-31 12:42:41 +0000341 //
342 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
343 // the internal implementation of the inline cost metrics rather than
344 // treating them as truly abstract units etc.
Chandler Carruth30b84162012-03-14 20:16:41 +0000345 if (Caller->hasLocalLinkage() ||
346 Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
Dale Johannesen30599242009-10-09 00:11:32 +0000347 int TotalSecondaryCost = 0;
Chandler Carruth0539c072012-03-31 12:42:41 +0000348 // The candidate cost to be imposed upon the current function.
349 int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000350 // This bool tracks what happens if we do NOT inline C into B.
Chandler Carruthb9e35fb2012-03-27 10:48:28 +0000351 bool callerWillBeRemoved = Caller->hasLocalLinkage();
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000352 // This bool tracks what happens if we DO inline C into B.
353 bool inliningPreventsSomeOuterInline = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000354 for (User *U : Caller->users()) {
355 CallSite CS2(U);
Dale Johannesen30599242009-10-09 00:11:32 +0000356
357 // If this isn't a call to Caller (it could be some other sort
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000358 // of reference) skip it. Such references will prevent the caller
359 // from being removed.
360 if (!CS2 || CS2.getCalledFunction() != Caller) {
361 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000362 continue;
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000363 }
Dale Johannesen30599242009-10-09 00:11:32 +0000364
365 InlineCost IC2 = getInlineCost(CS2);
Chandler Carruth7ae90d42012-04-11 10:15:10 +0000366 ++NumCallerCallersAnalyzed;
Chandler Carruth0539c072012-03-31 12:42:41 +0000367 if (!IC2) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000368 callerWillBeRemoved = false;
Chandler Carruth0539c072012-03-31 12:42:41 +0000369 continue;
370 }
371 if (IC2.isAlways())
Dale Johannesen30599242009-10-09 00:11:32 +0000372 continue;
373
Chandler Carruth0539c072012-03-31 12:42:41 +0000374 // See if inlining or original callsite would erase the cost delta of
375 // this callsite. We subtract off the penalty for the call instruction,
376 // which we would be deleting.
377 if (IC2.getCostDelta() <= CandidateCost) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000378 inliningPreventsSomeOuterInline = true;
Chandler Carruth0539c072012-03-31 12:42:41 +0000379 TotalSecondaryCost += IC2.getCost();
Dale Johannesen30599242009-10-09 00:11:32 +0000380 }
381 }
382 // If all outer calls to Caller would get inlined, the cost for the last
383 // one is set very low by getInlineCost, in anticipation that Caller will
384 // be removed entirely. We did not account for this above unless there
385 // is only one caller of Caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000386 if (callerWillBeRemoved && !Caller->use_empty())
Dale Johannesen96a5b872009-10-09 21:42:02 +0000387 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
Dale Johannesen30599242009-10-09 00:11:32 +0000388
Chandler Carruth0539c072012-03-31 12:42:41 +0000389 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
390 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
391 " Cost = " << IC.getCost() <<
Dale Johannesen30599242009-10-09 00:11:32 +0000392 ", outer Cost = " << TotalSecondaryCost << '\n');
393 return false;
394 }
395 }
396
Chandler Carruth0539c072012-03-31 12:42:41 +0000397 DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
398 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Dale Johannesen30599242009-10-09 00:11:32 +0000399 << ", Call: " << *CS.getInstruction() << '\n');
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000400 return true;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000401}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000402
Chris Lattnere8262672010-05-01 01:05:10 +0000403/// InlineHistoryIncludes - Return true if the specified inline history ID
404/// indicates an inline history that includes the specified function.
405static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
406 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
407 while (InlineHistoryID != -1) {
408 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
409 "Invalid inline history ID");
410 if (InlineHistory[InlineHistoryID].first == F)
411 return true;
412 InlineHistoryID = InlineHistory[InlineHistoryID].second;
413 }
414 return false;
415}
416
Chris Lattner4422d312010-04-16 22:42:17 +0000417bool Inliner::runOnSCC(CallGraphSCC &SCC) {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000418 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Rafael Espindola93512512014-02-25 17:30:31 +0000419 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +0000420 const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000421 const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
Chris Lattnerd075cc22003-08-31 19:10:30 +0000422
Dale Johannesen32dfb352009-03-23 23:39:20 +0000423 SmallPtrSet<Function*, 8> SCCFunctions;
David Greene0122fc42010-01-05 01:27:51 +0000424 DEBUG(dbgs() << "Inliner visiting SCC:");
Chris Lattner4422d312010-04-16 22:42:17 +0000425 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
426 Function *F = (*I)->getFunction();
Chris Lattner6754b822004-05-23 21:22:17 +0000427 if (F) SCCFunctions.insert(F);
David Greene0122fc42010-01-05 01:27:51 +0000428 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattnerd075cc22003-08-31 19:10:30 +0000429 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000430
Chris Lattner6754b822004-05-23 21:22:17 +0000431 // Scan through and identify all call sites ahead of time so that we only
432 // inline call sites in the original functions, not call sites that result
433 // from inlining other functions.
Chris Lattnere8262672010-05-01 01:05:10 +0000434 SmallVector<std::pair<CallSite, int>, 16> CallSites;
435
436 // When inlining a callee produces new call sites, we want to keep track of
437 // the fact that they were inlined from the callee. This allows us to avoid
438 // infinite inlining in some obscure cases. To represent this, we use an
439 // index into the InlineHistory vector.
440 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
Chris Lattner6754b822004-05-23 21:22:17 +0000441
Chris Lattner4422d312010-04-16 22:42:17 +0000442 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
443 Function *F = (*I)->getFunction();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000444 if (!F) continue;
445
446 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
447 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000448 CallSite CS(cast<Value>(I));
Dale Johannesen30599242009-10-09 00:11:32 +0000449 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattner9e507472009-08-31 05:34:32 +0000450 // never be inlined.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000451 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000452 continue;
453
Chris Lattner9e507472009-08-31 05:34:32 +0000454 // If this is a direct call to an external function, we can never inline
455 // it. If it is an indirect call, inlining may resolve it to be a
456 // direct call, so we keep it.
457 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
458 continue;
459
Chris Lattnere8262672010-05-01 01:05:10 +0000460 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000461 }
462 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000463
David Greene0122fc42010-01-05 01:27:51 +0000464 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000465
Chris Lattnera5cdd5e2010-04-20 00:47:08 +0000466 // If there are no calls in this function, exit early.
467 if (CallSites.empty())
468 return false;
469
Chris Lattner6754b822004-05-23 21:22:17 +0000470 // Now that we have all of the call sites, move the ones to functions in the
471 // current SCC to the end of the list.
472 unsigned FirstCallInSCC = CallSites.size();
473 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattnere8262672010-05-01 01:05:10 +0000474 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattner6754b822004-05-23 21:22:17 +0000475 if (SCCFunctions.count(F))
476 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000477
Chris Lattnerd3374e82009-08-27 06:29:33 +0000478
479 InlinedArrayAllocasTy InlinedArrayAllocas;
Rafael Espindola612886f2014-02-21 01:53:35 +0000480 InlineFunctionInfo InlineInfo(&CG, DL);
Chris Lattnerd3374e82009-08-27 06:29:33 +0000481
Chris Lattner6754b822004-05-23 21:22:17 +0000482 // Now that we have all of the call sites, loop over them and inline them if
483 // it looks profitable to do so.
484 bool Changed = false;
485 bool LocalChange;
486 do {
487 LocalChange = false;
488 // Iterate over the outer loop because inlining functions can cause indirect
489 // calls to become direct calls.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000490 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattnere8262672010-05-01 01:05:10 +0000491 CallSite CS = CallSites[CSi].first;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000492
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000493 Function *Caller = CS.getCaller();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000494 Function *Callee = CS.getCalledFunction();
495
496 // If this call site is dead and it is to a readonly function, we should
497 // just delete the call instead of trying to inline it, regardless of
498 // size. This happens because IPSCCP propagates the result out of the
499 // call and then we're left with the dead call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000500 if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
David Greene0122fc42010-01-05 01:27:51 +0000501 DEBUG(dbgs() << " -> Deleting dead call: "
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000502 << *CS.getInstruction() << "\n");
503 // Update the call graph by deleting the edge from Callee to Caller.
504 CG[Caller]->removeCallEdgeFor(CS);
505 CS.getInstruction()->eraseFromParent();
506 ++NumCallsDeleted;
507 } else {
508 // We can only inline direct calls to non-declarations.
Craig Topperf40110f2014-04-25 05:29:35 +0000509 if (!Callee || Callee->isDeclaration()) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000510
Eric Christopherea2820342010-07-13 18:27:13 +0000511 // If this call site was obtained by inlining another function, verify
Chris Lattnere8262672010-05-01 01:05:10 +0000512 // that the include path for the function did not include the callee
Chris Lattner5b6a8652010-12-06 07:38:40 +0000513 // itself. If so, we'd be recursively inlining the same function,
Chris Lattnere8262672010-05-01 01:05:10 +0000514 // which would provide the same callsites, which would cause us to
515 // infinitely inline.
516 int InlineHistoryID = CallSites[CSi].second;
517 if (InlineHistoryID != -1 &&
518 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
519 continue;
520
521
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000522 // If the policy determines that we should inline this function,
523 // try to do so.
524 if (!shouldInline(CS))
525 continue;
526
NAKAMURA Takumicd1fc4b2014-04-17 12:22:14 +0000527 // Get DebugLoc to report. CS will be invalid after Inliner.
528 DebugLoc DLoc = CS.getInstruction()->getDebugLoc();
529
Chris Lattner2eee5d32010-04-22 23:37:35 +0000530 // Attempt to inline the function.
Chris Lattnerfb212de2010-12-06 07:52:42 +0000531 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
Rafael Espindola612886f2014-02-21 01:53:35 +0000532 InlineHistoryID, InsertLifetime, DL))
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000533 continue;
534 ++NumInlined;
Diego Novilloa9298b22014-04-08 16:42:34 +0000535
536 // Report the inline decision.
537 Caller->getContext().emitOptimizationRemark(
NAKAMURA Takumicd1fc4b2014-04-17 12:22:14 +0000538 DEBUG_TYPE, *Caller, DLoc,
Diego Novilloa9298b22014-04-08 16:42:34 +0000539 Twine(Callee->getName() + " inlined into " + Caller->getName()));
540
Chris Lattnerc2432b92010-05-01 01:26:13 +0000541 // If inlining this function gave us any new call sites, throw them
Chris Lattner2eee5d32010-04-22 23:37:35 +0000542 // onto our worklist to process. They are useful inline candidates.
Chris Lattnerc2432b92010-05-01 01:26:13 +0000543 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattnere8262672010-05-01 01:05:10 +0000544 // Create a new inline history entry for this, so that we remember
545 // that these new callsites came about due to inlining Callee.
546 int NewHistoryID = InlineHistory.size();
547 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
548
Chris Lattnerc2432b92010-05-01 01:26:13 +0000549 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
Chris Lattnere8262672010-05-01 01:05:10 +0000550 i != e; ++i) {
Chris Lattnerc2432b92010-05-01 01:26:13 +0000551 Value *Ptr = InlineInfo.InlinedCalls[i];
Chandler Carruth21211992012-03-25 04:03:40 +0000552 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
Chris Lattnere8262672010-05-01 01:05:10 +0000553 }
Chris Lattnerc691de32010-04-23 18:37:01 +0000554 }
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000555 }
556
557 // If we inlined or deleted the last possible call site to the function,
558 // delete the function body now.
559 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattner9e507472009-08-31 05:34:32 +0000560 // TODO: Can remove if in SCC now.
Chris Lattner081375b2009-08-31 03:15:49 +0000561 !SCCFunctions.count(Callee) &&
Chris Lattner9e507472009-08-31 05:34:32 +0000562
Chris Lattner081375b2009-08-31 03:15:49 +0000563 // The function may be apparently dead, but if there are indirect
564 // callgraph references to the node, we cannot delete it yet, this
565 // could invalidate the CGSCC iterator.
566 CG[Callee]->getNumReferences() == 0) {
David Greene0122fc42010-01-05 01:27:51 +0000567 DEBUG(dbgs() << " -> Deleting dead function: "
Chris Lattnerd3374e82009-08-27 06:29:33 +0000568 << Callee->getName() << "\n");
569 CallGraphNode *CalleeNode = CG[Callee];
570
571 // Remove any call graph edges from the callee to its callees.
572 CalleeNode->removeAllCalledFunctions();
573
Chris Lattnerd3374e82009-08-27 06:29:33 +0000574 // Removing the node for callee from the call graph and delete it.
575 delete CG.removeFunctionFromModule(CalleeNode);
576 ++NumDeleted;
577 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000578
579 // Remove this call site from the list. If possible, use
580 // swap/pop_back for efficiency, but do not use it if doing so would
581 // move a call site to a function in this SCC before the
582 // 'FirstCallInSCC' barrier.
Chris Lattner4422d312010-04-16 22:42:17 +0000583 if (SCC.isSingular()) {
Benjamin Kramer5ac57e32010-05-31 12:50:41 +0000584 CallSites[CSi] = CallSites.back();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000585 CallSites.pop_back();
586 } else {
587 CallSites.erase(CallSites.begin()+CSi);
588 }
589 --CSi;
590
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000591 Changed = true;
592 LocalChange = true;
593 }
Chris Lattner6754b822004-05-23 21:22:17 +0000594 } while (LocalChange);
Chris Lattner4d25c862004-04-08 06:34:31 +0000595
Chris Lattnerd075cc22003-08-31 19:10:30 +0000596 return Changed;
597}
598
Chris Lattnerc87784f2004-04-20 22:06:53 +0000599// doFinalization - Remove now-dead linkonce functions at the end of
600// processing to avoid breaking the SCC traversal.
601bool Inliner::doFinalization(CallGraph &CG) {
Devang Patelf0ef3572008-11-05 01:39:16 +0000602 return removeDeadFunctions(CG);
603}
604
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000605/// removeDeadFunctions - Remove dead functions that are not included in
606/// DNR (Do Not Remove) list.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000607bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
608 SmallVector<CallGraphNode*, 16> FunctionsToRemove;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000609
610 // Scan for all of the functions, looking for ones that should now be removed
611 // from the program. Insert the dead ones in the FunctionsToRemove set.
612 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
613 CallGraphNode *CGN = I->second;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000614 Function *F = CGN->getFunction();
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000615 if (!F || F->isDeclaration())
616 continue;
617
618 // Handle the case when this function is called and we only want to care
619 // about always-inline functions. This is a bit of a hack to share code
620 // between here and the InlineAlways pass.
Bill Wendlingc9b22d72012-10-09 07:45:08 +0000621 if (AlwaysInlineOnly &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000622 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
623 Attribute::AlwaysInline))
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000624 continue;
625
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000626 // If the only remaining users of the function are dead constants, remove
627 // them.
628 F->removeDeadConstantUsers();
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000629
Eli Friedman1923a332011-10-20 05:23:42 +0000630 if (!F->isDefTriviallyDead())
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000631 continue;
632
633 // Remove any call graph edges from the function to its callees.
634 CGN->removeAllCalledFunctions();
Devang Patelf0ef3572008-11-05 01:39:16 +0000635
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000636 // 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);
Chris Lattner6455c512004-09-18 21:37:03 +0000640
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000641 // Removing the node for callee from the call graph and delete it.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000642 FunctionsToRemove.push_back(CGN);
Chris Lattnerc87784f2004-04-20 22:06:53 +0000643 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000644 if (FunctionsToRemove.empty())
645 return false;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000646
647 // Now that we know which functions to delete, do so. We didn't want to do
648 // this inline, because that would invalidate our CallGraph::iterator
649 // objects. :(
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000650 //
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000651 // Note that it doesn't matter that we are iterating over a non-stable order
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000652 // here to do this, it doesn't matter which order the functions are deleted
653 // in.
Chandler Carruth45ae88f2012-04-01 10:41:24 +0000654 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000655 FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
656 FunctionsToRemove.end()),
657 FunctionsToRemove.end());
658 for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
659 E = FunctionsToRemove.end();
660 I != E; ++I) {
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000661 delete CG.removeFunctionFromModule(*I);
662 ++NumDeleted;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000663 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000664 return true;
Chris Lattnerc87784f2004-04-20 22:06:53 +0000665}