* We were forgetting to pass varargs arguments through a call
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
index 546dd1ccba615be042b89541f2a955d7012353c3..822a2d894776db3e986d61656ca405e270625fea 100644 (file)
@@ -1,7 +1,14 @@
 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
+// 
+//                     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 pass reassociates commutative expressions in an order that is designed
-// to promote better constant propogation, GCSE, LICM, PRE...
+// to promote better constant propagation, GCSE, LICM, PRE...
 //
 // For example: 4 + (x + 5) -> x + (4 + 5)
 //
@@ -14,9 +21,6 @@
 // (starting at 2), which effectively gives values in deep loops higher rank
 // than values not in loops.
 //
-// This code was originally written by Chris Lattner, and was then cleaned up
-// and perfected by Casey Carter.
-//
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Transforms/Scalar.h"
@@ -26,6 +30,7 @@
 #include "llvm/Pass.h"
 #include "llvm/Constant.h"
 #include "llvm/Support/CFG.h"
+#include "Support/Debug.h"
 #include "Support/PostOrderIterator.h"
 #include "Support/Statistic.h"
 
@@ -36,6 +41,7 @@ namespace {
 
   class Reassociate : public FunctionPass {
     std::map<BasicBlock*, unsigned> RankMap;
+    std::map<Value*, unsigned> ValueRankMap;
   public:
     bool runOnFunction(Function &F);
 
@@ -55,33 +61,46 @@ namespace {
 Pass *createReassociatePass() { return new Reassociate(); }
 
 void Reassociate::BuildRankMap(Function &F) {
-  unsigned i = 1;
+  unsigned i = 2;
+
+  // Assign distinct ranks to function arguments
+  for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
+    ValueRankMap[I] = ++i;
+
   ReversePostOrderTraversal<Function*> RPOT(&F);
   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
          E = RPOT.end(); I != E; ++I)
-    RankMap[*I] = ++i;
+    RankMap[*I] = ++i << 16;
 }
 
 unsigned Reassociate::getRank(Value *V) {
-  if (isa<Argument>(V)) return 1;   // Function argument...
+  if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
+
   if (Instruction *I = dyn_cast<Instruction>(V)) {
-    // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
-    // can reassociate expressions for code motion!  Since we do not recurse for
-    // PHI nodes, we cannot have infinite recursion here, because there cannot
-    // be loops in the value graph (except for PHI nodes).
+    // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
+    // we can reassociate expressions for code motion!  Since we do not recurse
+    // for PHI nodes, we cannot have infinite recursion here, because there
+    // cannot be loops in the value graph that do not go through PHI nodes.
     //
-    if (I->getOpcode() == Instruction::PHINode ||
+    if (I->getOpcode() == Instruction::PHI ||
         I->getOpcode() == Instruction::Alloca ||
         I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
-        I->hasSideEffects())
+        I->mayWriteToMemory())  // Cannot move inst if it writes to memory!
       return RankMap[I->getParent()];
 
+    unsigned &CachedRank = ValueRankMap[I];
+    if (CachedRank) return CachedRank;    // Rank already known?
+
+    // If not, compute it!
     unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
     for (unsigned i = 0, e = I->getNumOperands();
          i != e && Rank != MaxRank; ++i)
       Rank = std::max(Rank, getRank(I->getOperand(i)));
 
-    return Rank;
+    DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
+                    << Rank+1 << "\n");
+
+    return CachedRank = Rank+1;
   }
 
   // Otherwise it's a global or constant, rank 0.
@@ -106,46 +125,41 @@ bool Reassociate::ReassociateExpr(BinaryOperator *I) {
     std::swap(LHSRank, RHSRank);
     Changed = true;
     ++NumSwapped;
-    DEBUG(std::cerr << "Transposed: " << I << " Result BB: " << I->getParent());
+    DEBUG(std::cerr << "Transposed: " << I
+          /* << " Result BB: " << I->getParent()*/);
   }
   
   // If the LHS is the same operator as the current one is, and if we are the
   // only expression using it...
   //
   if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
-    if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
+    if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
       // If the rank of our current RHS is less than the rank of the LHS's LHS,
       // then we reassociate the two instructions...
-      if (RHSRank < getRank(LHSI->getOperand(0))) {
-        unsigned TakeOp = 0;
-        if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
-          if (IOp->getOpcode() == LHSI->getOpcode())
-            TakeOp = 1;   // Hoist out non-tree portion
 
+      unsigned TakeOp = 0;
+      if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
+        if (IOp->getOpcode() == LHSI->getOpcode())
+          TakeOp = 1;   // Hoist out non-tree portion
+
+      if (RHSRank < getRank(LHSI->getOperand(TakeOp))) {
         // Convert ((a + 12) + 10) into (a + (12 + 10))
         I->setOperand(0, LHSI->getOperand(TakeOp));
+        LHSI->setOperand(TakeOp, RHS);
+        I->setOperand(1, LHSI);
 
         // Move the LHS expression forward, to ensure that it is dominated by
         // its operands.
-        std::string Name = LHSI->getName();
-        LHSI->setName("");
-        BinaryOperator *NewLHS =
-          BinaryOperator::create(LHSI->getOpcode(),
-                                 LHSI->getOperand(0), LHSI->getOperand(1),
-                                 Name, I);
-
-        NewLHS->setOperand(TakeOp, RHS);
-        I->setOperand(1, NewLHS);
-
-        assert(LHSI->use_size() == 0 && "References to LHS shouldn't exist!");
-        LHSI->getParent()->getInstList().erase(LHSI);
+        LHSI->getParent()->getInstList().remove(LHSI);
+        I->getParent()->getInstList().insert(I, LHSI);
 
         ++NumChanged;
-        DEBUG(std::cerr << "Reassociated: " << I << " Result BB: "
-                        << I->getParent());
+        DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
+                                                   << I->getParent()*/);
 
         // Since we modified the RHS instruction, make sure that we recheck it.
-        ReassociateExpr(NewLHS);
+        ReassociateExpr(LHSI);
+        ReassociateExpr(I);
         return true;
       }
     }
@@ -167,10 +181,10 @@ static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
   // the constants.  We assume that instcombine will clean up the mess later if
-  // we introduce tons of unneccesary negation instructions...
+  // we introduce tons of unnecessary negation instructions...
   //
   if (Instruction *I = dyn_cast<Instruction>(V))
-    if (I->getOpcode() == Instruction::Add && I->use_size() == 1) {
+    if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
       Value *RHS = NegateValue(I->getOperand(1), BI);
       Value *LHS = NegateValue(I->getOperand(0), BI);
 
@@ -195,6 +209,7 @@ bool Reassociate::ReassociateBB(BasicBlock *BB) {
   bool Changed = false;
   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
 
+    DEBUG(std::cerr << "Processing: " << *BI);
     if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) {
       // Convert a subtract into an add and a neg instruction... so that sub
       // instructions can be commuted with other add instructions...
@@ -218,14 +233,14 @@ bool Reassociate::ReassociateBB(BasicBlock *BB) {
       New->setOperand(1, NegateValue(New->getOperand(1), BI));
       
       Changed = true;
-      DEBUG(std::cerr << "Negated: " << New << " Result BB: " << BB);
+      DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
     }
 
     // If this instruction is a commutative binary operator, and the ranks of
     // the two operands are sorted incorrectly, fix it now.
     //
     if (BI->isAssociative()) {
-      BinaryOperator *I = cast<BinaryOperator>(&*BI);
+      BinaryOperator *I = cast<BinaryOperator>(BI);
       if (!I->use_empty()) {
         // Make sure that we don't have a tree-shaped computation.  If we do,
         // linearize it.  Convert (A+B)+(C+D) into ((A+B)+C)+D
@@ -234,7 +249,7 @@ bool Reassociate::ReassociateBB(BasicBlock *BB) {
         Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
         if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
             RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
-            RHSI->use_size() == 1) {
+            RHSI->hasOneUse()) {
           // Insert a new temporary instruction... (A+B)+C
           BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
                                                        RHSI->getOperand(0),
@@ -248,7 +263,7 @@ bool Reassociate::ReassociateBB(BasicBlock *BB) {
           I = Tmp;
           ++NumLinear;
           Changed = true;
-          DEBUG(std::cerr << "Linearized: " << I << " Result BB: " << BB);
+          DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
         }
 
         // Make sure that this expression is correctly reassociated with respect
@@ -273,5 +288,6 @@ bool Reassociate::runOnFunction(Function &F) {
 
   // We are done with the rank map...
   RankMap.clear();
+  ValueRankMap.clear();
   return Changed;
 }