LLVM API Documentation

Reassociate.cpp

Go to the documentation of this file.
00001 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass reassociates commutative expressions in an order that is designed
00011 // to promote better constant propagation, GCSE, LICM, PRE...
00012 //
00013 // For example: 4 + (x + 5) -> x + (4 + 5)
00014 //
00015 // In the implementation of this algorithm, constants are assigned rank = 0,
00016 // function arguments are rank = 1, and other values are assigned ranks
00017 // corresponding to the reverse post order traversal of current function
00018 // (starting at 2), which effectively gives values in deep loops higher rank
00019 // than values not in loops.
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #define DEBUG_TYPE "reassociate"
00024 #include "llvm/Transforms/Scalar.h"
00025 #include "llvm/Constants.h"
00026 #include "llvm/DerivedTypes.h"
00027 #include "llvm/Function.h"
00028 #include "llvm/Instructions.h"
00029 #include "llvm/Pass.h"
00030 #include "llvm/Assembly/Writer.h"
00031 #include "llvm/Support/CFG.h"
00032 #include "llvm/Support/Compiler.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/ADT/PostOrderIterator.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include <algorithm>
00037 #include <map>
00038 using namespace llvm;
00039 
00040 STATISTIC(NumLinear , "Number of insts linearized");
00041 STATISTIC(NumChanged, "Number of insts reassociated");
00042 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
00043 STATISTIC(NumFactor , "Number of multiplies factored");
00044 
00045 namespace {
00046   struct VISIBILITY_HIDDEN ValueEntry {
00047     unsigned Rank;
00048     Value *Op;
00049     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
00050   };
00051   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
00052     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
00053   }
00054 }
00055 
00056 #ifndef NDEBUG
00057 /// PrintOps - Print out the expression identified in the Ops list.
00058 ///
00059 static void PrintOps(Instruction *I, const std::vector<ValueEntry> &Ops) {
00060   Module *M = I->getParent()->getParent()->getParent();
00061   cerr << Instruction::getOpcodeName(I->getOpcode()) << " "
00062        << *Ops[0].Op->getType();
00063   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00064     WriteAsOperand(*cerr.stream() << " ", Ops[i].Op, false, M);
00065     cerr << "," << Ops[i].Rank;
00066   }
00067 }
00068 #endif
00069   
00070 namespace {
00071   class VISIBILITY_HIDDEN Reassociate : public FunctionPass {
00072     std::map<BasicBlock*, unsigned> RankMap;
00073     std::map<Value*, unsigned> ValueRankMap;
00074     bool MadeChange;
00075   public:
00076     static char ID; // Pass identification, replacement for typeid
00077     Reassociate() : FunctionPass(&ID) {}
00078 
00079     bool runOnFunction(Function &F);
00080 
00081     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00082       AU.setPreservesCFG();
00083     }
00084   private:
00085     void BuildRankMap(Function &F);
00086     unsigned getRank(Value *V);
00087     void ReassociateExpression(BinaryOperator *I);
00088     void RewriteExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops,
00089                          unsigned Idx = 0);
00090     Value *OptimizeExpression(BinaryOperator *I, std::vector<ValueEntry> &Ops);
00091     void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
00092     void LinearizeExpr(BinaryOperator *I);
00093     Value *RemoveFactorFromExpression(Value *V, Value *Factor);
00094     void ReassociateBB(BasicBlock *BB);
00095     
00096     void RemoveDeadBinaryOp(Value *V);
00097   };
00098 }
00099 
00100 char Reassociate::ID = 0;
00101 static RegisterPass<Reassociate> X("reassociate", "Reassociate expressions");
00102 
00103 // Public interface to the Reassociate pass
00104 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
00105 
00106 void Reassociate::RemoveDeadBinaryOp(Value *V) {
00107   Instruction *Op = dyn_cast<Instruction>(V);
00108   if (!Op || !isa<BinaryOperator>(Op) || !isa<CmpInst>(Op) || !Op->use_empty())
00109     return;
00110   
00111   Value *LHS = Op->getOperand(0), *RHS = Op->getOperand(1);
00112   RemoveDeadBinaryOp(LHS);
00113   RemoveDeadBinaryOp(RHS);
00114 }
00115 
00116 
00117 static bool isUnmovableInstruction(Instruction *I) {
00118   if (I->getOpcode() == Instruction::PHI ||
00119       I->getOpcode() == Instruction::Alloca ||
00120       I->getOpcode() == Instruction::Load ||
00121       I->getOpcode() == Instruction::Malloc ||
00122       I->getOpcode() == Instruction::Invoke ||
00123       I->getOpcode() == Instruction::Call ||
00124       I->getOpcode() == Instruction::UDiv || 
00125       I->getOpcode() == Instruction::SDiv ||
00126       I->getOpcode() == Instruction::FDiv ||
00127       I->getOpcode() == Instruction::URem ||
00128       I->getOpcode() == Instruction::SRem ||
00129       I->getOpcode() == Instruction::FRem)
00130     return true;
00131   return false;
00132 }
00133 
00134 void Reassociate::BuildRankMap(Function &F) {
00135   unsigned i = 2;
00136 
00137   // Assign distinct ranks to function arguments
00138   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
00139     ValueRankMap[I] = ++i;
00140 
00141   ReversePostOrderTraversal<Function*> RPOT(&F);
00142   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
00143          E = RPOT.end(); I != E; ++I) {
00144     BasicBlock *BB = *I;
00145     unsigned BBRank = RankMap[BB] = ++i << 16;
00146 
00147     // Walk the basic block, adding precomputed ranks for any instructions that
00148     // we cannot move.  This ensures that the ranks for these instructions are
00149     // all different in the block.
00150     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00151       if (isUnmovableInstruction(I))
00152         ValueRankMap[I] = ++BBRank;
00153   }
00154 }
00155 
00156 unsigned Reassociate::getRank(Value *V) {
00157   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
00158 
00159   Instruction *I = dyn_cast<Instruction>(V);
00160   if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
00161 
00162   unsigned &CachedRank = ValueRankMap[I];
00163   if (CachedRank) return CachedRank;    // Rank already known?
00164 
00165   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
00166   // we can reassociate expressions for code motion!  Since we do not recurse
00167   // for PHI nodes, we cannot have infinite recursion here, because there
00168   // cannot be loops in the value graph that do not go through PHI nodes.
00169   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
00170   for (unsigned i = 0, e = I->getNumOperands();
00171        i != e && Rank != MaxRank; ++i)
00172     Rank = std::max(Rank, getRank(I->getOperand(i)));
00173 
00174   // If this is a not or neg instruction, do not count it for rank.  This
00175   // assures us that X and ~X will have the same rank.
00176   if (!I->getType()->isInteger() ||
00177       (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
00178     ++Rank;
00179 
00180   //DOUT << "Calculated Rank[" << V->getName() << "] = "
00181   //     << Rank << "\n";
00182 
00183   return CachedRank = Rank;
00184 }
00185 
00186 /// isReassociableOp - Return true if V is an instruction of the specified
00187 /// opcode and if it only has one use.
00188 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
00189   if ((V->hasOneUse() || V->use_empty()) && isa<Instruction>(V) &&
00190       cast<Instruction>(V)->getOpcode() == Opcode)
00191     return cast<BinaryOperator>(V);
00192   return 0;
00193 }
00194 
00195 /// LowerNegateToMultiply - Replace 0-X with X*-1.
00196 ///
00197 static Instruction *LowerNegateToMultiply(Instruction *Neg) {
00198   Constant *Cst = ConstantInt::getAllOnesValue(Neg->getType());
00199 
00200   Instruction *Res = BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
00201   Res->takeName(Neg);
00202   Neg->replaceAllUsesWith(Res);
00203   Neg->eraseFromParent();
00204   return Res;
00205 }
00206 
00207 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
00208 // Note that if D is also part of the expression tree that we recurse to
00209 // linearize it as well.  Besides that case, this does not recurse into A,B, or
00210 // C.
00211 void Reassociate::LinearizeExpr(BinaryOperator *I) {
00212   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
00213   BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
00214   assert(isReassociableOp(LHS, I->getOpcode()) &&
00215          isReassociableOp(RHS, I->getOpcode()) &&
00216          "Not an expression that needs linearization?");
00217 
00218   DOUT << "Linear" << *LHS << *RHS << *I;
00219 
00220   // Move the RHS instruction to live immediately before I, avoiding breaking
00221   // dominator properties.
00222   RHS->moveBefore(I);
00223 
00224   // Move operands around to do the linearization.
00225   I->setOperand(1, RHS->getOperand(0));
00226   RHS->setOperand(0, LHS);
00227   I->setOperand(0, RHS);
00228 
00229   ++NumLinear;
00230   MadeChange = true;
00231   DOUT << "Linearized: " << *I;
00232 
00233   // If D is part of this expression tree, tail recurse.
00234   if (isReassociableOp(I->getOperand(1), I->getOpcode()))
00235     LinearizeExpr(I);
00236 }
00237 
00238 
00239 /// LinearizeExprTree - Given an associative binary expression tree, traverse
00240 /// all of the uses putting it into canonical form.  This forces a left-linear
00241 /// form of the the expression (((a+b)+c)+d), and collects information about the
00242 /// rank of the non-tree operands.
00243 ///
00244 /// NOTE: These intentionally destroys the expression tree operands (turning
00245 /// them into undef values) to reduce #uses of the values.  This means that the
00246 /// caller MUST use something like RewriteExprTree to put the values back in.
00247 ///
00248 void Reassociate::LinearizeExprTree(BinaryOperator *I,
00249                                     std::vector<ValueEntry> &Ops) {
00250   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
00251   unsigned Opcode = I->getOpcode();
00252 
00253   // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
00254   BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
00255   BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
00256 
00257   // If this is a multiply expression tree and it contains internal negations,
00258   // transform them into multiplies by -1 so they can be reassociated.
00259   if (I->getOpcode() == Instruction::Mul) {
00260     if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
00261       LHS = LowerNegateToMultiply(cast<Instruction>(LHS));
00262       LHSBO = isReassociableOp(LHS, Opcode);
00263     }
00264     if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
00265       RHS = LowerNegateToMultiply(cast<Instruction>(RHS));
00266       RHSBO = isReassociableOp(RHS, Opcode);
00267     }
00268   }
00269 
00270   if (!LHSBO) {
00271     if (!RHSBO) {
00272       // Neither the LHS or RHS as part of the tree, thus this is a leaf.  As
00273       // such, just remember these operands and their rank.
00274       Ops.push_back(ValueEntry(getRank(LHS), LHS));
00275       Ops.push_back(ValueEntry(getRank(RHS), RHS));
00276       
00277       // Clear the leaves out.
00278       I->setOperand(0, UndefValue::get(I->getType()));
00279       I->setOperand(1, UndefValue::get(I->getType()));
00280       return;
00281     } else {
00282       // Turn X+(Y+Z) -> (Y+Z)+X
00283       std::swap(LHSBO, RHSBO);
00284       std::swap(LHS, RHS);
00285       bool Success = !I->swapOperands();
00286       assert(Success && "swapOperands failed");
00287       Success = false;
00288       MadeChange = true;
00289     }
00290   } else if (RHSBO) {
00291     // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
00292     // part of the expression tree.
00293     LinearizeExpr(I);
00294     LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
00295     RHS = I->getOperand(1);
00296     RHSBO = 0;
00297   }
00298 
00299   // Okay, now we know that the LHS is a nested expression and that the RHS is
00300   // not.  Perform reassociation.
00301   assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
00302 
00303   // Move LHS right before I to make sure that the tree expression dominates all
00304   // values.
00305   LHSBO->moveBefore(I);
00306 
00307   // Linearize the expression tree on the LHS.
00308   LinearizeExprTree(LHSBO, Ops);
00309 
00310   // Remember the RHS operand and its rank.
00311   Ops.push_back(ValueEntry(getRank(RHS), RHS));
00312   
00313   // Clear the RHS leaf out.
00314   I->setOperand(1, UndefValue::get(I->getType()));
00315 }
00316 
00317 // RewriteExprTree - Now that the operands for this expression tree are
00318 // linearized and optimized, emit them in-order.  This function is written to be
00319 // tail recursive.
00320 void Reassociate::RewriteExprTree(BinaryOperator *I,
00321                                   std::vector<ValueEntry> &Ops,
00322                                   unsigned i) {
00323   if (i+2 == Ops.size()) {
00324     if (I->getOperand(0) != Ops[i].Op ||
00325         I->getOperand(1) != Ops[i+1].Op) {
00326       Value *OldLHS = I->getOperand(0);
00327       DOUT << "RA: " << *I;
00328       I->setOperand(0, Ops[i].Op);
00329       I->setOperand(1, Ops[i+1].Op);
00330       DOUT << "TO: " << *I;
00331       MadeChange = true;
00332       ++NumChanged;
00333       
00334       // If we reassociated a tree to fewer operands (e.g. (1+a+2) -> (a+3)
00335       // delete the extra, now dead, nodes.
00336       RemoveDeadBinaryOp(OldLHS);
00337     }
00338     return;
00339   }
00340   assert(i+2 < Ops.size() && "Ops index out of range!");
00341 
00342   if (I->getOperand(1) != Ops[i].Op) {
00343     DOUT << "RA: " << *I;
00344     I->setOperand(1, Ops[i].Op);
00345     DOUT << "TO: " << *I;
00346     MadeChange = true;
00347     ++NumChanged;
00348   }
00349   
00350   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
00351   assert(LHS->getOpcode() == I->getOpcode() &&
00352          "Improper expression tree!");
00353   
00354   // Compactify the tree instructions together with each other to guarantee
00355   // that the expression tree is dominated by all of Ops.
00356   LHS->moveBefore(I);
00357   RewriteExprTree(LHS, Ops, i+1);
00358 }
00359 
00360 
00361 
00362 // NegateValue - Insert instructions before the instruction pointed to by BI,
00363 // that computes the negative version of the value specified.  The negative
00364 // version of the value is returned, and BI is left pointing at the instruction
00365 // that should be processed next by the reassociation pass.
00366 //
00367 static Value *NegateValue(Value *V, Instruction *BI) {
00368   // We are trying to expose opportunity for reassociation.  One of the things
00369   // that we want to do to achieve this is to push a negation as deep into an
00370   // expression chain as possible, to expose the add instructions.  In practice,
00371   // this means that we turn this:
00372   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
00373   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
00374   // the constants.  We assume that instcombine will clean up the mess later if
00375   // we introduce tons of unnecessary negation instructions...
00376   //
00377   if (Instruction *I = dyn_cast<Instruction>(V))
00378     if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
00379       // Push the negates through the add.
00380       I->setOperand(0, NegateValue(I->getOperand(0), BI));
00381       I->setOperand(1, NegateValue(I->getOperand(1), BI));
00382 
00383       // We must move the add instruction here, because the neg instructions do
00384       // not dominate the old add instruction in general.  By moving it, we are
00385       // assured that the neg instructions we just inserted dominate the 
00386       // instruction we are about to insert after them.
00387       //
00388       I->moveBefore(BI);
00389       I->setName(I->getName()+".neg");
00390       return I;
00391     }
00392 
00393   // Insert a 'neg' instruction that subtracts the value from zero to get the
00394   // negation.
00395   //
00396   return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
00397 }
00398 
00399 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
00400 /// X-Y into (X + -Y).
00401 static bool ShouldBreakUpSubtract(Instruction *Sub) {
00402   // If this is a negation, we can't split it up!
00403   if (BinaryOperator::isNeg(Sub))
00404     return false;
00405   
00406   // Don't bother to break this up unless either the LHS is an associable add or
00407   // subtract or if this is only used by one.
00408   if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
00409       isReassociableOp(Sub->getOperand(0), Instruction::Sub))
00410     return true;
00411   if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
00412       isReassociableOp(Sub->getOperand(1), Instruction::Sub))
00413     return true;
00414   if (Sub->hasOneUse() && 
00415       (isReassociableOp(Sub->use_back(), Instruction::Add) ||
00416        isReassociableOp(Sub->use_back(), Instruction::Sub)))
00417     return true;
00418     
00419   return false;
00420 }
00421 
00422 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
00423 /// only used by an add, transform this into (X+(0-Y)) to promote better
00424 /// reassociation.
00425 static Instruction *BreakUpSubtract(Instruction *Sub) {
00426   // Convert a subtract into an add and a neg instruction... so that sub
00427   // instructions can be commuted with other add instructions...
00428   //
00429   // Calculate the negative value of Operand 1 of the sub instruction...
00430   // and set it as the RHS of the add instruction we just made...
00431   //
00432   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
00433   Instruction *New =
00434     BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
00435   New->takeName(Sub);
00436 
00437   // Everyone now refers to the add instruction.
00438   Sub->replaceAllUsesWith(New);
00439   Sub->eraseFromParent();
00440 
00441   DOUT << "Negated: " << *New;
00442   return New;
00443 }
00444 
00445 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
00446 /// by one, change this into a multiply by a constant to assist with further
00447 /// reassociation.
00448 static Instruction *ConvertShiftToMul(Instruction *Shl) {
00449   // If an operand of this shift is a reassociable multiply, or if the shift
00450   // is used by a reassociable multiply or add, turn into a multiply.
00451   if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) ||
00452       (Shl->hasOneUse() && 
00453        (isReassociableOp(Shl->use_back(), Instruction::Mul) ||
00454         isReassociableOp(Shl->use_back(), Instruction::Add)))) {
00455     Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
00456     MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
00457     
00458     Instruction *Mul = BinaryOperator::CreateMul(Shl->getOperand(0), MulCst,
00459                                                  "", Shl);
00460     Mul->takeName(Shl);
00461     Shl->replaceAllUsesWith(Mul);
00462     Shl->eraseFromParent();
00463     return Mul;
00464   }
00465   return 0;
00466 }
00467 
00468 // Scan backwards and forwards among values with the same rank as element i to
00469 // see if X exists.  If X does not exist, return i.
00470 static unsigned FindInOperandList(std::vector<ValueEntry> &Ops, unsigned i,
00471                                   Value *X) {
00472   unsigned XRank = Ops[i].Rank;
00473   unsigned e = Ops.size();
00474   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
00475     if (Ops[j].Op == X)
00476       return j;
00477   // Scan backwards
00478   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
00479     if (Ops[j].Op == X)
00480       return j;
00481   return i;
00482 }
00483 
00484 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
00485 /// and returning the result.  Insert the tree before I.
00486 static Value *EmitAddTreeOfValues(Instruction *I, std::vector<Value*> &Ops) {
00487   if (Ops.size() == 1) return Ops.back();
00488   
00489   Value *V1 = Ops.back();
00490   Ops.pop_back();
00491   Value *V2 = EmitAddTreeOfValues(I, Ops);
00492   return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
00493 }
00494 
00495 /// RemoveFactorFromExpression - If V is an expression tree that is a 
00496 /// multiplication sequence, and if this sequence contains a multiply by Factor,
00497 /// remove Factor from the tree and return the new tree.
00498 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
00499   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
00500   if (!BO) return 0;
00501   
00502   std::vector<ValueEntry> Factors;
00503   LinearizeExprTree(BO, Factors);
00504 
00505   bool FoundFactor = false;
00506   for (unsigned i = 0, e = Factors.size(); i != e; ++i)
00507     if (Factors[i].Op == Factor) {
00508       FoundFactor = true;
00509       Factors.erase(Factors.begin()+i);
00510       break;
00511     }
00512   if (!FoundFactor) {
00513     // Make sure to restore the operands to the expression tree.
00514     RewriteExprTree(BO, Factors);
00515     return 0;
00516   }
00517   
00518   if (Factors.size() == 1) return Factors[0].Op;
00519   
00520   RewriteExprTree(BO, Factors);
00521   return BO;
00522 }
00523 
00524 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
00525 /// add its operands as factors, otherwise add V to the list of factors.
00526 static void FindSingleUseMultiplyFactors(Value *V,
00527                                          std::vector<Value*> &Factors) {
00528   BinaryOperator *BO;
00529   if ((!V->hasOneUse() && !V->use_empty()) ||
00530       !(BO = dyn_cast<BinaryOperator>(V)) ||
00531       BO->getOpcode() != Instruction::Mul) {
00532     Factors.push_back(V);
00533     return;
00534   }
00535   
00536   // Otherwise, add the LHS and RHS to the list of factors.
00537   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors);
00538   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors);
00539 }
00540 
00541 
00542 
00543 Value *Reassociate::OptimizeExpression(BinaryOperator *I,
00544                                        std::vector<ValueEntry> &Ops) {
00545   // Now that we have the linearized expression tree, try to optimize it.
00546   // Start by folding any constants that we found.
00547   bool IterateOptimization = false;
00548   if (Ops.size() == 1) return Ops[0].Op;
00549 
00550   unsigned Opcode = I->getOpcode();
00551   
00552   if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
00553     if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
00554       Ops.pop_back();
00555       Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
00556       return OptimizeExpression(I, Ops);
00557     }
00558 
00559   // Check for destructive annihilation due to a constant being used.
00560   if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Ops.back().Op))
00561     switch (Opcode) {
00562     default: break;
00563     case Instruction::And:
00564       if (CstVal->isZero()) {                // ... & 0 -> 0
00565         ++NumAnnihil;
00566         return CstVal;
00567       } else if (CstVal->isAllOnesValue()) { // ... & -1 -> ...
00568         Ops.pop_back();
00569       }
00570       break;
00571     case Instruction::Mul:
00572       if (CstVal->isZero()) {                // ... * 0 -> 0
00573         ++NumAnnihil;
00574         return CstVal;
00575       } else if (cast<ConstantInt>(CstVal)->isOne()) {
00576         Ops.pop_back();                      // ... * 1 -> ...
00577       }
00578       break;
00579     case Instruction::Or:
00580       if (CstVal->isAllOnesValue()) {        // ... | -1 -> -1
00581         ++NumAnnihil;
00582         return CstVal;
00583       }
00584       // FALLTHROUGH!
00585     case Instruction::Add:
00586     case Instruction::Xor:
00587       if (CstVal->isZero())                  // ... [|^+] 0 -> ...
00588         Ops.pop_back();
00589       break;
00590     }
00591   if (Ops.size() == 1) return Ops[0].Op;
00592 
00593   // Handle destructive annihilation do to identities between elements in the
00594   // argument list here.
00595   switch (Opcode) {
00596   default: break;
00597   case Instruction::And:
00598   case Instruction::Or:
00599   case Instruction::Xor:
00600     // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
00601     // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
00602     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00603       // First, check for X and ~X in the operand list.
00604       assert(i < Ops.size());
00605       if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
00606         Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
00607         unsigned FoundX = FindInOperandList(Ops, i, X);
00608         if (FoundX != i) {
00609           if (Opcode == Instruction::And) {   // ...&X&~X = 0
00610             ++NumAnnihil;
00611             return Constant::getNullValue(X->getType());
00612           } else if (Opcode == Instruction::Or) {   // ...|X|~X = -1
00613             ++NumAnnihil;
00614             return ConstantInt::getAllOnesValue(X->getType());
00615           }
00616         }
00617       }
00618 
00619       // Next, check for duplicate pairs of values, which we assume are next to
00620       // each other, due to our sorting criteria.
00621       assert(i < Ops.size());
00622       if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
00623         if (Opcode == Instruction::And || Opcode == Instruction::Or) {
00624           // Drop duplicate values.
00625           Ops.erase(Ops.begin()+i);
00626           --i; --e;
00627           IterateOptimization = true;
00628           ++NumAnnihil;
00629         } else {
00630           assert(Opcode == Instruction::Xor);
00631           if (e == 2) {
00632             ++NumAnnihil;
00633             return Constant::getNullValue(Ops[0].Op->getType());
00634           }
00635           // ... X^X -> ...
00636           Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
00637           i -= 1; e -= 2;
00638           IterateOptimization = true;
00639           ++NumAnnihil;
00640         }
00641       }
00642     }
00643     break;
00644 
00645   case Instruction::Add:
00646     // Scan the operand lists looking for X and -X pairs.  If we find any, we
00647     // can simplify the expression. X+-X == 0.
00648     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00649       assert(i < Ops.size());
00650       // Check for X and -X in the operand list.
00651       if (BinaryOperator::isNeg(Ops[i].Op)) {
00652         Value *X = BinaryOperator::getNegArgument(Ops[i].Op);
00653         unsigned FoundX = FindInOperandList(Ops, i, X);
00654         if (FoundX != i) {
00655           // Remove X and -X from the operand list.
00656           if (Ops.size() == 2) {
00657             ++NumAnnihil;
00658             return Constant::getNullValue(X->getType());
00659           } else {
00660             Ops.erase(Ops.begin()+i);
00661             if (i < FoundX)
00662               --FoundX;
00663             else
00664               --i;   // Need to back up an extra one.
00665             Ops.erase(Ops.begin()+FoundX);
00666             IterateOptimization = true;
00667             ++NumAnnihil;
00668             --i;     // Revisit element.
00669             e -= 2;  // Removed two elements.
00670           }
00671         }
00672       }
00673     }
00674     
00675 
00676     // Scan the operand list, checking to see if there are any common factors
00677     // between operands.  Consider something like A*A+A*B*C+D.  We would like to
00678     // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
00679     // To efficiently find this, we count the number of times a factor occurs
00680     // for any ADD operands that are MULs.
00681     std::map<Value*, unsigned> FactorOccurrences;
00682     unsigned MaxOcc = 0;
00683     Value *MaxOccVal = 0;
00684     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00685       if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op)) {
00686         if (BOp->getOpcode() == Instruction::Mul && BOp->use_empty()) {
00687           // Compute all of the factors of this added value.
00688           std::vector<Value*> Factors;
00689           FindSingleUseMultiplyFactors(BOp, Factors);
00690           assert(Factors.size() > 1 && "Bad linearize!");
00691 
00692           // Add one to FactorOccurrences for each unique factor in this op.
00693           if (Factors.size() == 2) {
00694             unsigned Occ = ++FactorOccurrences[Factors[0]];
00695             if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[0]; }
00696             if (Factors[0] != Factors[1]) {   // Don't double count A*A.
00697               Occ = ++FactorOccurrences[Factors[1]];
00698               if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[1]; }
00699             }
00700           } else {
00701             std::set<Value*> Duplicates;
00702             for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
00703               if (Duplicates.insert(Factors[i]).second) {
00704                 unsigned Occ = ++FactorOccurrences[Factors[i]];
00705                 if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factors[i]; }
00706               }
00707             }
00708           }
00709         }
00710       }
00711     }
00712 
00713     // If any factor occurred more than one time, we can pull it out.
00714     if (MaxOcc > 1) {
00715       DOUT << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << "\n";
00716       
00717       // Create a new instruction that uses the MaxOccVal twice.  If we don't do
00718       // this, we could otherwise run into situations where removing a factor
00719       // from an expression will drop a use of maxocc, and this can cause 
00720       // RemoveFactorFromExpression on successive values to behave differently.
00721       Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
00722       std::vector<Value*> NewMulOps;
00723       for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00724         if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
00725           NewMulOps.push_back(V);
00726           Ops.erase(Ops.begin()+i);
00727           --i; --e;
00728         }
00729       }
00730       
00731       // No need for extra uses anymore.
00732       delete DummyInst;
00733 
00734       unsigned NumAddedValues = NewMulOps.size();
00735       Value *V = EmitAddTreeOfValues(I, NewMulOps);
00736       Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
00737 
00738       // Now that we have inserted V and its sole use, optimize it. This allows
00739       // us to handle cases that require multiple factoring steps, such as this:
00740       // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
00741       if (NumAddedValues > 1)
00742         ReassociateExpression(cast<BinaryOperator>(V));
00743       
00744       ++NumFactor;
00745       
00746       if (Ops.empty())
00747         return V2;
00748 
00749       // Add the new value to the list of things being added.
00750       Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
00751       
00752       // Rewrite the tree so that there is now a use of V.
00753       RewriteExprTree(I, Ops);
00754       return OptimizeExpression(I, Ops);
00755     }
00756     break;
00757   //case Instruction::Mul:
00758   }
00759 
00760   if (IterateOptimization)
00761     return OptimizeExpression(I, Ops);
00762   return 0;
00763 }
00764 
00765 
00766 /// ReassociateBB - Inspect all of the instructions in this basic block,
00767 /// reassociating them as we go.
00768 void Reassociate::ReassociateBB(BasicBlock *BB) {
00769   for (BasicBlock::iterator BBI = BB->begin(); BBI != BB->end(); ) {
00770     Instruction *BI = BBI++;
00771     if (BI->getOpcode() == Instruction::Shl &&
00772         isa<ConstantInt>(BI->getOperand(1)))
00773       if (Instruction *NI = ConvertShiftToMul(BI)) {
00774         MadeChange = true;
00775         BI = NI;
00776       }
00777 
00778     // Reject cases where it is pointless to do this.
00779     if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint() || 
00780         isa<VectorType>(BI->getType()))
00781       continue;  // Floating point ops are not associative.
00782 
00783     // If this is a subtract instruction which is not already in negate form,
00784     // see if we can convert it to X+-Y.
00785     if (BI->getOpcode() == Instruction::Sub) {
00786       if (ShouldBreakUpSubtract(BI)) {
00787         BI = BreakUpSubtract(BI);
00788         MadeChange = true;
00789       } else if (BinaryOperator::isNeg(BI)) {
00790         // Otherwise, this is a negation.  See if the operand is a multiply tree
00791         // and if this is not an inner node of a multiply tree.
00792         if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
00793             (!BI->hasOneUse() ||
00794              !isReassociableOp(BI->use_back(), Instruction::Mul))) {
00795           BI = LowerNegateToMultiply(BI);
00796           MadeChange = true;
00797         }
00798       }
00799     }
00800 
00801     // If this instruction is a commutative binary operator, process it.
00802     if (!BI->isAssociative()) continue;
00803     BinaryOperator *I = cast<BinaryOperator>(BI);
00804 
00805     // If this is an interior node of a reassociable tree, ignore it until we
00806     // get to the root of the tree, to avoid N^2 analysis.
00807     if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
00808       continue;
00809 
00810     // If this is an add tree that is used by a sub instruction, ignore it 
00811     // until we process the subtract.
00812     if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
00813         cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
00814       continue;
00815 
00816     ReassociateExpression(I);
00817   }
00818 }
00819 
00820 void Reassociate::ReassociateExpression(BinaryOperator *I) {
00821   
00822   // First, walk the expression tree, linearizing the tree, collecting
00823   std::vector<ValueEntry> Ops;
00824   LinearizeExprTree(I, Ops);
00825   
00826   DOUT << "RAIn:\t"; DEBUG(PrintOps(I, Ops)); DOUT << "\n";
00827   
00828   // Now that we have linearized the tree to a list and have gathered all of
00829   // the operands and their ranks, sort the operands by their rank.  Use a
00830   // stable_sort so that values with equal ranks will have their relative
00831   // positions maintained (and so the compiler is deterministic).  Note that
00832   // this sorts so that the highest ranking values end up at the beginning of
00833   // the vector.
00834   std::stable_sort(Ops.begin(), Ops.end());
00835   
00836   // OptimizeExpression - Now that we have the expression tree in a convenient
00837   // sorted form, optimize it globally if possible.
00838   if (Value *V = OptimizeExpression(I, Ops)) {
00839     // This expression tree simplified to something that isn't a tree,
00840     // eliminate it.
00841     DOUT << "Reassoc to scalar: " << *V << "\n";
00842     I->replaceAllUsesWith(V);
00843     RemoveDeadBinaryOp(I);
00844     return;
00845   }
00846   
00847   // We want to sink immediates as deeply as possible except in the case where
00848   // this is a multiply tree used only by an add, and the immediate is a -1.
00849   // In this case we reassociate to put the negation on the outside so that we
00850   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
00851   if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
00852       cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
00853       isa<ConstantInt>(Ops.back().Op) &&
00854       cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
00855     Ops.insert(Ops.begin(), Ops.back());
00856     Ops.pop_back();
00857   }
00858   
00859   DOUT << "RAOut:\t"; DEBUG(PrintOps(I, Ops)); DOUT << "\n";
00860   
00861   if (Ops.size() == 1) {
00862     // This expression tree simplified to something that isn't a tree,
00863     // eliminate it.
00864     I->replaceAllUsesWith(Ops[0].Op);
00865     RemoveDeadBinaryOp(I);
00866   } else {
00867     // Now that we ordered and optimized the expressions, splat them back into
00868     // the expression tree, removing any unneeded nodes.
00869     RewriteExprTree(I, Ops);
00870   }
00871 }
00872 
00873 
00874 bool Reassociate::runOnFunction(Function &F) {
00875   // Recalculate the rank map for F
00876   BuildRankMap(F);
00877 
00878   MadeChange = false;
00879   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
00880     ReassociateBB(FI);
00881 
00882   // We are done with the rank map...
00883   RankMap.clear();
00884   ValueRankMap.clear();
00885   return MadeChange;
00886 }
00887 



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.