When factoring multiply expressions across adds, factor both
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass reassociates commutative expressions in an order that is designed
11 // to promote better constant propagation, GCSE, LICM, PRE, etc.
12 //
13 // For example: 4 + (x + 5) -> x + (4 + 5)
14 //
15 // In the implementation of this algorithm, constants are assigned rank = 0,
16 // function arguments are rank = 1, and other values are assigned ranks
17 // corresponding to the reverse post order traversal of current function
18 // (starting at 2), which effectively gives values in deep loops higher rank
19 // than values not in loops.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #define DEBUG_TYPE "reassociate"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/IntrinsicInst.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Assembly/Writer.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ValueHandle.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/PostOrderIterator.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NumLinear , "Number of insts linearized");
43 STATISTIC(NumChanged, "Number of insts reassociated");
44 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
45 STATISTIC(NumFactor , "Number of multiplies factored");
46
47 namespace {
48   struct ValueEntry {
49     unsigned Rank;
50     Value *Op;
51     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
52   };
53   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
54     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
55   }
56 }
57
58 #ifndef NDEBUG
59 /// PrintOps - Print out the expression identified in the Ops list.
60 ///
61 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
62   Module *M = I->getParent()->getParent()->getParent();
63   errs() << Instruction::getOpcodeName(I->getOpcode()) << " "
64        << *Ops[0].Op->getType() << '\t';
65   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
66     errs() << "[ ";
67     WriteAsOperand(errs(), Ops[i].Op, false, M);
68     errs() << ", #" << Ops[i].Rank << "] ";
69   }
70 }
71 #endif
72   
73 namespace {
74   class Reassociate : public FunctionPass {
75     DenseMap<BasicBlock*, unsigned> RankMap;
76     DenseMap<AssertingVH<>, unsigned> ValueRankMap;
77     bool MadeChange;
78   public:
79     static char ID; // Pass identification, replacement for typeid
80     Reassociate() : FunctionPass(&ID) {}
81
82     bool runOnFunction(Function &F);
83
84     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.setPreservesCFG();
86     }
87   private:
88     void BuildRankMap(Function &F);
89     unsigned getRank(Value *V);
90     Value *ReassociateExpression(BinaryOperator *I);
91     void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops,
92                          unsigned Idx = 0);
93     Value *OptimizeExpression(BinaryOperator *I,
94                               SmallVectorImpl<ValueEntry> &Ops);
95     Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
96     void LinearizeExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
97     void LinearizeExpr(BinaryOperator *I);
98     Value *RemoveFactorFromExpression(Value *V, Value *Factor);
99     void ReassociateBB(BasicBlock *BB);
100     
101     void RemoveDeadBinaryOp(Value *V);
102   };
103 }
104
105 char Reassociate::ID = 0;
106 static RegisterPass<Reassociate> X("reassociate", "Reassociate expressions");
107
108 // Public interface to the Reassociate pass
109 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
110
111 void Reassociate::RemoveDeadBinaryOp(Value *V) {
112   Instruction *Op = dyn_cast<Instruction>(V);
113   if (!Op || !isa<BinaryOperator>(Op) || !Op->use_empty())
114     return;
115   
116   Value *LHS = Op->getOperand(0), *RHS = Op->getOperand(1);
117   
118   ValueRankMap.erase(Op);
119   Op->eraseFromParent();
120   RemoveDeadBinaryOp(LHS);
121   RemoveDeadBinaryOp(RHS);
122 }
123
124
125 static bool isUnmovableInstruction(Instruction *I) {
126   if (I->getOpcode() == Instruction::PHI ||
127       I->getOpcode() == Instruction::Alloca ||
128       I->getOpcode() == Instruction::Load ||
129       I->getOpcode() == Instruction::Invoke ||
130       (I->getOpcode() == Instruction::Call &&
131        !isa<DbgInfoIntrinsic>(I)) ||
132       I->getOpcode() == Instruction::UDiv || 
133       I->getOpcode() == Instruction::SDiv ||
134       I->getOpcode() == Instruction::FDiv ||
135       I->getOpcode() == Instruction::URem ||
136       I->getOpcode() == Instruction::SRem ||
137       I->getOpcode() == Instruction::FRem)
138     return true;
139   return false;
140 }
141
142 void Reassociate::BuildRankMap(Function &F) {
143   unsigned i = 2;
144
145   // Assign distinct ranks to function arguments
146   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
147     ValueRankMap[&*I] = ++i;
148
149   ReversePostOrderTraversal<Function*> RPOT(&F);
150   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
151          E = RPOT.end(); I != E; ++I) {
152     BasicBlock *BB = *I;
153     unsigned BBRank = RankMap[BB] = ++i << 16;
154
155     // Walk the basic block, adding precomputed ranks for any instructions that
156     // we cannot move.  This ensures that the ranks for these instructions are
157     // all different in the block.
158     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
159       if (isUnmovableInstruction(I))
160         ValueRankMap[&*I] = ++BBRank;
161   }
162 }
163
164 unsigned Reassociate::getRank(Value *V) {
165   Instruction *I = dyn_cast<Instruction>(V);
166   if (I == 0) {
167     if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
168     return 0;  // Otherwise it's a global or constant, rank 0.
169   }
170
171   if (unsigned Rank = ValueRankMap[I])
172     return Rank;    // Rank already known?
173
174   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
175   // we can reassociate expressions for code motion!  Since we do not recurse
176   // for PHI nodes, we cannot have infinite recursion here, because there
177   // cannot be loops in the value graph that do not go through PHI nodes.
178   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
179   for (unsigned i = 0, e = I->getNumOperands();
180        i != e && Rank != MaxRank; ++i)
181     Rank = std::max(Rank, getRank(I->getOperand(i)));
182
183   // If this is a not or neg instruction, do not count it for rank.  This
184   // assures us that X and ~X will have the same rank.
185   if (!I->getType()->isInteger() ||
186       (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
187     ++Rank;
188
189   //DEBUG(errs() << "Calculated Rank[" << V->getName() << "] = "
190   //     << Rank << "\n");
191
192   return ValueRankMap[I] = Rank;
193 }
194
195 /// isReassociableOp - Return true if V is an instruction of the specified
196 /// opcode and if it only has one use.
197 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
198   if ((V->hasOneUse() || V->use_empty()) && isa<Instruction>(V) &&
199       cast<Instruction>(V)->getOpcode() == Opcode)
200     return cast<BinaryOperator>(V);
201   return 0;
202 }
203
204 /// LowerNegateToMultiply - Replace 0-X with X*-1.
205 ///
206 static Instruction *LowerNegateToMultiply(Instruction *Neg,
207                               DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
208   Constant *Cst = Constant::getAllOnesValue(Neg->getType());
209
210   Instruction *Res = BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
211   ValueRankMap.erase(Neg);
212   Res->takeName(Neg);
213   Neg->replaceAllUsesWith(Res);
214   Neg->eraseFromParent();
215   return Res;
216 }
217
218 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
219 // Note that if D is also part of the expression tree that we recurse to
220 // linearize it as well.  Besides that case, this does not recurse into A,B, or
221 // C.
222 void Reassociate::LinearizeExpr(BinaryOperator *I) {
223   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
224   BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
225   assert(isReassociableOp(LHS, I->getOpcode()) &&
226          isReassociableOp(RHS, I->getOpcode()) &&
227          "Not an expression that needs linearization?");
228
229   DEBUG(errs() << "Linear" << *LHS << '\n' << *RHS << '\n' << *I << '\n');
230
231   // Move the RHS instruction to live immediately before I, avoiding breaking
232   // dominator properties.
233   RHS->moveBefore(I);
234
235   // Move operands around to do the linearization.
236   I->setOperand(1, RHS->getOperand(0));
237   RHS->setOperand(0, LHS);
238   I->setOperand(0, RHS);
239
240   ++NumLinear;
241   MadeChange = true;
242   DEBUG(errs() << "Linearized: " << *I << '\n');
243
244   // If D is part of this expression tree, tail recurse.
245   if (isReassociableOp(I->getOperand(1), I->getOpcode()))
246     LinearizeExpr(I);
247 }
248
249
250 /// LinearizeExprTree - Given an associative binary expression tree, traverse
251 /// all of the uses putting it into canonical form.  This forces a left-linear
252 /// form of the the expression (((a+b)+c)+d), and collects information about the
253 /// rank of the non-tree operands.
254 ///
255 /// NOTE: These intentionally destroys the expression tree operands (turning
256 /// them into undef values) to reduce #uses of the values.  This means that the
257 /// caller MUST use something like RewriteExprTree to put the values back in.
258 ///
259 void Reassociate::LinearizeExprTree(BinaryOperator *I,
260                                     SmallVectorImpl<ValueEntry> &Ops) {
261   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
262   unsigned Opcode = I->getOpcode();
263
264   // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
265   BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
266   BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
267
268   // If this is a multiply expression tree and it contains internal negations,
269   // transform them into multiplies by -1 so they can be reassociated.
270   if (I->getOpcode() == Instruction::Mul) {
271     if (!LHSBO && LHS->hasOneUse() && BinaryOperator::isNeg(LHS)) {
272       LHS = LowerNegateToMultiply(cast<Instruction>(LHS), ValueRankMap);
273       LHSBO = isReassociableOp(LHS, Opcode);
274     }
275     if (!RHSBO && RHS->hasOneUse() && BinaryOperator::isNeg(RHS)) {
276       RHS = LowerNegateToMultiply(cast<Instruction>(RHS), ValueRankMap);
277       RHSBO = isReassociableOp(RHS, Opcode);
278     }
279   }
280
281   if (!LHSBO) {
282     if (!RHSBO) {
283       // Neither the LHS or RHS as part of the tree, thus this is a leaf.  As
284       // such, just remember these operands and their rank.
285       Ops.push_back(ValueEntry(getRank(LHS), LHS));
286       Ops.push_back(ValueEntry(getRank(RHS), RHS));
287       
288       // Clear the leaves out.
289       I->setOperand(0, UndefValue::get(I->getType()));
290       I->setOperand(1, UndefValue::get(I->getType()));
291       return;
292     }
293     
294     // Turn X+(Y+Z) -> (Y+Z)+X
295     std::swap(LHSBO, RHSBO);
296     std::swap(LHS, RHS);
297     bool Success = !I->swapOperands();
298     assert(Success && "swapOperands failed");
299     Success = false;
300     MadeChange = true;
301   } else if (RHSBO) {
302     // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
303     // part of the expression tree.
304     LinearizeExpr(I);
305     LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
306     RHS = I->getOperand(1);
307     RHSBO = 0;
308   }
309
310   // Okay, now we know that the LHS is a nested expression and that the RHS is
311   // not.  Perform reassociation.
312   assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
313
314   // Move LHS right before I to make sure that the tree expression dominates all
315   // values.
316   LHSBO->moveBefore(I);
317
318   // Linearize the expression tree on the LHS.
319   LinearizeExprTree(LHSBO, Ops);
320
321   // Remember the RHS operand and its rank.
322   Ops.push_back(ValueEntry(getRank(RHS), RHS));
323   
324   // Clear the RHS leaf out.
325   I->setOperand(1, UndefValue::get(I->getType()));
326 }
327
328 // RewriteExprTree - Now that the operands for this expression tree are
329 // linearized and optimized, emit them in-order.  This function is written to be
330 // tail recursive.
331 void Reassociate::RewriteExprTree(BinaryOperator *I,
332                                   SmallVectorImpl<ValueEntry> &Ops,
333                                   unsigned i) {
334   if (i+2 == Ops.size()) {
335     if (I->getOperand(0) != Ops[i].Op ||
336         I->getOperand(1) != Ops[i+1].Op) {
337       Value *OldLHS = I->getOperand(0);
338       DEBUG(errs() << "RA: " << *I << '\n');
339       I->setOperand(0, Ops[i].Op);
340       I->setOperand(1, Ops[i+1].Op);
341       DEBUG(errs() << "TO: " << *I << '\n');
342       MadeChange = true;
343       ++NumChanged;
344       
345       // If we reassociated a tree to fewer operands (e.g. (1+a+2) -> (a+3)
346       // delete the extra, now dead, nodes.
347       RemoveDeadBinaryOp(OldLHS);
348     }
349     return;
350   }
351   assert(i+2 < Ops.size() && "Ops index out of range!");
352
353   if (I->getOperand(1) != Ops[i].Op) {
354     DEBUG(errs() << "RA: " << *I << '\n');
355     I->setOperand(1, Ops[i].Op);
356     DEBUG(errs() << "TO: " << *I << '\n');
357     MadeChange = true;
358     ++NumChanged;
359   }
360   
361   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
362   assert(LHS->getOpcode() == I->getOpcode() &&
363          "Improper expression tree!");
364   
365   // Compactify the tree instructions together with each other to guarantee
366   // that the expression tree is dominated by all of Ops.
367   LHS->moveBefore(I);
368   RewriteExprTree(LHS, Ops, i+1);
369 }
370
371
372
373 // NegateValue - Insert instructions before the instruction pointed to by BI,
374 // that computes the negative version of the value specified.  The negative
375 // version of the value is returned, and BI is left pointing at the instruction
376 // that should be processed next by the reassociation pass.
377 //
378 static Value *NegateValue(Value *V, Instruction *BI) {
379   if (Constant *C = dyn_cast<Constant>(V))
380     return ConstantExpr::getNeg(C);
381   
382   // We are trying to expose opportunity for reassociation.  One of the things
383   // that we want to do to achieve this is to push a negation as deep into an
384   // expression chain as possible, to expose the add instructions.  In practice,
385   // this means that we turn this:
386   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
387   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
388   // the constants.  We assume that instcombine will clean up the mess later if
389   // we introduce tons of unnecessary negation instructions.
390   //
391   if (Instruction *I = dyn_cast<Instruction>(V))
392     if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
393       // Push the negates through the add.
394       I->setOperand(0, NegateValue(I->getOperand(0), BI));
395       I->setOperand(1, NegateValue(I->getOperand(1), BI));
396
397       // We must move the add instruction here, because the neg instructions do
398       // not dominate the old add instruction in general.  By moving it, we are
399       // assured that the neg instructions we just inserted dominate the 
400       // instruction we are about to insert after them.
401       //
402       I->moveBefore(BI);
403       I->setName(I->getName()+".neg");
404       return I;
405     }
406   
407   // Okay, we need to materialize a negated version of V with an instruction.
408   // Scan the use lists of V to see if we have one already.
409   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
410     if (!BinaryOperator::isNeg(*UI)) continue;
411
412     // We found one!  Now we have to make sure that the definition dominates
413     // this use.  We do this by moving it to the entry block (if it is a
414     // non-instruction value) or right after the definition.  These negates will
415     // be zapped by reassociate later, so we don't need much finesse here.
416     BinaryOperator *TheNeg = cast<BinaryOperator>(*UI);
417     
418     BasicBlock::iterator InsertPt;
419     if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
420       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
421         InsertPt = II->getNormalDest()->begin();
422       } else {
423         InsertPt = InstInput;
424         ++InsertPt;
425       }
426       while (isa<PHINode>(InsertPt)) ++InsertPt;
427     } else {
428       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
429     }
430     TheNeg->moveBefore(InsertPt);
431     return TheNeg;
432   }
433
434   // Insert a 'neg' instruction that subtracts the value from zero to get the
435   // negation.
436   return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
437 }
438
439 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
440 /// X-Y into (X + -Y).
441 static bool ShouldBreakUpSubtract(Instruction *Sub) {
442   // If this is a negation, we can't split it up!
443   if (BinaryOperator::isNeg(Sub))
444     return false;
445   
446   // Don't bother to break this up unless either the LHS is an associable add or
447   // subtract or if this is only used by one.
448   if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
449       isReassociableOp(Sub->getOperand(0), Instruction::Sub))
450     return true;
451   if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
452       isReassociableOp(Sub->getOperand(1), Instruction::Sub))
453     return true;
454   if (Sub->hasOneUse() && 
455       (isReassociableOp(Sub->use_back(), Instruction::Add) ||
456        isReassociableOp(Sub->use_back(), Instruction::Sub)))
457     return true;
458     
459   return false;
460 }
461
462 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
463 /// only used by an add, transform this into (X+(0-Y)) to promote better
464 /// reassociation.
465 static Instruction *BreakUpSubtract(Instruction *Sub,
466                               DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
467   // Convert a subtract into an add and a neg instruction. This allows sub
468   // instructions to be commuted with other add instructions.
469   //
470   // Calculate the negative value of Operand 1 of the sub instruction,
471   // and set it as the RHS of the add instruction we just made.
472   //
473   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
474   Instruction *New =
475     BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
476   New->takeName(Sub);
477
478   // Everyone now refers to the add instruction.
479   ValueRankMap.erase(Sub);
480   Sub->replaceAllUsesWith(New);
481   Sub->eraseFromParent();
482
483   DEBUG(errs() << "Negated: " << *New << '\n');
484   return New;
485 }
486
487 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
488 /// by one, change this into a multiply by a constant to assist with further
489 /// reassociation.
490 static Instruction *ConvertShiftToMul(Instruction *Shl, 
491                               DenseMap<AssertingVH<>, unsigned> &ValueRankMap) {
492   // If an operand of this shift is a reassociable multiply, or if the shift
493   // is used by a reassociable multiply or add, turn into a multiply.
494   if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) ||
495       (Shl->hasOneUse() && 
496        (isReassociableOp(Shl->use_back(), Instruction::Mul) ||
497         isReassociableOp(Shl->use_back(), Instruction::Add)))) {
498     Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
499     MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
500     
501     Instruction *Mul =
502       BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
503     ValueRankMap.erase(Shl);
504     Mul->takeName(Shl);
505     Shl->replaceAllUsesWith(Mul);
506     Shl->eraseFromParent();
507     return Mul;
508   }
509   return 0;
510 }
511
512 // Scan backwards and forwards among values with the same rank as element i to
513 // see if X exists.  If X does not exist, return i.  This is useful when
514 // scanning for 'x' when we see '-x' because they both get the same rank.
515 static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
516                                   Value *X) {
517   unsigned XRank = Ops[i].Rank;
518   unsigned e = Ops.size();
519   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
520     if (Ops[j].Op == X)
521       return j;
522   // Scan backwards.
523   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
524     if (Ops[j].Op == X)
525       return j;
526   return i;
527 }
528
529 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
530 /// and returning the result.  Insert the tree before I.
531 static Value *EmitAddTreeOfValues(Instruction *I, SmallVectorImpl<Value*> &Ops){
532   if (Ops.size() == 1) return Ops.back();
533   
534   Value *V1 = Ops.back();
535   Ops.pop_back();
536   Value *V2 = EmitAddTreeOfValues(I, Ops);
537   return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
538 }
539
540 /// RemoveFactorFromExpression - If V is an expression tree that is a 
541 /// multiplication sequence, and if this sequence contains a multiply by Factor,
542 /// remove Factor from the tree and return the new tree.
543 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
544   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
545   if (!BO) return 0;
546   
547   SmallVector<ValueEntry, 8> Factors;
548   LinearizeExprTree(BO, Factors);
549
550   bool FoundFactor = false;
551   bool NeedsNegate = false;
552   for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
553     if (Factors[i].Op == Factor) {
554       FoundFactor = true;
555       Factors.erase(Factors.begin()+i);
556       break;
557     }
558     
559     // If this is a negative version of this factor, remove it.
560     if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
561       if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
562         if (FC1->getValue() == -FC2->getValue()) {
563           FoundFactor = NeedsNegate = true;
564           Factors.erase(Factors.begin()+i);
565           break;
566         }
567   }
568   
569   if (!FoundFactor) {
570     // Make sure to restore the operands to the expression tree.
571     RewriteExprTree(BO, Factors);
572     return 0;
573   }
574   
575   BasicBlock::iterator InsertPt = BO; ++InsertPt;
576   
577   // If this was just a single multiply, remove the multiply and return the only
578   // remaining operand.
579   if (Factors.size() == 1) {
580     ValueRankMap.erase(BO);
581     BO->eraseFromParent();
582     V = Factors[0].Op;
583   } else {
584     RewriteExprTree(BO, Factors);
585     V = BO;
586   }
587   
588   if (NeedsNegate)
589     V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
590   
591   return V;
592 }
593
594 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
595 /// add its operands as factors, otherwise add V to the list of factors.
596 static void FindSingleUseMultiplyFactors(Value *V,
597                                          SmallVectorImpl<Value*> &Factors) {
598   BinaryOperator *BO;
599   if ((!V->hasOneUse() && !V->use_empty()) ||
600       !(BO = dyn_cast<BinaryOperator>(V)) ||
601       BO->getOpcode() != Instruction::Mul) {
602     Factors.push_back(V);
603     return;
604   }
605   
606   // Otherwise, add the LHS and RHS to the list of factors.
607   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors);
608   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors);
609 }
610
611 /// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
612 /// instruction.  This optimizes based on identities.  If it can be reduced to
613 /// a single Value, it is returned, otherwise the Ops list is mutated as
614 /// necessary.
615 static Value *OptimizeAndOrXor(unsigned Opcode,
616                                SmallVectorImpl<ValueEntry> &Ops) {
617   // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
618   // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
619   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
620     // First, check for X and ~X in the operand list.
621     assert(i < Ops.size());
622     if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
623       Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
624       unsigned FoundX = FindInOperandList(Ops, i, X);
625       if (FoundX != i) {
626         if (Opcode == Instruction::And)   // ...&X&~X = 0
627           return Constant::getNullValue(X->getType());
628         
629         if (Opcode == Instruction::Or)    // ...|X|~X = -1
630           return Constant::getAllOnesValue(X->getType());
631       }
632     }
633     
634     // Next, check for duplicate pairs of values, which we assume are next to
635     // each other, due to our sorting criteria.
636     assert(i < Ops.size());
637     if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
638       if (Opcode == Instruction::And || Opcode == Instruction::Or) {
639         // Drop duplicate values for And and Or.
640         Ops.erase(Ops.begin()+i);
641         --i; --e;
642         ++NumAnnihil;
643         continue;
644       }
645       
646       // Drop pairs of values for Xor.
647       assert(Opcode == Instruction::Xor);
648       if (e == 2)
649         return Constant::getNullValue(Ops[0].Op->getType());
650       
651       // Y ^ X^X -> Y
652       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
653       i -= 1; e -= 2;
654       ++NumAnnihil;
655     }
656   }
657   return 0;
658 }
659
660 /// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
661 /// optimizes based on identities.  If it can be reduced to a single Value, it
662 /// is returned, otherwise the Ops list is mutated as necessary.
663 Value *Reassociate::OptimizeAdd(Instruction *I,
664                                 SmallVectorImpl<ValueEntry> &Ops) {
665   // Scan the operand lists looking for X and -X pairs.  If we find any, we
666   // can simplify the expression. X+-X == 0.  While we're at it, scan for any
667   // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
668   //
669   // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
670   //
671   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
672     Value *TheOp = Ops[i].Op;
673     // Check to see if we've seen this operand before.  If so, we factor all
674     // instances of the operand together.  Due to our sorting criteria, we know
675     // that these need to be next to each other in the vector.
676     if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
677       // Rescan the list, remove all instances of this operand from the expr.
678       unsigned NumFound = 0;
679       do {
680         Ops.erase(Ops.begin()+i);
681         ++NumFound;
682       } while (i != Ops.size() && Ops[i].Op == TheOp);
683       
684       DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
685       ++NumFactor;
686       
687       // Insert a new multiply.
688       Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
689       Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
690       
691       // Now that we have inserted a multiply, optimize it. This allows us to
692       // handle cases that require multiple factoring steps, such as this:
693       // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
694       Mul = ReassociateExpression(cast<BinaryOperator>(Mul));
695       
696       // If every add operand was a duplicate, return the multiply.
697       if (Ops.empty())
698         return Mul;
699       
700       // Otherwise, we had some input that didn't have the dupe, such as
701       // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
702       // things being added by this operation.
703       Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
704       
705       --i;
706       e = Ops.size();
707       continue;
708     }
709     
710     // Check for X and -X in the operand list.
711     if (!BinaryOperator::isNeg(TheOp))
712       continue;
713     
714     Value *X = BinaryOperator::getNegArgument(TheOp);
715     unsigned FoundX = FindInOperandList(Ops, i, X);
716     if (FoundX == i)
717       continue;
718     
719     // Remove X and -X from the operand list.
720     if (Ops.size() == 2)
721       return Constant::getNullValue(X->getType());
722     
723     Ops.erase(Ops.begin()+i);
724     if (i < FoundX)
725       --FoundX;
726     else
727       --i;   // Need to back up an extra one.
728     Ops.erase(Ops.begin()+FoundX);
729     ++NumAnnihil;
730     --i;     // Revisit element.
731     e -= 2;  // Removed two elements.
732   }
733   
734   // Scan the operand list, checking to see if there are any common factors
735   // between operands.  Consider something like A*A+A*B*C+D.  We would like to
736   // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
737   // To efficiently find this, we count the number of times a factor occurs
738   // for any ADD operands that are MULs.
739   DenseMap<Value*, unsigned> FactorOccurrences;
740   
741   // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
742   // where they are actually the same multiply.
743   unsigned MaxOcc = 0;
744   Value *MaxOccVal = 0;
745   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
746     BinaryOperator *BOp = dyn_cast<BinaryOperator>(Ops[i].Op);
747     if (BOp == 0 || BOp->getOpcode() != Instruction::Mul || !BOp->use_empty())
748       continue;
749     
750     // Compute all of the factors of this added value.
751     SmallVector<Value*, 8> Factors;
752     FindSingleUseMultiplyFactors(BOp, Factors);
753     assert(Factors.size() > 1 && "Bad linearize!");
754     
755     // Add one to FactorOccurrences for each unique factor in this op.
756     SmallPtrSet<Value*, 8> Duplicates;
757     for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
758       Value *Factor = Factors[i];
759       if (!Duplicates.insert(Factor)) continue;
760       
761       unsigned Occ = ++FactorOccurrences[Factor];
762       if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
763       
764       // If Factor is a negative constant, add the negated value as a factor
765       // because we can percolate the negate out.  Watch for minint, which
766       // cannot be positivified.
767       if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
768         if (CI->getValue().isNegative() && !CI->getValue().isMinSignedValue()) {
769           Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
770           assert(!Duplicates.count(Factor) &&
771                  "Shouldn't have two constant factors, missed a canonicalize");
772           
773           unsigned Occ = ++FactorOccurrences[Factor];
774           if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
775         }
776     }
777   }
778   
779   // If any factor occurred more than one time, we can pull it out.
780   if (MaxOcc > 1) {
781     DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
782     ++NumFactor;
783
784     // Create a new instruction that uses the MaxOccVal twice.  If we don't do
785     // this, we could otherwise run into situations where removing a factor
786     // from an expression will drop a use of maxocc, and this can cause 
787     // RemoveFactorFromExpression on successive values to behave differently.
788     Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
789     SmallVector<Value*, 4> NewMulOps;
790     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
791       if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
792         NewMulOps.push_back(V);
793         Ops.erase(Ops.begin()+i);
794         --i; --e;
795       }
796     }
797     
798     // No need for extra uses anymore.
799     delete DummyInst;
800     
801     unsigned NumAddedValues = NewMulOps.size();
802     Value *V = EmitAddTreeOfValues(I, NewMulOps);
803     
804     // Now that we have inserted the add tree, optimize it. This allows us to
805     // handle cases that require multiple factoring steps, such as this:
806     // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
807     assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
808     V = ReassociateExpression(cast<BinaryOperator>(V));
809
810     // Create the multiply.
811     Value *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
812
813     // Rerun associate on the multiply in case the inner expression turned into
814     // a multiply.  We want to make sure that we keep things in canonical form.
815     V2 = ReassociateExpression(cast<BinaryOperator>(V2));
816     
817     // If every add operand included the factor (e.g. "A*B + A*C"), then the
818     // entire result expression is just the multiply "A*(B+C)".
819     if (Ops.empty())
820       return V2;
821     
822     // Otherwise, we had some input that didn't have the factor, such as
823     // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
824     // things being added by this operation.
825     Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
826   }
827   
828   return 0;
829 }
830
831 Value *Reassociate::OptimizeExpression(BinaryOperator *I,
832                                        SmallVectorImpl<ValueEntry> &Ops) {
833   // Now that we have the linearized expression tree, try to optimize it.
834   // Start by folding any constants that we found.
835   bool IterateOptimization = false;
836   if (Ops.size() == 1) return Ops[0].Op;
837
838   unsigned Opcode = I->getOpcode();
839   
840   if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
841     if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
842       Ops.pop_back();
843       Ops.back().Op = ConstantExpr::get(Opcode, V1, V2);
844       return OptimizeExpression(I, Ops);
845     }
846
847   // Check for destructive annihilation due to a constant being used.
848   if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Ops.back().Op))
849     switch (Opcode) {
850     default: break;
851     case Instruction::And:
852       if (CstVal->isZero())                  // X & 0 -> 0
853         return CstVal;
854       if (CstVal->isAllOnesValue())          // X & -1 -> X
855         Ops.pop_back();
856       break;
857     case Instruction::Mul:
858       if (CstVal->isZero()) {                // X * 0 -> 0
859         ++NumAnnihil;
860         return CstVal;
861       }
862         
863       if (cast<ConstantInt>(CstVal)->isOne())
864         Ops.pop_back();                      // X * 1 -> X
865       break;
866     case Instruction::Or:
867       if (CstVal->isAllOnesValue())          // X | -1 -> -1
868         return CstVal;
869       // FALLTHROUGH!
870     case Instruction::Add:
871     case Instruction::Xor:
872       if (CstVal->isZero())                  // X [|^+] 0 -> X
873         Ops.pop_back();
874       break;
875     }
876   if (Ops.size() == 1) return Ops[0].Op;
877
878   // Handle destructive annihilation due to identities between elements in the
879   // argument list here.
880   switch (Opcode) {
881   default: break;
882   case Instruction::And:
883   case Instruction::Or:
884   case Instruction::Xor: {
885     unsigned NumOps = Ops.size();
886     if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
887       return Result;
888     IterateOptimization |= Ops.size() != NumOps;
889     break;
890   }
891
892   case Instruction::Add: {
893     unsigned NumOps = Ops.size();
894     if (Value *Result = OptimizeAdd(I, Ops))
895       return Result;
896     IterateOptimization |= Ops.size() != NumOps;
897   }
898
899     break;
900   //case Instruction::Mul:
901   }
902
903   if (IterateOptimization)
904     return OptimizeExpression(I, Ops);
905   return 0;
906 }
907
908
909 /// ReassociateBB - Inspect all of the instructions in this basic block,
910 /// reassociating them as we go.
911 void Reassociate::ReassociateBB(BasicBlock *BB) {
912   for (BasicBlock::iterator BBI = BB->begin(); BBI != BB->end(); ) {
913     Instruction *BI = BBI++;
914     if (BI->getOpcode() == Instruction::Shl &&
915         isa<ConstantInt>(BI->getOperand(1)))
916       if (Instruction *NI = ConvertShiftToMul(BI, ValueRankMap)) {
917         MadeChange = true;
918         BI = NI;
919       }
920
921     // Reject cases where it is pointless to do this.
922     if (!isa<BinaryOperator>(BI) || BI->getType()->isFloatingPoint() || 
923         isa<VectorType>(BI->getType()))
924       continue;  // Floating point ops are not associative.
925
926     // If this is a subtract instruction which is not already in negate form,
927     // see if we can convert it to X+-Y.
928     if (BI->getOpcode() == Instruction::Sub) {
929       if (ShouldBreakUpSubtract(BI)) {
930         BI = BreakUpSubtract(BI, ValueRankMap);
931         MadeChange = true;
932       } else if (BinaryOperator::isNeg(BI)) {
933         // Otherwise, this is a negation.  See if the operand is a multiply tree
934         // and if this is not an inner node of a multiply tree.
935         if (isReassociableOp(BI->getOperand(1), Instruction::Mul) &&
936             (!BI->hasOneUse() ||
937              !isReassociableOp(BI->use_back(), Instruction::Mul))) {
938           BI = LowerNegateToMultiply(BI, ValueRankMap);
939           MadeChange = true;
940         }
941       }
942     }
943
944     // If this instruction is a commutative binary operator, process it.
945     if (!BI->isAssociative()) continue;
946     BinaryOperator *I = cast<BinaryOperator>(BI);
947
948     // If this is an interior node of a reassociable tree, ignore it until we
949     // get to the root of the tree, to avoid N^2 analysis.
950     if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
951       continue;
952
953     // If this is an add tree that is used by a sub instruction, ignore it 
954     // until we process the subtract.
955     if (I->hasOneUse() && I->getOpcode() == Instruction::Add &&
956         cast<Instruction>(I->use_back())->getOpcode() == Instruction::Sub)
957       continue;
958
959     ReassociateExpression(I);
960   }
961 }
962
963 Value *Reassociate::ReassociateExpression(BinaryOperator *I) {
964   
965   // First, walk the expression tree, linearizing the tree, collecting the
966   // operand information.
967   SmallVector<ValueEntry, 8> Ops;
968   LinearizeExprTree(I, Ops);
969   
970   DEBUG(errs() << "RAIn:\t"; PrintOps(I, Ops); errs() << '\n');
971   
972   // Now that we have linearized the tree to a list and have gathered all of
973   // the operands and their ranks, sort the operands by their rank.  Use a
974   // stable_sort so that values with equal ranks will have their relative
975   // positions maintained (and so the compiler is deterministic).  Note that
976   // this sorts so that the highest ranking values end up at the beginning of
977   // the vector.
978   std::stable_sort(Ops.begin(), Ops.end());
979   
980   // OptimizeExpression - Now that we have the expression tree in a convenient
981   // sorted form, optimize it globally if possible.
982   if (Value *V = OptimizeExpression(I, Ops)) {
983     // This expression tree simplified to something that isn't a tree,
984     // eliminate it.
985     DEBUG(errs() << "Reassoc to scalar: " << *V << '\n');
986     I->replaceAllUsesWith(V);
987     RemoveDeadBinaryOp(I);
988     ++NumAnnihil;
989     return V;
990   }
991   
992   // We want to sink immediates as deeply as possible except in the case where
993   // this is a multiply tree used only by an add, and the immediate is a -1.
994   // In this case we reassociate to put the negation on the outside so that we
995   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
996   if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
997       cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
998       isa<ConstantInt>(Ops.back().Op) &&
999       cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
1000     ValueEntry Tmp = Ops.pop_back_val();
1001     Ops.insert(Ops.begin(), Tmp);
1002   }
1003   
1004   DEBUG(errs() << "RAOut:\t"; PrintOps(I, Ops); errs() << '\n');
1005   
1006   if (Ops.size() == 1) {
1007     // This expression tree simplified to something that isn't a tree,
1008     // eliminate it.
1009     I->replaceAllUsesWith(Ops[0].Op);
1010     RemoveDeadBinaryOp(I);
1011     return Ops[0].Op;
1012   }
1013   
1014   // Now that we ordered and optimized the expressions, splat them back into
1015   // the expression tree, removing any unneeded nodes.
1016   RewriteExprTree(I, Ops);
1017   return I;
1018 }
1019
1020
1021 bool Reassociate::runOnFunction(Function &F) {
1022   // Recalculate the rank map for F
1023   BuildRankMap(F);
1024
1025   MadeChange = false;
1026   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1027     ReassociateBB(FI);
1028
1029   // We are done with the rank map.
1030   RankMap.clear();
1031   ValueRankMap.clear();
1032   return MadeChange;
1033 }
1034