Moved Inliner.h to include/llvm/Transforms/IPO/InlinerPass.h
[oota-llvm.git] / lib / Transforms / IPO / InlineSimple.cpp
index 0c950c7ba3f4337062013ac3a4dd44449ad39657..83cfe901a09f383fa041aa304f0cd530f0e6b819 100644 (file)
@@ -1,26 +1,33 @@
 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file was developed by the LLVM research group and is distributed under
 // the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
 // This file implements bottom-up inlining of functions into callees.
 //
 //===----------------------------------------------------------------------===//
 
-#include "Inliner.h"
+#define DEBUG_TYPE "inline"
+#include "llvm/CallingConv.h"
 #include "llvm/Instructions.h"
-#include "llvm/Function.h"
+#include "llvm/IntrinsicInst.h"
+#include "llvm/Module.h"
 #include "llvm/Type.h"
+#include "llvm/Analysis/CallGraph.h"
 #include "llvm/Support/CallSite.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/IPO/InlinerPass.h"
+#include <set>
+
 using namespace llvm;
 
 namespace {
-  struct ArgInfo {
+  struct VISIBILITY_HIDDEN ArgInfo {
     unsigned ConstantWeight;
     unsigned AllocaWeight;
 
@@ -30,7 +37,7 @@ namespace {
 
   // FunctionInfo - For each function, calculate the size of it in blocks and
   // instructions.
-  struct FunctionInfo {
+  struct VISIBILITY_HIDDEN FunctionInfo {
     // NumInsts, NumBlocks - Keep track of how large each function is, which is
     // used to estimate the code size cost of inlining it.
     unsigned NumInsts, NumBlocks;
@@ -42,14 +49,23 @@ namespace {
     std::vector<ArgInfo> ArgumentWeights;
 
     FunctionInfo() : NumInsts(0), NumBlocks(0) {}
+
+    /// analyzeFunction - Fill in the current structure with information gleaned
+    /// from the specified function.
+    void analyzeFunction(Function *F);
   };
 
-  class SimpleInliner : public Inliner {
+  class VISIBILITY_HIDDEN SimpleInliner : public Inliner {
     std::map<const Function*, FunctionInfo> CachedFunctionInfo;
+    std::set<const Function*> NeverInline; // Functions that are never inlined
   public:
+    SimpleInliner() : Inliner(&ID) {}
+    static char ID; // Pass identification, replacement for typeid
     int getInlineCost(CallSite CS);
+    virtual bool doInitialization(CallGraph &CG);
   };
-  RegisterOpt<SimpleInliner> X("inline", "Function Integration/Inlining");
+  char SimpleInliner::ID = 0;
+  RegisterPass<SimpleInliner> X("inline", "Function Integration/Inlining");
 }
 
 Pass *llvm::createFunctionInliningPass() { return new SimpleInliner(); }
@@ -78,8 +94,7 @@ static unsigned CountCodeReductionForConstant(Value *V) {
       Instruction &Inst = cast<Instruction>(**UI);
       bool AllOperandsConstant = true;
       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
-        if (!isa<Constant>(Inst.getOperand(i)) &&
-            !isa<GlobalValue>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
+        if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
           AllOperandsConstant = false;
           break;
         }
@@ -87,7 +102,7 @@ static unsigned CountCodeReductionForConstant(Value *V) {
       if (AllOperandsConstant) {
         // We will get to remove this instruction...
         Reduction += 7;
-        
+
         // And any other instructions that use it which become constants
         // themselves.
         Reduction += CountCodeReductionForConstant(&Inst);
@@ -124,6 +139,53 @@ static unsigned CountCodeReductionForAlloca(Value *V) {
   return Reduction;
 }
 
+/// analyzeFunction - Fill in the current structure with information gleaned
+/// from the specified function.
+void FunctionInfo::analyzeFunction(Function *F) {
+  unsigned NumInsts = 0, NumBlocks = 0;
+
+  // Look at the size of the callee.  Each basic block counts as 20 units, and
+  // each instruction counts as 10.
+  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
+    for (BasicBlock::const_iterator II = BB->begin(), E = BB->end();
+         II != E; ++II) {
+      if (isa<DbgInfoIntrinsic>(II)) continue;  // Debug intrinsics don't count.
+      
+      // Noop casts, including ptr <-> int,  don't count.
+      if (const CastInst *CI = dyn_cast<CastInst>(II)) {
+        if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || 
+            isa<PtrToIntInst>(CI))
+          continue;
+      } else if (const GetElementPtrInst *GEPI =
+                         dyn_cast<GetElementPtrInst>(II)) {
+        // If a GEP has all constant indices, it will probably be folded with
+        // a load/store.
+        bool AllConstant = true;
+        for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
+          if (!isa<ConstantInt>(GEPI->getOperand(i))) {
+            AllConstant = false;
+            break;
+          }
+        if (AllConstant) continue;
+      }
+      
+      ++NumInsts;
+    }
+
+    ++NumBlocks;
+  }
+
+  this->NumBlocks = NumBlocks;
+  this->NumInsts  = NumInsts;
+
+  // Check out all of the arguments to the function, figuring out how much
+  // code can be eliminated if one of the arguments is a constant.
+  for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
+    ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
+                                      CountCodeReductionForAlloca(I)));
+}
+
+
 // getInlineCost - The heuristic used to determine if we should inline the
 // function call or not.
 //
@@ -135,6 +197,9 @@ int SimpleInliner::getInlineCost(CallSite CS) {
   // Don't inline a directly recursive call.
   if (Caller == Callee) return 2000000000;
 
+  // Don't inline functions marked noinline
+  if (NeverInline.count(Callee)) return 2000000000;
+  
   // InlineCost - This value measures how good of an inline candidate this call
   // site is to inline.  A lower inline cost make is more likely for the call to
   // be inlined.  This value may go negative.
@@ -147,34 +212,26 @@ int SimpleInliner::getInlineCost(CallSite CS) {
   if (Callee->hasInternalLinkage() && Callee->hasOneUse())
     InlineCost -= 30000;
 
-  // Get information about the callee...
-  FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet...
-  if (CalleeFI.NumBlocks == 0) {
-    unsigned NumInsts = 0, NumBlocks = 0;
-
-    // Look at the size of the callee.  Each basic block counts as 20 units, and
-    // each instruction counts as 10.
-    for (Function::const_iterator BB = Callee->begin(), E = Callee->end();
-         BB != E; ++BB) {
-      NumInsts += BB->size();
-      NumBlocks++;
-    }
-
-    CalleeFI.NumBlocks = NumBlocks;
-    CalleeFI.NumInsts  = NumInsts;
+  // If this function uses the coldcc calling convention, prefer not to inline
+  // it.
+  if (Callee->getCallingConv() == CallingConv::Cold)
+    InlineCost += 2000;
 
-    // Check out all of the arguments to the function, figuring out how much
-    // code can be eliminated if one of the arguments is a constant.
-    std::vector<ArgInfo> &ArgWeights = CalleeFI.ArgumentWeights;
+  // If the instruction after the call, or if the normal destination of the
+  // invoke is an unreachable instruction, the function is noreturn.  As such,
+  // there is little point in inlining this.
+  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
+    if (isa<UnreachableInst>(II->getNormalDest()->begin()))
+      InlineCost += 10000;
+  } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
+    InlineCost += 10000;
 
-    for (Function::aiterator I = Callee->abegin(), E = Callee->aend();
-         I != E; ++I)
-      ArgWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
-                                   CountCodeReductionForAlloca(I)));
-  }
+  // Get information about the callee...
+  FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
 
+  // If we haven't calculated this information yet, do so now.
+  if (CalleeFI.NumBlocks == 0)
+    CalleeFI.analyzeFunction(Callee);
 
   // Add to the inline quality for properties that make the call valuable to
   // inline.  This includes factors that indicate that the result of inlining
@@ -198,14 +255,14 @@ int SimpleInliner::getInlineCost(CallSite CS) {
     // significant future optimization possibilities (like scalar promotion, and
     // scalarization), so encourage the inlining of the function.
     //
-    else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
+    else if (isa<AllocaInst>(I)) {
       if (ArgNo < CalleeFI.ArgumentWeights.size())
         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
 
     // If this is a constant being passed into the function, use the argument
     // weights calculated for the callee to determine how much will be folded
     // away with this information.
-    } else if (isa<Constant>(I) || isa<GlobalVariable>(I)) {
+    } else if (isa<Constant>(I)) {
       if (ArgNo < CalleeFI.ArgumentWeights.size())
         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
     }
@@ -217,13 +274,7 @@ int SimpleInliner::getInlineCost(CallSite CS) {
   // Don't inline into something too big, which would make it bigger.  Here, we
   // count each basic block as a single unit.
   //
-  // FIXME: THIS IS A TOTAL HACK.  The problem is that we don't keep track of
-  // which call sites are the result of an inlining operation.  Because of this,
-  // if we inline a recursive function into a callee, we will see a new call to
-  // the recursive function.  Every time we inline we get a new callsite for the
-  // function, which only stops when the caller reaches its inlining limit.
-  // Until the real problem is fixed, we apply this gnasty hack.
-  InlineCost += Caller->size();
+  InlineCost += Caller->size()/20;
 
 
   // Look at the size of the callee.  Each basic block counts as 20 units, and
@@ -232,3 +283,37 @@ int SimpleInliner::getInlineCost(CallSite CS) {
   return InlineCost;
 }
 
+// doInitialization - Initializes the vector of functions that have been
+// annotated with the noinline attribute.
+bool SimpleInliner::doInitialization(CallGraph &CG) {
+  
+  Module &M = CG.getModule();
+  
+  // Get llvm.noinline
+  GlobalVariable *GV = M.getNamedGlobal("llvm.noinline");
+  
+  if (GV == 0)
+    return false;
+
+  const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
+  
+  if (InitList == 0)
+    return false;
+
+  // Iterate over each element and add to the NeverInline set
+  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
+        
+    // Get Source
+    const Constant *Elt = InitList->getOperand(i);
+        
+    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Elt))
+      if (CE->getOpcode() == Instruction::BitCast) 
+        Elt = CE->getOperand(0);
+    
+    // Insert into set of functions to never inline
+    if (const Function *F = dyn_cast<Function>(Elt))
+      NeverInline.insert(F);
+  }
+  
+  return false;
+}