This change is to fix rdar://12571717 which is about assertion in Reassociate pass.
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1
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/Transforms/Utils/Local.h"
26 #include "llvm/Constants.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Function.h"
29 #include "llvm/IRBuilder.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/IntrinsicInst.h"
32 #include "llvm/Pass.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/PostOrderIterator.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Assembly/Writer.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <deque>
45 #include <set>
46 using namespace llvm;
47
48 STATISTIC(NumChanged, "Number of insts reassociated");
49 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
50 STATISTIC(NumFactor , "Number of multiplies factored");
51
52 namespace {
53   struct ValueEntry {
54     unsigned Rank;
55     Value *Op;
56     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
57   };
58   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
59     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
60   }
61 }
62
63 #ifndef NDEBUG
64 /// PrintOps - Print out the expression identified in the Ops list.
65 ///
66 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
67   Module *M = I->getParent()->getParent()->getParent();
68   dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
69        << *Ops[0].Op->getType() << '\t';
70   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
71     dbgs() << "[ ";
72     WriteAsOperand(dbgs(), Ops[i].Op, false, M);
73     dbgs() << ", #" << Ops[i].Rank << "] ";
74   }
75 }
76 #endif
77
78 namespace {
79   /// \brief Utility class representing a base and exponent pair which form one
80   /// factor of some product.
81   struct Factor {
82     Value *Base;
83     unsigned Power;
84
85     Factor(Value *Base, unsigned Power) : Base(Base), Power(Power) {}
86
87     /// \brief Sort factors by their Base.
88     struct BaseSorter {
89       bool operator()(const Factor &LHS, const Factor &RHS) {
90         return LHS.Base < RHS.Base;
91       }
92     };
93
94     /// \brief Compare factors for equal bases.
95     struct BaseEqual {
96       bool operator()(const Factor &LHS, const Factor &RHS) {
97         return LHS.Base == RHS.Base;
98       }
99     };
100
101     /// \brief Sort factors in descending order by their power.
102     struct PowerDescendingSorter {
103       bool operator()(const Factor &LHS, const Factor &RHS) {
104         return LHS.Power > RHS.Power;
105       }
106     };
107
108     /// \brief Compare factors for equal powers.
109     struct PowerEqual {
110       bool operator()(const Factor &LHS, const Factor &RHS) {
111         return LHS.Power == RHS.Power;
112       }
113     };
114   };
115 }
116
117 namespace {
118
119   class Reassociate;
120
121   class isInstDeadFunc {
122   public:
123     bool operator() (Instruction* I) {
124       return isInstructionTriviallyDead(I);
125     }
126   };
127   
128   class RmInstCallBackFunc {
129     Reassociate *reassoc_;
130   public:
131     RmInstCallBackFunc(Reassociate* ra): reassoc_(ra) {}
132     inline void operator() (Instruction*);
133   };
134
135   // The worklist has following traits:
136   //  - it is pretty much a dequeue.
137   //  - has "set" semantic, meaning all elements in the worklist are distinct.
138   //  - efficient in-place element removal (by replacing the element with
139   //    invalid value 0).
140   //
141   class RedoWorklist {
142   public:
143     typedef AssertingVH<Instruction> value_type;
144     typedef std::set<value_type> set_type;
145     typedef std::deque<value_type> deque_type;
146     // caller cannot modify element via iterator, hence constant.
147     typedef deque_type::const_iterator iterator;
148     typedef deque_type::const_iterator const_iterator;
149     typedef deque_type::size_type size_type;
150   
151     RedoWorklist() {}
152   
153     bool empty() const {
154       return deque_.empty();
155     }
156   
157     size_type size() const {
158       return deque_.size();
159     }
160
161     // return true iff X is in the worklist
162     bool found(const value_type &X) {
163       return set_.find(X) != set_.end();
164     }
165   
166     iterator begin() {
167       return deque_.begin();
168     }
169   
170     const_iterator begin() const {
171       return deque_.begin();
172     }
173   
174     iterator end() {
175       return deque_.end();
176     }
177   
178     const_iterator end() const {
179       return deque_.end();
180     }
181   
182     const value_type &back() const {
183       assert(!empty() && "worklist is empty");
184       return deque_.back();
185     }
186   
187     // If element X is already in the worklist, do nothing but return false;
188     // otherwise, append X to the worklist and return true.
189     //
190     bool push_back(const value_type &X) {
191       bool result = set_.insert(X).second;
192       if (result)
193         deque_.push_back(X);
194       return result;
195     }
196   
197     // insert() is the alias of push_back()
198     bool insert(const value_type &X) {
199       return push_back(X);
200     }
201
202     void clear() {
203       set_.clear();
204       deque_.clear();
205     }
206   
207     void pop_back() {
208       assert(!empty() && "worklist is empty");
209       set_.erase(back());
210       deque_.pop_back();
211     }
212     
213     value_type pop_back_val() {
214       value_type Ret = back();
215       pop_back();
216       return Ret;
217     }
218
219     const value_type &front() const {
220       assert(!empty() && "worklist is empty");
221       return deque_.front();
222     }
223
224     void pop_front() {
225       assert(!empty() && "worklist is empty");
226       set_.erase(front());
227       deque_.pop_front();
228     }
229     
230     value_type pop_front_val() {
231       value_type Ret = front();
232       pop_front();
233       return Ret;
234     }
235
236     // Remove an element from the worklist. Return true iff the element was 
237     // in the worklist.
238     bool remove(const value_type& X);
239
240     template <typename pred, typename call_back_func>
241     int inplace_remove(pred p, call_back_func cb);
242
243     template <typename pred, typename call_back_func>
244     int inplace_rremove(pred p, call_back_func cb);
245
246     void append(RedoWorklist&);
247
248   private:
249     set_type set_;
250     deque_type deque_;
251   };
252
253   class Reassociate : public FunctionPass {
254     friend class RmInstCallBackFunc;
255
256     DenseMap<BasicBlock*, unsigned> RankMap;
257     DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
258     RedoWorklist RedoInsts;
259     RedoWorklist TmpRedoInsts;
260     bool MadeChange;
261   public:
262     static char ID; // Pass identification, replacement for typeid
263     Reassociate() : FunctionPass(ID) {
264       initializeReassociatePass(*PassRegistry::getPassRegistry());
265     }
266
267     bool runOnFunction(Function &F);
268
269     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
270       AU.setPreservesCFG();
271     }
272   private:
273     void BuildRankMap(Function &F);
274     unsigned getRank(Value *V);
275     void ReassociateExpression(BinaryOperator *I);
276     void RewriteExprTree(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
277     Value *OptimizeExpression(BinaryOperator *I,
278                               SmallVectorImpl<ValueEntry> &Ops);
279     Value *OptimizeAdd(Instruction *I, SmallVectorImpl<ValueEntry> &Ops);
280     bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
281                                 SmallVectorImpl<Factor> &Factors);
282     Value *buildMinimalMultiplyDAG(IRBuilder<> &Builder,
283                                    SmallVectorImpl<Factor> &Factors);
284     void removeNegFromMulOps(SmallVectorImpl<ValueEntry> &Ops);
285     Value *OptimizeMul(BinaryOperator *I, SmallVectorImpl<ValueEntry> &Ops);
286     Value *RemoveFactorFromExpression(Value *V, Value *Factor);
287     void EraseInst(Instruction *I);
288     void EraseInstCallBack(Instruction *I);
289     void EraseAllDeadInst();
290     void OptimizeInst(Instruction *I);
291   };
292 }
293
294 char Reassociate::ID = 0;
295 INITIALIZE_PASS(Reassociate, "reassociate",
296                 "Reassociate expressions", false, false)
297
298 // Public interface to the Reassociate pass
299 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
300
301 /// isReassociableOp - Return true if V is an instruction of the specified
302 /// opcode and if it only has one use.
303 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
304   if (V->hasOneUse() && isa<Instruction>(V) &&
305       cast<Instruction>(V)->getOpcode() == Opcode)
306     return cast<BinaryOperator>(V);
307   return 0;
308 }
309
310 static bool isUnmovableInstruction(Instruction *I) {
311   if (I->getOpcode() == Instruction::PHI ||
312       I->getOpcode() == Instruction::LandingPad ||
313       I->getOpcode() == Instruction::Alloca ||
314       I->getOpcode() == Instruction::Load ||
315       I->getOpcode() == Instruction::Invoke ||
316       (I->getOpcode() == Instruction::Call &&
317        !isa<DbgInfoIntrinsic>(I)) ||
318       I->getOpcode() == Instruction::UDiv ||
319       I->getOpcode() == Instruction::SDiv ||
320       I->getOpcode() == Instruction::FDiv ||
321       I->getOpcode() == Instruction::URem ||
322       I->getOpcode() == Instruction::SRem ||
323       I->getOpcode() == Instruction::FRem)
324     return true;
325   return false;
326 }
327
328 inline void RmInstCallBackFunc::operator() (Instruction* I) {
329   reassoc_->EraseInstCallBack(I);
330 }
331
332 // Remove an item from the worklist. Return true iff the element was 
333 // in the worklist.
334 bool RedoWorklist::remove(const value_type& X) {
335   if (set_.erase(X)) {
336     deque_type::iterator I = std::find(deque_.begin(), deque_.end(), X);
337     assert(I != deque_.end() && "Can not find element");
338     deque_.erase(I);
339     return true;
340   }
341   return false;
342 }
343
344 // Forward go through each element e, calling p(e) to tell if e should be 
345 // removed or not; if p(e) = true, then e will be replaced with NULL to 
346 // indicate it is removed from the worklist, and functor cb will be 
347 // called for further processing on e. The functors should not invalidate
348 // the iterator by inserting or deleteing element to and from the worklist.
349 // 
350 // Returns the number of instruction being deleted.
351 template <typename pred, typename call_back_func>
352 int RedoWorklist::inplace_remove(pred p, call_back_func cb) {
353   int cnt = 0;
354   for (typename deque_type::iterator iter = deque_.begin(),
355        iter_e = deque_.end(); iter != iter_e; iter++) {
356     value_type &element = *iter;
357     if (p(element) && set_.erase(element)) {
358       Instruction* t = element;
359       element.~value_type();
360       new (&element) value_type(NULL);
361       cb(t);
362       cnt ++;
363     }
364   }
365   return cnt;
366 }
367
368 // inplace_rremove() is the same as inplace_remove() except that elements 
369 // are visited in backward order.
370 template <typename pred, typename call_back_func>
371 int RedoWorklist::inplace_rremove(pred p, call_back_func cb) {
372   int cnt = 0;
373   for (typename deque_type::reverse_iterator iter = deque_.rbegin(),
374        iter_e = deque_.rend(); iter != iter_e; iter++) {
375     value_type &element = *iter;
376     if (p(element) && set_.erase(element)) {
377       Instruction* t = element;
378       element.~value_type();
379       new (&element) value_type(NULL);
380       cb(t);
381       cnt ++;
382     }
383   }
384   return cnt;
385 }
386
387 void RedoWorklist::append(RedoWorklist& that) {
388   deque_type &that_deque = that.deque_;
389
390   while (!that_deque.empty()) {
391     push_back(that_deque.front());
392     that_deque.pop_front();
393   }
394   that.clear();
395 }
396
397 void Reassociate::BuildRankMap(Function &F) {
398   unsigned i = 2;
399
400   // Assign distinct ranks to function arguments
401   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
402     ValueRankMap[&*I] = ++i;
403
404   ReversePostOrderTraversal<Function*> RPOT(&F);
405   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
406          E = RPOT.end(); I != E; ++I) {
407     BasicBlock *BB = *I;
408     unsigned BBRank = RankMap[BB] = ++i << 16;
409
410     // Walk the basic block, adding precomputed ranks for any instructions that
411     // we cannot move.  This ensures that the ranks for these instructions are
412     // all different in the block.
413     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
414       if (isUnmovableInstruction(I))
415         ValueRankMap[&*I] = ++BBRank;
416   }
417 }
418
419 unsigned Reassociate::getRank(Value *V) {
420   Instruction *I = dyn_cast<Instruction>(V);
421   if (I == 0) {
422     if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument.
423     return 0;  // Otherwise it's a global or constant, rank 0.
424   }
425
426   if (unsigned Rank = ValueRankMap[I])
427     return Rank;    // Rank already known?
428
429   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
430   // we can reassociate expressions for code motion!  Since we do not recurse
431   // for PHI nodes, we cannot have infinite recursion here, because there
432   // cannot be loops in the value graph that do not go through PHI nodes.
433   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
434   for (unsigned i = 0, e = I->getNumOperands();
435        i != e && Rank != MaxRank; ++i)
436     Rank = std::max(Rank, getRank(I->getOperand(i)));
437
438   // If this is a not or neg instruction, do not count it for rank.  This
439   // assures us that X and ~X will have the same rank.
440   if (!I->getType()->isIntegerTy() ||
441       (!BinaryOperator::isNot(I) && !BinaryOperator::isNeg(I)))
442     ++Rank;
443
444   //DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = "
445   //     << Rank << "\n");
446
447   return ValueRankMap[I] = Rank;
448 }
449
450 /// LowerNegateToMultiply - Replace 0-X with X*-1.
451 ///
452 static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
453   Constant *Cst = Constant::getAllOnesValue(Neg->getType());
454
455   BinaryOperator *Res =
456     BinaryOperator::CreateMul(Neg->getOperand(1), Cst, "",Neg);
457   Neg->setOperand(1, Constant::getNullValue(Neg->getType())); // Drop use of op.
458   Res->takeName(Neg);
459   Neg->replaceAllUsesWith(Res);
460   Res->setDebugLoc(Neg->getDebugLoc());
461   return Res;
462 }
463
464 /// CarmichaelShift - Returns k such that lambda(2^Bitwidth) = 2^k, where lambda
465 /// is the Carmichael function. This means that x^(2^k) === 1 mod 2^Bitwidth for
466 /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
467 /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
468 /// even x in Bitwidth-bit arithmetic.
469 static unsigned CarmichaelShift(unsigned Bitwidth) {
470   if (Bitwidth < 3)
471     return Bitwidth - 1;
472   return Bitwidth - 2;
473 }
474
475 /// IncorporateWeight - Add the extra weight 'RHS' to the existing weight 'LHS',
476 /// reducing the combined weight using any special properties of the operation.
477 /// The existing weight LHS represents the computation X op X op ... op X where
478 /// X occurs LHS times.  The combined weight represents  X op X op ... op X with
479 /// X occurring LHS + RHS times.  If op is "Xor" for example then the combined
480 /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
481 /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
482 static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
483   // If we were working with infinite precision arithmetic then the combined
484   // weight would be LHS + RHS.  But we are using finite precision arithmetic,
485   // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
486   // for nilpotent operations and addition, but not for idempotent operations
487   // and multiplication), so it is important to correctly reduce the combined
488   // weight back into range if wrapping would be wrong.
489
490   // If RHS is zero then the weight didn't change.
491   if (RHS.isMinValue())
492     return;
493   // If LHS is zero then the combined weight is RHS.
494   if (LHS.isMinValue()) {
495     LHS = RHS;
496     return;
497   }
498   // From this point on we know that neither LHS nor RHS is zero.
499
500   if (Instruction::isIdempotent(Opcode)) {
501     // Idempotent means X op X === X, so any non-zero weight is equivalent to a
502     // weight of 1.  Keeping weights at zero or one also means that wrapping is
503     // not a problem.
504     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
505     return; // Return a weight of 1.
506   }
507   if (Instruction::isNilpotent(Opcode)) {
508     // Nilpotent means X op X === 0, so reduce weights modulo 2.
509     assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
510     LHS = 0; // 1 + 1 === 0 modulo 2.
511     return;
512   }
513   if (Opcode == Instruction::Add) {
514     // TODO: Reduce the weight by exploiting nsw/nuw?
515     LHS += RHS;
516     return;
517   }
518
519   assert(Opcode == Instruction::Mul && "Unknown associative operation!");
520   unsigned Bitwidth = LHS.getBitWidth();
521   // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
522   // can be replaced with W-CM.  That's because x^W=x^(W-CM) for every Bitwidth
523   // bit number x, since either x is odd in which case x^CM = 1, or x is even in
524   // which case both x^W and x^(W - CM) are zero.  By subtracting off multiples
525   // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
526   // which by a happy accident means that they can always be represented using
527   // Bitwidth bits.
528   // TODO: Reduce the weight by exploiting nsw/nuw?  (Could do much better than
529   // the Carmichael number).
530   if (Bitwidth > 3) {
531     /// CM - The value of Carmichael's lambda function.
532     APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
533     // Any weight W >= Threshold can be replaced with W - CM.
534     APInt Threshold = CM + Bitwidth;
535     assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
536     // For Bitwidth 4 or more the following sum does not overflow.
537     LHS += RHS;
538     while (LHS.uge(Threshold))
539       LHS -= CM;
540   } else {
541     // To avoid problems with overflow do everything the same as above but using
542     // a larger type.
543     unsigned CM = 1U << CarmichaelShift(Bitwidth);
544     unsigned Threshold = CM + Bitwidth;
545     assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
546            "Weights not reduced!");
547     unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
548     while (Total >= Threshold)
549       Total -= CM;
550     LHS = Total;
551   }
552 }
553
554 /// EvaluateRepeatedConstant - Compute C op C op ... op C where the constant C
555 /// is repeated Weight times.
556 static Constant *EvaluateRepeatedConstant(unsigned Opcode, Constant *C,
557                                           APInt Weight) {
558   // For addition the result can be efficiently computed as the product of the
559   // constant and the weight.
560   if (Opcode == Instruction::Add)
561     return ConstantExpr::getMul(C, ConstantInt::get(C->getContext(), Weight));
562
563   // The weight might be huge, so compute by repeated squaring to ensure that
564   // compile time is proportional to the logarithm of the weight.
565   Constant *Result = 0;
566   Constant *Power = C; // Successively C, C op C, (C op C) op (C op C) etc.
567   // Visit the bits in Weight.
568   while (Weight != 0) {
569     // If the current bit in Weight is non-zero do Result = Result op Power.
570     if (Weight[0])
571       Result = Result ? ConstantExpr::get(Opcode, Result, Power) : Power;
572     // Move on to the next bit if any more are non-zero.
573     Weight = Weight.lshr(1);
574     if (Weight.isMinValue())
575       break;
576     // Square the power.
577     Power = ConstantExpr::get(Opcode, Power, Power);
578   }
579
580   assert(Result && "Only positive weights supported!");
581   return Result;
582 }
583
584 typedef std::pair<Value*, APInt> RepeatedValue;
585
586 /// LinearizeExprTree - Given an associative binary expression, return the leaf
587 /// nodes in Ops along with their weights (how many times the leaf occurs).  The
588 /// original expression is the same as
589 ///   (Ops[0].first op Ops[0].first op ... Ops[0].first)  <- Ops[0].second times
590 /// op
591 ///   (Ops[1].first op Ops[1].first op ... Ops[1].first)  <- Ops[1].second times
592 /// op
593 ///   ...
594 /// op
595 ///   (Ops[N].first op Ops[N].first op ... Ops[N].first)  <- Ops[N].second times
596 ///
597 /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct, and
598 /// they are all non-constant except possibly for the last one, which if it is
599 /// constant will have weight one (Ops[N].second === 1).
600 ///
601 /// This routine may modify the function, in which case it returns 'true'.  The
602 /// changes it makes may well be destructive, changing the value computed by 'I'
603 /// to something completely different.  Thus if the routine returns 'true' then
604 /// you MUST either replace I with a new expression computed from the Ops array,
605 /// or use RewriteExprTree to put the values back in.
606 ///
607 /// A leaf node is either not a binary operation of the same kind as the root
608 /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
609 /// opcode), or is the same kind of binary operator but has a use which either
610 /// does not belong to the expression, or does belong to the expression but is
611 /// a leaf node.  Every leaf node has at least one use that is a non-leaf node
612 /// of the expression, while for non-leaf nodes (except for the root 'I') every
613 /// use is a non-leaf node of the expression.
614 ///
615 /// For example:
616 ///           expression graph        node names
617 ///
618 ///                     +        |        I
619 ///                    / \       |
620 ///                   +   +      |      A,  B
621 ///                  / \ / \     |
622 ///                 *   +   *    |    C,  D,  E
623 ///                / \ / \ / \   |
624 ///                   +   *      |      F,  G
625 ///
626 /// The leaf nodes are C, E, F and G.  The Ops array will contain (maybe not in
627 /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
628 ///
629 /// The expression is maximal: if some instruction is a binary operator of the
630 /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
631 /// then the instruction also belongs to the expression, is not a leaf node of
632 /// it, and its operands also belong to the expression (but may be leaf nodes).
633 ///
634 /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
635 /// order to ensure that every non-root node in the expression has *exactly one*
636 /// use by a non-leaf node of the expression.  This destruction means that the
637 /// caller MUST either replace 'I' with a new expression or use something like
638 /// RewriteExprTree to put the values back in if the routine indicates that it
639 /// made a change by returning 'true'.
640 ///
641 /// In the above example either the right operand of A or the left operand of B
642 /// will be replaced by undef.  If it is B's operand then this gives:
643 ///
644 ///                     +        |        I
645 ///                    / \       |
646 ///                   +   +      |      A,  B - operand of B replaced with undef
647 ///                  / \   \     |
648 ///                 *   +   *    |    C,  D,  E
649 ///                / \ / \ / \   |
650 ///                   +   *      |      F,  G
651 ///
652 /// Note that such undef operands can only be reached by passing through 'I'.
653 /// For example, if you visit operands recursively starting from a leaf node
654 /// then you will never see such an undef operand unless you get back to 'I',
655 /// which requires passing through a phi node.
656 ///
657 /// Note that this routine may also mutate binary operators of the wrong type
658 /// that have all uses inside the expression (i.e. only used by non-leaf nodes
659 /// of the expression) if it can turn them into binary operators of the right
660 /// type and thus make the expression bigger.
661
662 static bool LinearizeExprTree(BinaryOperator *I,
663                               SmallVectorImpl<RepeatedValue> &Ops) {
664   DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
665   unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
666   unsigned Opcode = I->getOpcode();
667   assert(Instruction::isAssociative(Opcode) &&
668          Instruction::isCommutative(Opcode) &&
669          "Expected an associative and commutative operation!");
670   // If we see an absorbing element then the entire expression must be equal to
671   // it.  For example, if this is a multiplication expression and zero occurs as
672   // an operand somewhere in it then the result of the expression must be zero.
673   Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, I->getType());
674
675   // Visit all operands of the expression, keeping track of their weight (the
676   // number of paths from the expression root to the operand, or if you like
677   // the number of times that operand occurs in the linearized expression).
678   // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
679   // while A has weight two.
680
681   // Worklist of non-leaf nodes (their operands are in the expression too) along
682   // with their weights, representing a certain number of paths to the operator.
683   // If an operator occurs in the worklist multiple times then we found multiple
684   // ways to get to it.
685   SmallVector<std::pair<BinaryOperator*, APInt>, 8> Worklist; // (Op, Weight)
686   Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
687   bool MadeChange = false;
688
689   // Leaves of the expression are values that either aren't the right kind of
690   // operation (eg: a constant, or a multiply in an add tree), or are, but have
691   // some uses that are not inside the expression.  For example, in I = X + X,
692   // X = A + B, the value X has two uses (by I) that are in the expression.  If
693   // X has any other uses, for example in a return instruction, then we consider
694   // X to be a leaf, and won't analyze it further.  When we first visit a value,
695   // if it has more than one use then at first we conservatively consider it to
696   // be a leaf.  Later, as the expression is explored, we may discover some more
697   // uses of the value from inside the expression.  If all uses turn out to be
698   // from within the expression (and the value is a binary operator of the right
699   // kind) then the value is no longer considered to be a leaf, and its operands
700   // are explored.
701
702   // Leaves - Keeps track of the set of putative leaves as well as the number of
703   // paths to each leaf seen so far.
704   typedef DenseMap<Value*, APInt> LeafMap;
705   LeafMap Leaves; // Leaf -> Total weight so far.
706   SmallVector<Value*, 8> LeafOrder; // Ensure deterministic leaf output order.
707
708 #ifndef NDEBUG
709   SmallPtrSet<Value*, 8> Visited; // For sanity checking the iteration scheme.
710 #endif
711   while (!Worklist.empty()) {
712     std::pair<BinaryOperator*, APInt> P = Worklist.pop_back_val();
713     I = P.first; // We examine the operands of this binary operator.
714
715     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { // Visit operands.
716       Value *Op = I->getOperand(OpIdx);
717       APInt Weight = P.second; // Number of paths to this operand.
718       DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
719       assert(!Op->use_empty() && "No uses, so how did we get to it?!");
720
721       // If the expression contains an absorbing element then there is no need
722       // to analyze it further: it must evaluate to the absorbing element.
723       if (Op == Absorber && !Weight.isMinValue()) {
724         Ops.push_back(std::make_pair(Absorber, APInt(Bitwidth, 1)));
725         return MadeChange;
726       }
727
728       // If this is a binary operation of the right kind with only one use then
729       // add its operands to the expression.
730       if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
731         assert(Visited.insert(Op) && "Not first visit!");
732         DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
733         Worklist.push_back(std::make_pair(BO, Weight));
734         continue;
735       }
736
737       // Appears to be a leaf.  Is the operand already in the set of leaves?
738       LeafMap::iterator It = Leaves.find(Op);
739       if (It == Leaves.end()) {
740         // Not in the leaf map.  Must be the first time we saw this operand.
741         assert(Visited.insert(Op) && "Not first visit!");
742         if (!Op->hasOneUse()) {
743           // This value has uses not accounted for by the expression, so it is
744           // not safe to modify.  Mark it as being a leaf.
745           DEBUG(dbgs() << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
746           LeafOrder.push_back(Op);
747           Leaves[Op] = Weight;
748           continue;
749         }
750         // No uses outside the expression, try morphing it.
751       } else if (It != Leaves.end()) {
752         // Already in the leaf map.
753         assert(Visited.count(Op) && "In leaf map but not visited!");
754
755         // Update the number of paths to the leaf.
756         IncorporateWeight(It->second, Weight, Opcode);
757
758 #if 0   // TODO: Re-enable once PR13021 is fixed.
759         // The leaf already has one use from inside the expression.  As we want
760         // exactly one such use, drop this new use of the leaf.
761         assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
762         I->setOperand(OpIdx, UndefValue::get(I->getType()));
763         MadeChange = true;
764
765         // If the leaf is a binary operation of the right kind and we now see
766         // that its multiple original uses were in fact all by nodes belonging
767         // to the expression, then no longer consider it to be a leaf and add
768         // its operands to the expression.
769         if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
770           DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
771           Worklist.push_back(std::make_pair(BO, It->second));
772           Leaves.erase(It);
773           continue;
774         }
775 #endif
776
777         // If we still have uses that are not accounted for by the expression
778         // then it is not safe to modify the value.
779         if (!Op->hasOneUse())
780           continue;
781
782         // No uses outside the expression, try morphing it.
783         Weight = It->second;
784         Leaves.erase(It); // Since the value may be morphed below.
785       }
786
787       // At this point we have a value which, first of all, is not a binary
788       // expression of the right kind, and secondly, is only used inside the
789       // expression.  This means that it can safely be modified.  See if we
790       // can usefully morph it into an expression of the right kind.
791       assert((!isa<Instruction>(Op) ||
792               cast<Instruction>(Op)->getOpcode() != Opcode) &&
793              "Should have been handled above!");
794       assert(Op->hasOneUse() && "Has uses outside the expression tree!");
795
796       // If this is a multiply expression, turn any internal negations into
797       // multiplies by -1 so they can be reassociated.
798       BinaryOperator *BO = dyn_cast<BinaryOperator>(Op);
799       if (Opcode == Instruction::Mul && BO && BinaryOperator::isNeg(BO)) {
800         DEBUG(dbgs() << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
801         BO = LowerNegateToMultiply(BO);
802         DEBUG(dbgs() << *BO << 'n');
803         Worklist.push_back(std::make_pair(BO, Weight));
804         MadeChange = true;
805         continue;
806       }
807
808       // Failed to morph into an expression of the right type.  This really is
809       // a leaf.
810       DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
811       assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
812       LeafOrder.push_back(Op);
813       Leaves[Op] = Weight;
814     }
815   }
816
817   // The leaves, repeated according to their weights, represent the linearized
818   // form of the expression.
819   Constant *Cst = 0; // Accumulate constants here.
820   for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
821     Value *V = LeafOrder[i];
822     LeafMap::iterator It = Leaves.find(V);
823     if (It == Leaves.end())
824       // Node initially thought to be a leaf wasn't.
825       continue;
826     assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
827     APInt Weight = It->second;
828     if (Weight.isMinValue())
829       // Leaf already output or weight reduction eliminated it.
830       continue;
831     // Ensure the leaf is only output once.
832     It->second = 0;
833     // Glob all constants together into Cst.
834     if (Constant *C = dyn_cast<Constant>(V)) {
835       C = EvaluateRepeatedConstant(Opcode, C, Weight);
836       Cst = Cst ? ConstantExpr::get(Opcode, Cst, C) : C;
837       continue;
838     }
839     // Add non-constant
840     Ops.push_back(std::make_pair(V, Weight));
841   }
842
843   // Add any constants back into Ops, all globbed together and reduced to having
844   // weight 1 for the convenience of users.
845   Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
846   if (Cst && Cst != Identity) {
847     // If combining multiple constants resulted in the absorber then the entire
848     // expression must evaluate to the absorber.
849     if (Cst == Absorber)
850       Ops.clear();
851     Ops.push_back(std::make_pair(Cst, APInt(Bitwidth, 1)));
852   }
853
854   // For nilpotent operations or addition there may be no operands, for example
855   // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
856   // in both cases the weight reduces to 0 causing the value to be skipped.
857   if (Ops.empty()) {
858     assert(Identity && "Associative operation without identity!");
859     Ops.push_back(std::make_pair(Identity, APInt(Bitwidth, 1)));
860   }
861
862   return MadeChange;
863 }
864
865 // RewriteExprTree - Now that the operands for this expression tree are
866 // linearized and optimized, emit them in-order.
867 void Reassociate::RewriteExprTree(BinaryOperator *I,
868                                   SmallVectorImpl<ValueEntry> &Ops) {
869   assert(Ops.size() > 1 && "Single values should be used directly!");
870
871   // Since our optimizations never increase the number of operations, the new
872   // expression can always be written by reusing the existing binary operators
873   // from the original expression tree, without creating any new instructions,
874   // though the rewritten expression may have a completely different topology.
875   // We take care to not change anything if the new expression will be the same
876   // as the original.  If more than trivial changes (like commuting operands)
877   // were made then we are obliged to clear out any optional subclass data like
878   // nsw flags.
879
880   /// NodesToRewrite - Nodes from the original expression available for writing
881   /// the new expression into.
882   SmallVector<BinaryOperator*, 8> NodesToRewrite;
883   unsigned Opcode = I->getOpcode();
884   BinaryOperator *Op = I;
885
886   // ExpressionChanged - Non-null if the rewritten expression differs from the
887   // original in some non-trivial way, requiring the clearing of optional flags.
888   // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
889   BinaryOperator *ExpressionChanged = 0;
890   for (unsigned i = 0; ; ++i) {
891     // The last operation (which comes earliest in the IR) is special as both
892     // operands will come from Ops, rather than just one with the other being
893     // a subexpression.
894     if (i+2 == Ops.size()) {
895       Value *NewLHS = Ops[i].Op;
896       Value *NewRHS = Ops[i+1].Op;
897       Value *OldLHS = Op->getOperand(0);
898       Value *OldRHS = Op->getOperand(1);
899
900       if (NewLHS == OldLHS && NewRHS == OldRHS)
901         // Nothing changed, leave it alone.
902         break;
903
904       if (NewLHS == OldRHS && NewRHS == OldLHS) {
905         // The order of the operands was reversed.  Swap them.
906         DEBUG(dbgs() << "RA: " << *Op << '\n');
907         Op->swapOperands();
908         DEBUG(dbgs() << "TO: " << *Op << '\n');
909         MadeChange = true;
910         ++NumChanged;
911         break;
912       }
913
914       // The new operation differs non-trivially from the original. Overwrite
915       // the old operands with the new ones.
916       DEBUG(dbgs() << "RA: " << *Op << '\n');
917       if (NewLHS != OldLHS) {
918         if (BinaryOperator *BO = isReassociableOp(OldLHS, Opcode))
919           NodesToRewrite.push_back(BO);
920         Op->setOperand(0, NewLHS);
921       }
922       if (NewRHS != OldRHS) {
923         if (BinaryOperator *BO = isReassociableOp(OldRHS, Opcode))
924           NodesToRewrite.push_back(BO);
925         Op->setOperand(1, NewRHS);
926       }
927       DEBUG(dbgs() << "TO: " << *Op << '\n');
928
929       ExpressionChanged = Op;
930       MadeChange = true;
931       ++NumChanged;
932
933       break;
934     }
935
936     // Not the last operation.  The left-hand side will be a sub-expression
937     // while the right-hand side will be the current element of Ops.
938     Value *NewRHS = Ops[i].Op;
939     if (NewRHS != Op->getOperand(1)) {
940       DEBUG(dbgs() << "RA: " << *Op << '\n');
941       if (NewRHS == Op->getOperand(0)) {
942         // The new right-hand side was already present as the left operand.  If
943         // we are lucky then swapping the operands will sort out both of them.
944         Op->swapOperands();
945       } else {
946         // Overwrite with the new right-hand side.
947         if (BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode))
948           NodesToRewrite.push_back(BO);
949         Op->setOperand(1, NewRHS);
950         ExpressionChanged = Op;
951       }
952       DEBUG(dbgs() << "TO: " << *Op << '\n');
953       MadeChange = true;
954       ++NumChanged;
955     }
956
957     // Now deal with the left-hand side.  If this is already an operation node
958     // from the original expression then just rewrite the rest of the expression
959     // into it.
960     if (BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode)) {
961       Op = BO;
962       continue;
963     }
964
965     // Otherwise, grab a spare node from the original expression and use that as
966     // the left-hand side.  If there are no nodes left then the optimizers made
967     // an expression with more nodes than the original!  This usually means that
968     // they did something stupid but it might mean that the problem was just too
969     // hard (finding the mimimal number of multiplications needed to realize a
970     // multiplication expression is NP-complete).  Whatever the reason, smart or
971     // stupid, create a new node if there are none left.
972     BinaryOperator *NewOp;
973     if (NodesToRewrite.empty()) {
974       Constant *Undef = UndefValue::get(I->getType());
975       NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
976                                      Undef, Undef, "", I);
977     } else {
978       NewOp = NodesToRewrite.pop_back_val();
979     }
980
981     DEBUG(dbgs() << "RA: " << *Op << '\n');
982     Op->setOperand(0, NewOp);
983     DEBUG(dbgs() << "TO: " << *Op << '\n');
984     ExpressionChanged = Op;
985     MadeChange = true;
986     ++NumChanged;
987     Op = NewOp;
988   }
989
990   // If the expression changed non-trivially then clear out all subclass data
991   // starting from the operator specified in ExpressionChanged, and compactify
992   // the operators to just before the expression root to guarantee that the
993   // expression tree is dominated by all of Ops.
994   if (ExpressionChanged)
995     do {
996       ExpressionChanged->clearSubclassOptionalData();
997       if (ExpressionChanged == I)
998         break;
999       ExpressionChanged->moveBefore(I);
1000       ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->use_begin());
1001     } while (1);
1002
1003   // Throw away any left over nodes from the original expression.
1004   for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
1005     RedoInsts.insert(NodesToRewrite[i]);
1006 }
1007
1008 /// NegateValue - Insert instructions before the instruction pointed to by BI,
1009 /// that computes the negative version of the value specified.  The negative
1010 /// version of the value is returned, and BI is left pointing at the instruction
1011 /// that should be processed next by the reassociation pass.
1012 static Value *NegateValue(Value *V, Instruction *BI) {
1013   if (Constant *C = dyn_cast<Constant>(V))
1014     return ConstantExpr::getNeg(C);
1015
1016   // We are trying to expose opportunity for reassociation.  One of the things
1017   // that we want to do to achieve this is to push a negation as deep into an
1018   // expression chain as possible, to expose the add instructions.  In practice,
1019   // this means that we turn this:
1020   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
1021   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
1022   // the constants.  We assume that instcombine will clean up the mess later if
1023   // we introduce tons of unnecessary negation instructions.
1024   //
1025   if (BinaryOperator *I = isReassociableOp(V, Instruction::Add)) {
1026     // Push the negates through the add.
1027     I->setOperand(0, NegateValue(I->getOperand(0), BI));
1028     I->setOperand(1, NegateValue(I->getOperand(1), BI));
1029
1030     // We must move the add instruction here, because the neg instructions do
1031     // not dominate the old add instruction in general.  By moving it, we are
1032     // assured that the neg instructions we just inserted dominate the
1033     // instruction we are about to insert after them.
1034     //
1035     I->moveBefore(BI);
1036     I->setName(I->getName()+".neg");
1037     return I;
1038   }
1039
1040   // Okay, we need to materialize a negated version of V with an instruction.
1041   // Scan the use lists of V to see if we have one already.
1042   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1043     User *U = *UI;
1044     if (!BinaryOperator::isNeg(U)) continue;
1045
1046     // We found one!  Now we have to make sure that the definition dominates
1047     // this use.  We do this by moving it to the entry block (if it is a
1048     // non-instruction value) or right after the definition.  These negates will
1049     // be zapped by reassociate later, so we don't need much finesse here.
1050     BinaryOperator *TheNeg = cast<BinaryOperator>(U);
1051
1052     // Verify that the negate is in this function, V might be a constant expr.
1053     if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
1054       continue;
1055
1056     BasicBlock::iterator InsertPt;
1057     if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
1058       if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
1059         InsertPt = II->getNormalDest()->begin();
1060       } else {
1061         InsertPt = InstInput;
1062         ++InsertPt;
1063       }
1064       while (isa<PHINode>(InsertPt)) ++InsertPt;
1065     } else {
1066       InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
1067     }
1068     TheNeg->moveBefore(InsertPt);
1069     return TheNeg;
1070   }
1071
1072   // Insert a 'neg' instruction that subtracts the value from zero to get the
1073   // negation.
1074   return BinaryOperator::CreateNeg(V, V->getName() + ".neg", BI);
1075 }
1076
1077 /// ShouldBreakUpSubtract - Return true if we should break up this subtract of
1078 /// X-Y into (X + -Y).
1079 static bool ShouldBreakUpSubtract(Instruction *Sub) {
1080   // If this is a negation, we can't split it up!
1081   if (BinaryOperator::isNeg(Sub))
1082     return false;
1083
1084   // Don't bother to break this up unless either the LHS is an associable add or
1085   // subtract or if this is only used by one.
1086   if (isReassociableOp(Sub->getOperand(0), Instruction::Add) ||
1087       isReassociableOp(Sub->getOperand(0), Instruction::Sub))
1088     return true;
1089   if (isReassociableOp(Sub->getOperand(1), Instruction::Add) ||
1090       isReassociableOp(Sub->getOperand(1), Instruction::Sub))
1091     return true;
1092   if (Sub->hasOneUse() &&
1093       (isReassociableOp(Sub->use_back(), Instruction::Add) ||
1094        isReassociableOp(Sub->use_back(), Instruction::Sub)))
1095     return true;
1096
1097   return false;
1098 }
1099
1100 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
1101 /// only used by an add, transform this into (X+(0-Y)) to promote better
1102 /// reassociation.
1103 static BinaryOperator *BreakUpSubtract(Instruction *Sub) {
1104   // Convert a subtract into an add and a neg instruction. This allows sub
1105   // instructions to be commuted with other add instructions.
1106   //
1107   // Calculate the negative value of Operand 1 of the sub instruction,
1108   // and set it as the RHS of the add instruction we just made.
1109   //
1110   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
1111   BinaryOperator *New =
1112     BinaryOperator::CreateAdd(Sub->getOperand(0), NegVal, "", Sub);
1113   Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
1114   Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
1115   New->takeName(Sub);
1116
1117   // Everyone now refers to the add instruction.
1118   Sub->replaceAllUsesWith(New);
1119   New->setDebugLoc(Sub->getDebugLoc());
1120
1121   DEBUG(dbgs() << "Negated: " << *New << '\n');
1122   return New;
1123 }
1124
1125 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
1126 /// by one, change this into a multiply by a constant to assist with further
1127 /// reassociation.
1128 static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
1129   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
1130   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
1131
1132   BinaryOperator *Mul =
1133     BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
1134   Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
1135   Mul->takeName(Shl);
1136   Shl->replaceAllUsesWith(Mul);
1137   Mul->setDebugLoc(Shl->getDebugLoc());
1138   return Mul;
1139 }
1140
1141 /// FindInOperandList - Scan backwards and forwards among values with the same
1142 /// rank as element i to see if X exists.  If X does not exist, return i.  This
1143 /// is useful when scanning for 'x' when we see '-x' because they both get the
1144 /// same rank.
1145 static unsigned FindInOperandList(SmallVectorImpl<ValueEntry> &Ops, unsigned i,
1146                                   Value *X) {
1147   unsigned XRank = Ops[i].Rank;
1148   unsigned e = Ops.size();
1149   for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j)
1150     if (Ops[j].Op == X)
1151       return j;
1152   // Scan backwards.
1153   for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j)
1154     if (Ops[j].Op == X)
1155       return j;
1156   return i;
1157 }
1158
1159 /// EmitAddTreeOfValues - Emit a tree of add instructions, summing Ops together
1160 /// and returning the result.  Insert the tree before I.
1161 static Value *EmitAddTreeOfValues(Instruction *I,
1162                                   SmallVectorImpl<WeakVH> &Ops){
1163   if (Ops.size() == 1) return Ops.back();
1164
1165   Value *V1 = Ops.back();
1166   Ops.pop_back();
1167   Value *V2 = EmitAddTreeOfValues(I, Ops);
1168   return BinaryOperator::CreateAdd(V2, V1, "tmp", I);
1169 }
1170
1171 /// RemoveFactorFromExpression - If V is an expression tree that is a
1172 /// multiplication sequence, and if this sequence contains a multiply by Factor,
1173 /// remove Factor from the tree and return the new tree.
1174 Value *Reassociate::RemoveFactorFromExpression(Value *V, Value *Factor) {
1175   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
1176   if (!BO) return 0;
1177
1178   SmallVector<RepeatedValue, 8> Tree;
1179   MadeChange |= LinearizeExprTree(BO, Tree);
1180   SmallVector<ValueEntry, 8> Factors;
1181   Factors.reserve(Tree.size());
1182   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1183     RepeatedValue E = Tree[i];
1184     Factors.append(E.second.getZExtValue(),
1185                    ValueEntry(getRank(E.first), E.first));
1186   }
1187
1188   bool FoundFactor = false;
1189   bool NeedsNegate = false;
1190   for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1191     if (Factors[i].Op == Factor) {
1192       FoundFactor = true;
1193       Factors.erase(Factors.begin()+i);
1194       break;
1195     }
1196
1197     // If this is a negative version of this factor, remove it.
1198     if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor))
1199       if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
1200         if (FC1->getValue() == -FC2->getValue()) {
1201           FoundFactor = NeedsNegate = true;
1202           Factors.erase(Factors.begin()+i);
1203           break;
1204         }
1205   }
1206
1207   if (!FoundFactor) {
1208     // Make sure to restore the operands to the expression tree.
1209     RewriteExprTree(BO, Factors);
1210     return 0;
1211   }
1212
1213   BasicBlock::iterator InsertPt = BO; ++InsertPt;
1214
1215   // If this was just a single multiply, remove the multiply and return the only
1216   // remaining operand.
1217   if (Factors.size() == 1) {
1218     RedoInsts.insert(BO);
1219     V = Factors[0].Op;
1220   } else {
1221     RewriteExprTree(BO, Factors);
1222     V = BO;
1223   }
1224
1225   if (NeedsNegate)
1226     V = BinaryOperator::CreateNeg(V, "neg", InsertPt);
1227
1228   return V;
1229 }
1230
1231 /// FindSingleUseMultiplyFactors - If V is a single-use multiply, recursively
1232 /// add its operands as factors, otherwise add V to the list of factors.
1233 ///
1234 /// Ops is the top-level list of add operands we're trying to factor.
1235 static void FindSingleUseMultiplyFactors(Value *V,
1236                                          SmallVectorImpl<Value*> &Factors,
1237                                        const SmallVectorImpl<ValueEntry> &Ops) {
1238   BinaryOperator *BO = isReassociableOp(V, Instruction::Mul);
1239   if (!BO) {
1240     Factors.push_back(V);
1241     return;
1242   }
1243
1244   // Otherwise, add the LHS and RHS to the list of factors.
1245   FindSingleUseMultiplyFactors(BO->getOperand(1), Factors, Ops);
1246   FindSingleUseMultiplyFactors(BO->getOperand(0), Factors, Ops);
1247 }
1248
1249 /// OptimizeAndOrXor - Optimize a series of operands to an 'and', 'or', or 'xor'
1250 /// instruction.  This optimizes based on identities.  If it can be reduced to
1251 /// a single Value, it is returned, otherwise the Ops list is mutated as
1252 /// necessary.
1253 static Value *OptimizeAndOrXor(unsigned Opcode,
1254                                SmallVectorImpl<ValueEntry> &Ops) {
1255   // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
1256   // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
1257   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1258     // First, check for X and ~X in the operand list.
1259     assert(i < Ops.size());
1260     if (BinaryOperator::isNot(Ops[i].Op)) {    // Cannot occur for ^.
1261       Value *X = BinaryOperator::getNotArgument(Ops[i].Op);
1262       unsigned FoundX = FindInOperandList(Ops, i, X);
1263       if (FoundX != i) {
1264         if (Opcode == Instruction::And)   // ...&X&~X = 0
1265           return Constant::getNullValue(X->getType());
1266
1267         if (Opcode == Instruction::Or)    // ...|X|~X = -1
1268           return Constant::getAllOnesValue(X->getType());
1269       }
1270     }
1271
1272     // Next, check for duplicate pairs of values, which we assume are next to
1273     // each other, due to our sorting criteria.
1274     assert(i < Ops.size());
1275     if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
1276       if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1277         // Drop duplicate values for And and Or.
1278         Ops.erase(Ops.begin()+i);
1279         --i; --e;
1280         ++NumAnnihil;
1281         continue;
1282       }
1283
1284       // Drop pairs of values for Xor.
1285       assert(Opcode == Instruction::Xor);
1286       if (e == 2)
1287         return Constant::getNullValue(Ops[0].Op->getType());
1288
1289       // Y ^ X^X -> Y
1290       Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1291       i -= 1; e -= 2;
1292       ++NumAnnihil;
1293     }
1294   }
1295   return 0;
1296 }
1297
1298 /// OptimizeAdd - Optimize a series of operands to an 'add' instruction.  This
1299 /// optimizes based on identities.  If it can be reduced to a single Value, it
1300 /// is returned, otherwise the Ops list is mutated as necessary.
1301 Value *Reassociate::OptimizeAdd(Instruction *I,
1302                                 SmallVectorImpl<ValueEntry> &Ops) {
1303   // Scan the operand lists looking for X and -X pairs.  If we find any, we
1304   // can simplify the expression. X+-X == 0.  While we're at it, scan for any
1305   // duplicates.  We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
1306   //
1307   // TODO: We could handle "X + ~X" -> "-1" if we wanted, since "-X = ~X+1".
1308   //
1309   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1310     Value *TheOp = Ops[i].Op;
1311     // Check to see if we've seen this operand before.  If so, we factor all
1312     // instances of the operand together.  Due to our sorting criteria, we know
1313     // that these need to be next to each other in the vector.
1314     if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
1315       // Rescan the list, remove all instances of this operand from the expr.
1316       unsigned NumFound = 0;
1317       do {
1318         Ops.erase(Ops.begin()+i);
1319         ++NumFound;
1320       } while (i != Ops.size() && Ops[i].Op == TheOp);
1321
1322       DEBUG(errs() << "\nFACTORING [" << NumFound << "]: " << *TheOp << '\n');
1323       ++NumFactor;
1324
1325       // Insert a new multiply.
1326       Value *Mul = ConstantInt::get(cast<IntegerType>(I->getType()), NumFound);
1327       Mul = BinaryOperator::CreateMul(TheOp, Mul, "factor", I);
1328
1329       // Now that we have inserted a multiply, optimize it. This allows us to
1330       // handle cases that require multiple factoring steps, such as this:
1331       // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
1332       RedoInsts.insert(cast<Instruction>(Mul));
1333
1334       // If every add operand was a duplicate, return the multiply.
1335       if (Ops.empty())
1336         return Mul;
1337
1338       // Otherwise, we had some input that didn't have the dupe, such as
1339       // "A + A + B" -> "A*2 + B".  Add the new multiply to the list of
1340       // things being added by this operation.
1341       Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
1342
1343       --i;
1344       e = Ops.size();
1345       continue;
1346     }
1347
1348     // Check for X and -X in the operand list.
1349     if (!BinaryOperator::isNeg(TheOp))
1350       continue;
1351
1352     Value *X = BinaryOperator::getNegArgument(TheOp);
1353     unsigned FoundX = FindInOperandList(Ops, i, X);
1354     if (FoundX == i)
1355       continue;
1356
1357     // Remove X and -X from the operand list.
1358     if (Ops.size() == 2)
1359       return Constant::getNullValue(X->getType());
1360
1361     Ops.erase(Ops.begin()+i);
1362     if (i < FoundX)
1363       --FoundX;
1364     else
1365       --i;   // Need to back up an extra one.
1366     Ops.erase(Ops.begin()+FoundX);
1367     ++NumAnnihil;
1368     --i;     // Revisit element.
1369     e -= 2;  // Removed two elements.
1370   }
1371
1372   // Scan the operand list, checking to see if there are any common factors
1373   // between operands.  Consider something like A*A+A*B*C+D.  We would like to
1374   // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
1375   // To efficiently find this, we count the number of times a factor occurs
1376   // for any ADD operands that are MULs.
1377   DenseMap<Value*, unsigned> FactorOccurrences;
1378
1379   // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
1380   // where they are actually the same multiply.
1381   unsigned MaxOcc = 0;
1382   Value *MaxOccVal = 0;
1383   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1384     BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
1385     if (!BOp)
1386       continue;
1387
1388     // Compute all of the factors of this added value.
1389     SmallVector<Value*, 8> Factors;
1390     FindSingleUseMultiplyFactors(BOp, Factors, Ops);
1391     assert(Factors.size() > 1 && "Bad linearize!");
1392
1393     // Add one to FactorOccurrences for each unique factor in this op.
1394     SmallPtrSet<Value*, 8> Duplicates;
1395     for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1396       Value *Factor = Factors[i];
1397       if (!Duplicates.insert(Factor)) continue;
1398
1399       unsigned Occ = ++FactorOccurrences[Factor];
1400       if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
1401
1402       // If Factor is a negative constant, add the negated value as a factor
1403       // because we can percolate the negate out.  Watch for minint, which
1404       // cannot be positivified.
1405       if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor))
1406         if (CI->isNegative() && !CI->isMinValue(true)) {
1407           Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
1408           assert(!Duplicates.count(Factor) &&
1409                  "Shouldn't have two constant factors, missed a canonicalize");
1410
1411           unsigned Occ = ++FactorOccurrences[Factor];
1412           if (Occ > MaxOcc) { MaxOcc = Occ; MaxOccVal = Factor; }
1413         }
1414     }
1415   }
1416
1417   // If any factor occurred more than one time, we can pull it out.
1418   if (MaxOcc > 1) {
1419     DEBUG(errs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal << '\n');
1420     ++NumFactor;
1421
1422     // Create a new instruction that uses the MaxOccVal twice.  If we don't do
1423     // this, we could otherwise run into situations where removing a factor
1424     // from an expression will drop a use of maxocc, and this can cause
1425     // RemoveFactorFromExpression on successive values to behave differently.
1426     Instruction *DummyInst = BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal);
1427     SmallVector<WeakVH, 4> NewMulOps;
1428     for (unsigned i = 0; i != Ops.size(); ++i) {
1429       // Only try to remove factors from expressions we're allowed to.
1430       BinaryOperator *BOp = isReassociableOp(Ops[i].Op, Instruction::Mul);
1431       if (!BOp)
1432         continue;
1433
1434       if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1435         // The factorized operand may occur several times.  Convert them all in
1436         // one fell swoop.
1437         for (unsigned j = Ops.size(); j != i;) {
1438           --j;
1439           if (Ops[j].Op == Ops[i].Op) {
1440             NewMulOps.push_back(V);
1441             Ops.erase(Ops.begin()+j);
1442           }
1443         }
1444         --i;
1445       }
1446     }
1447
1448     // No need for extra uses anymore.
1449     delete DummyInst;
1450
1451     unsigned NumAddedValues = NewMulOps.size();
1452     Value *V = EmitAddTreeOfValues(I, NewMulOps);
1453
1454     // Now that we have inserted the add tree, optimize it. This allows us to
1455     // handle cases that require multiple factoring steps, such as this:
1456     // A*A*B + A*A*C   -->   A*(A*B+A*C)   -->   A*(A*(B+C))
1457     assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
1458     (void)NumAddedValues;
1459     if (Instruction *VI = dyn_cast<Instruction>(V))
1460       RedoInsts.insert(VI);
1461
1462     // Create the multiply.
1463     Instruction *V2 = BinaryOperator::CreateMul(V, MaxOccVal, "tmp", I);
1464
1465     // Rerun associate on the multiply in case the inner expression turned into
1466     // a multiply.  We want to make sure that we keep things in canonical form.
1467     RedoInsts.insert(V2);
1468
1469     // If every add operand included the factor (e.g. "A*B + A*C"), then the
1470     // entire result expression is just the multiply "A*(B+C)".
1471     if (Ops.empty())
1472       return V2;
1473
1474     // Otherwise, we had some input that didn't have the factor, such as
1475     // "A*B + A*C + D" -> "A*(B+C) + D".  Add the new multiply to the list of
1476     // things being added by this operation.
1477     Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
1478   }
1479
1480   return 0;
1481 }
1482
1483 namespace {
1484   /// \brief Predicate tests whether a ValueEntry's op is in a map.
1485   struct IsValueInMap {
1486     const DenseMap<Value *, unsigned> &Map;
1487
1488     IsValueInMap(const DenseMap<Value *, unsigned> &Map) : Map(Map) {}
1489
1490     bool operator()(const ValueEntry &Entry) {
1491       return Map.find(Entry.Op) != Map.end();
1492     }
1493   };
1494 }
1495
1496 /// \brief Build up a vector of value/power pairs factoring a product.
1497 ///
1498 /// Given a series of multiplication operands, build a vector of factors and
1499 /// the powers each is raised to when forming the final product. Sort them in
1500 /// the order of descending power.
1501 ///
1502 ///      (x*x)          -> [(x, 2)]
1503 ///     ((x*x)*x)       -> [(x, 3)]
1504 ///   ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1505 ///
1506 /// \returns Whether any factors have a power greater than one.
1507 bool Reassociate::collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1508                                          SmallVectorImpl<Factor> &Factors) {
1509   // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1510   // Compute the sum of powers of simplifiable factors.
1511   unsigned FactorPowerSum = 0;
1512   for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1513     Value *Op = Ops[Idx-1].Op;
1514
1515     // Count the number of occurrences of this value.
1516     unsigned Count = 1;
1517     for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1518       ++Count;
1519     // Track for simplification all factors which occur 2 or more times.
1520     if (Count > 1)
1521       FactorPowerSum += Count;
1522   }
1523
1524   // We can only simplify factors if the sum of the powers of our simplifiable
1525   // factors is 4 or higher. When that is the case, we will *always* have
1526   // a simplification. This is an important invariant to prevent cyclicly
1527   // trying to simplify already minimal formations.
1528   if (FactorPowerSum < 4)
1529     return false;
1530
1531   // Now gather the simplifiable factors, removing them from Ops.
1532   FactorPowerSum = 0;
1533   for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1534     Value *Op = Ops[Idx-1].Op;
1535
1536     // Count the number of occurrences of this value.
1537     unsigned Count = 1;
1538     for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1539       ++Count;
1540     if (Count == 1)
1541       continue;
1542     // Move an even number of occurrences to Factors.
1543     Count &= ~1U;
1544     Idx -= Count;
1545     FactorPowerSum += Count;
1546     Factors.push_back(Factor(Op, Count));
1547     Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
1548   }
1549
1550   // None of the adjustments above should have reduced the sum of factor powers
1551   // below our mininum of '4'.
1552   assert(FactorPowerSum >= 4);
1553
1554   std::sort(Factors.begin(), Factors.end(), Factor::PowerDescendingSorter());
1555   return true;
1556 }
1557
1558 /// \brief Build a tree of multiplies, computing the product of Ops.
1559 static Value *buildMultiplyTree(IRBuilder<> &Builder,
1560                                 SmallVectorImpl<Value*> &Ops) {
1561   if (Ops.size() == 1)
1562     return Ops.back();
1563
1564   Value *LHS = Ops.pop_back_val();
1565   do {
1566     LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
1567   } while (!Ops.empty());
1568
1569   return LHS;
1570 }
1571
1572 /// \brief Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1573 ///
1574 /// Given a vector of values raised to various powers, where no two values are
1575 /// equal and the powers are sorted in decreasing order, compute the minimal
1576 /// DAG of multiplies to compute the final product, and return that product
1577 /// value.
1578 Value *Reassociate::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
1579                                             SmallVectorImpl<Factor> &Factors) {
1580   assert(Factors[0].Power);
1581   SmallVector<Value *, 4> OuterProduct;
1582   for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1583        Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1584     if (Factors[Idx].Power != Factors[LastIdx].Power) {
1585       LastIdx = Idx;
1586       continue;
1587     }
1588
1589     // We want to multiply across all the factors with the same power so that
1590     // we can raise them to that power as a single entity. Build a mini tree
1591     // for that.
1592     SmallVector<Value *, 4> InnerProduct;
1593     InnerProduct.push_back(Factors[LastIdx].Base);
1594     do {
1595       InnerProduct.push_back(Factors[Idx].Base);
1596       ++Idx;
1597     } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1598
1599     // Reset the base value of the first factor to the new expression tree.
1600     // We'll remove all the factors with the same power in a second pass.
1601     Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
1602     if (Instruction *MI = dyn_cast<Instruction>(M))
1603       RedoInsts.insert(MI);
1604
1605     LastIdx = Idx;
1606   }
1607   // Unique factors with equal powers -- we've folded them into the first one's
1608   // base.
1609   Factors.erase(std::unique(Factors.begin(), Factors.end(),
1610                             Factor::PowerEqual()),
1611                 Factors.end());
1612
1613   // Iteratively collect the base of each factor with an add power into the
1614   // outer product, and halve each power in preparation for squaring the
1615   // expression.
1616   for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
1617     if (Factors[Idx].Power & 1)
1618       OuterProduct.push_back(Factors[Idx].Base);
1619     Factors[Idx].Power >>= 1;
1620   }
1621   if (Factors[0].Power) {
1622     Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1623     OuterProduct.push_back(SquareRoot);
1624     OuterProduct.push_back(SquareRoot);
1625   }
1626   if (OuterProduct.size() == 1)
1627     return OuterProduct.front();
1628
1629   Value *V = buildMultiplyTree(Builder, OuterProduct);
1630   return V;
1631 }
1632
1633 // Multiply Ops may have some negation operators. This situation arises
1634 // when the negation operators have multiple uses, and LinearizeExprTree() has
1635 // to treat them as leaf operands. Before multiplication optimization begins,
1636 // get rid of the negations wherever possible.
1637 void Reassociate::removeNegFromMulOps(SmallVectorImpl<ValueEntry> &Ops) {
1638   int32_t NegIdx = -1;
1639
1640   // loop over all elements except the last one
1641   for (int32_t Idx = 0, IdxEnd = Ops.size() - 1; Idx < IdxEnd; Idx++) {
1642     ValueEntry &VE = Ops[Idx];
1643     if (!BinaryOperator::isNeg(VE.Op))
1644       continue;
1645     
1646     if (NegIdx < 0) {
1647       NegIdx = Idx;
1648       continue;
1649     }
1650
1651     // Find a pair of negation operators, say -X and -Y, change them to 
1652     // X and Y respectively.
1653     ValueEntry &VEX = Ops[NegIdx];
1654     Value *OpX = cast<BinaryOperator>(VEX.Op)->getOperand(1);
1655     VEX.Op = OpX;
1656     VEX.Rank = getRank(OpX);
1657
1658     Value *OpY = cast<BinaryOperator>(VE.Op)->getOperand(1);
1659     VE.Op = OpY;
1660     VE.Rank = getRank(OpY);
1661     NegIdx = -1;
1662   }
1663
1664   if (NegIdx >= 0) {
1665     // We have visited odd number of negation operators so far. 
1666     // Check if the last element is negation as well. 
1667     ValueEntry &Last = Ops.back();
1668     Value *LastOp = Last.Op;
1669     if (!isa<ConstantInt>(LastOp) && !BinaryOperator::isNeg(LastOp))
1670       return;
1671
1672     ValueEntry& PrevNeg = Ops[NegIdx]; 
1673     Value *Op = cast<BinaryOperator>(PrevNeg.Op)->getOperand(1);
1674     PrevNeg.Op = Op;
1675     PrevNeg.Rank = getRank(Op);
1676
1677     if (isa<ConstantInt>(LastOp))
1678       Last.Op = ConstantExpr::getNeg(cast<Constant>(LastOp));
1679     else {
1680       LastOp = cast<BinaryOperator>(PrevNeg.Op)->getOperand(1);
1681       Last.Op = LastOp;
1682       Last.Rank = getRank(LastOp);
1683     }
1684   }
1685 }
1686
1687 Value *Reassociate::OptimizeMul(BinaryOperator *I,
1688                                 SmallVectorImpl<ValueEntry> &Ops) {
1689
1690   // Simplify the operands: (-x)*(-y) -> x*y, and (-x)*c -> x*(-c)
1691   removeNegFromMulOps(Ops);
1692
1693   // We can only optimize the multiplies when there is a chain of more than
1694   // three, such that a balanced tree might require fewer total multiplies.
1695   if (Ops.size() < 4)
1696     return 0;
1697
1698   // Try to turn linear trees of multiplies without other uses of the
1699   // intermediate stages into minimal multiply DAGs with perfect sub-expression
1700   // re-use.
1701   SmallVector<Factor, 4> Factors;
1702   if (!collectMultiplyFactors(Ops, Factors))
1703     return 0; // All distinct factors, so nothing left for us to do.
1704
1705   IRBuilder<> Builder(I);
1706   Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1707   if (Ops.empty())
1708     return V;
1709
1710   ValueEntry NewEntry = ValueEntry(getRank(V), V);
1711   Ops.insert(std::lower_bound(Ops.begin(), Ops.end(), NewEntry), NewEntry);
1712   return 0;
1713 }
1714
1715 Value *Reassociate::OptimizeExpression(BinaryOperator *I,
1716                                        SmallVectorImpl<ValueEntry> &Ops) {
1717   // Now that we have the linearized expression tree, try to optimize it.
1718   // Start by folding any constants that we found.
1719   if (Ops.size() == 1) return Ops[0].Op;
1720
1721   unsigned Opcode = I->getOpcode();
1722
1723   // Handle destructive annihilation due to identities between elements in the
1724   // argument list here.
1725   unsigned NumOps = Ops.size();
1726   switch (Opcode) {
1727   default: break;
1728   case Instruction::And:
1729   case Instruction::Or:
1730   case Instruction::Xor:
1731     if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
1732       return Result;
1733     break;
1734
1735   case Instruction::Add:
1736     if (Value *Result = OptimizeAdd(I, Ops))
1737       return Result;
1738     break;
1739
1740   case Instruction::Mul:
1741     if (Value *Result = OptimizeMul(I, Ops))
1742       return Result;
1743     break;
1744   }
1745
1746   if (Ops.size() != NumOps)
1747     return OptimizeExpression(I, Ops);
1748   return 0;
1749 }
1750
1751 // EraseInstCallBack is a helper function of EraseInst which will be called to 
1752 // delete an individual instruction, and it is also a callback funciton when 
1753 // EraseAllDeadInst is called to delete all dead instruciton in the Redo 
1754 // worklist (RedoInsts). 
1755 //  
1756 void Reassociate::EraseInstCallBack(Instruction *I) {
1757   DEBUG(dbgs() << "Erase instruction :" << *I << "\n");
1758   assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1759   SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1760   // Erase the dead instruction.
1761   ValueRankMap.erase(I);
1762   I->eraseFromParent();
1763   // Optimize its operands.
1764   SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
1765   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1766     if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1767       // If this is a node in an expression tree, climb to the expression root
1768       // and add that since that's where optimization actually happens.
1769       unsigned Opcode = Op->getOpcode();
1770       while (Op->hasOneUse() && Op->use_back()->getOpcode() == Opcode &&
1771              Visited.insert(Op))
1772         Op = Op->use_back();
1773       
1774       // The caller may be itearating the RedoInsts. Inserting a new element to 
1775       // RedoInsts will invaidate the iterator. Instead, we temporally place the 
1776       // new candidate to TmpRedoInsts. It is up to caller to combine 
1777       // TmpRedoInsts and RedoInsts together.
1778       //
1779       if (!RedoInsts.found(Op))
1780         TmpRedoInsts.insert(Op);
1781     }
1782 }
1783
1784 /// EraseInst - Zap the given instruction, adding interesting operands to the
1785 /// work list.
1786 void Reassociate::EraseInst(Instruction *I) {
1787   RedoInsts.remove(I);
1788
1789   // Since EraseInstCallBack() put new reassociation candidates to TmpRedoInsts
1790   // we need to copy the candidates back to RedoInsts.
1791   TmpRedoInsts.clear();
1792   EraseInstCallBack(I);
1793   RedoInsts.append(TmpRedoInsts);
1794 }
1795
1796 /// EraseAllDeadInst - Remove all dead instructions from the worklist. 
1797 void Reassociate::EraseAllDeadInst() {
1798   TmpRedoInsts.clear();
1799   RedoInsts.inplace_rremove(isInstDeadFunc(), RmInstCallBackFunc(this));
1800   RedoInsts.append(TmpRedoInsts);
1801 }
1802
1803 /// OptimizeInst - Inspect and optimize the given instruction. Note that erasing
1804 /// instructions is not allowed.
1805 void Reassociate::OptimizeInst(Instruction *I) {
1806   // Only consider operations that we understand.
1807   if (!isa<BinaryOperator>(I))
1808     return;
1809
1810   DEBUG(dbgs() << "\n>Opt Instruction: " << *I << '\n');
1811
1812   if (I->getOpcode() == Instruction::Shl &&
1813       isa<ConstantInt>(I->getOperand(1)))
1814     // If an operand of this shift is a reassociable multiply, or if the shift
1815     // is used by a reassociable multiply or add, turn into a multiply.
1816     if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
1817         (I->hasOneUse() &&
1818          (isReassociableOp(I->use_back(), Instruction::Mul) ||
1819           isReassociableOp(I->use_back(), Instruction::Add)))) {
1820       Instruction *NI = ConvertShiftToMul(I);
1821       RedoInsts.insert(I);
1822       MadeChange = true;
1823       I = NI;
1824     }
1825
1826   // Floating point binary operators are not associative, but we can still
1827   // commute (some) of them, to canonicalize the order of their operands.
1828   // This can potentially expose more CSE opportunities, and makes writing
1829   // other transformations simpler.
1830   if ((I->getType()->isFloatingPointTy() || I->getType()->isVectorTy())) {
1831     // FAdd and FMul can be commuted.
1832     if (I->getOpcode() != Instruction::FMul &&
1833         I->getOpcode() != Instruction::FAdd)
1834       return;
1835
1836     Value *LHS = I->getOperand(0);
1837     Value *RHS = I->getOperand(1);
1838     unsigned LHSRank = getRank(LHS);
1839     unsigned RHSRank = getRank(RHS);
1840
1841     // Sort the operands by rank.
1842     if (RHSRank < LHSRank) {
1843       I->setOperand(0, RHS);
1844       I->setOperand(1, LHS);
1845     }
1846
1847     return;
1848   }
1849
1850   // Do not reassociate boolean (i1) expressions.  We want to preserve the
1851   // original order of evaluation for short-circuited comparisons that
1852   // SimplifyCFG has folded to AND/OR expressions.  If the expression
1853   // is not further optimized, it is likely to be transformed back to a
1854   // short-circuited form for code gen, and the source order may have been
1855   // optimized for the most likely conditions.
1856   if (I->getType()->isIntegerTy(1))
1857     return;
1858
1859   // If this is a subtract instruction which is not already in negate form,
1860   // see if we can convert it to X+-Y.
1861   if (I->getOpcode() == Instruction::Sub) {
1862     if (ShouldBreakUpSubtract(I)) {
1863       Instruction *NI = BreakUpSubtract(I);
1864       RedoInsts.insert(I);
1865       MadeChange = true;
1866       I = NI;
1867     } else if (BinaryOperator::isNeg(I)) {
1868       // Otherwise, this is a negation.  See if the operand is a multiply tree
1869       // and if this is not an inner node of a multiply tree.
1870       if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
1871           (!I->hasOneUse() ||
1872            !isReassociableOp(I->use_back(), Instruction::Mul))) {
1873         Instruction *NI = LowerNegateToMultiply(I);
1874         RedoInsts.insert(I);
1875         MadeChange = true;
1876         I = NI;
1877       }
1878     }
1879   }
1880
1881   // If this instruction is an associative binary operator, process it.
1882   if (!I->isAssociative()) return;
1883   BinaryOperator *BO = cast<BinaryOperator>(I);
1884
1885   // If this is an interior node of a reassociable tree, ignore it until we
1886   // get to the root of the tree, to avoid N^2 analysis.
1887   unsigned Opcode = BO->getOpcode();
1888   if (BO->hasOneUse() && BO->use_back()->getOpcode() == Opcode)
1889     return;
1890
1891   // If this is an add tree that is used by a sub instruction, ignore it
1892   // until we process the subtract.
1893   if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
1894       cast<Instruction>(BO->use_back())->getOpcode() == Instruction::Sub)
1895     return;
1896
1897   ReassociateExpression(BO);
1898 }
1899
1900 void Reassociate::ReassociateExpression(BinaryOperator *I) {
1901
1902   // First, walk the expression tree, linearizing the tree, collecting the
1903   // operand information.
1904   SmallVector<RepeatedValue, 8> Tree;
1905   MadeChange |= LinearizeExprTree(I, Tree);
1906   SmallVector<ValueEntry, 8> Ops;
1907   Ops.reserve(Tree.size());
1908   for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1909     RepeatedValue E = Tree[i];
1910     Ops.append(E.second.getZExtValue(),
1911                ValueEntry(getRank(E.first), E.first));
1912   }
1913
1914   DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
1915
1916   // Now that we have linearized the tree to a list and have gathered all of
1917   // the operands and their ranks, sort the operands by their rank.  Use a
1918   // stable_sort so that values with equal ranks will have their relative
1919   // positions maintained (and so the compiler is deterministic).  Note that
1920   // this sorts so that the highest ranking values end up at the beginning of
1921   // the vector.
1922   std::stable_sort(Ops.begin(), Ops.end());
1923
1924   // OptimizeExpression - Now that we have the expression tree in a convenient
1925   // sorted form, optimize it globally if possible.
1926   if (Value *V = OptimizeExpression(I, Ops)) {
1927     if (V == I)
1928       // Self-referential expression in unreachable code.
1929       return;
1930     // This expression tree simplified to something that isn't a tree,
1931     // eliminate it.
1932     DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
1933     I->replaceAllUsesWith(V);
1934     if (Instruction *VI = dyn_cast<Instruction>(V))
1935       VI->setDebugLoc(I->getDebugLoc());
1936     RedoInsts.insert(I);
1937     ++NumAnnihil;
1938     return;
1939   }
1940
1941   // We want to sink immediates as deeply as possible except in the case where
1942   // this is a multiply tree used only by an add, and the immediate is a -1.
1943   // In this case we reassociate to put the negation on the outside so that we
1944   // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
1945   if (I->getOpcode() == Instruction::Mul && I->hasOneUse() &&
1946       cast<Instruction>(I->use_back())->getOpcode() == Instruction::Add &&
1947       isa<ConstantInt>(Ops.back().Op) &&
1948       cast<ConstantInt>(Ops.back().Op)->isAllOnesValue()) {
1949     ValueEntry Tmp = Ops.pop_back_val();
1950     Ops.insert(Ops.begin(), Tmp);
1951   }
1952
1953   DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
1954
1955   if (Ops.size() == 1) {
1956     if (Ops[0].Op == I)
1957       // Self-referential expression in unreachable code.
1958       return;
1959
1960     // This expression tree simplified to something that isn't a tree,
1961     // eliminate it.
1962     I->replaceAllUsesWith(Ops[0].Op);
1963     if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
1964       OI->setDebugLoc(I->getDebugLoc());
1965     RedoInsts.insert(I);
1966     return;
1967   }
1968
1969   // Now that we ordered and optimized the expressions, splat them back into
1970   // the expression tree, removing any unneeded nodes.
1971   RewriteExprTree(I, Ops);
1972 }
1973
1974 bool Reassociate::runOnFunction(Function &F) {
1975   // Calculate the rank map for F
1976   BuildRankMap(F);
1977
1978   MadeChange = false;
1979   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1980     // Optimize every instruction in the basic block.
1981     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE; )
1982       if (isInstructionTriviallyDead(II)) {
1983         EraseInst(II++);
1984       } else {
1985         OptimizeInst(II);
1986         assert(II->getParent() == BI && "Moved to a different block!");
1987         ++II;
1988       }
1989
1990     DEBUG(dbgs() << "Process instructions in worklist\n");
1991     EraseAllDeadInst();
1992
1993     // If this produced extra instructions to optimize, handle them now.
1994     while (!RedoInsts.empty()) {
1995       Instruction *I = RedoInsts.pop_front_val();
1996       if (!I)
1997         continue;
1998       if (isInstructionTriviallyDead(I))
1999         EraseInst(I);
2000       else
2001         OptimizeInst(I);
2002     }
2003   }
2004
2005   // We are done with the rank map.
2006   RankMap.clear();
2007   ValueRankMap.clear();
2008
2009   return MadeChange;
2010 }