blob: 9590df966e6293280a1e8baa8db2017513b6e904 [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"
Chris Lattnerd075cc22003-08-31 19:10:30 +000017#include "llvm/Module.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Dale Johannesen20509682009-03-19 18:03:56 +000019#include "llvm/IntrinsicInst.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 Carruth595fda82012-03-12 11:19:33 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerf94bed32007-01-30 23:28:39 +000023#include "llvm/Target/TargetData.h"
Tanya Lattnerab11b1c2007-06-19 22:29:50 +000024#include "llvm/Transforms/IPO/InlinerPass.h"
Chris Lattnerd075cc22003-08-31 19:10:30 +000025#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner5c89f4b2009-11-12 21:58:18 +000026#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerb9d0a962009-08-27 04:32:07 +000031#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/ADT/Statistic.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
Dan Gohmand78c4002008-05-13 00:00:25 +000040static cl::opt<int>
Jakob Stoklund Olesen113fb542010-02-04 18:48:20 +000041InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
42 cl::desc("Control the amount of inlining to perform (default = 225)"));
Chris Lattnerd075cc22003-08-31 19:10:30 +000043
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +000044static cl::opt<int>
45HintThreshold("inlinehint-threshold", cl::Hidden, cl::init(325),
46 cl::desc("Threshold for inlining functions with inline hint"));
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +000047
48// Threshold to use when optsize is specified (and there is no -inline-limit).
49const int OptSizeThreshold = 75;
50
Owen Andersona7aed182010-08-06 18:33:48 +000051Inliner::Inliner(char &ID)
Chad Rosier07d37bc2012-02-25 02:56:01 +000052 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(true) {}
Chris Lattnerd075cc22003-08-31 19:10:30 +000053
Chad Rosier07d37bc2012-02-25 02:56:01 +000054Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
Jakob Stoklund Olesen31a7eb42010-11-02 23:40:26 +000055 : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() > 0 ?
Chad Rosier07d37bc2012-02-25 02:56:01 +000056 InlineLimit : Threshold),
57 InsertLifetime(InsertLifetime) {}
Chris Lattner22ad7ab2008-01-12 06:49:13 +000058
Chris Lattnerf94bed32007-01-30 23:28:39 +000059/// getAnalysisUsage - For this class, we declare that we require and preserve
60/// the call graph. If the derived class implements this method, it should
61/// always explicitly call the implementation here.
62void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Chris Lattnerf94bed32007-01-30 23:28:39 +000063 CallGraphSCCPass::getAnalysisUsage(Info);
64}
65
Chris Lattnerd3374e82009-08-27 06:29:33 +000066
Chris Lattner229907c2011-07-18 04:54:35 +000067typedef DenseMap<ArrayType*, std::vector<AllocaInst*> >
Chris Lattnerd3374e82009-08-27 06:29:33 +000068InlinedArrayAllocasTy;
69
70/// InlineCallIfPossible - If it is possible to inline the specified call site,
71/// do so and update the CallGraph for this operation.
72///
73/// This function also does some basic book-keeping to update the IR. The
Chris Lattner0e890182009-08-28 04:48:54 +000074/// InlinedArrayAllocas map keeps track of any allocas that are already
75/// available from other functions inlined into the caller. If we are able to
76/// inline this call site we attempt to reuse already available allocas or add
77/// any new allocas to the set if not possible.
Chris Lattner4ba01ec2010-04-22 23:07:58 +000078static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
Chris Lattnerfb212de2010-12-06 07:52:42 +000079 InlinedArrayAllocasTy &InlinedArrayAllocas,
Chad Rosier07d37bc2012-02-25 02:56:01 +000080 int InlineHistory, bool InsertLifetime) {
Chris Lattner6754b822004-05-23 21:22:17 +000081 Function *Callee = CS.getCalledFunction();
Bill Wendlingf5260d22008-11-21 00:09:21 +000082 Function *Caller = CS.getCaller();
83
Chris Lattnerd3374e82009-08-27 06:29:33 +000084 // Try to inline the function. Get the list of static allocas that were
85 // inlined.
Chad Rosier07d37bc2012-02-25 02:56:01 +000086 if (!InlineFunction(CS, IFI, InsertLifetime))
Chris Lattnerb9d0a962009-08-27 04:32:07 +000087 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +000088
Bill Wendling26c6a3e2008-11-21 00:06:32 +000089 // If the inlined function had a higher stack protection level than the
90 // calling function, then bump up the caller's stack protection level.
Bill Wendling26c6a3e2008-11-21 00:06:32 +000091 if (Callee->hasFnAttr(Attribute::StackProtectReq))
92 Caller->addFnAttr(Attribute::StackProtectReq);
93 else if (Callee->hasFnAttr(Attribute::StackProtect) &&
94 !Caller->hasFnAttr(Attribute::StackProtectReq))
95 Caller->addFnAttr(Attribute::StackProtect);
96
Chris Lattnerd3374e82009-08-27 06:29:33 +000097 // Look at all of the allocas that we inlined through this call site. If we
98 // have already inlined other allocas through other calls into this function,
99 // then we know that they have disjoint lifetimes and that we can merge them.
100 //
101 // There are many heuristics possible for merging these allocas, and the
102 // different options have different tradeoffs. One thing that we *really*
103 // don't want to hurt is SRoA: once inlining happens, often allocas are no
104 // longer address taken and so they can be promoted.
105 //
106 // Our "solution" for that is to only merge allocas whose outermost type is an
107 // array type. These are usually not promoted because someone is using a
108 // variable index into them. These are also often the most important ones to
109 // merge.
110 //
111 // A better solution would be to have real memory lifetime markers in the IR
112 // and not have the inliner do any merging of allocas at all. This would
113 // allow the backend to do proper stack slot coloring of all allocas that
114 // *actually make it to the backend*, which is really what we want.
115 //
116 // Because we don't have this information, we do this simple and useful hack.
117 //
118 SmallPtrSet<AllocaInst*, 16> UsedAllocas;
119
Chris Lattnerfb212de2010-12-06 07:52:42 +0000120 // When processing our SCC, check to see if CS was inlined from some other
121 // call site. For example, if we're processing "A" in this code:
122 // A() { B() }
123 // B() { x = alloca ... C() }
124 // C() { y = alloca ... }
125 // Assume that C was not inlined into B initially, and so we're processing A
126 // and decide to inline B into A. Doing this makes an alloca available for
127 // reuse and makes a callsite (C) available for inlining. When we process
128 // the C call site we don't want to do any alloca merging between X and Y
129 // because their scopes are not disjoint. We could make this smarter by
130 // keeping track of the inline history for each alloca in the
131 // InlinedArrayAllocas but this isn't likely to be a significant win.
132 if (InlineHistory != -1) // Only do merging for top-level call sites in SCC.
133 return true;
134
Chris Lattnerd3374e82009-08-27 06:29:33 +0000135 // Loop over all the allocas we have so far and see if they can be merged with
136 // a previously inlined alloca. If not, remember that we had it.
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000137 for (unsigned AllocaNo = 0, e = IFI.StaticAllocas.size();
Chris Lattnerd3374e82009-08-27 06:29:33 +0000138 AllocaNo != e; ++AllocaNo) {
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000139 AllocaInst *AI = IFI.StaticAllocas[AllocaNo];
Chris Lattnerd3374e82009-08-27 06:29:33 +0000140
141 // Don't bother trying to merge array allocations (they will usually be
142 // canonicalized to be an allocation *of* an array), or allocations whose
143 // type is not itself an array (because we're afraid of pessimizing SRoA).
Chris Lattner229907c2011-07-18 04:54:35 +0000144 ArrayType *ATy = dyn_cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerd3374e82009-08-27 06:29:33 +0000145 if (ATy == 0 || AI->isArrayAllocation())
146 continue;
147
148 // Get the list of all available allocas for this array type.
149 std::vector<AllocaInst*> &AllocasForType = InlinedArrayAllocas[ATy];
150
151 // Loop over the allocas in AllocasForType to see if we can reuse one. Note
152 // that we have to be careful not to reuse the same "available" alloca for
153 // multiple different allocas that we just inlined, we use the 'UsedAllocas'
154 // set to keep track of which "available" allocas are being used by this
155 // function. Also, AllocasForType can be empty of course!
156 bool MergedAwayAlloca = false;
157 for (unsigned i = 0, e = AllocasForType.size(); i != e; ++i) {
158 AllocaInst *AvailableAlloca = AllocasForType[i];
159
160 // The available alloca has to be in the right function, not in some other
161 // function in this SCC.
162 if (AvailableAlloca->getParent() != AI->getParent())
163 continue;
164
165 // If the inlined function already uses this alloca then we can't reuse
166 // it.
167 if (!UsedAllocas.insert(AvailableAlloca))
168 continue;
169
170 // Otherwise, we *can* reuse it, RAUW AI into AvailableAlloca and declare
171 // success!
Chris Lattner5b6a8652010-12-06 07:38:40 +0000172 DEBUG(dbgs() << " ***MERGED ALLOCA: " << *AI << "\n\t\tINTO: "
173 << *AvailableAlloca << '\n');
Chris Lattnerd3374e82009-08-27 06:29:33 +0000174
175 AI->replaceAllUsesWith(AvailableAlloca);
176 AI->eraseFromParent();
177 MergedAwayAlloca = true;
178 ++NumMergedAllocas;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000179 IFI.StaticAllocas[AllocaNo] = 0;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000180 break;
181 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000182
Chris Lattnerd3374e82009-08-27 06:29:33 +0000183 // If we already nuked the alloca, we're done with it.
184 if (MergedAwayAlloca)
185 continue;
Chris Lattner5b6a8652010-12-06 07:38:40 +0000186
Chris Lattnerd3374e82009-08-27 06:29:33 +0000187 // If we were unable to merge away the alloca either because there are no
188 // allocas of the right type available or because we reused them all
189 // already, remember that this alloca came from an inlined function and mark
190 // it used so we don't reuse it for other allocas from this inline
191 // operation.
192 AllocasForType.push_back(AI);
193 UsedAllocas.insert(AI);
Chris Lattner6754b822004-05-23 21:22:17 +0000194 }
Chris Lattnerd3374e82009-08-27 06:29:33 +0000195
Chris Lattner6754b822004-05-23 21:22:17 +0000196 return true;
Chris Lattnerd075cc22003-08-31 19:10:30 +0000197}
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000198
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000199unsigned Inliner::getInlineThreshold(CallSite CS) const {
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000200 int thres = InlineThreshold;
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000201
202 // Listen to optsize when -inline-limit is not given.
203 Function *Caller = CS.getCaller();
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000204 if (Caller && !Caller->isDeclaration() &&
205 Caller->hasFnAttr(Attribute::OptimizeForSize) &&
206 InlineLimit.getNumOccurrences() == 0)
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000207 thres = OptSizeThreshold;
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000208
Jakob Stoklund Olesen492b8b42010-02-13 01:51:53 +0000209 // Listen to inlinehint when it would increase the threshold.
210 Function *Callee = CS.getCalledFunction();
211 if (HintThreshold > thres && Callee && !Callee->isDeclaration() &&
212 Callee->hasFnAttr(Attribute::InlineHint))
213 thres = HintThreshold;
214
215 return thres;
Jakob Stoklund Olesen8a19d3c2010-01-20 17:51:28 +0000216}
217
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000218/// shouldInline - Return true if the inliner should attempt to inline
219/// at the given CallSite.
220bool Inliner::shouldInline(CallSite CS) {
Daniel Dunbar3933e662008-10-30 19:26:59 +0000221 InlineCost IC = getInlineCost(CS);
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000222
Daniel Dunbar3933e662008-10-30 19:26:59 +0000223 if (IC.isAlways()) {
David Greene0122fc42010-01-05 01:27:51 +0000224 DEBUG(dbgs() << " Inlining: cost=always"
Bill Wendling2602bb42009-07-31 19:52:24 +0000225 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000226 return true;
227 }
228
229 if (IC.isNever()) {
David Greene0122fc42010-01-05 01:27:51 +0000230 DEBUG(dbgs() << " NOT Inlining: cost=never"
Bill Wendling2602bb42009-07-31 19:52:24 +0000231 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbar3933e662008-10-30 19:26:59 +0000232 return false;
233 }
234
235 int Cost = IC.getValue();
Dale Johannesen30599242009-10-09 00:11:32 +0000236 Function *Caller = CS.getCaller();
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000237 int CurrentThreshold = getInlineThreshold(CS);
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000238 float FudgeFactor = getInlineFudgeFactor(CS);
Jakob Stoklund Olesend62c2f52010-03-09 00:59:53 +0000239 int AdjThreshold = (int)(CurrentThreshold * FudgeFactor);
240 if (Cost >= AdjThreshold) {
David Greene0122fc42010-01-05 01:27:51 +0000241 DEBUG(dbgs() << " NOT Inlining: cost=" << Cost
Jakob Stoklund Olesend62c2f52010-03-09 00:59:53 +0000242 << ", thres=" << AdjThreshold
Bill Wendling2602bb42009-07-31 19:52:24 +0000243 << ", Call: " << *CS.getInstruction() << "\n");
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000244 return false;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000245 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000246
Dale Johannesen30599242009-10-09 00:11:32 +0000247 // Try to detect the case where the current inlining candidate caller
248 // (call it B) is a static function and is an inlining candidate elsewhere,
249 // and the current candidate callee (call it C) is large enough that
250 // inlining it into B would make B too big to inline later. In these
251 // circumstances it may be best not to inline C into B, but to inline B
252 // into its callers.
253 if (Caller->hasLocalLinkage()) {
254 int TotalSecondaryCost = 0;
255 bool outerCallsFound = false;
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000256 // This bool tracks what happens if we do NOT inline C into B.
257 bool callerWillBeRemoved = true;
258 // This bool tracks what happens if we DO inline C into B.
259 bool inliningPreventsSomeOuterInline = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000260 for (Value::use_iterator I = Caller->use_begin(), E =Caller->use_end();
261 I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000262 CallSite CS2(*I);
Dale Johannesen30599242009-10-09 00:11:32 +0000263
264 // If this isn't a call to Caller (it could be some other sort
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000265 // of reference) skip it. Such references will prevent the caller
266 // from being removed.
267 if (!CS2 || CS2.getCalledFunction() != Caller) {
268 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000269 continue;
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000270 }
Dale Johannesen30599242009-10-09 00:11:32 +0000271
272 InlineCost IC2 = getInlineCost(CS2);
273 if (IC2.isNever())
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000274 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000275 if (IC2.isAlways() || IC2.isNever())
276 continue;
277
278 outerCallsFound = true;
279 int Cost2 = IC2.getValue();
Jakob Stoklund Olesen74bb06c2010-02-06 01:16:28 +0000280 int CurrentThreshold2 = getInlineThreshold(CS2);
Dale Johannesen30599242009-10-09 00:11:32 +0000281 float FudgeFactor2 = getInlineFudgeFactor(CS2);
282
283 if (Cost2 >= (int)(CurrentThreshold2 * FudgeFactor2))
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000284 callerWillBeRemoved = false;
Dale Johannesen30599242009-10-09 00:11:32 +0000285
Dale Johannesen96a5b872009-10-09 21:42:02 +0000286 // See if we have this case. We subtract off the penalty
Dale Johannesen30599242009-10-09 00:11:32 +0000287 // for the call instruction, which we would be deleting.
288 if (Cost2 < (int)(CurrentThreshold2 * FudgeFactor2) &&
Dale Johannesen96a5b872009-10-09 21:42:02 +0000289 Cost2 + Cost - (InlineConstants::CallPenalty + 1) >=
290 (int)(CurrentThreshold2 * FudgeFactor2)) {
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000291 inliningPreventsSomeOuterInline = true;
Dale Johannesen30599242009-10-09 00:11:32 +0000292 TotalSecondaryCost += Cost2;
293 }
294 }
295 // If all outer calls to Caller would get inlined, the cost for the last
296 // one is set very low by getInlineCost, in anticipation that Caller will
297 // be removed entirely. We did not account for this above unless there
298 // is only one caller of Caller.
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000299 if (callerWillBeRemoved && Caller->use_begin() != Caller->use_end())
Dale Johannesen96a5b872009-10-09 21:42:02 +0000300 TotalSecondaryCost += InlineConstants::LastCallToStaticBonus;
Dale Johannesen30599242009-10-09 00:11:32 +0000301
Dale Johannesena71d2cc2011-01-04 19:01:54 +0000302 if (outerCallsFound && inliningPreventsSomeOuterInline &&
Dale Johannesen30599242009-10-09 00:11:32 +0000303 TotalSecondaryCost < Cost) {
David Greene0122fc42010-01-05 01:27:51 +0000304 DEBUG(dbgs() << " NOT Inlining: " << *CS.getInstruction() <<
Dale Johannesen30599242009-10-09 00:11:32 +0000305 " Cost = " << Cost <<
306 ", outer Cost = " << TotalSecondaryCost << '\n');
307 return false;
308 }
309 }
310
David Greene0122fc42010-01-05 01:27:51 +0000311 DEBUG(dbgs() << " Inlining: cost=" << Cost
Jakob Stoklund Olesend62c2f52010-03-09 00:59:53 +0000312 << ", thres=" << AdjThreshold
Dale Johannesen30599242009-10-09 00:11:32 +0000313 << ", Call: " << *CS.getInstruction() << '\n');
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000314 return true;
Daniel Dunbare7fbf9f42008-10-29 01:02:02 +0000315}
Chris Lattnerd075cc22003-08-31 19:10:30 +0000316
Chris Lattnere8262672010-05-01 01:05:10 +0000317/// InlineHistoryIncludes - Return true if the specified inline history ID
318/// indicates an inline history that includes the specified function.
319static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
320 const SmallVectorImpl<std::pair<Function*, int> > &InlineHistory) {
321 while (InlineHistoryID != -1) {
322 assert(unsigned(InlineHistoryID) < InlineHistory.size() &&
323 "Invalid inline history ID");
324 if (InlineHistory[InlineHistoryID].first == F)
325 return true;
326 InlineHistoryID = InlineHistory[InlineHistoryID].second;
327 }
328 return false;
329}
330
Chandler Carruth595fda82012-03-12 11:19:33 +0000331/// \brief Simplify arguments going into a particular callsite.
332///
333/// This is important to do each time we add a callsite due to inlining so that
334/// constants and other entities which feed into inline cost estimation are
335/// properly recognized when analyzing the new callsite. Consider:
336/// void outer(int x) {
337/// if (x < 42)
338/// return inner(42 - x);
339/// ...
340/// }
341/// void inner(int x) {
342/// ...
343/// }
344///
345/// The inliner gives calls to 'outer' with a constant argument a bonus because
346/// it will delete one side of a branch. But the resulting call to 'inner'
347/// will, after inlining, also have a constant operand. We need to do just
348/// enough constant folding to expose this for callsite arguments. The rest
349/// will be taken care of after the inliner finishes running.
350static void simplifyCallSiteArguments(const TargetData *TD, CallSite CS) {
351 // FIXME: It would be nice to avoid this smallvector if RAUW doesn't
352 // invalidate operand iterators in any cases.
353 SmallVector<std::pair<Value *, Value*>, 4> SimplifiedArgs;
354 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
355 I != E; ++I)
356 if (Instruction *Inst = dyn_cast<Instruction>(*I))
357 if (Value *SimpleArg = SimplifyInstruction(Inst, TD))
358 SimplifiedArgs.push_back(std::make_pair(Inst, SimpleArg));
359 for (unsigned Idx = 0, Size = SimplifiedArgs.size(); Idx != Size; ++Idx)
360 SimplifiedArgs[Idx].first->replaceAllUsesWith(SimplifiedArgs[Idx].second);
361}
Chris Lattnere8262672010-05-01 01:05:10 +0000362
Chris Lattner4422d312010-04-16 22:42:17 +0000363bool Inliner::runOnSCC(CallGraphSCC &SCC) {
Chris Lattnerd075cc22003-08-31 19:10:30 +0000364 CallGraph &CG = getAnalysis<CallGraph>();
Dan Gohman67243a42009-07-24 18:13:53 +0000365 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerd075cc22003-08-31 19:10:30 +0000366
Dale Johannesen32dfb352009-03-23 23:39:20 +0000367 SmallPtrSet<Function*, 8> SCCFunctions;
David Greene0122fc42010-01-05 01:27:51 +0000368 DEBUG(dbgs() << "Inliner visiting SCC:");
Chris Lattner4422d312010-04-16 22:42:17 +0000369 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
370 Function *F = (*I)->getFunction();
Chris Lattner6754b822004-05-23 21:22:17 +0000371 if (F) SCCFunctions.insert(F);
David Greene0122fc42010-01-05 01:27:51 +0000372 DEBUG(dbgs() << " " << (F ? F->getName() : "INDIRECTNODE"));
Chris Lattnerd075cc22003-08-31 19:10:30 +0000373 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000374
Chris Lattner6754b822004-05-23 21:22:17 +0000375 // Scan through and identify all call sites ahead of time so that we only
376 // inline call sites in the original functions, not call sites that result
377 // from inlining other functions.
Chris Lattnere8262672010-05-01 01:05:10 +0000378 SmallVector<std::pair<CallSite, int>, 16> CallSites;
379
380 // When inlining a callee produces new call sites, we want to keep track of
381 // the fact that they were inlined from the callee. This allows us to avoid
382 // infinite inlining in some obscure cases. To represent this, we use an
383 // index into the InlineHistory vector.
384 SmallVector<std::pair<Function*, int>, 8> InlineHistory;
Chris Lattner6754b822004-05-23 21:22:17 +0000385
Chris Lattner4422d312010-04-16 22:42:17 +0000386 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
387 Function *F = (*I)->getFunction();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000388 if (!F) continue;
389
390 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
391 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000392 CallSite CS(cast<Value>(I));
Dale Johannesen30599242009-10-09 00:11:32 +0000393 // If this isn't a call, or it is a call to an intrinsic, it can
Chris Lattner9e507472009-08-31 05:34:32 +0000394 // never be inlined.
Gabor Greif62f0aac2010-07-28 22:50:26 +0000395 if (!CS || isa<IntrinsicInst>(I))
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000396 continue;
397
Chris Lattner9e507472009-08-31 05:34:32 +0000398 // If this is a direct call to an external function, we can never inline
399 // it. If it is an indirect call, inlining may resolve it to be a
400 // direct call, so we keep it.
401 if (CS.getCalledFunction() && CS.getCalledFunction()->isDeclaration())
402 continue;
403
Chris Lattnere8262672010-05-01 01:05:10 +0000404 CallSites.push_back(std::make_pair(CS, -1));
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000405 }
406 }
Chris Lattnerd075cc22003-08-31 19:10:30 +0000407
David Greene0122fc42010-01-05 01:27:51 +0000408 DEBUG(dbgs() << ": " << CallSites.size() << " call sites.\n");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000409
Chris Lattnera5cdd5e2010-04-20 00:47:08 +0000410 // If there are no calls in this function, exit early.
411 if (CallSites.empty())
412 return false;
413
Chris Lattner6754b822004-05-23 21:22:17 +0000414 // Now that we have all of the call sites, move the ones to functions in the
415 // current SCC to the end of the list.
416 unsigned FirstCallInSCC = CallSites.size();
417 for (unsigned i = 0; i < FirstCallInSCC; ++i)
Chris Lattnere8262672010-05-01 01:05:10 +0000418 if (Function *F = CallSites[i].first.getCalledFunction())
Chris Lattner6754b822004-05-23 21:22:17 +0000419 if (SCCFunctions.count(F))
420 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000421
Chris Lattnerd3374e82009-08-27 06:29:33 +0000422
423 InlinedArrayAllocasTy InlinedArrayAllocas;
Chris Lattner4ba01ec2010-04-22 23:07:58 +0000424 InlineFunctionInfo InlineInfo(&CG, TD);
Chris Lattnerd3374e82009-08-27 06:29:33 +0000425
Chris Lattner6754b822004-05-23 21:22:17 +0000426 // Now that we have all of the call sites, loop over them and inline them if
427 // it looks profitable to do so.
428 bool Changed = false;
429 bool LocalChange;
430 do {
431 LocalChange = false;
432 // Iterate over the outer loop because inlining functions can cause indirect
433 // calls to become direct calls.
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000434 for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi) {
Chris Lattnere8262672010-05-01 01:05:10 +0000435 CallSite CS = CallSites[CSi].first;
Chris Lattnerd3374e82009-08-27 06:29:33 +0000436
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000437 Function *Caller = CS.getCaller();
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000438 Function *Callee = CS.getCalledFunction();
439
440 // If this call site is dead and it is to a readonly function, we should
441 // just delete the call instead of trying to inline it, regardless of
442 // size. This happens because IPSCCP propagates the result out of the
443 // call and then we're left with the dead call.
Chris Lattner5c89f4b2009-11-12 21:58:18 +0000444 if (isInstructionTriviallyDead(CS.getInstruction())) {
David Greene0122fc42010-01-05 01:27:51 +0000445 DEBUG(dbgs() << " -> Deleting dead call: "
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000446 << *CS.getInstruction() << "\n");
447 // Update the call graph by deleting the edge from Callee to Caller.
448 CG[Caller]->removeCallEdgeFor(CS);
449 CS.getInstruction()->eraseFromParent();
450 ++NumCallsDeleted;
Jakob Stoklund Olesenb495cad2010-03-09 23:02:17 +0000451 // Update the cached cost info with the missing call
452 growCachedCostInfo(Caller, NULL);
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000453 } else {
454 // We can only inline direct calls to non-declarations.
455 if (Callee == 0 || Callee->isDeclaration()) continue;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000456
Eric Christopherea2820342010-07-13 18:27:13 +0000457 // If this call site was obtained by inlining another function, verify
Chris Lattnere8262672010-05-01 01:05:10 +0000458 // that the include path for the function did not include the callee
Chris Lattner5b6a8652010-12-06 07:38:40 +0000459 // itself. If so, we'd be recursively inlining the same function,
Chris Lattnere8262672010-05-01 01:05:10 +0000460 // which would provide the same callsites, which would cause us to
461 // infinitely inline.
462 int InlineHistoryID = CallSites[CSi].second;
463 if (InlineHistoryID != -1 &&
464 InlineHistoryIncludes(Callee, InlineHistoryID, InlineHistory))
465 continue;
466
467
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000468 // If the policy determines that we should inline this function,
469 // try to do so.
470 if (!shouldInline(CS))
471 continue;
472
Chris Lattner2eee5d32010-04-22 23:37:35 +0000473 // Attempt to inline the function.
Chris Lattnerfb212de2010-12-06 07:52:42 +0000474 if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
Chad Rosier07d37bc2012-02-25 02:56:01 +0000475 InlineHistoryID, InsertLifetime))
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000476 continue;
477 ++NumInlined;
Chris Lattnere8262672010-05-01 01:05:10 +0000478
Chris Lattnerc2432b92010-05-01 01:26:13 +0000479 // If inlining this function gave us any new call sites, throw them
Chris Lattner2eee5d32010-04-22 23:37:35 +0000480 // onto our worklist to process. They are useful inline candidates.
Chris Lattnerc2432b92010-05-01 01:26:13 +0000481 if (!InlineInfo.InlinedCalls.empty()) {
Chris Lattnere8262672010-05-01 01:05:10 +0000482 // Create a new inline history entry for this, so that we remember
483 // that these new callsites came about due to inlining Callee.
484 int NewHistoryID = InlineHistory.size();
485 InlineHistory.push_back(std::make_pair(Callee, InlineHistoryID));
486
Chris Lattnerc2432b92010-05-01 01:26:13 +0000487 for (unsigned i = 0, e = InlineInfo.InlinedCalls.size();
Chris Lattnere8262672010-05-01 01:05:10 +0000488 i != e; ++i) {
Chris Lattnerc2432b92010-05-01 01:26:13 +0000489 Value *Ptr = InlineInfo.InlinedCalls[i];
Chandler Carruth595fda82012-03-12 11:19:33 +0000490 CallSite NewCS = Ptr;
491 simplifyCallSiteArguments(TD, NewCS);
492 CallSites.push_back(std::make_pair(NewCS, NewHistoryID));
Chris Lattnere8262672010-05-01 01:05:10 +0000493 }
Chris Lattnerc691de32010-04-23 18:37:01 +0000494 }
Chris Lattner2eee5d32010-04-22 23:37:35 +0000495
Jakob Stoklund Olesenb495cad2010-03-09 23:02:17 +0000496 // Update the cached cost info with the inlined call.
497 growCachedCostInfo(Caller, Callee);
Chris Lattnereb9acbf2009-11-12 07:56:08 +0000498 }
499
500 // If we inlined or deleted the last possible call site to the function,
501 // delete the function body now.
502 if (Callee && Callee->use_empty() && Callee->hasLocalLinkage() &&
Chris Lattner9e507472009-08-31 05:34:32 +0000503 // TODO: Can remove if in SCC now.
Chris Lattner081375b2009-08-31 03:15:49 +0000504 !SCCFunctions.count(Callee) &&
Chris Lattner9e507472009-08-31 05:34:32 +0000505
Chris Lattner081375b2009-08-31 03:15:49 +0000506 // The function may be apparently dead, but if there are indirect
507 // callgraph references to the node, we cannot delete it yet, this
508 // could invalidate the CGSCC iterator.
509 CG[Callee]->getNumReferences() == 0) {
David Greene0122fc42010-01-05 01:27:51 +0000510 DEBUG(dbgs() << " -> Deleting dead function: "
Chris Lattnerd3374e82009-08-27 06:29:33 +0000511 << Callee->getName() << "\n");
512 CallGraphNode *CalleeNode = CG[Callee];
513
514 // Remove any call graph edges from the callee to its callees.
515 CalleeNode->removeAllCalledFunctions();
516
517 resetCachedCostInfo(Callee);
518
519 // Removing the node for callee from the call graph and delete it.
520 delete CG.removeFunctionFromModule(CalleeNode);
521 ++NumDeleted;
522 }
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000523
524 // Remove this call site from the list. If possible, use
525 // swap/pop_back for efficiency, but do not use it if doing so would
526 // move a call site to a function in this SCC before the
527 // 'FirstCallInSCC' barrier.
Chris Lattner4422d312010-04-16 22:42:17 +0000528 if (SCC.isSingular()) {
Benjamin Kramer5ac57e32010-05-31 12:50:41 +0000529 CallSites[CSi] = CallSites.back();
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000530 CallSites.pop_back();
531 } else {
532 CallSites.erase(CallSites.begin()+CSi);
533 }
534 --CSi;
535
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000536 Changed = true;
537 LocalChange = true;
538 }
Chris Lattner6754b822004-05-23 21:22:17 +0000539 } while (LocalChange);
Chris Lattner4d25c862004-04-08 06:34:31 +0000540
Chris Lattnerd075cc22003-08-31 19:10:30 +0000541 return Changed;
542}
543
Chris Lattnerc87784f2004-04-20 22:06:53 +0000544// doFinalization - Remove now-dead linkonce functions at the end of
545// processing to avoid breaking the SCC traversal.
546bool Inliner::doFinalization(CallGraph &CG) {
Devang Patelf0ef3572008-11-05 01:39:16 +0000547 return removeDeadFunctions(CG);
548}
549
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000550/// removeDeadFunctions - Remove dead functions that are not included in
551/// DNR (Do Not Remove) list.
Devang Patelf0ef3572008-11-05 01:39:16 +0000552bool Inliner::removeDeadFunctions(CallGraph &CG,
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000553 SmallPtrSet<const Function *, 16> *DNR) {
554 SmallPtrSet<CallGraphNode*, 16> FunctionsToRemove;
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000555
556 // Scan for all of the functions, looking for ones that should now be removed
557 // from the program. Insert the dead ones in the FunctionsToRemove set.
558 for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
559 CallGraphNode *CGN = I->second;
Chris Lattner081375b2009-08-31 03:15:49 +0000560 if (CGN->getFunction() == 0)
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000561 continue;
562
563 Function *F = CGN->getFunction();
564
565 // If the only remaining users of the function are dead constants, remove
566 // them.
567 F->removeDeadConstantUsers();
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000568
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000569 if (DNR && DNR->count(F))
570 continue;
Eli Friedman1923a332011-10-20 05:23:42 +0000571 if (!F->isDefTriviallyDead())
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000572 continue;
573
574 // Remove any call graph edges from the function to its callees.
575 CGN->removeAllCalledFunctions();
Devang Patelf0ef3572008-11-05 01:39:16 +0000576
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000577 // Remove any edges from the external node to the function's call graph
578 // node. These edges might have been made irrelegant due to
579 // optimization of the program.
580 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
Chris Lattner6455c512004-09-18 21:37:03 +0000581
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000582 // Removing the node for callee from the call graph and delete it.
583 FunctionsToRemove.insert(CGN);
Chris Lattnerc87784f2004-04-20 22:06:53 +0000584 }
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000585
586 // Now that we know which functions to delete, do so. We didn't want to do
587 // this inline, because that would invalidate our CallGraph::iterator
588 // objects. :(
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000589 //
590 // Note that it doesn't matter that we are iterating over a non-stable set
591 // here to do this, it doesn't matter which order the functions are deleted
592 // in.
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000593 bool Changed = false;
Chris Lattner5eef6ad2009-08-27 03:51:50 +0000594 for (SmallPtrSet<CallGraphNode*, 16>::iterator I = FunctionsToRemove.begin(),
595 E = FunctionsToRemove.end(); I != E; ++I) {
Dale Johannesen20509682009-03-19 18:03:56 +0000596 resetCachedCostInfo((*I)->getFunction());
Chris Lattnerbe8bb802004-04-21 20:44:33 +0000597 delete CG.removeFunctionFromModule(*I);
598 ++NumDeleted;
599 Changed = true;
600 }
601
Chris Lattnerc87784f2004-04-20 22:06:53 +0000602 return Changed;
603}