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, etc.
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/ADT/DenseMap.h"
00026 #include "llvm/ADT/PostOrderIterator.h"
00027 #include "llvm/ADT/STLExtras.h"
00028 #include "llvm/ADT/SetVector.h"
00029 #include "llvm/ADT/Statistic.h"
00030 #include "llvm/Assembly/Writer.h"
00031 #include "llvm/IR/Constants.h"
00032 #include "llvm/IR/DerivedTypes.h"
00033 #include "llvm/IR/Function.h"
00034 #include "llvm/IR/IRBuilder.h"
00035 #include "llvm/IR/Instructions.h"
00036 #include "llvm/IR/IntrinsicInst.h"
00037 #include "llvm/Pass.h"
00038 #include "llvm/Support/CFG.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/ValueHandle.h"
00041 #include "llvm/Support/raw_ostream.h"
00042 #include "llvm/Transforms/Utils/Local.h"
00043 #include <algorithm>
00044 using namespace llvm;
00045 
00046 STATISTIC(NumChanged, "Number of insts reassociated");
00047 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
00048 STATISTIC(NumFactor , "Number of multiplies factored");
00049 
00050 namespace {
00051   struct ValueEntry {
00052     unsigned Rank;
00053     Value *Op;
00054     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
00055   };
00056   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
00057     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
00058   }
00059 }
00060 
00061 #ifndef NDEBUG
00062 /// PrintOps - Print out the expression identified in the Ops list.
00063 ///
00064 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
00065   Module *M = I->getParent()->getParent()->getParent();
00066   dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
00067        << *Ops[0].Op->getType() << '\t';
00068   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00069     dbgs() << "[ ";
00070     WriteAsOperand(dbgs(), Ops[i].Op, false, M);
00071     dbgs() << ", #" << Ops[i].Rank << "] ";
00072   }
00073 }
00074 #endif
00075 
00076 namespace {
00077   /// \brief Utility class representing a base and exponent pair which form one
00078   /// factor of some product.
00079   struct Factor {
00080     Value *Base;
00081     unsigned Power;
00082 
00083     Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
00084 
00085     /// \brief Sort factors by their Base.
00086     struct BaseSorter {
00087       bool operator()(const Factor &LHS, const Factor &RHS) {
00088         return LHS.Base < RHS.Base;
00089       }
00090     };
00091 
00092     /// \brief Compare factors for equal bases.
00093     struct BaseEqual {
00094       bool operator()(const Factor &LHS, const Factor &RHS) {
00095         return LHS.Base == RHS.Base;
00096       }
00097     };
00098 
00099     /// \brief Sort factors in descending order by their power.
00100     struct PowerDescendingSorter {
00101       bool operator()(const Factor &LHS, const Factor &RHS) {
00102         return LHS.Power > RHS.Power;
00103       }
00104     };
00105 
00106     /// \brief Compare factors for equal powers.
00107     struct PowerEqual {
00108       bool operator()(const Factor &LHS, const Factor &RHS) {
00109         return LHS.Power == RHS.Power;
00110       }
00111     };
00112   };
00113   
00114   /// Utility class representing a non-constant Xor-operand. We classify
00115   /// non-constant Xor-Operands into two categories:
00116   ///  C1) The operand is in the form "X & C", where C is a constant and C != ~0
00117   ///  C2)
00118   ///    C2.1) The operand is in the form of "X | C", where C is a non-zero
00119   ///          constant.
00120   ///    C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
00121   ///          operand as "E | 0"
00122   class XorOpnd {
00123   public:
00124     XorOpnd(Value *V);
00125     const XorOpnd &operator=(const XorOpnd &That);
00126 
00127     bool isInvalid() const { return SymbolicPart == 0; }
00128     bool isOrExpr() const { return isOr; }
00129     Value *getValue() const { return OrigVal; }
00130     Value *getSymbolicPart() const { return SymbolicPart; }
00131     unsigned getSymbolicRank() const { return SymbolicRank; }
00132     const APInt &getConstPart() const { return ConstPart; }
00133 
00134     void Invalidate() { SymbolicPart = OrigVal = 0; }
00135     void setSymbolicRank(unsigned R) { SymbolicRank = R; }
00136 
00137     // Sort the XorOpnd-Pointer in ascending order of symbolic-value-rank.
00138     // The purpose is twofold:
00139     // 1) Cluster together the operands sharing the same symbolic-value.
00140     // 2) Operand having smaller symbolic-value-rank is permuted earlier, which 
00141     //   could potentially shorten crital path, and expose more loop-invariants.
00142     //   Note that values' rank are basically defined in RPO order (FIXME). 
00143     //   So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier 
00144     //   than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
00145     //   "z" in the order of X-Y-Z is better than any other orders.
00146     struct PtrSortFunctor {
00147       bool operator()(XorOpnd * const &LHS, XorOpnd * const &RHS) {
00148         return LHS->getSymbolicRank() < RHS->getSymbolicRank();
00149       }
00150     };
00151   private:
00152     Value *OrigVal;
00153     Value *SymbolicPart;
00154     APInt ConstPart;
00155     unsigned SymbolicRank;
00156     bool isOr;
00157   };
00158 }
00159 
00160 namespace {
00161   class Reassociate : public FunctionPass {
00162     DenseMap<BasicBlock*, unsigned> RankMap;
00163     DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
00164     SetVector<AssertingVH<Instruction> > RedoInsts;
00165     bool MadeChange;
00166   public:
00167     static char ID; // Pass identification, replacement for typeid
00168     Reassociate() : FunctionPass(ID) {
00169       initializeReassociatePass(*PassRegistry::getPassRegistry());
00170     }
00171 
00172     bool runOnFunction(Function &F);
00173 
00174     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00175       AU.setPreservesCFG();
00176     }
00177   private:
00178     void BuildRankMap(Function &F);
00179     unsigned getRank(Value *V);
00180     void ReassociateExpression(BinaryOperator *I);
00181     void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
00182     Value *OptimizeExpression(BinaryOperator *I,
00183                               SmallVectorImpl<ValueEntry> &Ops);
00184     Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
00185     Value *OptimizeXor(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
00186     bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, APInt &ConstOpnd,
00187                         Value *&Res);
00188     bool CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
00189                         APInt &ConstOpnd, Value *&Res);
00190     bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
00191                                 SmallVectorImpl<Factor> &Factors);
00192     Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
00193                                    SmallVectorImpl<Factor> &Factors);
00194     Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
00195     Value *RemoveFactorFromExpression(Value *V, Value *Factor);
00196     void EraseInst(Instruction *I);
00197     void OptimizeInst(Instruction *I);
00198   };
00199 }
00200 
00201 XorOpnd::XorOpnd(Value *V) {
00202   assert(!isa<ConstantInt>(V) && "No ConstantInt");
00203   OrigVal = V;
00204   Instruction *I = dyn_cast<Instruction>(V);
00205   SymbolicRank = 0;
00206 
00207   if (I && (I->getOpcode() == Instruction::Or ||
00208             I->getOpcode() == Instruction::And)) {
00209     Value *V0 = I->getOperand(0);
00210     Value *V1 = I->getOperand(1);
00211     if (isa<ConstantInt>(V0))
00212       std::swap(V0, V1);
00213 
00214     if (ConstantInt *C = dyn_cast<ConstantInt>(V1)) {
00215       ConstPart = C->getValue();
00216       SymbolicPart = V0;
00217       isOr = (I->getOpcode() == Instruction::Or);
00218       return;
00219     }
00220   }
00221 
00222   // view the operand as "V | 0"
00223   SymbolicPart = V;
00224   ConstPart = APInt::getNullValue(V->getType()->getIntegerBitWidth());
00225   isOr = true;
00226 }
00227 
00228 const XorOpnd &XorOpnd::operator=(const XorOpnd &That) {
00229   OrigVal = That.OrigVal;
00230   SymbolicPart = That.SymbolicPart;
00231   ConstPart = That.ConstPart;
00232   SymbolicRank = That.SymbolicRank;
00233   isOr = That.isOr;
00234   return *this;
00235 }
00236 
00237 char Reassociate::ID = 0;
00238 INITIALIZE_PASS(Reassociate, "reassociate",
00239                 "Reassociate expressions", false, false)
00240 
00241 // Public interface to the Reassociate pass
00242 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
00243 
00244 /// isReassociableOp - Return true if V is an instruction of the specified
00245 /// opcode and if it only has one use.
00246 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
00247   if (V->hasOneUse() && isa<Instruction>(V) &&
00248       cast<Instruction>(V)->getOpcode() == Opcode)
00249     return cast<BinaryOperator>(V);
00250   return 0;
00251 }
00252 
00253 static bool isUnmovableInstruction(Instruction *I) {
00254   if (I->getOpcode() == Instruction::PHI ||
00255       I->getOpcode() == Instruction::LandingPad ||
00256       I->getOpcode() == Instruction::Alloca ||
00257       I->getOpcode() == Instruction::Load ||
00258       I->getOpcode() == Instruction::Invoke ||
00259       (I->getOpcode() == Instruction::Call &&
00260        !isa<DbgInfoIntrinsic>(I)) ||
00261       I->getOpcode() == Instruction::UDiv ||
00262       I->getOpcode() == Instruction::SDiv ||
00263       I->getOpcode() == Instruction::FDiv ||
00264       I->getOpcode() == Instruction::URem ||
00265       I->getOpcode() == Instruction::SRem ||
00266       I->getOpcode() == Instruction::FRem)
00267     return true;
00268   return false;
00269 }
00270 
00271 void Reassociate::BuildRankMap(Function &F) {
00272   unsigned i = 2;
00273 
00274   // Assign distinct ranks to function arguments
00275   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
00276     ValueRankMap[&*I] = ++i;
00277 
00278   ReversePostOrderTraversal<Function*> RPOT(&F);
00279   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
00280          E = RPOT.end(); I != E; ++I) {
00281     BasicBlock *BB = *I;
00282     unsigned BBRank = RankMap[BB] = ++i << 16;
00283 
00284     // Walk the basic block, adding precomputed ranks for any instructions that
00285     // we cannot move.  This ensures that the ranks for these instructions are
00286     // all different in the block.
00287     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00288       if (isUnmovableInstruction(I))
00289         ValueRankMap[&*I] = ++BBRank;
00290   }
00291 }
00292 
00293 unsigned Reassociate::getRank(Value *V) {
00294   Instruction *I = dyn_cast<Instruction>(V);
00295   if (I == 0) {
00296     if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
00297     return 0;  // Otherwise it's a global or constant, rank 0.
00298   }
00299 
00300   if (unsigned Rank = ValueRankMap[I])
00301     return Rank;    // Rank already known?
00302 
00303   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
00304   // we can reassociate expressions for code motion!  Since we do not recurse
00305   // for PHI nodes, we cannot have infinite recursion here, because there
00306   // cannot be loops in the value graph that do not go through PHI nodes.
00307   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
00308   for (unsigned i = 0, e = I->getNumOperands();
00309        i != e && Rank != MaxRank; ++i)
00310     Rank = std::max(Rank, getRank(I->getOperand(i)));
00311 
00312   // If this is a not or neg instruction, do not count it for rank.  This
00313   // assures us that X and ~X will have the same rank.
00314   if (!I->getType()->isIntegerTy() ||
00315       (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
00316     ++Rank;
00317 
00318   //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
00319   //     << Rank << "\n");
00320 
00321   return ValueRankMap[I] = Rank;
00322 }
00323 
00324 /// LowerNegateToMultiply - Replace 0-X with X*-1.
00325 ///
00326 static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
00327   Constant *Cst = Constant::getAllOnesValue(Neg->getType());
00328 
00329   BinaryOperator *Res =
00330     BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
00331   Neg->setOperand(1, Constant::getNullValue(Neg->getType())); // Drop use of op.
00332   Res->takeName(Neg);
00333   Neg->replaceAllUsesWith(Res);
00334   Res->setDebugLoc(Neg->getDebugLoc());
00335   return Res;
00336 }
00337 
00338 /// CarmichaelShift - Returns k such that lambda(2^Bitwidth) = 2^k, where lambda
00339 /// is the Carmichael function. This means that x^(2^k) === 1 mod 2^Bitwidth for
00340 /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
00341 /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
00342 /// even x in Bitwidth-bit arithmetic.
00343 static unsigned CarmichaelShift(unsigned Bitwidth) {
00344   if (Bitwidth < 3)
00345     return Bitwidth - 1;
00346   return Bitwidth - 2;
00347 }
00348 
00349 /// IncorporateWeight - Add the extra weight 'RHS' to the existing weight 'LHS',
00350 /// reducing the combined weight using any special properties of the operation.
00351 /// The existing weight LHS represents the computation X op X op ... op X where
00352 /// X occurs LHS times.  The combined weight represents  X op X op ... op X with
00353 /// X occurring LHS + RHS times.  If op is "Xor" for example then the combined
00354 /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
00355 /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
00356 static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
00357   // If we were working with infinite precision arithmetic then the combined
00358   // weight would be LHS + RHS.  But we are using finite precision arithmetic,
00359   // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
00360   // for nilpotent operations and addition, but not for idempotent operations
00361   // and multiplication), so it is important to correctly reduce the combined
00362   // weight back into range if wrapping would be wrong.
00363 
00364   // If RHS is zero then the weight didn't change.
00365   if (RHS.isMinValue())
00366     return;
00367   // If LHS is zero then the combined weight is RHS.
00368   if (LHS.isMinValue()) {
00369     LHS = RHS;
00370     return;
00371   }
00372   // From this point on we know that neither LHS nor RHS is zero.
00373 
00374   if (Instruction::isIdempotent(Opcode)) {
00375     // Idempotent means X op X === X, so any non-zero weight is equivalent to a
00376     // weight of 1.  Keeping weights at zero or one also means that wrapping is
00377     // not a problem.
00378     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
00379     return; // Return a weight of 1.
00380   }
00381   if (Instruction::isNilpotent(Opcode)) {
00382     // Nilpotent means X op X === 0, so reduce weights modulo 2.
00383     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
00384     LHS = 0; // 1 + 1 === 0 modulo 2.
00385     return;
00386   }
00387   if (Opcode == Instruction::Add) {
00388     // TODO: Reduce the weight by exploiting nsw/nuw?
00389     LHS += RHS;
00390     return;
00391   }
00392 
00393   assert(Opcode == Instruction::Mul && "Unknown associative operation!");
00394   unsigned Bitwidth = LHS.getBitWidth();
00395   // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
00396   // can be replaced with W-CM.  That's because x^W=x^(W-CM) for every Bitwidth
00397   // bit number x, since either x is odd in which case x^CM = 1, or x is even in
00398   // which case both x^W and x^(W - CM) are zero.  By subtracting off multiples
00399   // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
00400   // which by a happy accident means that they can always be represented using
00401   // Bitwidth bits.
00402   // TODO: Reduce the weight by exploiting nsw/nuw?  (Could do much better than
00403   // the Carmichael number).
00404   if (Bitwidth > 3) {
00405     /// CM - The value of Carmichael's lambda function.
00406     APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
00407     // Any weight W >= Threshold can be replaced with W - CM.
00408     APInt Threshold = CM + Bitwidth;
00409     assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
00410     // For Bitwidth 4 or more the following sum does not overflow.
00411     LHS += RHS;
00412     while (LHS.uge(Threshold))
00413       LHS -= CM;
00414   } else {
00415     // To avoid problems with overflow do everything the same as above but using
00416     // a larger type.
00417     unsigned CM = 1U << CarmichaelShift(Bitwidth);
00418     unsigned Threshold = CM + Bitwidth;
00419     assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
00420            "Weights not reduced!");
00421     unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
00422     while (Total >= Threshold)
00423       Total -= CM;
00424     LHS = Total;
00425   }
00426 }
00427 
00428 typedef std::pair<Value*, APInt> RepeatedValue;
00429 
00430 /// LinearizeExprTree - Given an associative binary expression, return the leaf
00431 /// nodes in Ops along with their weights (how many times the leaf occurs).  The
00432 /// original expression is the same as
00433 ///   (Ops[0].first op Ops[0].first op ... Ops[0].first)  <- Ops[0].second times
00434 /// op
00435 ///   (Ops[1].first op Ops[1].first op ... Ops[1].first)  <- Ops[1].second times
00436 /// op
00437 ///   ...
00438 /// op
00439 ///   (Ops[N].first op Ops[N].first op ... Ops[N].first)  <- Ops[N].second times
00440 ///
00441 /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
00442 ///
00443 /// This routine may modify the function, in which case it returns 'true'.  The
00444 /// changes it makes may well be destructive, changing the value computed by 'I'
00445 /// to something completely different.  Thus if the routine returns 'true' then
00446 /// you MUST either replace I with a new expression computed from the Ops array,
00447 /// or use RewriteExprTree to put the values back in.
00448 ///
00449 /// A leaf node is either not a binary operation of the same kind as the root
00450 /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
00451 /// opcode), or is the same kind of binary operator but has a use which either
00452 /// does not belong to the expression, or does belong to the expression but is
00453 /// a leaf node.  Every leaf node has at least one use that is a non-leaf node
00454 /// of the expression, while for non-leaf nodes (except for the root 'I') every
00455 /// use is a non-leaf node of the expression.
00456 ///
00457 /// For example:
00458 ///           expression graph        node names
00459 ///
00460 ///                     +        |        I
00461 ///                    / \       |
00462 ///                   +   +      |      A,  B
00463 ///                  / \ / \     |
00464 ///                 *   +   *    |    C,  D,  E
00465 ///                / \ / \ / \   |
00466 ///                   +   *      |      F,  G
00467 ///
00468 /// The leaf nodes are C, E, F and G.  The Ops array will contain (maybe not in
00469 /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
00470 ///
00471 /// The expression is maximal: if some instruction is a binary operator of the
00472 /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
00473 /// then the instruction also belongs to the expression, is not a leaf node of
00474 /// it, and its operands also belong to the expression (but may be leaf nodes).
00475 ///
00476 /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
00477 /// order to ensure that every non-root node in the expression has *exactly one*
00478 /// use by a non-leaf node of the expression.  This destruction means that the
00479 /// caller MUST either replace 'I' with a new expression or use something like
00480 /// RewriteExprTree to put the values back in if the routine indicates that it
00481 /// made a change by returning 'true'.
00482 ///
00483 /// In the above example either the right operand of A or the left operand of B
00484 /// will be replaced by undef.  If it is B's operand then this gives:
00485 ///
00486 ///                     +        |        I
00487 ///                    / \       |
00488 ///                   +   +      |      A,  B - operand of B replaced with undef
00489 ///                  / \   \     |
00490 ///                 *   +   *    |    C,  D,  E
00491 ///                / \ / \ / \   |
00492 ///                   +   *      |      F,  G
00493 ///
00494 /// Note that such undef operands can only be reached by passing through 'I'.
00495 /// For example, if you visit operands recursively starting from a leaf node
00496 /// then you will never see such an undef operand unless you get back to 'I',
00497 /// which requires passing through a phi node.
00498 ///
00499 /// Note that this routine may also mutate binary operators of the wrong type
00500 /// that have all uses inside the expression (i.e. only used by non-leaf nodes
00501 /// of the expression) if it can turn them into binary operators of the right
00502 /// type and thus make the expression bigger.
00503 
00504 static bool LinearizeExprTree(BinaryOperator *I,
00505                               SmallVectorImpl<RepeatedValue> &Ops) {
00506   DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
00507   unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
00508   unsigned Opcode = I->getOpcode();
00509   assert(Instruction::isAssociative(Opcode) &&
00510          Instruction::isCommutative(Opcode) &&
00511          "Expected an associative and commutative operation!");
00512 
00513   // Visit all operands of the expression, keeping track of their weight (the
00514   // number of paths from the expression root to the operand, or if you like
00515   // the number of times that operand occurs in the linearized expression).
00516   // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
00517   // while A has weight two.
00518 
00519   // Worklist of non-leaf nodes (their operands are in the expression too) along
00520   // with their weights, representing a certain number of paths to the operator.
00521   // If an operator occurs in the worklist multiple times then we found multiple
00522   // ways to get to it.
00523   SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
00524   Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
00525   bool MadeChange = false;
00526 
00527   // Leaves of the expression are values that either aren't the right kind of
00528   // operation (eg: a constant, or a multiply in an add tree), or are, but have
00529   // some uses that are not inside the expression.  For example, in I = X + X,
00530   // X = A + B, the value X has two uses (by I) that are in the expression.  If
00531   // X has any other uses, for example in a return instruction, then we consider
00532   // X to be a leaf, and won't analyze it further.  When we first visit a value,
00533   // if it has more than one use then at first we conservatively consider it to
00534   // be a leaf.  Later, as the expression is explored, we may discover some more
00535   // uses of the value from inside the expression.  If all uses turn out to be
00536   // from within the expression (and the value is a binary operator of the right
00537   // kind) then the value is no longer considered to be a leaf, and its operands
00538   // are explored.
00539 
00540   // Leaves - Keeps track of the set of putative leaves as well as the number of
00541   // paths to each leaf seen so far.
00542   typedef DenseMap<Value*, APInt> LeafMap;
00543   LeafMap Leaves; // Leaf -> Total weight so far.
00544   SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
00545 
00546 #ifndef NDEBUG
00547   SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
00548 #endif
00549   while (!Worklist.empty()) {
00550     std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
00551     I = P.first; // We examine the operands of this binary operator.
00552 
00553     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
00554       Value *Op = I->getOperand(OpIdx);
00555       APInt Weight = P.second; // Number of paths to this operand.
00556       DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
00557       assert(!Op->use_empty() && "No uses, so how did we get to it?!");
00558 
00559       // If this is a binary operation of the right kind with only one use then
00560       // add its operands to the expression.
00561       if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
00562         assert(Visited.insert(Op) && "Not first visit!");
00563         DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
00564         Worklist.push_back(std::make_pair(BO, Weight));
00565         continue;
00566       }
00567 
00568       // Appears to be a leaf.  Is the operand already in the set of leaves?
00569       LeafMap::iterator It = Leaves.find(Op);
00570       if (It == Leaves.end()) {
00571         // Not in the leaf map.  Must be the first time we saw this operand.
00572         assert(Visited.insert(Op) && "Not first visit!");
00573         if (!Op->hasOneUse()) {
00574           // This value has uses not accounted for by the expression, so it is
00575           // not safe to modify.  Mark it as being a leaf.
00576           DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
00577           LeafOrder.push_back(Op);
00578           Leaves[Op] = Weight;
00579           continue;
00580         }
00581         // No uses outside the expression, try morphing it.
00582       } else if (It != Leaves.end()) {
00583         // Already in the leaf map.
00584         assert(Visited.count(Op) && "In leaf map but not visited!");
00585 
00586         // Update the number of paths to the leaf.
00587         IncorporateWeight(It->second, Weight, Opcode);
00588 
00589 #if 0   // TODO: Re-enable once PR13021 is fixed.
00590         // The leaf already has one use from inside the expression.  As we want
00591         // exactly one such use, drop this new use of the leaf.
00592         assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
00593         I->setOperand(OpIdx, UndefValue::get(I->getType()));
00594         MadeChange = true;
00595 
00596         // If the leaf is a binary operation of the right kind and we now see
00597         // that its multiple original uses were in fact all by nodes belonging
00598         // to the expression, then no longer consider it to be a leaf and add
00599         // its operands to the expression.
00600         if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
00601           DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
00602           Worklist.push_back(std::make_pair(BO, It->second));
00603           Leaves.erase(It);
00604           continue;
00605         }
00606 #endif
00607 
00608         // If we still have uses that are not accounted for by the expression
00609         // then it is not safe to modify the value.
00610         if (!Op->hasOneUse())
00611           continue;
00612 
00613         // No uses outside the expression, try morphing it.
00614         Weight = It->second;
00615         Leaves.erase(It); // Since the value may be morphed below.
00616       }
00617 
00618       // At this point we have a value which, first of all, is not a binary
00619       // expression of the right kind, and secondly, is only used inside the
00620       // expression.  This means that it can safely be modified.  See if we
00621       // can usefully morph it into an expression of the right kind.
00622       assert((!isa<Instruction>(Op) ||
00623               cast<Instruction>(Op)->getOpcode() != Opcode) &&
00624              "Should have been handled above!");
00625       assert(Op->hasOneUse() && "Has uses outside the expression tree!");
00626 
00627       // If this is a multiply expression, turn any internal negations into
00628       // multiplies by -1 so they can be reassociated.
00629       BinaryOperator *BO = dyn_cast<BinaryOperator>(Op);
00630       if (Opcode == Instruction::Mul && BO && BinaryOperator::isNeg(BO)) {
00631         DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
00632         BO = LowerNegateToMultiply(BO);
00633         DEBUG(dbgs() << *BO << 'n');
00634         Worklist.push_back(std::make_pair(BO, Weight));
00635         MadeChange = true;
00636         continue;
00637       }
00638 
00639       // Failed to morph into an expression of the right type.  This really is
00640       // a leaf.
00641       DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
00642       assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
00643       LeafOrder.push_back(Op);
00644       Leaves[Op] = Weight;
00645     }
00646   }
00647 
00648   // The leaves, repeated according to their weights, represent the linearized
00649   // form of the expression.
00650   for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
00651     Value *V = LeafOrder[i];
00652     LeafMap::iterator It = Leaves.find(V);
00653     if (It == Leaves.end())
00654       // Node initially thought to be a leaf wasn't.
00655       continue;
00656     assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
00657     APInt Weight = It->second;
00658     if (Weight.isMinValue())
00659       // Leaf already output or weight reduction eliminated it.
00660       continue;
00661     // Ensure the leaf is only output once.
00662     It->second = 0;
00663     Ops.push_back(std::make_pair(V, Weight));
00664   }
00665 
00666   // For nilpotent operations or addition there may be no operands, for example
00667   // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
00668   // in both cases the weight reduces to 0 causing the value to be skipped.
00669   if (Ops.empty()) {
00670     Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
00671     assert(Identity && "Associative operation without identity!");
00672     Ops.push_back(std::make_pair(Identity, APInt(Bitwidth, 1)));
00673   }
00674 
00675   return MadeChange;
00676 }
00677 
00678 // RewriteExprTree - Now that the operands for this expression tree are
00679 // linearized and optimized, emit them in-order.
00680 void Reassociate::RewriteExprTree(BinaryOperator *I,
00681                                   SmallVectorImpl<ValueEntry> &Ops) {
00682   assert(Ops.size() > 1 && "Single values should be used directly!");
00683 
00684   // Since our optimizations should never increase the number of operations, the
00685   // new expression can usually be written reusing the existing binary operators
00686   // from the original expression tree, without creating any new instructions,
00687   // though the rewritten expression may have a completely different topology.
00688   // We take care to not change anything if the new expression will be the same
00689   // as the original.  If more than trivial changes (like commuting operands)
00690   // were made then we are obliged to clear out any optional subclass data like
00691   // nsw flags.
00692 
00693   /// NodesToRewrite - Nodes from the original expression available for writing
00694   /// the new expression into.
00695   SmallVector<BinaryOperator*, 8> NodesToRewrite;
00696   unsigned Opcode = I->getOpcode();
00697   BinaryOperator *Op = I;
00698 
00699   /// NotRewritable - The operands being written will be the leaves of the new
00700   /// expression and must not be used as inner nodes (via NodesToRewrite) by
00701   /// mistake.  Inner nodes are always reassociable, and usually leaves are not
00702   /// (if they were they would have been incorporated into the expression and so
00703   /// would not be leaves), so most of the time there is no danger of this.  But
00704   /// in rare cases a leaf may become reassociable if an optimization kills uses
00705   /// of it, or it may momentarily become reassociable during rewriting (below)
00706   /// due it being removed as an operand of one of its uses.  Ensure that misuse
00707   /// of leaf nodes as inner nodes cannot occur by remembering all of the future
00708   /// leaves and refusing to reuse any of them as inner nodes.
00709   SmallPtrSet<Value*, 8> NotRewritable;
00710   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00711     NotRewritable.insert(Ops[i].Op);
00712 
00713   // ExpressionChanged - Non-null if the rewritten expression differs from the
00714   // original in some non-trivial way, requiring the clearing of optional flags.
00715   // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
00716   BinaryOperator *ExpressionChanged = 0;
00717   for (unsigned i = 0; ; ++i) {
00718     // The last operation (which comes earliest in the IR) is special as both
00719     // operands will come from Ops, rather than just one with the other being
00720     // a subexpression.
00721     if (i+2 == Ops.size()) {
00722       Value *NewLHS = Ops[i].Op;
00723       Value *NewRHS = Ops[i+1].Op;
00724       Value *OldLHS = Op->getOperand(0);
00725       Value *OldRHS = Op->getOperand(1);
00726 
00727       if (NewLHS == OldLHS && NewRHS == OldRHS)
00728         // Nothing changed, leave it alone.
00729         break;
00730 
00731       if (NewLHS == OldRHS && NewRHS == OldLHS) {
00732         // The order of the operands was reversed.  Swap them.
00733         DEBUG(dbgs() << "RA: " << *Op << '\n');
00734         Op->swapOperands();
00735         DEBUG(dbgs() << "TO: " << *Op << '\n');
00736         MadeChange = true;
00737         ++NumChanged;
00738         break;
00739       }
00740 
00741       // The new operation differs non-trivially from the original. Overwrite
00742       // the old operands with the new ones.
00743       DEBUG(dbgs() << "RA: " << *Op << '\n');
00744       if (NewLHS != OldLHS) {
00745         BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
00746         if (BO && !NotRewritable.count(BO))
00747           NodesToRewrite.push_back(BO);
00748         Op->setOperand(0, NewLHS);
00749       }
00750       if (NewRHS != OldRHS) {
00751         BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
00752         if (BO && !NotRewritable.count(BO))
00753           NodesToRewrite.push_back(BO);
00754         Op->setOperand(1, NewRHS);
00755       }
00756       DEBUG(dbgs() << "TO: " << *Op << '\n');
00757 
00758       ExpressionChanged = Op;
00759       MadeChange = true;
00760       ++NumChanged;
00761 
00762       break;
00763     }
00764 
00765     // Not the last operation.  The left-hand side will be a sub-expression
00766     // while the right-hand side will be the current element of Ops.
00767     Value *NewRHS = Ops[i].Op;
00768     if (NewRHS != Op->getOperand(1)) {
00769       DEBUG(dbgs() << "RA: " << *Op << '\n');
00770       if (NewRHS == Op->getOperand(0)) {
00771         // The new right-hand side was already present as the left operand.  If
00772         // we are lucky then swapping the operands will sort out both of them.
00773         Op->swapOperands();
00774       } else {
00775         // Overwrite with the new right-hand side.
00776         BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
00777         if (BO && !NotRewritable.count(BO))
00778           NodesToRewrite.push_back(BO);
00779         Op->setOperand(1, NewRHS);
00780         ExpressionChanged = Op;
00781       }
00782       DEBUG(dbgs() << "TO: " << *Op << '\n');
00783       MadeChange = true;
00784       ++NumChanged;
00785     }
00786 
00787     // Now deal with the left-hand side.  If this is already an operation node
00788     // from the original expression then just rewrite the rest of the expression
00789     // into it.
00790     BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
00791     if (BO && !NotRewritable.count(BO)) {
00792       Op = BO;
00793       continue;
00794     }
00795 
00796     // Otherwise, grab a spare node from the original expression and use that as
00797     // the left-hand side.  If there are no nodes left then the optimizers made
00798     // an expression with more nodes than the original!  This usually means that
00799     // they did something stupid but it might mean that the problem was just too
00800     // hard (finding the mimimal number of multiplications needed to realize a
00801     // multiplication expression is NP-complete).  Whatever the reason, smart or
00802     // stupid, create a new node if there are none left.
00803     BinaryOperator *NewOp;
00804     if (NodesToRewrite.empty()) {
00805       Constant *Undef = UndefValue::get(I->getType());
00806       NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
00807                                      Undef, Undef, "", I);
00808     } else {
00809       NewOp = NodesToRewrite.pop_back_val();
00810     }
00811 
00812     DEBUG(dbgs() << "RA: " << *Op << '\n');
00813     Op->setOperand(0, NewOp);
00814     DEBUG(dbgs() << "TO: " << *Op << '\n');
00815     ExpressionChanged = Op;
00816     MadeChange = true;
00817     ++NumChanged;
00818     Op = NewOp;
00819   }
00820 
00821   // If the expression changed non-trivially then clear out all subclass data
00822   // starting from the operator specified in ExpressionChanged, and compactify
00823   // the operators to just before the expression root to guarantee that the
00824   // expression tree is dominated by all of Ops.
00825   if (ExpressionChanged)
00826     do {
00827       ExpressionChanged->clearSubclassOptionalData();
00828       if (ExpressionChanged == I)
00829         break;
00830       ExpressionChanged->moveBefore(I);
00831       ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->use_begin());
00832     } while (1);
00833 
00834   // Throw away any left over nodes from the original expression.
00835   for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
00836     RedoInsts.insert(NodesToRewrite[i]);
00837 }
00838 
00839 /// NegateValue - Insert instructions before the instruction pointed to by BI,
00840 /// that computes the negative version of the value specified.  The negative
00841 /// version of the value is returned, and BI is left pointing at the instruction
00842 /// that should be processed next by the reassociation pass.
00843 static Value *NegateValue(Value *V, Instruction *BI) {
00844   if (Constant *C = dyn_cast<Constant>(V))
00845     return ConstantExpr::getNeg(C);
00846 
00847   // We are trying to expose opportunity for reassociation.  One of the things
00848   // that we want to do to achieve this is to push a negation as deep into an
00849   // expression chain as possible, to expose the add instructions.  In practice,
00850   // this means that we turn this:
00851   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
00852   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
00853   // the constants.  We assume that instcombine will clean up the mess later if
00854   // we introduce tons of unnecessary negation instructions.
00855   //
00856   if (BinaryOperator *I = isReassociableOp(V, Instruction::Add)) {
00857     // Push the negates through the add.
00858     I->setOperand(0, NegateValue(I->getOperand(0), BI));
00859     I->setOperand(1, NegateValue(I->getOperand(1), BI));
00860 
00861     // We must move the add instruction here, because the neg instructions do
00862     // not dominate the old add instruction in general.  By moving it, we are
00863     // assured that the neg instructions we just inserted dominate the
00864     // instruction we are about to insert after them.
00865     //
00866     I->moveBefore(BI);
00867     I->setName(I->getName()+".neg");
00868     return I;
00869   }
00870 
00871   // Okay, we need to materialize a negated version of V with an instruction.
00872   // Scan the use lists of V to see if we have one already.
00873   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
00874     User *U = *UI;
00875     if (!BinaryOperator::isNeg(U)) continue;
00876 
00877     // We found one!  Now we have to make sure that the definition dominates
00878     // this use.  We do this by moving it to the entry block (if it is a
00879     // non-instruction value) or right after the definition.  These negates will
00880     // be zapped by reassociate later, so we don't need much finesse here.
00881     BinaryOperator *TheNeg = cast<BinaryOperator>(U);
00882 
00883     // Verify that the negate is in this function, V might be a constant expr.
00884     if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
00885       continue;
00886 
00887     BasicBlock::iterator InsertPt;
00888     if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
00889       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
00890         InsertPt = II->getNormalDest()->begin();
00891       } else {
00892         InsertPt = InstInput;
00893         ++InsertPt;
00894       }
00895       while (isa<PHINode>(InsertPt)) ++InsertPt;
00896     } else {
00897       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
00898     }
00899     TheNeg->moveBefore(InsertPt);
00900     return TheNeg;
00901   }
00902 
00903   // Insert a 'neg' instruction that subtracts the value from zero to get the
00904   // negation.
00905   return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
00906 }
00907 
00908 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
00909 /// X-Y into (X + -Y).
00910 static bool ShouldBreakUpSubtract(Instruction *Sub) {
00911   // If this is a negation, we can't split it up!
00912   if (BinaryOperator::isNeg(Sub))
00913     return false;
00914 
00915   // Don't bother to break this up unless either the LHS is an associable add or
00916   // subtract or if this is only used by one.
00917   if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
00918       isReassociableOp(Sub->getOperand(0), Instruction::Sub))
00919     return true;
00920   if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
00921       isReassociableOp(Sub->getOperand(1), Instruction::Sub))
00922     return true;
00923   if (Sub->hasOneUse() &&
00924       (isReassociableOp(Sub->use_back(), Instruction::Add) ||
00925        isReassociableOp(Sub->use_back(), Instruction::Sub)))
00926     return true;
00927 
00928   return false;
00929 }
00930 
00931 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
00932 /// only used by an add, transform this into (X+(0-Y)) to promote better
00933 /// reassociation.
00934 static BinaryOperator *BreakUpSubtract(Instruction *Sub) {
00935   // Convert a subtract into an add and a neg instruction. This allows sub
00936   // instructions to be commuted with other add instructions.
00937   //
00938   // Calculate the negative value of Operand 1 of the sub instruction,
00939   // and set it as the RHS of the add instruction we just made.
00940   //
00941   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
00942   BinaryOperator *New =
00943     BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
00944   Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
00945   Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
00946   New->takeName(Sub);
00947 
00948   // Everyone now refers to the add instruction.
00949   Sub->replaceAllUsesWith(New);
00950   New->setDebugLoc(Sub->getDebugLoc());
00951 
00952   DEBUG(dbgs() << "Negated: " << *New << '\n');
00953   return New;
00954 }
00955 
00956 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
00957 /// by one, change this into a multiply by a constant to assist with further
00958 /// reassociation.
00959 static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
00960   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
00961   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
00962 
00963   BinaryOperator *Mul =
00964     BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
00965   Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
00966   Mul->takeName(Shl);
00967   Shl->replaceAllUsesWith(Mul);
00968   Mul->setDebugLoc(Shl->getDebugLoc());
00969   return Mul;
00970 }
00971 
00972 /// FindInOperandList - Scan backwards and forwards among values with the same
00973 /// rank as element i to see if X exists.  If X does not exist, return i.  This
00974 /// is useful when scanning for 'x' when we see '-x' because they both get the
00975 /// same rank.
00976 static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
00977                                   Value *X) {
00978   unsigned XRank = Ops[i].Rank;
00979   unsigned e = Ops.size();
00980   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
00981     if (Ops[j].Op == X)
00982       return j;
00983   // Scan backwards.
00984   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
00985     if (Ops[j].Op == X)
00986       return j;
00987   return i;
00988 }
00989 
00990 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
00991 /// and returning the result.  Insert the tree before I.
00992 static Value *EmitAddTreeOfValues(Instruction *I,
00993                                   SmallVectorImpl<WeakVH> &Ops){
00994   if (Ops.size() == 1) return Ops.back();
00995 
00996   Value *V1 = Ops.back();
00997   Ops.pop_back();
00998   Value *V2 = EmitAddTreeOfValues(I, Ops);
00999   return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
01000 }
01001 
01002 /// RemoveFactorFromExpression - If V is an expression tree that is a
01003 /// multiplication sequence, and if this sequence contains a multiply by Factor,
01004 /// remove Factor from the tree and return the new tree.
01005 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
01006   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
01007   if (!BO) return 0;
01008 
01009   SmallVector<RepeatedValue, 8> Tree;
01010   MadeChange |= LinearizeExprTree(BO, Tree);
01011   SmallVector<ValueEntry, 8> Factors;
01012   Factors.reserve(Tree.size());
01013   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
01014     RepeatedValue E = Tree[i];
01015     Factors.append(E.second.getZExtValue(),
01016                    ValueEntry(getRank(E.first), E.first));
01017   }
01018 
01019   bool FoundFactor = false;
01020   bool NeedsNegate = false;
01021   for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
01022     if (Factors[i].Op == Factor) {
01023       FoundFactor = true;
01024       Factors.erase(Factors.begin()+i);
01025       break;
01026     }
01027 
01028     // If this is a negative version of this factor, remove it.
01029     if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
01030       if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
01031         if (FC1->getValue() == -FC2->getValue()) {
01032           FoundFactor = NeedsNegate = true;
01033           Factors.erase(Factors.begin()+i);
01034           break;
01035         }
01036   }
01037 
01038   if (!FoundFactor) {
01039     // Make sure to restore the operands to the expression tree.
01040     RewriteExprTree(BO, Factors);
01041     return 0;
01042   }
01043 
01044   BasicBlock::iterator InsertPt = BO; ++InsertPt;
01045 
01046   // If this was just a single multiply, remove the multiply and return the only
01047   // remaining operand.
01048   if (Factors.size() == 1) {
01049     RedoInsts.insert(BO);
01050     V = Factors[0].Op;
01051   } else {
01052     RewriteExprTree(BO, Factors);
01053     V = BO;
01054   }
01055 
01056   if (NeedsNegate)
01057     V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
01058 
01059   return V;
01060 }
01061 
01062 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
01063 /// add its operands as factors, otherwise add V to the list of factors.
01064 ///
01065 /// Ops is the top-level list of add operands we're trying to factor.
01066 static void FindSingleUseMultiplyFactors(Value *V,
01067                                          SmallVectorImpl<Value*> &Factors,
01068                                        const SmallVectorImpl<ValueEntry> &Ops) {
01069   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
01070   if (!BO) {
01071     Factors.push_back(V);
01072     return;
01073   }
01074 
01075   // Otherwise, add the LHS and RHS to the list of factors.
01076   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
01077   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
01078 }
01079 
01080 /// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
01081 /// instruction.  This optimizes based on identities.  If it can be reduced to
01082 /// a single Value, it is returned, otherwise the Ops list is mutated as
01083 /// necessary.
01084 static Value *OptimizeAndOrXor(unsigned Opcode,
01085                                SmallVectorImpl<ValueEntry> &Ops) {
01086   // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
01087   // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
01088   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01089     // First, check for X and ~X in the operand list.
01090     assert(i < Ops.size());
01091     if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
01092       Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
01093       unsigned FoundX = FindInOperandList(Ops, i, X);
01094       if (FoundX != i) {
01095         if (Opcode == Instruction::And)   // ...&X&~X = 0
01096           return Constant::getNullValue(X->getType());
01097 
01098         if (Opcode == Instruction::Or)    // ...|X|~X = -1
01099           return Constant::getAllOnesValue(X->getType());
01100       }
01101     }
01102 
01103     // Next, check for duplicate pairs of values, which we assume are next to
01104     // each other, due to our sorting criteria.
01105     assert(i < Ops.size());
01106     if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
01107       if (Opcode == Instruction::And || Opcode == Instruction::Or) {
01108         // Drop duplicate values for And and Or.
01109         Ops.erase(Ops.begin()+i);
01110         --i; --e;
01111         ++NumAnnihil;
01112         continue;
01113       }
01114 
01115       // Drop pairs of values for Xor.
01116       assert(Opcode == Instruction::Xor);
01117       if (e == 2)
01118         return Constant::getNullValue(Ops[0].Op->getType());
01119 
01120       // Y ^ X^X -> Y
01121       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
01122       i -= 1; e -= 2;
01123       ++NumAnnihil;
01124     }
01125   }
01126   return 0;
01127 }
01128 
01129 /// Helper funciton of CombineXorOpnd(). It creates a bitwise-and
01130 /// instruction with the given two operands, and return the resulting
01131 /// instruction. There are two special cases: 1) if the constant operand is 0,
01132 /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
01133 /// be returned.
01134 static Value *createAndInstr(Instruction *InsertBefore, Value *Opnd, 
01135                              const APInt &ConstOpnd) {
01136   if (ConstOpnd != 0) {
01137     if (!ConstOpnd.isAllOnesValue()) {
01138       LLVMContext &Ctx = Opnd->getType()->getContext();
01139       Instruction *I;
01140       I = BinaryOperator::CreateAnd(Opnd, ConstantInt::get(Ctx, ConstOpnd),
01141                                     "and.ra", InsertBefore);
01142       I->setDebugLoc(InsertBefore->getDebugLoc());
01143       return I;
01144     }
01145     return Opnd;
01146   }
01147   return 0;
01148 }
01149 
01150 // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
01151 // into "R ^ C", where C would be 0, and R is a symbolic value.
01152 //
01153 // If it was successful, true is returned, and the "R" and "C" is returned
01154 // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
01155 // and both "Res" and "ConstOpnd" remain unchanged.
01156 //  
01157 bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
01158                                  APInt &ConstOpnd, Value *&Res) {
01159   // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2 
01160   //                       = ((x | c1) ^ c1) ^ (c1 ^ c2)
01161   //                       = (x & ~c1) ^ (c1 ^ c2)
01162   // It is useful only when c1 == c2.
01163   if (Opnd1->isOrExpr() && Opnd1->getConstPart() != 0) {
01164     if (!Opnd1->getValue()->hasOneUse())
01165       return false;
01166 
01167     const APInt &C1 = Opnd1->getConstPart();
01168     if (C1 != ConstOpnd)
01169       return false;
01170 
01171     Value *X = Opnd1->getSymbolicPart();
01172     Res = createAndInstr(I, X, ~C1);
01173     // ConstOpnd was C2, now C1 ^ C2.
01174     ConstOpnd ^= C1;
01175 
01176     if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
01177       RedoInsts.insert(T);
01178     return true;
01179   }
01180   return false;
01181 }
01182 
01183                            
01184 // Helper function of OptimizeXor(). It tries to simplify
01185 // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
01186 // symbolic value. 
01187 // 
01188 // If it was successful, true is returned, and the "R" and "C" is returned 
01189 // via "Res" and "ConstOpnd", respectively (If the entire expression is
01190 // evaluated to a constant, the Res is set to NULL); otherwise, false is
01191 // returned, and both "Res" and "ConstOpnd" remain unchanged.
01192 bool Reassociate::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1, XorOpnd *Opnd2,
01193                                  APInt &ConstOpnd, Value *&Res) {
01194   Value *X = Opnd1->getSymbolicPart();
01195   if (X != Opnd2->getSymbolicPart())
01196     return false;
01197 
01198   // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
01199   int DeadInstNum = 1;
01200   if (Opnd1->getValue()->hasOneUse())
01201     DeadInstNum++;
01202   if (Opnd2->getValue()->hasOneUse())
01203     DeadInstNum++;
01204 
01205   // Xor-Rule 2:
01206   //  (x | c1) ^ (x & c2)
01207   //   = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
01208   //   = (x & ~c1) ^ (x & c2) ^ c1               // Xor-Rule 1
01209   //   = (x & c3) ^ c1, where c3 = ~c1 ^ c2      // Xor-rule 3
01210   //
01211   if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
01212     if (Opnd2->isOrExpr())
01213       std::swap(Opnd1, Opnd2);
01214 
01215     const APInt &C1 = Opnd1->getConstPart();
01216     const APInt &C2 = Opnd2->getConstPart();
01217     APInt C3((~C1) ^ C2);
01218 
01219     // Do not increase code size!
01220     if (C3 != 0 && !C3.isAllOnesValue()) {
01221       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
01222       if (NewInstNum > DeadInstNum)
01223         return false;
01224     }
01225 
01226     Res = createAndInstr(I, X, C3);
01227     ConstOpnd ^= C1;
01228 
01229   } else if (Opnd1->isOrExpr()) {
01230     // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
01231     //
01232     const APInt &C1 = Opnd1->getConstPart();
01233     const APInt &C2 = Opnd2->getConstPart();
01234     APInt C3 = C1 ^ C2;
01235     
01236     // Do not increase code size
01237     if (C3 != 0 && !C3.isAllOnesValue()) {
01238       int NewInstNum = ConstOpnd != 0 ? 1 : 2;
01239       if (NewInstNum > DeadInstNum)
01240         return false;
01241     }
01242 
01243     Res = createAndInstr(I, X, C3);
01244     ConstOpnd ^= C3;
01245   } else {
01246     // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
01247     //
01248     const APInt &C1 = Opnd1->getConstPart();
01249     const APInt &C2 = Opnd2->getConstPart();
01250     APInt C3 = C1 ^ C2;
01251     Res = createAndInstr(I, X, C3);
01252   }
01253 
01254   // Put the original operands in the Redo list; hope they will be deleted
01255   // as dead code.
01256   if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
01257     RedoInsts.insert(T);
01258   if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
01259     RedoInsts.insert(T);
01260 
01261   return true;
01262 }
01263 
01264 /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
01265 /// to a single Value, it is returned, otherwise the Ops list is mutated as
01266 /// necessary.
01267 Value *Reassociate::OptimizeXor(Instruction *I,
01268                                 SmallVectorImpl<ValueEntry> &Ops) {
01269   if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
01270     return V;
01271       
01272   if (Ops.size() == 1)
01273     return 0;
01274 
01275   SmallVector<XorOpnd, 8> Opnds;
01276   SmallVector<XorOpnd*, 8> OpndPtrs;
01277   Type *Ty = Ops[0].Op->getType();
01278   APInt ConstOpnd(Ty->getIntegerBitWidth(), 0);
01279 
01280   // Step 1: Convert ValueEntry to XorOpnd
01281   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01282     Value *V = Ops[i].Op;
01283     if (!isa<ConstantInt>(V)) {
01284       XorOpnd O(V);
01285       O.setSymbolicRank(getRank(O.getSymbolicPart()));
01286       Opnds.push_back(O);
01287     } else
01288       ConstOpnd ^= cast<ConstantInt>(V)->getValue();
01289   }
01290 
01291   // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
01292   //  It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
01293   //  the "OpndPtrs" as well. For the similar reason, do not fuse this loop
01294   //  with the previous loop --- the iterator of the "Opnds" may be invalidated
01295   //  when new elements are added to the vector.
01296   for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
01297     OpndPtrs.push_back(&Opnds[i]);
01298 
01299   // Step 2: Sort the Xor-Operands in a way such that the operands containing
01300   //  the same symbolic value cluster together. For instance, the input operand
01301   //  sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
01302   //  ("x | 123", "x & 789", "y & 456").
01303   std::sort(OpndPtrs.begin(), OpndPtrs.end(), XorOpnd::PtrSortFunctor());
01304 
01305   // Step 3: Combine adjacent operands
01306   XorOpnd *PrevOpnd = 0;
01307   bool Changed = false;
01308   for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
01309     XorOpnd *CurrOpnd = OpndPtrs[i];
01310     // The combined value
01311     Value *CV;
01312 
01313     // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
01314     if (ConstOpnd != 0 && CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
01315       Changed = true;
01316       if (CV)
01317         *CurrOpnd = XorOpnd(CV);
01318       else {
01319         CurrOpnd->Invalidate();
01320         continue;
01321       }
01322     }
01323 
01324     if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
01325       PrevOpnd = CurrOpnd;
01326       continue;
01327     }
01328 
01329     // step 3.2: When previous and current operands share the same symbolic
01330     //  value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd" 
01331     //    
01332     if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
01333       // Remove previous operand
01334       PrevOpnd->Invalidate();
01335       if (CV) {
01336         *CurrOpnd = XorOpnd(CV);
01337         PrevOpnd = CurrOpnd;
01338       } else {
01339         CurrOpnd->Invalidate();
01340         PrevOpnd = 0;
01341       }
01342       Changed = true;
01343     }
01344   }
01345 
01346   // Step 4: Reassemble the Ops
01347   if (Changed) {
01348     Ops.clear();
01349     for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
01350       XorOpnd &O = Opnds[i];
01351       if (O.isInvalid())
01352         continue;
01353       ValueEntry VE(getRank(O.getValue()), O.getValue());
01354       Ops.push_back(VE);
01355     }
01356     if (ConstOpnd != 0) {
01357       Value *C = ConstantInt::get(Ty->getContext(), ConstOpnd);
01358       ValueEntry VE(getRank(C), C);
01359       Ops.push_back(VE);
01360     }
01361     int Sz = Ops.size();
01362     if (Sz == 1)
01363       return Ops.back().Op;
01364     else if (Sz == 0) {
01365       assert(ConstOpnd == 0);
01366       return ConstantInt::get(Ty->getContext(), ConstOpnd);
01367     }
01368   }
01369 
01370   return 0;
01371 }
01372 
01373 /// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
01374 /// optimizes based on identities.  If it can be reduced to a single Value, it
01375 /// is returned, otherwise the Ops list is mutated as necessary.
01376 Value *Reassociate::OptimizeAdd(Instruction *I,
01377                                 SmallVectorImpl<ValueEntry> &Ops) {
01378   // Scan the operand lists looking for X and -X pairs.  If we find any, we
01379   // can simplify the expression. X+-X == 0.  While we're at it, scan for any
01380   // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
01381   //
01382   // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
01383   //
01384   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01385     Value *TheOp = Ops[i].Op;
01386     // Check to see if we've seen this operand before.  If so, we factor all
01387     // instances of the operand together.  Due to our sorting criteria, we know
01388     // that these need to be next to each other in the vector.
01389     if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
01390       // Rescan the list, remove all instances of this operand from the expr.
01391       unsigned NumFound = 0;
01392       do {
01393         Ops.erase(Ops.begin()+i);
01394         ++NumFound;
01395       } while (i != Ops.size() && Ops[i].Op == TheOp);
01396 
01397       DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
01398       ++NumFactor;
01399 
01400       // Insert a new multiply.
01401       Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
01402       Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
01403 
01404       // Now that we have inserted a multiply, optimize it. This allows us to
01405       // handle cases that require multiple factoring steps, such as this:
01406       // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
01407       RedoInsts.insert(cast<Instruction>(Mul));
01408 
01409       // If every add operand was a duplicate, return the multiply.
01410       if (Ops.empty())
01411         return Mul;
01412 
01413       // Otherwise, we had some input that didn't have the dupe, such as
01414       // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
01415       // things being added by this operation.
01416       Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
01417 
01418       --i;
01419       e = Ops.size();
01420       continue;
01421     }
01422 
01423     // Check for X and -X in the operand list.
01424     if (!BinaryOperator::isNeg(TheOp))
01425       continue;
01426 
01427     Value *X = BinaryOperator::getNegArgument(TheOp);
01428     unsigned FoundX = FindInOperandList(Ops, i, X);
01429     if (FoundX == i)
01430       continue;
01431 
01432     // Remove X and -X from the operand list.
01433     if (Ops.size() == 2)
01434       return Constant::getNullValue(X->getType());
01435 
01436     Ops.erase(Ops.begin()+i);
01437     if (i < FoundX)
01438       --FoundX;
01439     else
01440       --i;   // Need to back up an extra one.
01441     Ops.erase(Ops.begin()+FoundX);
01442     ++NumAnnihil;
01443     --i;     // Revisit element.
01444     e -= 2;  // Removed two elements.
01445   }
01446 
01447   // Scan the operand list, checking to see if there are any common factors
01448   // between operands.  Consider something like A*A+A*B*C+D.  We would like to
01449   // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
01450   // To efficiently find this, we count the number of times a factor occurs
01451   // for any ADD operands that are MULs.
01452   DenseMap<Value*, unsigned> FactorOccurrences;
01453 
01454   // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
01455   // where they are actually the same multiply.
01456   unsigned MaxOcc = 0;
01457   Value *MaxOccVal = 0;
01458   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
01459     BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
01460     if (!BOp)
01461       continue;
01462 
01463     // Compute all of the factors of this added value.
01464     SmallVector<Value*, 8> Factors;
01465     FindSingleUseMultiplyFactors(BOp, Factors, Ops);
01466     assert(Factors.size() > 1 && "Bad linearize!");
01467 
01468     // Add one to FactorOccurrences for each unique factor in this op.
01469     SmallPtrSet<Value*, 8> Duplicates;
01470     for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
01471       Value *Factor = Factors[i];
01472       if (!Duplicates.insert(Factor)) continue;
01473 
01474       unsigned Occ = ++FactorOccurrences[Factor];
01475       if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
01476 
01477       // If Factor is a negative constant, add the negated value as a factor
01478       // because we can percolate the negate out.  Watch for minint, which
01479       // cannot be positivified.
01480       if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
01481         if (CI->isNegative() && !CI->isMinValue(true)) {
01482           Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
01483           assert(!Duplicates.count(Factor) &&
01484                  "Shouldn't have two constant factors, missed a canonicalize");
01485 
01486           unsigned Occ = ++FactorOccurrences[Factor];
01487           if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
01488         }
01489     }
01490   }
01491 
01492   // If any factor occurred more than one time, we can pull it out.
01493   if (MaxOcc > 1) {
01494     DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
01495     ++NumFactor;
01496 
01497     // Create a new instruction that uses the MaxOccVal twice.  If we don't do
01498     // this, we could otherwise run into situations where removing a factor
01499     // from an expression will drop a use of maxocc, and this can cause
01500     // RemoveFactorFromExpression on successive values to behave differently.
01501     Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
01502     SmallVector<WeakVH, 4> NewMulOps;
01503     for (unsigned i = 0; i != Ops.size(); ++i) {
01504       // Only try to remove factors from expressions we're allowed to.
01505       BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
01506       if (!BOp)
01507         continue;
01508 
01509       if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
01510         // The factorized operand may occur several times.  Convert them all in
01511         // one fell swoop.
01512         for (unsigned j = Ops.size(); j != i;) {
01513           --j;
01514           if (Ops[j].Op == Ops[i].Op) {
01515             NewMulOps.push_back(V);
01516             Ops.erase(Ops.begin()+j);
01517           }
01518         }
01519         --i;
01520       }
01521     }
01522 
01523     // No need for extra uses anymore.
01524     delete DummyInst;
01525 
01526     unsigned NumAddedValues = NewMulOps.size();
01527     Value *V = EmitAddTreeOfValues(I, NewMulOps);
01528 
01529     // Now that we have inserted the add tree, optimize it. This allows us to
01530     // handle cases that require multiple factoring steps, such as this:
01531     // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
01532     assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
01533     (void)NumAddedValues;
01534     if (Instruction *VI = dyn_cast<Instruction>(V))
01535       RedoInsts.insert(VI);
01536 
01537     // Create the multiply.
01538     Instruction *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
01539 
01540     // Rerun associate on the multiply in case the inner expression turned into
01541     // a multiply.  We want to make sure that we keep things in canonical form.
01542     RedoInsts.insert(V2);
01543 
01544     // If every add operand included the factor (e.g. "A*B + A*C"), then the
01545     // entire result expression is just the multiply "A*(B+C)".
01546     if (Ops.empty())
01547       return V2;
01548 
01549     // Otherwise, we had some input that didn't have the factor, such as
01550     // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
01551     // things being added by this operation.
01552     Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
01553   }
01554 
01555   return 0;
01556 }
01557 
01558 namespace {
01559   /// \brief Predicate tests whether a ValueEntry's op is in a map.
01560   struct IsValueInMap {
01561     const DenseMap<Value *, unsigned> &Map;
01562 
01563     IsValueInMap(const DenseMap<Value *, unsigned> &Map) : Map(Map) {}
01564 
01565     bool operator()(const ValueEntry &Entry) {
01566       return Map.find(Entry.Op) != Map.end();
01567     }
01568   };
01569 }
01570 
01571 /// \brief Build up a vector of value/power pairs factoring a product.
01572 ///
01573 /// Given a series of multiplication operands, build a vector of factors and
01574 /// the powers each is raised to when forming the final product. Sort them in
01575 /// the order of descending power.
01576 ///
01577 ///      (x*x)          -> [(x, 2)]
01578 ///     ((x*x)*x)       -> [(x, 3)]
01579 ///   ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
01580 ///
01581 /// \returns Whether any factors have a power greater than one.
01582 bool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
01583                                          SmallVectorImpl<Factor> &Factors) {
01584   // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
01585   // Compute the sum of powers of simplifiable factors.
01586   unsigned FactorPowerSum = 0;
01587   for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
01588     Value *Op = Ops[Idx-1].Op;
01589 
01590     // Count the number of occurrences of this value.
01591     unsigned Count = 1;
01592     for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
01593       ++Count;
01594     // Track for simplification all factors which occur 2 or more times.
01595     if (Count > 1)
01596       FactorPowerSum += Count;
01597   }
01598 
01599   // We can only simplify factors if the sum of the powers of our simplifiable
01600   // factors is 4 or higher. When that is the case, we will *always* have
01601   // a simplification. This is an important invariant to prevent cyclicly
01602   // trying to simplify already minimal formations.
01603   if (FactorPowerSum < 4)
01604     return false;
01605 
01606   // Now gather the simplifiable factors, removing them from Ops.
01607   FactorPowerSum = 0;
01608   for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
01609     Value *Op = Ops[Idx-1].Op;
01610 
01611     // Count the number of occurrences of this value.
01612     unsigned Count = 1;
01613     for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
01614       ++Count;
01615     if (Count == 1)
01616       continue;
01617     // Move an even number of occurrences to Factors.
01618     Count &= ~1U;
01619     Idx -= Count;
01620     FactorPowerSum += Count;
01621     Factors.push_back(Factor(Op, Count));
01622     Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
01623   }
01624 
01625   // None of the adjustments above should have reduced the sum of factor powers
01626   // below our mininum of '4'.
01627   assert(FactorPowerSum >= 4);
01628 
01629   std::sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
01630   return true;
01631 }
01632 
01633 /// \brief Build a tree of multiplies, computing the product of Ops.
01634 static Value *buildMultiplyTree(IRBuilder<> &Builder,
01635                                 SmallVectorImpl<Value*> &Ops) {
01636   if (Ops.size() == 1)
01637     return Ops.back();
01638 
01639   Value *LHS = Ops.pop_back_val();
01640   do {
01641     LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
01642   } while (!Ops.empty());
01643 
01644   return LHS;
01645 }
01646 
01647 /// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
01648 ///
01649 /// Given a vector of values raised to various powers, where no two values are
01650 /// equal and the powers are sorted in decreasing order, compute the minimal
01651 /// DAG of multiplies to compute the final product, and return that product
01652 /// value.
01653 Value *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
01654                                             SmallVectorImpl<Factor> &Factors) {
01655   assert(Factors[0].Power);
01656   SmallVector<Value *, 4> OuterProduct;
01657   for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
01658        Idx < Size && Factors[Idx].Power > 0; ++Idx) {
01659     if (Factors[Idx].Power != Factors[LastIdx].Power) {
01660       LastIdx = Idx;
01661       continue;
01662     }
01663 
01664     // We want to multiply across all the factors with the same power so that
01665     // we can raise them to that power as a single entity. Build a mini tree
01666     // for that.
01667     SmallVector<Value *, 4> InnerProduct;
01668     InnerProduct.push_back(Factors[LastIdx].Base);
01669     do {
01670       InnerProduct.push_back(Factors[Idx].Base);
01671       ++Idx;
01672     } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
01673 
01674     // Reset the base value of the first factor to the new expression tree.
01675     // We'll remove all the factors with the same power in a second pass.
01676     Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
01677     if (Instruction *MI = dyn_cast<Instruction>(M))
01678       RedoInsts.insert(MI);
01679 
01680     LastIdx = Idx;
01681   }
01682   // Unique factors with equal powers -- we've folded them into the first one's
01683   // base.
01684   Factors.erase(std::unique(Factors.begin(), Factors.end(),
01685                             Factor::PowerEqual()),
01686                 Factors.end());
01687 
01688   // Iteratively collect the base of each factor with an add power into the
01689   // outer product, and halve each power in preparation for squaring the
01690   // expression.
01691   for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
01692     if (Factors[Idx].Power & 1)
01693       OuterProduct.push_back(Factors[Idx].Base);
01694     Factors[Idx].Power >>= 1;
01695   }
01696   if (Factors[0].Power) {
01697     Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
01698     OuterProduct.push_back(SquareRoot);
01699     OuterProduct.push_back(SquareRoot);
01700   }
01701   if (OuterProduct.size() == 1)
01702     return OuterProduct.front();
01703 
01704   Value *V = buildMultiplyTree(Builder, OuterProduct);
01705   return V;
01706 }
01707 
01708 Value *Reassociate::OptimizeMul(BinaryOperator *I,
01709                                 SmallVectorImpl<ValueEntry> &Ops) {
01710   // We can only optimize the multiplies when there is a chain of more than
01711   // three, such that a balanced tree might require fewer total multiplies.
01712   if (Ops.size() < 4)
01713     return 0;
01714 
01715   // Try to turn linear trees of multiplies without other uses of the
01716   // intermediate stages into minimal multiply DAGs with perfect sub-expression
01717   // re-use.
01718   SmallVector<Factor, 4> Factors;
01719   if (!collectMultiplyFactors(Ops, Factors))
01720     return 0; // All distinct factors, so nothing left for us to do.
01721 
01722   IRBuilder<> Builder(I);
01723   Value *V = buildMinimalMultiplyDAG(Builder, Factors);
01724   if (Ops.empty())
01725     return V;
01726 
01727   ValueEntry NewEntry = ValueEntry(getRank(V), V);
01728   Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
01729   return 0;
01730 }
01731 
01732 Value *Reassociate::OptimizeExpression(BinaryOperator *I,
01733                                        SmallVectorImpl<ValueEntry> &Ops) {
01734   // Now that we have the linearized expression tree, try to optimize it.
01735   // Start by folding any constants that we found.
01736   Constant *Cst = 0;
01737   unsigned Opcode = I->getOpcode();
01738   while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
01739     Constant *C = cast<Constant>(Ops.pop_back_val().Op);
01740     Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
01741   }
01742   // If there was nothing but constants then we are done.
01743   if (Ops.empty())
01744     return Cst;
01745 
01746   // Put the combined constant back at the end of the operand list, except if
01747   // there is no point.  For example, an add of 0 gets dropped here, while a
01748   // multiplication by zero turns the whole expression into zero.
01749   if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
01750     if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
01751       return Cst;
01752     Ops.push_back(ValueEntry(0, Cst));
01753   }
01754 
01755   if (Ops.size() == 1) return Ops[0].Op;
01756 
01757   // Handle destructive annihilation due to identities between elements in the
01758   // argument list here.
01759   unsigned NumOps = Ops.size();
01760   switch (Opcode) {
01761   default: break;
01762   case Instruction::And:
01763   case Instruction::Or:
01764     if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
01765       return Result;
01766     break;
01767 
01768   case Instruction::Xor:
01769     if (Value *Result = OptimizeXor(I, Ops))
01770       return Result;
01771     break;
01772 
01773   case Instruction::Add:
01774     if (Value *Result = OptimizeAdd(I, Ops))
01775       return Result;
01776     break;
01777 
01778   case Instruction::Mul:
01779     if (Value *Result = OptimizeMul(I, Ops))
01780       return Result;
01781     break;
01782   }
01783 
01784   if (Ops.size() != NumOps)
01785     return OptimizeExpression(I, Ops);
01786   return 0;
01787 }
01788 
01789 /// EraseInst - Zap the given instruction, adding interesting operands to the
01790 /// work list.
01791 void Reassociate::EraseInst(Instruction *I) {
01792   assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
01793   SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
01794   // Erase the dead instruction.
01795   ValueRankMap.erase(I);
01796   RedoInsts.remove(I);
01797   I->eraseFromParent();
01798   // Optimize its operands.
01799   SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
01800   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
01801     if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
01802       // If this is a node in an expression tree, climb to the expression root
01803       // and add that since that's where optimization actually happens.
01804       unsigned Opcode = Op->getOpcode();
01805       while (Op->hasOneUse() && Op->use_back()->getOpcode() == Opcode &&
01806              Visited.insert(Op))
01807         Op = Op->use_back();
01808       RedoInsts.insert(Op);
01809     }
01810 }
01811 
01812 /// OptimizeInst - Inspect and optimize the given instruction. Note that erasing
01813 /// instructions is not allowed.
01814 void Reassociate::OptimizeInst(Instruction *I) {
01815   // Only consider operations that we understand.
01816   if (!isa<BinaryOperator>(I))
01817     return;
01818 
01819   if (I->getOpcode() == Instruction::Shl &&
01820       isa<ConstantInt>(I->getOperand(1)))
01821     // If an operand of this shift is a reassociable multiply, or if the shift
01822     // is used by a reassociable multiply or add, turn into a multiply.
01823     if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
01824         (I->hasOneUse() &&
01825          (isReassociableOp(I->use_back(), Instruction::Mul) ||
01826           isReassociableOp(I->use_back(), Instruction::Add)))) {
01827       Instruction *NI = ConvertShiftToMul(I);
01828       RedoInsts.insert(I);
01829       MadeChange = true;
01830       I = NI;
01831     }
01832 
01833   // Floating point binary operators are not associative, but we can still
01834   // commute (some) of them, to canonicalize the order of their operands.
01835   // This can potentially expose more CSE opportunities, and makes writing
01836   // other transformations simpler.
01837   if ((I->getType()->isFloatingPointTy() || I->getType()->isVectorTy())) {
01838     // FAdd and FMul can be commuted.
01839     if (I->getOpcode() != Instruction::FMul &&
01840         I->getOpcode() != Instruction::FAdd)
01841       return;
01842 
01843     Value *LHS = I->getOperand(0);
01844     Value *RHS = I->getOperand(1);
01845     unsigned LHSRank = getRank(LHS);
01846     unsigned RHSRank = getRank(RHS);
01847 
01848     // Sort the operands by rank.
01849     if (RHSRank < LHSRank) {
01850       I->setOperand(0, RHS);
01851       I->setOperand(1, LHS);
01852     }
01853 
01854     return;
01855   }
01856 
01857   // Do not reassociate boolean (i1) expressions.  We want to preserve the
01858   // original order of evaluation for short-circuited comparisons that
01859   // SimplifyCFG has folded to AND/OR expressions.  If the expression
01860   // is not further optimized, it is likely to be transformed back to a
01861   // short-circuited form for code gen, and the source order may have been
01862   // optimized for the most likely conditions.
01863   if (I->getType()->isIntegerTy(1))
01864     return;
01865 
01866   // If this is a subtract instruction which is not already in negate form,
01867   // see if we can convert it to X+-Y.
01868   if (I->getOpcode() == Instruction::Sub) {
01869     if (ShouldBreakUpSubtract(I)) {
01870       Instruction *NI = BreakUpSubtract(I);
01871       RedoInsts.insert(I);
01872       MadeChange = true;
01873       I = NI;
01874     } else if (BinaryOperator::isNeg(I)) {
01875       // Otherwise, this is a negation.  See if the operand is a multiply tree
01876       // and if this is not an inner node of a multiply tree.
01877       if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
01878           (!I->hasOneUse() ||
01879            !isReassociableOp(I->use_back(), Instruction::Mul))) {
01880         Instruction *NI = LowerNegateToMultiply(I);
01881         RedoInsts.insert(I);
01882         MadeChange = true;
01883         I = NI;
01884       }
01885     }
01886   }
01887 
01888   // If this instruction is an associative binary operator, process it.
01889   if (!I->isAssociative()) return;
01890   BinaryOperator *BO = cast<BinaryOperator>(I);
01891 
01892   // If this is an interior node of a reassociable tree, ignore it until we
01893   // get to the root of the tree, to avoid N^2 analysis.
01894   unsigned Opcode = BO->getOpcode();
01895   if (BO->hasOneUse() && BO->use_back()->getOpcode() == Opcode)
01896     return;
01897 
01898   // If this is an add tree that is used by a sub instruction, ignore it
01899   // until we process the subtract.
01900   if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
01901       cast<Instruction>(BO->use_back())->getOpcode() == Instruction::Sub)
01902     return;
01903 
01904   ReassociateExpression(BO);
01905 }
01906 
01907 void Reassociate::ReassociateExpression(BinaryOperator *I) {
01908 
01909   // First, walk the expression tree, linearizing the tree, collecting the
01910   // operand information.
01911   SmallVector<RepeatedValue, 8> Tree;
01912   MadeChange |= LinearizeExprTree(I, Tree);
01913   SmallVector<ValueEntry, 8> Ops;
01914   Ops.reserve(Tree.size());
01915   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
01916     RepeatedValue E = Tree[i];
01917     Ops.append(E.second.getZExtValue(),
01918                ValueEntry(getRank(E.first), E.first));
01919   }
01920 
01921   DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
01922 
01923   // Now that we have linearized the tree to a list and have gathered all of
01924   // the operands and their ranks, sort the operands by their rank.  Use a
01925   // stable_sort so that values with equal ranks will have their relative
01926   // positions maintained (and so the compiler is deterministic).  Note that
01927   // this sorts so that the highest ranking values end up at the beginning of
01928   // the vector.
01929   std::stable_sort(Ops.begin(), Ops.end());
01930 
01931   // OptimizeExpression - Now that we have the expression tree in a convenient
01932   // sorted form, optimize it globally if possible.
01933   if (Value *V = OptimizeExpression(I, Ops)) {
01934     if (V == I)
01935       // Self-referential expression in unreachable code.
01936       return;
01937     // This expression tree simplified to something that isn't a tree,
01938     // eliminate it.
01939     DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
01940     I->replaceAllUsesWith(V);
01941     if (Instruction *VI = dyn_cast<Instruction>(V))
01942       VI->setDebugLoc(I->getDebugLoc());
01943     RedoInsts.insert(I);
01944     ++NumAnnihil;
01945     return;
01946   }
01947 
01948   // We want to sink immediates as deeply as possible except in the case where
01949   // this is a multiply tree used only by an add, and the immediate is a -1.
01950   // In this case we reassociate to put the negation on the outside so that we
01951   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
01952   if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
01953       cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
01954       isa<ConstantInt>(Ops.back().Op) &&
01955       cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
01956     ValueEntry Tmp = Ops.pop_back_val();
01957     Ops.insert(Ops.begin(), Tmp);
01958   }
01959 
01960   DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
01961 
01962   if (Ops.size() == 1) {
01963     if (Ops[0].Op == I)
01964       // Self-referential expression in unreachable code.
01965       return;
01966 
01967     // This expression tree simplified to something that isn't a tree,
01968     // eliminate it.
01969     I->replaceAllUsesWith(Ops[0].Op);
01970     if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
01971       OI->setDebugLoc(I->getDebugLoc());
01972     RedoInsts.insert(I);
01973     return;
01974   }
01975 
01976   // Now that we ordered and optimized the expressions, splat them back into
01977   // the expression tree, removing any unneeded nodes.
01978   RewriteExprTree(I, Ops);
01979 }
01980 
01981 bool Reassociate::runOnFunction(Function &F) {
01982   // Calculate the rank map for F
01983   BuildRankMap(F);
01984 
01985   MadeChange = false;
01986   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
01987     // Optimize every instruction in the basic block.
01988     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
01989       if (isInstructionTriviallyDead(II)) {
01990         EraseInst(II++);
01991       } else {
01992         OptimizeInst(II);
01993         assert(II->getParent() == BI && "Moved to a different block!");
01994         ++II;
01995       }
01996 
01997     // If this produced extra instructions to optimize, handle them now.
01998     while (!RedoInsts.empty()) {
01999       Instruction *I = RedoInsts.pop_back_val();
02000       if (isInstructionTriviallyDead(I))
02001         EraseInst(I);
02002       else
02003         OptimizeInst(I);
02004     }
02005   }
02006 
02007   // We are done with the rank map.
02008   RankMap.clear();
02009   ValueRankMap.clear();
02010 
02011   return MadeChange;
02012 }