Move EVER MORE stuff over to LLVMContext.
[oota-llvm.git] / lib / Transforms / Scalar / TailDuplication.cpp
index 97e8b186e525d6fe25c9afbe746df6b0060a96c9..5f7221051c22c0d7a3f7eabd6e0bdd7f14793412 100644 (file)
@@ -2,8 +2,8 @@
 //
 //                     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 is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
 #include "llvm/Pass.h"
 #include "llvm/Type.h"
 #include "llvm/Support/CFG.h"
+#include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include <map>
 using namespace llvm;
 
 STATISTIC(NumEliminated, "Number of unconditional branches eliminated");
 
+static cl::opt<unsigned>
+TailDupThreshold("taildup-threshold",
+                 cl::desc("Max block size to tail duplicate"),
+                 cl::init(1), cl::Hidden);
+
 namespace {
-  cl::opt<unsigned>
-  Threshold("taildup-threshold", cl::desc("Max block size to tail duplicate"),
-            cl::init(6), cl::Hidden);
-  class TailDup : public FunctionPass {
+  class VISIBILITY_HIDDEN TailDup : public FunctionPass {
     bool runOnFunction(Function &F);
+  public:
+    static char ID; // Pass identification, replacement for typeid
+    TailDup() : FunctionPass(&ID) {}
+
   private:
-    inline bool shouldEliminateUnconditionalBranch(TerminatorInst *TI);
+    inline bool shouldEliminateUnconditionalBranch(TerminatorInst *, unsigned);
     inline void eliminateUnconditionalBranch(BranchInst *BI);
+    SmallPtrSet<BasicBlock*, 4> CycleDetector;
   };
-  RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
 }
 
+char TailDup::ID = 0;
+static RegisterPass<TailDup> X("tailduplicate", "Tail Duplication");
+
 // Public interface to the Tail Duplication pass
 FunctionPass *llvm::createTailDuplicationPass() { return new TailDup(); }
 
 /// runOnFunction - Top level algorithm - Loop over each unconditional branch in
-/// the function, eliminating it if it looks attractive enough.
-///
+/// the function, eliminating it if it looks attractive enough.  CycleDetector
+/// prevents infinite loops by checking that we aren't redirecting a branch to
+/// a place it already pointed to earlier; see PR 2323.
 bool TailDup::runOnFunction(Function &F) {
   bool Changed = false;
-  for (Function::iterator I = F.begin(), E = F.end(); I != E; )
-    if (shouldEliminateUnconditionalBranch(I->getTerminator())) {
+  CycleDetector.clear();
+  for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
+    if (shouldEliminateUnconditionalBranch(I->getTerminator(),
+                                           TailDupThreshold)) {
       eliminateUnconditionalBranch(cast<BranchInst>(I->getTerminator()));
       Changed = true;
     } else {
       ++I;
+      CycleDetector.clear();
     }
+  }
   return Changed;
 }
 
@@ -75,7 +93,8 @@ bool TailDup::runOnFunction(Function &F) {
 /// We don't count PHI nodes in the count since they will be removed when the
 /// contents of the block are copied over.
 ///
-bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
+bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI,
+                                                 unsigned Threshold) {
   BranchInst *BI = dyn_cast<BranchInst>(TI);
   if (!BI || !BI->isUnconditional()) return false;  // Not an uncond branch!
 
@@ -94,21 +113,28 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
   if (!DTI->use_empty())
     return false;
 
-  // Do not bother working on dead blocks...
-  pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
-  if (PI == PE && Dest != Dest->getParent()->begin())
-    return false;   // It's just a dead block, ignore it...
-
-  // Also, do not bother with blocks with only a single predecessor: simplify
+  // Do not bother with blocks with only a single predecessor: simplify
   // CFG will fold these two blocks together!
+  pred_iterator PI = pred_begin(Dest), PE = pred_end(Dest);
   ++PI;
   if (PI == PE) return false;  // Exactly one predecessor!
 
-  BasicBlock::iterator I = Dest->begin();
-  while (isa<PHINode>(*I)) ++I;
+  BasicBlock::iterator I = Dest->getFirstNonPHI();
 
   for (unsigned Size = 0; I != Dest->end(); ++I) {
     if (Size == Threshold) return false;  // The block is too large.
+    
+    // Don't tail duplicate call instructions.  They are very large compared to
+    // other instructions.
+    if (isa<CallInst>(I) || isa<InvokeInst>(I)) return false;
+
+    // Allso alloca and malloc.
+    if (isa<AllocationInst>(I)) return false;
+
+    // Some vector instructions can expand into a number of instructions.
+    if (isa<ShuffleVectorInst>(I) || isa<ExtractElementInst>(I) ||
+        isa<InsertElementInst>(I)) return false;
+    
     // Only count instructions that are not debugger intrinsics.
     if (!isa<DbgInfoIntrinsic>(I)) ++Size;
   }
@@ -126,7 +152,7 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
       if (TooMany-- == 0) return false;
   }
   
-  // Finally, if this unconditional branch is a fall-through, be careful about
+  // If this unconditional branch is a fall-through, be careful about
   // tail duplicating it.  In particular, we don't want to taildup it if the
   // original block will still be there after taildup is completed: doing so
   // would eliminate the fall-through, requiring unconditional branches.
@@ -156,6 +182,11 @@ bool TailDup::shouldEliminateUnconditionalBranch(TerminatorInst *TI) {
     }
   }
 
