LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

InlineSimple.cpp

Go to the documentation of this file.
00001 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements bottom-up inlining of functions into callees.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Inliner.h"
00015 #include "llvm/Instructions.h"
00016 #include "llvm/IntrinsicInst.h"
00017 #include "llvm/Function.h"
00018 #include "llvm/Type.h"
00019 #include "llvm/Support/CallSite.h"
00020 #include "llvm/Transforms/IPO.h"
00021 using namespace llvm;
00022 
00023 namespace {
00024   struct ArgInfo {
00025     unsigned ConstantWeight;
00026     unsigned AllocaWeight;
00027 
00028     ArgInfo(unsigned CWeight, unsigned AWeight)
00029       : ConstantWeight(CWeight), AllocaWeight(AWeight) {}
00030   };
00031 
00032   // FunctionInfo - For each function, calculate the size of it in blocks and
00033   // instructions.
00034   struct FunctionInfo {
00035     // HasAllocas - Keep track of whether or not a function contains an alloca
00036     // instruction that is not in the entry block of the function.  Inlining
00037     // this call could cause us to blow out the stack, because the stack memory
00038     // would never be released.
00039     //
00040     // FIXME: LLVM needs a way of dealloca'ing memory, which would make this
00041     // irrelevant!
00042     //
00043     bool HasAllocas;
00044 
00045     // NumInsts, NumBlocks - Keep track of how large each function is, which is
00046     // used to estimate the code size cost of inlining it.
00047     unsigned NumInsts, NumBlocks;
00048 
00049     // ArgumentWeights - Each formal argument of the function is inspected to
00050     // see if it is used in any contexts where making it a constant or alloca
00051     // would reduce the code size.  If so, we add some value to the argument
00052     // entry here.
00053     std::vector<ArgInfo> ArgumentWeights;
00054 
00055     FunctionInfo() : HasAllocas(false), NumInsts(0), NumBlocks(0) {}
00056 
00057     /// analyzeFunction - Fill in the current structure with information gleaned
00058     /// from the specified function.
00059     void analyzeFunction(Function *F);
00060   };
00061 
00062   class SimpleInliner : public Inliner {
00063     std::map<const Function*, FunctionInfo> CachedFunctionInfo;
00064   public:
00065     int getInlineCost(CallSite CS);
00066   };
00067   RegisterOpt<SimpleInliner> X("inline", "Function Integration/Inlining");
00068 }
00069 
00070 ModulePass *llvm::createFunctionInliningPass() { return new SimpleInliner(); }
00071 
00072 // CountCodeReductionForConstant - Figure out an approximation for how many
00073 // instructions will be constant folded if the specified value is constant.
00074 //
00075 static unsigned CountCodeReductionForConstant(Value *V) {
00076   unsigned Reduction = 0;
00077   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
00078     if (isa<BranchInst>(*UI))
00079       Reduction += 40;          // Eliminating a conditional branch is a big win
00080     else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
00081       // Eliminating a switch is a big win, proportional to the number of edges
00082       // deleted.
00083       Reduction += (SI->getNumSuccessors()-1) * 40;
00084     else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
00085       // Turning an indirect call into a direct call is a BIG win
00086       Reduction += CI->getCalledValue() == V ? 500 : 0;
00087     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
00088       // Turning an indirect call into a direct call is a BIG win
00089       Reduction += II->getCalledValue() == V ? 500 : 0;
00090     } else {
00091       // Figure out if this instruction will be removed due to simple constant
00092       // propagation.
00093       Instruction &Inst = cast<Instruction>(**UI);
00094       bool AllOperandsConstant = true;
00095       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
00096         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
00097           AllOperandsConstant = false;
00098           break;
00099         }
00100 
00101       if (AllOperandsConstant) {
00102         // We will get to remove this instruction...
00103         Reduction += 7;
00104         
00105         // And any other instructions that use it which become constants
00106         // themselves.
00107         Reduction += CountCodeReductionForConstant(&Inst);
00108       }
00109     }
00110 
00111   return Reduction;
00112 }
00113 
00114 // CountCodeReductionForAlloca - Figure out an approximation of how much smaller
00115 // the function will be if it is inlined into a context where an argument
00116 // becomes an alloca.
00117 //
00118 static unsigned CountCodeReductionForAlloca(Value *V) {
00119   if (!isa<PointerType>(V->getType())) return 0;  // Not a pointer
00120   unsigned Reduction = 0;
00121   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
00122     Instruction *I = cast<Instruction>(*UI);
00123     if (isa<LoadInst>(I) || isa<StoreInst>(I))
00124       Reduction += 10;
00125     else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00126       // If the GEP has variable indices, we won't be able to do much with it.
00127       for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
00128            I != E; ++I)
00129         if (!isa<Constant>(*I)) return 0;
00130       Reduction += CountCodeReductionForAlloca(GEP)+15;
00131     } else {
00132       // If there is some other strange instruction, we're not going to be able
00133       // to do much if we inline this.
00134       return 0;
00135     }
00136   }
00137 
00138   return Reduction;
00139 }
00140 
00141 /// analyzeFunction - Fill in the current structure with information gleaned
00142 /// from the specified function.
00143 void FunctionInfo::analyzeFunction(Function *F) {
00144   unsigned NumInsts = 0, NumBlocks = 0;
00145 
00146   // Look at the size of the callee.  Each basic block counts as 20 units, and
00147   // each instruction counts as 10.
00148   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
00149     for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
00150          II != E; ++II) {
00151       if (!isa<DbgInfoIntrinsic>(II)) ++NumInsts;
00152 
00153       // If there is an alloca in the body of the function, we cannot currently
00154       // inline the function without the risk of exploding the stack.
00155       if (isa<AllocaInst>(II) && BB != F->begin()) {
00156         HasAllocas = true;
00157         this->NumBlocks = this->NumInsts = 1;
00158         return;
00159       }
00160     }
00161 
00162     ++NumBlocks;
00163   }
00164 
00165   this->NumBlocks = NumBlocks;
00166   this->NumInsts  = NumInsts;
00167 
00168   // Check out all of the arguments to the function, figuring out how much
00169   // code can be eliminated if one of the arguments is a constant.
00170   for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
00171     ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
00172                                       CountCodeReductionForAlloca(I)));
00173 }
00174 
00175 
00176 // getInlineCost - The heuristic used to determine if we should inline the
00177 // function call or not.
00178 //
00179 int SimpleInliner::getInlineCost(CallSite CS) {
00180   Instruction *TheCall = CS.getInstruction();
00181   Function *Callee = CS.getCalledFunction();
00182   const Function *Caller = TheCall->getParent()->getParent();
00183 
00184   // Don't inline a directly recursive call.
00185   if (Caller == Callee) return 2000000000;
00186 
00187   // InlineCost - This value measures how good of an inline candidate this call
00188   // site is to inline.  A lower inline cost make is more likely for the call to
00189   // be inlined.  This value may go negative.
00190   //
00191   int InlineCost = 0;
00192 
00193   // If there is only one call of the function, and it has internal linkage,
00194   // make it almost guaranteed to be inlined.
00195   //
00196   if (Callee->hasInternalLinkage() && Callee->hasOneUse())
00197     InlineCost -= 30000;
00198 
00199   // Get information about the callee...
00200   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
00201 
00202   // If we haven't calculated this information yet, do so now.
00203   if (CalleeFI.NumBlocks == 0)
00204     CalleeFI.analyzeFunction(Callee);
00205 
00206   // Don't inline calls to functions with allocas that are not in the entry
00207   // block of the function.
00208   if (CalleeFI.HasAllocas)
00209     return 2000000000;
00210 
00211   // Add to the inline quality for properties that make the call valuable to
00212   // inline.  This includes factors that indicate that the result of inlining
00213   // the function will be optimizable.  Currently this just looks at arguments
00214   // passed into the function.
00215   //
00216   unsigned ArgNo = 0;
00217   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00218        I != E; ++I, ++ArgNo) {
00219     // Each argument passed in has a cost at both the caller and the callee
00220     // sides.  This favors functions that take many arguments over functions
00221     // that take few arguments.
00222     InlineCost -= 20;
00223 
00224     // If this is a function being passed in, it is very likely that we will be
00225     // able to turn an indirect function call into a direct function call.
00226     if (isa<Function>(I))
00227       InlineCost -= 100;
00228 
00229     // If an alloca is passed in, inlining this function is likely to allow
00230     // significant future optimization possibilities (like scalar promotion, and
00231     // scalarization), so encourage the inlining of the function.
00232     //
00233     else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00234       if (ArgNo < CalleeFI.ArgumentWeights.size())
00235         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
00236 
00237     // If this is a constant being passed into the function, use the argument
00238     // weights calculated for the callee to determine how much will be folded
00239     // away with this information.
00240     } else if (isa<Constant>(I)) {
00241       if (ArgNo < CalleeFI.ArgumentWeights.size())
00242         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
00243     }
00244   }
00245 
00246   // Now that we have considered all of the factors that make the call site more
00247   // likely to be inlined, look at factors that make us not want to inline it.
00248 
00249   // Don't inline into something too big, which would make it bigger.  Here, we
00250   // count each basic block as a single unit.
00251   //
00252   InlineCost += Caller->size()/20;
00253 
00254 
00255   // Look at the size of the callee.  Each basic block counts as 20 units, and
00256   // each instruction counts as 5.
00257   InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
00258   return InlineCost;
00259 }
00260