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