+  // Finally, check that we haven't redirected to this target block earlier;
+  // there are cases where we loop forever if we don't check this (PR 2323).
+  if (!CycleDetector.insert(Dest))
+    return false;
+
   return true;
 }
 
@@ -223,12 +254,11 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
     // If there are non-phi instructions in DestBlock that have no operands
     // defined in DestBlock, and if the instruction has no side effects, we can
     // move the instruction to DomBlock instead of duplicating it.
-    BasicBlock::iterator BBI = DestBlock->begin();
-    while (isa<PHINode>(BBI)) ++BBI;
+    BasicBlock::iterator BBI = DestBlock->getFirstNonPHI();
     while (!isa<TerminatorInst>(BBI)) {
       Instruction *I = BBI++;
 
-      bool CanHoist = !I->isTrapping() && !I->mayWriteToMemory();
+      bool CanHoist = !I->isTrapping() && !I->mayHaveSideEffects();
       if (CanHoist) {
         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(op)))
@@ -252,40 +282,10 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   // this reason, we spill all values that are used outside of the tail to the
   // stack.
   for (BasicBlock::iterator I = DestBlock->begin(); I != DestBlock->end(); ++I)
-    for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
-         ++UI) {
-      bool ShouldDemote = false;
-      if (cast<Instruction>(*UI)->getParent() != DestBlock) {
-        // We must allow our successors to use tail values in their PHI nodes
-        // (if the incoming value corresponds to the tail block).
-        if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
-          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
-            if (PN->getIncomingValue(i) == I &&
-                PN->getIncomingBlock(i) != DestBlock) {
-              ShouldDemote = true;
-              break;
-            }
-
-        } else {
-          ShouldDemote = true;
-        }
-      } else if (PHINode *PN = dyn_cast<PHINode>(cast<Instruction>(*UI))) {
-        // If the user of this instruction is a PHI node in the current block,
-        // which has an entry from another block using the value, spill it.
-        for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
-          if (PN->getIncomingValue(i) == I &&
-              PN->getIncomingBlock(i) != DestBlock) {
-            ShouldDemote = true;
-            break;
-          }
-      }
-
-      if (ShouldDemote) {
-        // We found a use outside of the tail.  Create a new stack slot to
-        // break this inter-block usage pattern.
-        DemoteRegToStack(*I);
-        break;
-      }
+    if (I->isUsedOutsideOfBlock(DestBlock)) {
+      // We found a use outside of the tail.  Create a new stack slot to
+      // break this inter-block usage pattern.
+      DemoteRegToStack(*Context, *I);
     }
 
   // We are going to have to map operands from the original block B to the new
@@ -304,7 +304,7 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   // keeping track of the mapping...
   //
   for (; BI != DestBlock->end(); ++BI) {
-    Instruction *New = BI->clone();
+    Instruction *New = BI->clone(*Context);
     New->setName(BI->getName());
     SourceBlock->getInstList().push_back(New);
     ValueMapping[BI] = New;
@@ -317,9 +317,12 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   //
   BI = Branch; ++BI;  // Get an iterator to the first new instruction
   for (; BI != SourceBlock->end(); ++BI)
-    for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i)
-      if (Value *Remapped = ValueMapping[BI->getOperand(i)])
-        BI->setOperand(i, Remapped);
+    for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i) {
+      std::map<Value*, Value*>::const_iterator I =
+        ValueMapping.find(BI->getOperand(i));
+      if (I != ValueMapping.end())
+        BI->setOperand(i, I->second);
+    }
 
   // Next we check to see if any of the successors of DestBlock had PHI nodes.
   // If so, we need to add entries to the PHI nodes for SourceBlock now.
@@ -333,8 +336,9 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
       Value *IV = PN->getIncomingValueForBlock(DestBlock);
 
       // Remap the value if necessary...
-      if (Value *MappedIV = ValueMapping[IV])
-        IV = MappedIV;
+      std::map<Value*, Value*>::const_iterator I = ValueMapping.find(IV);
+      if (I != ValueMapping.end())
+        IV = I->second;
       PN->addIncoming(IV, SourceBlock);
     }
   }
@@ -349,10 +353,17 @@ void TailDup::eliminateUnconditionalBranch(BranchInst *Branch) {
   // instructions one last time, constant propagating and DCE'ing them, because
   // they may not be needed anymore.
   //
-  if (HadPHINodes)
-    while (BI != SourceBlock->end())
-      if (!dceInstruction(BI) && !doConstantPropagation(BI))
-        ++BI;
+  if (HadPHINodes) {
+    while (BI != SourceBlock->end()) {
+      Instruction *Inst = BI++;
+      if (isInstructionTriviallyDead(Inst))
+        Inst->eraseFromParent();
+      else if (Constant *C = ConstantFoldInstruction(Inst, Context)) {
+        Inst->replaceAllUsesWith(C);
+        Inst->eraseFromParent();
+      }
+    }
+  }
 
   ++NumEliminated;  // We just killed a branch!
 }