1 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements bottom-up inlining of functions into callees.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/CallingConv.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Transforms/IPO.h"
29 struct VISIBILITY_HIDDEN ArgInfo {
30 unsigned ConstantWeight;
31 unsigned AllocaWeight;
33 ArgInfo(unsigned CWeight, unsigned AWeight)
34 : ConstantWeight(CWeight), AllocaWeight(AWeight) {}
37 // FunctionInfo - For each function, calculate the size of it in blocks and
39 struct VISIBILITY_HIDDEN FunctionInfo {
40 // NumInsts, NumBlocks - Keep track of how large each function is, which is
41 // used to estimate the code size cost of inlining it.
42 unsigned NumInsts, NumBlocks;
44 // ArgumentWeights - Each formal argument of the function is inspected to
45 // see if it is used in any contexts where making it a constant or alloca
46 // would reduce the code size. If so, we add some value to the argument
48 std::vector<ArgInfo> ArgumentWeights;
50 FunctionInfo() : NumInsts(0), NumBlocks(0) {}
52 /// analyzeFunction - Fill in the current structure with information gleaned
53 /// from the specified function.
54 void analyzeFunction(Function *F);
57 class VISIBILITY_HIDDEN SimpleInliner : public Inliner {
58 std::map<const Function*, FunctionInfo> CachedFunctionInfo;
59 std::set<const Function*> NeverInline; // Functions that are never inlined
61 SimpleInliner() : Inliner(&ID) {}
62 static char ID; // Pass identification, replacement for typeid
63 int getInlineCost(CallSite CS);
64 virtual bool doInitialization(CallGraph &CG);
66 char SimpleInliner::ID = 0;
67 RegisterPass<SimpleInliner> X("inline", "Function Integration/Inlining");
70 Pass *llvm::createFunctionInliningPass() { return new SimpleInliner(); }
72 // CountCodeReductionForConstant - Figure out an approximation for how many
73 // instructions will be constant folded if the specified value is constant.
75 static unsigned CountCodeReductionForConstant(Value *V) {
76 unsigned Reduction = 0;
77 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
78 if (isa<BranchInst>(*UI))
79 Reduction += 40; // Eliminating a conditional branch is a big win
80 else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
81 // Eliminating a switch is a big win, proportional to the number of edges
83 Reduction += (SI->getNumSuccessors()-1) * 40;
84 else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
85 // Turning an indirect call into a direct call is a BIG win
86 Reduction += CI->getCalledValue() == V ? 500 : 0;
87 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
88 // Turning an indirect call into a direct call is a BIG win
89 Reduction += II->getCalledValue() == V ? 500 : 0;
91 // Figure out if this instruction will be removed due to simple constant
93 Instruction &Inst = cast<Instruction>(**UI);
94 bool AllOperandsConstant = true;
95 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
96 if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
97 AllOperandsConstant = false;
101 if (AllOperandsConstant) {
102 // We will get to remove this instruction...
105 // And any other instructions that use it which become constants
107 Reduction += CountCodeReductionForConstant(&Inst);
114 // CountCodeReductionForAlloca - Figure out an approximation of how much smaller
115 // the function will be if it is inlined into a context where an argument
116 // becomes an alloca.
118 static unsigned CountCodeReductionForAlloca(Value *V) {
119 if (!isa<PointerType>(V->getType())) return 0; // Not a pointer
120 unsigned Reduction = 0;
121 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
122 Instruction *I = cast<Instruction>(*UI);
123 if (isa<LoadInst>(I) || isa<StoreInst>(I))
125 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
126 // If the GEP has variable indices, we won't be able to do much with it.
127 for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
129 if (!isa<Constant>(*I)) return 0;
130 Reduction += CountCodeReductionForAlloca(GEP)+15;
132 // If there is some other strange instruction, we're not going to be able
133 // to do much if we inline this.
141 /// analyzeFunction - Fill in the current structure with information gleaned
142 /// from the specified function.
143 void FunctionInfo::analyzeFunction(Function *F) {
144 unsigned NumInsts = 0, NumBlocks = 0;
146 // Look at the size of the callee. Each basic block counts as 20 units, and
147 // each instruction counts as 10.
148 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
149 for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
151 if (isa<DbgInfoIntrinsic>(II)) continue; // Debug intrinsics don't count.
153 // Noop casts, including ptr <-> int, don't count.
154 if (const CastInst *CI = dyn_cast<CastInst>(II)) {
155 if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) ||
156 isa<PtrToIntInst>(CI))
158 } else if (const GetElementPtrInst *GEPI =
159 dyn_cast<GetElementPtrInst>(II)) {
160 // If a GEP has all constant indices, it will probably be folded with
162 bool AllConstant = true;
163 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
164 if (!isa<ConstantInt>(GEPI->getOperand(i))) {
168 if (AllConstant) continue;
177 this->NumBlocks = NumBlocks;
178 this->NumInsts = NumInsts;
180 // Check out all of the arguments to the function, figuring out how much
181 // code can be eliminated if one of the arguments is a constant.
182 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
183 ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
184 CountCodeReductionForAlloca(I)));
188 // getInlineCost - The heuristic used to determine if we should inline the
189 // function call or not.
191 int SimpleInliner::getInlineCost(CallSite CS) {
192 Instruction *TheCall = CS.getInstruction();
193 Function *Callee = CS.getCalledFunction();
194 const Function *Caller = TheCall->getParent()->getParent();
196 // Don't inline a directly recursive call.
197 if (Caller == Callee) return 2000000000;
199 // Don't inline functions marked noinline
200 if (NeverInline.count(Callee)) return 2000000000;
202 // InlineCost - This value measures how good of an inline candidate this call
203 // site is to inline. A lower inline cost make is more likely for the call to
204 // be inlined. This value may go negative.
208 // If there is only one call of the function, and it has internal linkage,
209 // make it almost guaranteed to be inlined.
211 if (Callee->hasInternalLinkage() && Callee->hasOneUse())
214 // If this function uses the coldcc calling convention, prefer not to inline
216 if (Callee->getCallingConv() == CallingConv::Cold)
219 // If the instruction after the call, or if the normal destination of the
220 // invoke is an unreachable instruction, the function is noreturn. As such,
221 // there is little point in inlining this.
222 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
223 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
225 } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
228 // Get information about the callee...
229 FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
231 // If we haven't calculated this information yet, do so now.
232 if (CalleeFI.NumBlocks == 0)
233 CalleeFI.analyzeFunction(Callee);
235 // Add to the inline quality for properties that make the call valuable to
236 // inline. This includes factors that indicate that the result of inlining
237 // the function will be optimizable. Currently this just looks at arguments
238 // passed into the function.
241 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
242 I != E; ++I, ++ArgNo) {
243 // Each argument passed in has a cost at both the caller and the callee
244 // sides. This favors functions that take many arguments over functions
245 // that take few arguments.
248 // If this is a function being passed in, it is very likely that we will be
249 // able to turn an indirect function call into a direct function call.
250 if (isa<Function>(I))
253 // If an alloca is passed in, inlining this function is likely to allow
254 // significant future optimization possibilities (like scalar promotion, and
255 // scalarization), so encourage the inlining of the function.
257 else if (isa<AllocaInst>(I)) {
258 if (ArgNo < CalleeFI.ArgumentWeights.size())
259 InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
261 // If this is a constant being passed into the function, use the argument
262 // weights calculated for the callee to determine how much will be folded
263 // away with this information.
264 } else if (isa<Constant>(I)) {
265 if (ArgNo < CalleeFI.ArgumentWeights.size())
266 InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
270 // Now that we have considered all of the factors that make the call site more
271 // likely to be inlined, look at factors that make us not want to inline it.
273 // Don't inline into something too big, which would make it bigger. Here, we
274 // count each basic block as a single unit.
276 InlineCost += Caller->size()/20;
279 // Look at the size of the callee. Each basic block counts as 20 units, and
280 // each instruction counts as 5.
281 InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
285 // doInitialization - Initializes the vector of functions that have been
286 // annotated with the noinline attribute.
287 bool SimpleInliner::doInitialization(CallGraph &CG) {
289 Module &M = CG.getModule();
292 GlobalVariable *GV = M.getNamedGlobal("llvm.noinline");
297 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
302 // Iterate over each element and add to the NeverInline set
303 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
306 const Constant *Elt = InitList->getOperand(i);
308 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Elt))
309 if (CE->getOpcode() == Instruction::BitCast)
310 Elt = CE->getOperand(0);
312 // Insert into set of functions to never inline
313 if (const Function *F = dyn_cast<Function>(Elt))
314 NeverInline.insert(F);