blob: 663ddb75f42361dea66c8430aaae3fe4d8128614 [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
Chris Lattner1631bcb2006-12-19 22:09:18 +000016#define DEBUG_TYPE "inline"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/Transforms/IPO/InlinerPass.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Chris Lattnerd075cc22003-08-31 19:10:30 +000020#include "llvm/Analysis/CallGraph.h"
Dan Gohman4552e3c2009-10-13 18:30:07 +000021#include "llvm/Analysis/InlineCost.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/Module.h"
Chris Lattner5c89f4b2009-11-12 21:58:18 +000026#include "llvm/Support/CallSite.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
Chris Lattner1631bcb2006-12-19 22:09:18 +000035STATISTIC(NumInlined, "Number of functions inlined");
Chris Lattnerb49a6222010-05-01 17:19:38 +000036STATISTIC(NumCallsDeleted, "Number of call sites deleted, not inlined");
Chris Lattner1631bcb2006-12-19 22:09:18 +000037STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
Chris Lattnerd3374e82009-08-27 06:29:33 +000038STATISTIC(NumMergedAllocas, "Number of allocas merged together");
Chris Lattner1631bcb2006-12-19 22:09:18 +000039
Benjamin Kramerbde91762012-06-02 10:20:22 +000040// This weirdly named statistic tracks the number of times that, when attempting
Chandler Carruth7ae90d42012-04-11 10:15:10 +000041// to inline a function A into B, we analyze the callers of B in order to see
42// if those would be more profitable and blocked inline steps.
43STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
44
Dan Gohmand78c4002008-05-13 00:00:25 +000045static cl::opt<int>
Jakob Stoklund Olesen113fb542010-02-04 18:48:20 +000046InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
47 cl::desc("Control the amount of inlining to perform (default = 225)"));
Chris Lattnerd075cc22003-08-31 19:10:30 +000048
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +000049static cl::opt<int>
50HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
51 cl::desc("Threshold for inlining functions with inline hint"));
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000052
53// Threshold to use when optsize is specified (and there is no -inline-limit).
54const int OptSizeThreshold = 75;
55
Owen Andersona7aed182010-08-06 18:33:48 +000056Inliner::Inliner(char &ID)
Chad Rosier07d37bc2012-02-25 02:56:01 +000057 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
Chris Lattnerd075cc22003-08-31 19:10:30 +000058
Chad Rosier07d37bc2012-02-25 02:56:01 +000059Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
Jakob Stoklund Olesen31a7eb42010-11-02 23:40:26 +000060 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
Chad Rosier07d37bc2012-02-25 02:56:01 +000061 InlineLimit : Threshold),
62 InsertLifetime(InsertLifetime) {}
Chris Lattner22ad7ab2008-01-12 06:49:13 +000063
Chris Lattnerf94bed32007-01-30 23:28:39 +000064/// getAnalysisUsage - For this class, we declare that we require and preserve
65/// the call graph. If the derived class implements this method, it should
66/// always explicitly call the implementation here.
Chandler Carruthe40e60e2012-12-27 11:17:15 +000067void Inliner::getAnalysisUsage(AnalysisUsage &AU) const {
68 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnerf94bed32007-01-30 23:28:39 +000069}
70
Chris Lattnerd3374e82009-08-27 06:29:33 +000071
Chris Lattner229907c2011-07-18 04:54:35 +000072typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
Chris Lattnerd3374e82009-08-27 06:29:33 +000073InlinedArrayAllocasTy;
74
Bill Wendlingd154e2832013-01-23 06:41:41 +000075/// \brief If the inlined function had a higher stack protection level than the
76/// calling function, then bump up the caller's stack protection level.
77static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
78 // If upgrading the SSP attribute, clear out the old SSP Attributes first.
79 // Having multiple SSP attributes doesn't actually hurt, but it adds useless
80 // clutter to the IR.
81 AttrBuilder B;
82 B.addAttribute(Attribute::StackProtect)
83 .addAttribute(Attribute::StackProtectStrong);
84 AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(),
85 AttributeSet::FunctionIndex,
86 B);
87 AttributeSet CallerAttr = Caller->getAttributes(),
88 CalleeAttr = Callee->getAttributes();
89
90 if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
91 Attribute::StackProtectReq)) {
92 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
93 Caller->addFnAttr(Attribute::StackProtectReq);
94 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
95 Attribute::StackProtectStrong) &&
96 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
97 Attribute::StackProtectReq)) {
98 Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr);
99 Caller->addFnAttr(Attribute::StackProtectStrong);
100 } else if (CalleeAttr.hasAttribute(AttributeSet::FunctionIndex,
101 Attribute::StackProtect) &&
102 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
103 Attribute::StackProtectReq) &&
104 !CallerAttr.hasAttribute(AttributeSet::FunctionIndex,
105 Attribute::StackProtectStrong))
106 Caller->addFnAttr(Attribute::StackProtect);
107}
108
Chris Lattnerd3374e82009-08-27 06:29:33 +0000109/// InlineCallIfPossible - If it is possible to inline the specified call site,
110/// do so and update the CallGraph for this operation.
111///
112/// This function also does some basic book-keeping to update the IR. The
Chris Lattner0e890182009-08-28 04:48:54 +0000113/// InlinedArrayAllocas map keeps track of any allocas that are already
114/// available from other functions inlined into the caller. If we are able to
115/// inline this call site we attempt to reuse already available allocas or add
116/// any new allocas to the set if not possible.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000117static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
Chris Lattnerfb212de2010-12-06 07:52:42 +0000118 InlinedArrayAllocasTy &InlinedArrayAllocas,
Chad Rosier07d37bc2012-02-25 02:56:01 +0000119 int InlineHistory, bool InsertLifetime) {
Chris Lattner6754b822004-05-23 21:22:17 +0000120 Function *Callee = CS.getCalledFunction();
Bill Wendlingf5260d22008-11-21 00:09:21 +0000121 Function *Caller = CS.getCaller();
122
Chris Lattnerd3374e82009-08-27 06:29:33 +0000123 // Try to inline the function. Get the list of static allocas that were
124 // inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +0000125 if (!InlineFunction(CS, IFI, InsertLifetime))
Chris Lattnerb9d0a962009-08-27 04:32:07 +0000126 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000127
Bill Wendlingd154e2832013-01-23 06:41:41 +0000128 AdjustCallerSSPLevel(Caller, Callee);
Bill Wendling26c6a3e2008-11-21 00:06:32 +0000129
Chris Lattnerd3374e82009-08-27 06:29:33 +0000130 // Look at all of the allocas that we inlined through this call site. If we
131 // have already inlined other allocas through other calls into this function,
132 // then we know that they have disjoint lifetimes and that we can merge them.
133 //
134 // There are many heuristics possible for merging these allocas, and the
135 // different options have different tradeoffs. One thing that we *really*
136 // don't want to hurt is SRoA: once inlining happens, often allocas are no
137 // longer address taken and so they can be promoted.
138 //
139 // Our "solution" for that is to only merge allocas whose outermost type is an
140 // array type. These are usually not promoted because someone is using a
141 // variable index into them. These are also often the most important ones to
142 // merge.
143 //
144 // A better solution would be to have real memory lifetime markers in the IR
145 // and not have the inliner do any merging of allocas at all. This would
146 // allow the backend to do proper stack slot coloring of all allocas that
147 // *actually make it to the backend*, which is really what we want.
148 //
149 // Because we don't have this information, we do this simple and useful hack.
150 //
151 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
152
Chris Lattnerfb212de2010-12-06 07:52:42 +0000153 // When processing our SCC, check to see if CS was inlined from some other
154 // call site. For example, if we're processing "A" in this code:
155 // A() { B() }
156 // B() { x = alloca ... C() }
157 // C() { y = alloca ... }
158 // Assume that C was not inlined into B initially, and so we're processing A
159 // and decide to inline B into A. Doing this makes an alloca available for
160 // reuse and makes a callsite (C) available for inlining. When we process
161 // the C call site we don't want to do any alloca merging between X and Y
162 // because their scopes are not disjoint. We could make this smarter by
163 // keeping track of the inline history for each alloca in the
164 // InlinedArrayAllocas but this isn't likely to be a significant win.
165 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
166 return true;
167
Chris Lattnerd3374e82009-08-27 06:29:33 +0000168 // Loop over all the allocas we have so far and see if they can be merged with
169 // a previously inlined alloca. If not, remember that we had it.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000170 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
Chris Lattnerd3374e82009-08-27 06:29:33 +0000171 AllocaNo != e; ++AllocaNo) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000172 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chris Lattnerd3374e82009-08-27 06:29:33 +0000173
174 // Don't bother trying to merge array allocations (they will usually be
175 // canonicalized to be an allocation *of* an array), or allocations whose
176 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattner229907c2011-07-18 04:54:35 +0000177 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerd3374e82009-08-27 06:29:33 +0000178 if (ATy == 0 || AI->isArrayAllocation())
179 continue;
180
181 // Get the list of all available allocas for this array type.
182 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
183
184 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
185 // that we have to be careful not to reuse the same "available" alloca for
186 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
187 // set to keep track of which "available" allocas are being used by this
188 // function. Also, AllocasForType can be empty of course!
189 bool MergedAwayAlloca = false;
190 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
191 AllocaInst *AvailableAlloca = AllocasForType[i];
192
193 // The available alloca has to be in the right function, not in some other
194 // function in this SCC.
195 if (AvailableAlloca->getParent() != AI->getParent())
196 continue;
197
198 // If the inlined function already uses this alloca then we can't reuse
199 // it.
200 if (!UsedAllocas.insert(AvailableAlloca))
201 continue;
202
203 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
204 // success!
Chris Lattner5b6a8652010-12-06 07:38:40 +0000205 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
206 << *AvailableAlloca << '\n');
Chris Lattnerd3374e82009-08-27 06:29:33 +0000207
208 AI->replaceAllUsesWith(AvailableAlloca);
209 AI->eraseFromParent();
210 MergedAwayAlloca = true;
211 ++NumMergedAllocas;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000212 IFI.StaticAllocas[AllocaNo] = 0;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000213 break;
214 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000215
Chris Lattnerd3374e82009-08-27 06:29:33 +0000216 // If we already nuked the alloca, we're done with it.
217 if (MergedAwayAlloca)
218 continue;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000219
Chris Lattnerd3374e82009-08-27 06:29:33 +0000220 // If we were unable to merge away the alloca either because there are no
221 // allocas of the right type available or because we reused them all
222 // already, remember that this alloca came from an inlined function and mark
223 // it used so we don't reuse it for other allocas from this inline
224 // operation.
225 AllocasForType.push_back(AI);
226 UsedAllocas.insert(AI);
Chris Lattner6754b822004-05-23 21:22:17 +0000227 }
Chris Lattnerd3374e82009-08-27 06:29:33 +0000228
Chris Lattner6754b822004-05-23 21:22:17 +0000229 return true;
Chris Lattnerd075cc22003-08-31 19:10:30 +0000230}
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000231
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000232unsigned Inliner::getInlineThreshold(CallSite CS) const {
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000233 int thres = InlineThreshold; // -inline-threshold or else selected by
234 // overall opt level
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000235
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000236 // If -inline-threshold is not given, listen to the optsize attribute when it
237 // would decrease the threshold.
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000238 Function *Caller = CS.getCaller();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000239 bool OptSize = Caller && !Caller->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000240 Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
241 Attribute::OptimizeForSize);
Nadav Rotem97d44342012-09-13 16:27:32 +0000242 if (!(InlineLimit.getNumOccurrences() > 0) && OptSize &&
243 OptSizeThreshold < thres)
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000244 thres = OptSizeThreshold;
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000245
Quentin Colombetc0dba202012-12-13 01:05:25 +0000246 // Listen to the inlinehint attribute when it would increase the threshold
247 // and the caller does not need to minimize its size.
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000248 Function *Callee = CS.getCalledFunction();
Patrik Hägglund8a1e3162012-05-23 13:42:57 +0000249 bool InlineHint = Callee && !Callee->isDeclaration() &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000250 Callee->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
251 Attribute::InlineHint);
Quentin Colombetc0dba202012-12-13 01:05:25 +0000252 if (InlineHint && HintThreshold > thres
Bill Wendling698e84f2012-12-30 10:32:01 +0000253 && !Caller->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
254 Attribute::MinSize))
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000255 thres = HintThreshold;
256
257 return thres;
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000258}
259
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000260/// shouldInline - Return true if the inliner should attempt to inline
261/// at the given CallSite.
262bool Inliner::shouldInline(CallSite CS) {
Daniel Dunbar3933e662008-10-30 19:26:59 +0000263 InlineCost IC = getInlineCost(CS);
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000264
Daniel Dunbar3933e662008-10-30 19:26:59 +0000265 if (IC.isAlways()) {
David Greene0122fc42010-01-05 01:27:51 +0000266 DEBUG(dbgs() << " Inlining: cost=always"
Bill Wendling2602bb42009-07-31 19:52:24 +0000267 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000268 return true;
269 }
270
271 if (IC.isNever()) {
David Greene0122fc42010-01-05 01:27:51 +0000272 DEBUG(dbgs() << " NOT Inlining: cost=never"
Bill Wendling2602bb42009-07-31 19:52:24 +0000273 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000274 return false;
275 }
276
Dale Johannesen30599242009-10-09 00:11:32 +0000277 Function *Caller = CS.getCaller();
Chandler Carruth0539c072012-03-31 12:42:41 +0000278 if (!IC) {
279 DEBUG(dbgs() << " NOT Inlining: cost=" << IC.getCost()
280 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Bill Wendling2602bb42009-07-31 19:52:24 +0000281 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000282 return false;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000283 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000284
Chandler Carruth30b84162012-03-14 20:16:41 +0000285 // Try to detect the case where the current inlining candidate caller (call
286 // it B) is a static or linkonce-ODR function and is an inlining candidate
287 // elsewhere, and the current candidate callee (call it C) is large enough
288 // that inlining it into B would make B too big to inline later. In these
289 // circumstances it may be best not to inline C into B, but to inline B into
290 // its callers.
291 //
292 // This only applies to static and linkonce-ODR functions because those are
293 // expected to be available for inlining in the translation units where they
294 // are used. Thus we will always have the opportunity to make local inlining
295 // decisions. Importantly the linkonce-ODR linkage covers inline functions
296 // and templates in C++.
Chandler Carruth0539c072012-03-31 12:42:41 +0000297 //
298 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
299 // the internal implementation of the inline cost metrics rather than
300 // treating them as truly abstract units etc.
Chandler Carruth30b84162012-03-14 20:16:41 +0000301 if (Caller->hasLocalLinkage() ||
302 Caller->getLinkage() == GlobalValue::LinkOnceODRLinkage) {
Dale Johannesen30599242009-10-09 00:11:32 +0000303 int TotalSecondaryCost = 0;
Chandler Carruth0539c072012-03-31 12:42:41 +0000304 // The candidate cost to be imposed upon the current function.
305 int CandidateCost = IC.getCost() - (InlineConstants::CallPenalty + 1);
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000306 // This bool tracks what happens if we do NOT inline C into B.
Chandler Carruthb9e35fb2012-03-27 10:48:28 +0000307 bool callerWillBeRemoved = Caller->hasLocalLinkage();
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000308 // This bool tracks what happens if we DO inline C into B.
309 bool inliningPreventsSomeOuterInline = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000310 for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
311 I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000312 CallSite CS2(*I);
Dale Johannesen30599242009-10-09 00:11:32 +0000313
314 // If this isn't a call to Caller (it could be some other sort
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000315 // of reference) skip it. Such references will prevent the caller
316 // from being removed.
317 if (!CS2 || CS2.getCalledFunction() != Caller) {
318 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000319 continue;
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000320 }
Dale Johannesen30599242009-10-09 00:11:32 +0000321
322 InlineCost IC2 = getInlineCost(CS2);
Chandler Carruth7ae90d42012-04-11 10:15:10 +0000323 ++NumCallerCallersAnalyzed;
Chandler Carruth0539c072012-03-31 12:42:41 +0000324 if (!IC2) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000325 callerWillBeRemoved = false;
Chandler Carruth0539c072012-03-31 12:42:41 +0000326 continue;
327 }
328 if (IC2.isAlways())
Dale Johannesen30599242009-10-09 00:11:32 +0000329 continue;
330
Chandler Carruth0539c072012-03-31 12:42:41 +0000331 // See if inlining or original callsite would erase the cost delta of
332 // this callsite. We subtract off the penalty for the call instruction,
333 // which we would be deleting.
334 if (IC2.getCostDelta() <= CandidateCost) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000335 inliningPreventsSomeOuterInline = true;
Chandler Carruth0539c072012-03-31 12:42:41 +0000336 TotalSecondaryCost += IC2.getCost();
Dale Johannesen30599242009-10-09 00:11:32 +0000337 }
338 }
339 // If all outer calls to Caller would get inlined, the cost for the last
340 // one is set very low by getInlineCost, in anticipation that Caller will
341 // be removed entirely. We did not account for this above unless there
342 // is only one caller of Caller.
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000343 if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
Dale Johannesen96a5b872009-10-09 21:42:02 +0000344 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
Dale Johannesen30599242009-10-09 00:11:32 +0000345
Chandler Carruth0539c072012-03-31 12:42:41 +0000346 if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost()) {
347 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
348 " Cost = " << IC.getCost() <<
Dale Johannesen30599242009-10-09 00:11:32 +0000349 ", outer Cost = " << TotalSecondaryCost << '\n');
350 return false;
351 }
352 }
353
Chandler Carruth0539c072012-03-31 12:42:41 +0000354 DEBUG(dbgs() << " Inlining: cost=" << IC.getCost()
355 << ", thres=" << (IC.getCostDelta() + IC.getCost())
Dale Johannesen30599242009-10-09 00:11:32 +0000356 << ", Call: " << *CS.getInstruction() << '\n');
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000357 return true;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000358}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000359
Chris Lattnere8262672010-05-01 01:05:10 +0000360/// InlineHistoryIncludes - Return true if the specified inline history ID
361/// indicates an inline history that includes the specified function.
362static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
363 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
364 while (InlineHistoryID != -1) {
365 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
366 "Invalid inline history ID");
367 if (InlineHistory[InlineHistoryID].first == F)
368 return true;
369 InlineHistoryID = InlineHistory[InlineHistoryID].second;
370 }
371 return false;
372}
373
Chris Lattner4422d312010-04-16 22:42:17 +0000374bool Inliner::runOnSCC(CallGraphSCC &SCC) {
Chris Lattnerd075cc22003-08-31 19:10:30 +0000375 CallGraph &CG = getAnalysis<CallGraph>();
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000376 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000377 const TargetLibraryInfo *TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
Chris Lattnerd075cc22003-08-31 19:10:30 +0000378
Dale Johannesen32dfb352009-03-23 23:39:20 +0000379 SmallPtrSet<Function*, 8> SCCFunctions;
David Greene0122fc42010-01-05 01:27:51 +0000380 DEBUG(dbgs() << "Inliner visiting SCC:");
Chris Lattner4422d312010-04-16 22:42:17 +0000381 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
382 Function *F = (*I)->getFunction();
Chris Lattner6754b822004-05-23 21:22:17 +0000383 if (F) SCCFunctions.insert(F);
David Greene0122fc42010-01-05 01:27:51 +0000384 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattnerd075cc22003-08-31 19:10:30 +0000385 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000386
Chris Lattner6754b822004-05-23 21:22:17 +0000387 // Scan through and identify all call sites ahead of time so that we only
388 // inline call sites in the original functions, not call sites that result
389 // from inlining other functions.
Chris Lattnere8262672010-05-01 01:05:10 +0000390 SmallVector<std::pair<CallSite, int>, 16> CallSites;
391
392 // When inlining a callee produces new call sites, we want to keep track of
393 // the fact that they were inlined from the callee. This allows us to avoid
394 // infinite inlining in some obscure cases. To represent this, we use an
395 // index into the InlineHistory vector.
396 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
Chris Lattner6754b822004-05-23 21:22:17 +0000397
Chris Lattner4422d312010-04-16 22:42:17 +0000398 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
399 Function *F = (*I)->getFunction();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000400 if (!F) continue;
401
402 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
403 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000404 CallSite CS(cast<Value>(I));
Dale Johannesen30599242009-10-09 00:11:32 +0000405 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattner9e507472009-08-31 05:34:32 +0000406 // never be inlined.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000407 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000408 continue;
409
Chris Lattner9e507472009-08-31 05:34:32 +0000410 // If this is a direct call to an external function, we can never inline
411 // it. If it is an indirect call, inlining may resolve it to be a
412 // direct call, so we keep it.
413 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
414 continue;
415
Chris Lattnere8262672010-05-01 01:05:10 +0000416 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000417 }
418 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000419
David Greene0122fc42010-01-05 01:27:51 +0000420 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000421
Chris Lattnera5cdd5e2010-04-20 00:47:08 +0000422 // If there are no calls in this function, exit early.
423 if (CallSites.empty())
424 return false;
425
Chris Lattner6754b822004-05-23 21:22:17 +0000426 // Now that we have all of the call sites, move the ones to functions in the
427 // current SCC to the end of the list.
428 unsigned FirstCallInSCC = CallSites.size();
429 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattnere8262672010-05-01 01:05:10 +0000430 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattner6754b822004-05-23 21:22:17 +0000431 if (SCCFunctions.count(F))
432 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000433
Chris Lattnerd3374e82009-08-27 06:29:33 +0000434
435 InlinedArrayAllocasTy InlinedArrayAllocas;
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000436 InlineFunctionInfo InlineInfo(&CG, TD);
Chris Lattnerd3374e82009-08-27 06:29:33 +0000437
Chris Lattner6754b822004-05-23 21:22:17 +0000438 // Now that we have all of the call sites, loop over them and inline them if
439 // it looks profitable to do so.
440 bool Changed = false;
441 bool LocalChange;
442 do {
443 LocalChange = false;
444 // Iterate over the outer loop because inlining functions can cause indirect
445 // calls to become direct calls.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000446 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattnere8262672010-05-01 01:05:10 +0000447 CallSite CS = CallSites[CSi].first;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000448
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000449 Function *Caller = CS.getCaller();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000450 Function *Callee = CS.getCalledFunction();
451
452 // If this call site is dead and it is to a readonly function, we should
453 // just delete the call instead of trying to inline it, regardless of
454 // size. This happens because IPSCCP propagates the result out of the
455 // call and then we're left with the dead call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000456 if (isInstructionTriviallyDead(CS.getInstruction(), TLI)) {
David Greene0122fc42010-01-05 01:27:51 +0000457 DEBUG(dbgs() << " -> Deleting dead call: "
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000458 << *CS.getInstruction() << "\n");
459 // Update the call graph by deleting the edge from Callee to Caller.
460 CG[Caller]->removeCallEdgeFor(CS);
461 CS.getInstruction()->eraseFromParent();
462 ++NumCallsDeleted;
463 } else {
464 // We can only inline direct calls to non-declarations.
465 if (Callee == 0 || Callee->isDeclaration()) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000466
Eric Christopherea2820342010-07-13 18:27:13 +0000467 // If this call site was obtained by inlining another function, verify
Chris Lattnere8262672010-05-01 01:05:10 +0000468 // that the include path for the function did not include the callee
Chris Lattner5b6a8652010-12-06 07:38:40 +0000469 // itself. If so, we'd be recursively inlining the same function,
Chris Lattnere8262672010-05-01 01:05:10 +0000470 // which would provide the same callsites, which would cause us to
471 // infinitely inline.
472 int InlineHistoryID = CallSites[CSi].second;
473 if (InlineHistoryID != -1 &&
474 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
475 continue;
476
477
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000478 // If the policy determines that we should inline this function,
479 // try to do so.
480 if (!shouldInline(CS))
481 continue;
482
Chris Lattner2eee5d32010-04-22 23:37:35 +0000483 // Attempt to inline the function.
Chris Lattnerfb212de2010-12-06 07:52:42 +0000484 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
Chad Rosier07d37bc2012-02-25 02:56:01 +0000485 InlineHistoryID, InsertLifetime))
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000486 continue;
487 ++NumInlined;
Chris Lattnere8262672010-05-01 01:05:10 +0000488
Chris Lattnerc2432b92010-05-01 01:26:13 +0000489 // If inlining this function gave us any new call sites, throw them
Chris Lattner2eee5d32010-04-22 23:37:35 +0000490 // onto our worklist to process. They are useful inline candidates.
Chris Lattnerc2432b92010-05-01 01:26:13 +0000491 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattnere8262672010-05-01 01:05:10 +0000492 // Create a new inline history entry for this, so that we remember
493 // that these new callsites came about due to inlining Callee.
494 int NewHistoryID = InlineHistory.size();
495 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
496
Chris Lattnerc2432b92010-05-01 01:26:13 +0000497 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
Chris Lattnere8262672010-05-01 01:05:10 +0000498 i != e; ++i) {
Chris Lattnerc2432b92010-05-01 01:26:13 +0000499 Value *Ptr = InlineInfo.InlinedCalls[i];
Chandler Carruth21211992012-03-25 04:03:40 +0000500 CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID));
Chris Lattnere8262672010-05-01 01:05:10 +0000501 }
Chris Lattnerc691de32010-04-23 18:37:01 +0000502 }
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000503 }
504
505 // If we inlined or deleted the last possible call site to the function,
506 // delete the function body now.
507 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattner9e507472009-08-31 05:34:32 +0000508 // TODO: Can remove if in SCC now.
Chris Lattner081375b2009-08-31 03:15:49 +0000509 !SCCFunctions.count(Callee) &&
Chris Lattner9e507472009-08-31 05:34:32 +0000510
Chris Lattner081375b2009-08-31 03:15:49 +0000511 // The function may be apparently dead, but if there are indirect
512 // callgraph references to the node, we cannot delete it yet, this
513 // could invalidate the CGSCC iterator.
514 CG[Callee]->getNumReferences() == 0) {
David Greene0122fc42010-01-05 01:27:51 +0000515 DEBUG(dbgs() << " -> Deleting dead function: "
Chris Lattnerd3374e82009-08-27 06:29:33 +0000516 << Callee->getName() << "\n");
517 CallGraphNode *CalleeNode = CG[Callee];
518
519 // Remove any call graph edges from the callee to its callees.
520 CalleeNode->removeAllCalledFunctions();
521
Chris Lattnerd3374e82009-08-27 06:29:33 +0000522 // Removing the node for callee from the call graph and delete it.
523 delete CG.removeFunctionFromModule(CalleeNode);
524 ++NumDeleted;
525 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000526
527 // Remove this call site from the list. If possible, use
528 // swap/pop_back for efficiency, but do not use it if doing so would
529 // move a call site to a function in this SCC before the
530 // 'FirstCallInSCC' barrier.
Chris Lattner4422d312010-04-16 22:42:17 +0000531 if (SCC.isSingular()) {
Benjamin Kramer5ac57e32010-05-31 12:50:41 +0000532 CallSites[CSi] = CallSites.back();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000533 CallSites.pop_back();
534 } else {
535 CallSites.erase(CallSites.begin()+CSi);
536 }
537 --CSi;
538
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000539 Changed = true;
540 LocalChange = true;
541 }
Chris Lattner6754b822004-05-23 21:22:17 +0000542 } while (LocalChange);
Chris Lattner4d25c862004-04-08 06:34:31 +0000543
Chris Lattnerd075cc22003-08-31 19:10:30 +0000544 return Changed;
545}
546
Chris Lattnerc87784f2004-04-20 22:06:53 +0000547// doFinalization - Remove now-dead linkonce functions at the end of
548// processing to avoid breaking the SCC traversal.
549bool Inliner::doFinalization(CallGraph &CG) {
Devang Patelf0ef3572008-11-05 01:39:16 +0000550 return removeDeadFunctions(CG);
551}
552
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000553/// removeDeadFunctions - Remove dead functions that are not included in
554/// DNR (Do Not Remove) list.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000555bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
556 SmallVector<CallGraphNode*, 16> FunctionsToRemove;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000557
558 // Scan for all of the functions, looking for ones that should now be removed
559 // from the program. Insert the dead ones in the FunctionsToRemove set.
560 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
561 CallGraphNode *CGN = I->second;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000562 Function *F = CGN->getFunction();
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000563 if (!F || F->isDeclaration())
564 continue;
565
566 // Handle the case when this function is called and we only want to care
567 // about always-inline functions. This is a bit of a hack to share code
568 // between here and the InlineAlways pass.
Bill Wendlingc9b22d72012-10-09 07:45:08 +0000569 if (AlwaysInlineOnly &&
Bill Wendling698e84f2012-12-30 10:32:01 +0000570 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
571 Attribute::AlwaysInline))
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000572 continue;
573
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000574 // If the only remaining users of the function are dead constants, remove
575 // them.
576 F->removeDeadConstantUsers();
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000577
Eli Friedman1923a332011-10-20 05:23:42 +0000578 if (!F->isDefTriviallyDead())
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000579 continue;
580
581 // Remove any call graph edges from the function to its callees.
582 CGN->removeAllCalledFunctions();
Devang Patelf0ef3572008-11-05 01:39:16 +0000583
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000584 // Remove any edges from the external node to the function's call graph
585 // node. These edges might have been made irrelegant due to
586 // optimization of the program.
587 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
Chris Lattner6455c512004-09-18 21:37:03 +0000588
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000589 // Removing the node for callee from the call graph and delete it.
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000590 FunctionsToRemove.push_back(CGN);
Chris Lattnerc87784f2004-04-20 22:06:53 +0000591 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000592 if (FunctionsToRemove.empty())
593 return false;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000594
595 // Now that we know which functions to delete, do so. We didn't want to do
596 // this inline, because that would invalidate our CallGraph::iterator
597 // objects. :(
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000598 //
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000599 // Note that it doesn't matter that we are iterating over a non-stable order
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000600 // here to do this, it doesn't matter which order the functions are deleted
601 // in.
Chandler Carruth45ae88f2012-04-01 10:41:24 +0000602 array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000603 FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
604 FunctionsToRemove.end()),
605 FunctionsToRemove.end());
606 for (SmallVectorImpl<CallGraphNode *>::iterator I = FunctionsToRemove.begin(),
607 E = FunctionsToRemove.end();
608 I != E; ++I) {
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000609 delete CG.removeFunctionFromModule(*I);
610 ++NumDeleted;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000611 }
Chandler Carruthd7a5f2a2012-03-16 06:10:13 +0000612 return true;
Chris Lattnerc87784f2004-04-20 22:06:53 +0000613}