Rewrite the guts of the reassociate pass to be more efficient and logical. Instead
[oota-llvm.git] / lib / Transforms / Scalar / Reassociate.cpp
1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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...
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/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Type.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/Statistic.h"
34 #include <algorithm>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> NumLinear ("reassociate","Number of insts linearized");
39   Statistic<> NumChanged("reassociate","Number of insts reassociated");
40   Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
41
42   struct ValueEntry {
43     unsigned Rank;
44     Value *Op;
45     ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
46   };
47   inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
48     return LHS.Rank > RHS.Rank;   // Sort so that highest rank goes to start.
49   }
50
51   class Reassociate : public FunctionPass {
52     std::map<BasicBlock*, unsigned> RankMap;
53     std::map<Value*, unsigned> ValueRankMap;
54     bool MadeChange;
55   public:
56     bool runOnFunction(Function &F);
57
58     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59       AU.setPreservesCFG();
60     }
61   private:
62     void BuildRankMap(Function &F);
63     unsigned getRank(Value *V);
64     void RewriteExprTree(BinaryOperator *I, unsigned Idx,
65                          std::vector<ValueEntry> &Ops);
66     void LinearizeExprTree(BinaryOperator *I, std::vector<ValueEntry> &Ops);
67     void LinearizeExpr(BinaryOperator *I);
68     void ReassociateBB(BasicBlock *BB);
69   };
70
71   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
72 }
73
74 // Public interface to the Reassociate pass
75 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
76
77 void Reassociate::BuildRankMap(Function &F) {
78   unsigned i = 2;
79
80   // Assign distinct ranks to function arguments
81   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
82     ValueRankMap[I] = ++i;
83
84   ReversePostOrderTraversal<Function*> RPOT(&F);
85   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
86          E = RPOT.end(); I != E; ++I)
87     RankMap[*I] = ++i << 16;
88 }
89
90 unsigned Reassociate::getRank(Value *V) {
91   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
92
93   Instruction *I = dyn_cast<Instruction>(V);
94   if (I == 0) return 0;  // Otherwise it's a global or constant, rank 0.
95
96   unsigned &CachedRank = ValueRankMap[I];
97   if (CachedRank) return CachedRank;    // Rank already known?
98   
99   // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
100   // we can reassociate expressions for code motion!  Since we do not recurse
101   // for PHI nodes, we cannot have infinite recursion here, because there
102   // cannot be loops in the value graph that do not go through PHI nodes.
103   //
104   if (I->getOpcode() == Instruction::PHI ||
105       I->getOpcode() == Instruction::Alloca ||
106       I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
107       I->mayWriteToMemory())  // Cannot move inst if it writes to memory!
108     return RankMap[I->getParent()];
109   
110   // If not, compute it!
111   unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
112   for (unsigned i = 0, e = I->getNumOperands();
113        i != e && Rank != MaxRank; ++i)
114     Rank = std::max(Rank, getRank(I->getOperand(i)));
115   
116   DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
117         << Rank+1 << "\n");
118   
119   return CachedRank = Rank+1;
120 }
121
122 /// isReassociableOp - Return true if V is an instruction of the specified
123 /// opcode and if it only has one use.
124 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
125   if (V->hasOneUse() && isa<Instruction>(V) &&
126       cast<Instruction>(V)->getOpcode() == Opcode)
127     return cast<BinaryOperator>(V);
128   return 0;
129 }
130
131 // Given an expression of the form '(A+B)+(D+C)', turn it into '(((A+B)+C)+D)'.
132 // Note that if D is also part of the expression tree that we recurse to
133 // linearize it as well.  Besides that case, this does not recurse into A,B, or
134 // C.
135 void Reassociate::LinearizeExpr(BinaryOperator *I) {
136   BinaryOperator *LHS = cast<BinaryOperator>(I->getOperand(0));
137   BinaryOperator *RHS = cast<BinaryOperator>(I->getOperand(1));
138   assert(isReassociableOp(LHS, I->getOpcode()) && 
139          isReassociableOp(RHS, I->getOpcode()) &&
140          "Not an expression that needs linearization?");
141
142   DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
143
144   // Move the RHS instruction to live immediately before I, avoiding breaking
145   // dominator properties.
146   I->getParent()->getInstList().splice(I, RHS->getParent()->getInstList(), RHS);
147
148   // Move operands around to do the linearization.
149   I->setOperand(1, RHS->getOperand(0));
150   RHS->setOperand(0, LHS);
151   I->setOperand(0, RHS);
152   
153   ++NumLinear;
154   MadeChange = true;
155   DEBUG(std::cerr << "Linearized: " << *I);
156
157   // If D is part of this expression tree, tail recurse.
158   if (isReassociableOp(I->getOperand(1), I->getOpcode()))
159     LinearizeExpr(I);
160 }
161
162
163 /// LinearizeExprTree - Given an associative binary expression tree, traverse
164 /// all of the uses putting it into canonical form.  This forces a left-linear
165 /// form of the the expression (((a+b)+c)+d), and collects information about the
166 /// rank of the non-tree operands.
167 ///
168 /// This returns the rank of the RHS operand, which is known to be the highest
169 /// rank value in the expression tree.
170 ///
171 void Reassociate::LinearizeExprTree(BinaryOperator *I,
172                                     std::vector<ValueEntry> &Ops) {
173   Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
174   unsigned Opcode = I->getOpcode();
175
176   // First step, linearize the expression if it is in ((A+B)+(C+D)) form.
177   BinaryOperator *LHSBO = isReassociableOp(LHS, Opcode);
178   BinaryOperator *RHSBO = isReassociableOp(RHS, Opcode);
179
180   if (!LHSBO) {
181     if (!RHSBO) {
182       // Neither the LHS or RHS as part of the tree, thus this is a leaf.  As
183       // such, just remember these operands and their rank.
184       Ops.push_back(ValueEntry(getRank(LHS), LHS));
185       Ops.push_back(ValueEntry(getRank(RHS), RHS));
186       return;
187     } else {
188       // Turn X+(Y+Z) -> (Y+Z)+X
189       std::swap(LHSBO, RHSBO);
190       std::swap(LHS, RHS);
191       bool Success = !I->swapOperands();
192       assert(Success && "swapOperands failed");
193       MadeChange = true;
194     }
195   } else if (RHSBO) {
196     // Turn (A+B)+(C+D) -> (((A+B)+C)+D).  This guarantees the the RHS is not
197     // part of the expression tree.
198     LinearizeExpr(I);
199     LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
200     RHS = I->getOperand(1);
201     RHSBO = 0;
202   }
203
204   // Okay, now we know that the LHS is a nested expression and that the RHS is
205   // not.  Perform reassociation.
206   assert(!isReassociableOp(RHS, Opcode) && "LinearizeExpr failed!");
207
208   // Move LHS right before I to make sure that the tree expression dominates all
209   // values.
210   I->getParent()->getInstList().splice(I,
211                                       LHSBO->getParent()->getInstList(), LHSBO);
212
213   // Linearize the expression tree on the LHS.
214   LinearizeExprTree(LHSBO, Ops);
215
216   // Remember the RHS operand and its rank.
217   Ops.push_back(ValueEntry(getRank(RHS), RHS));
218 }
219
220 // RewriteExprTree - Now that the operands for this expression tree are
221 // linearized and optimized, emit them in-order.  This function is written to be
222 // tail recursive.
223 void Reassociate::RewriteExprTree(BinaryOperator *I, unsigned i,
224                                   std::vector<ValueEntry> &Ops) {
225   if (i+2 == Ops.size()) {
226     if (I->getOperand(0) != Ops[i].Op ||
227         I->getOperand(1) != Ops[i+1].Op) {
228       DEBUG(std::cerr << "RA: " << *I);
229       I->setOperand(0, Ops[i].Op);
230       I->setOperand(1, Ops[i+1].Op);
231       DEBUG(std::cerr << "TO: " << *I);
232       MadeChange = true;
233       ++NumChanged;
234     }
235     return;
236   }
237   assert(i+2 < Ops.size() && "Ops index out of range!");
238
239   if (I->getOperand(1) != Ops[i].Op) {
240     DEBUG(std::cerr << "RA: " << *I);
241     I->setOperand(1, Ops[i].Op);
242     DEBUG(std::cerr << "TO: " << *I);
243     MadeChange = true;
244     ++NumChanged;
245   }
246   RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
247 }
248
249
250
251 // NegateValue - Insert instructions before the instruction pointed to by BI,
252 // that computes the negative version of the value specified.  The negative
253 // version of the value is returned, and BI is left pointing at the instruction
254 // that should be processed next by the reassociation pass.
255 //
256 static Value *NegateValue(Value *V, Instruction *BI) {
257   // We are trying to expose opportunity for reassociation.  One of the things
258   // that we want to do to achieve this is to push a negation as deep into an
259   // expression chain as possible, to expose the add instructions.  In practice,
260   // this means that we turn this:
261   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
262   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
263   // the constants.  We assume that instcombine will clean up the mess later if
264   // we introduce tons of unnecessary negation instructions...
265   //
266   if (Instruction *I = dyn_cast<Instruction>(V))
267     if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
268       Value *RHS = NegateValue(I->getOperand(1), BI);
269       Value *LHS = NegateValue(I->getOperand(0), BI);
270
271       // We must actually insert a new add instruction here, because the neg
272       // instructions do not dominate the old add instruction in general.  By
273       // adding it now, we are assured that the neg instructions we just
274       // inserted dominate the instruction we are about to insert after them.
275       //
276       return BinaryOperator::create(Instruction::Add, LHS, RHS,
277                                     I->getName()+".neg", BI);
278     }
279
280   // Insert a 'neg' instruction that subtracts the value from zero to get the
281   // negation.
282   //
283   return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
284 }
285
286 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
287 /// only used by an add, transform this into (X+(0-Y)) to promote better
288 /// reassociation.
289 static Instruction *BreakUpSubtract(Instruction *Sub) {
290   // Reject cases where it is pointless to do this.
291   if (Sub->getType()->isFloatingPoint())
292     return 0;  // Floating point adds are not associative.
293
294   // Don't bother to break this up unless either the LHS is an associable add or
295   // if this is only used by one.
296   if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
297       !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
298       !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
299     return 0;
300
301   // Convert a subtract into an add and a neg instruction... so that sub
302   // instructions can be commuted with other add instructions...
303   //
304   // Calculate the negative value of Operand 1 of the sub instruction...
305   // and set it as the RHS of the add instruction we just made...
306   //
307   std::string Name = Sub->getName();
308   Sub->setName("");
309   Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
310   Instruction *New =
311     BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
312
313   // Everyone now refers to the add instruction.
314   Sub->replaceAllUsesWith(New);
315   Sub->eraseFromParent();
316   
317   DEBUG(std::cerr << "Negated: " << *New);
318   return New;
319 }
320
321 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or is used
322 /// by one, change this into a multiply by a constant to assist with further
323 /// reassociation.
324 static Instruction *ConvertShiftToMul(Instruction *Shl) {
325   if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
326       !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
327     return 0;
328
329   Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
330   MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
331
332   std::string Name = Shl->getName();  Shl->setName("");
333   Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
334                                                Name, Shl);
335   Shl->replaceAllUsesWith(Mul);
336   Shl->eraseFromParent();
337   return Mul;
338 }
339
340
341 /// ReassociateBB - Inspect all of the instructions in this basic block,
342 /// reassociating them as we go.
343 void Reassociate::ReassociateBB(BasicBlock *BB) {
344   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
345     // If this is a subtract instruction which is not already in negate form,
346     // see if we can convert it to X+-Y.
347     if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
348       if (Instruction *NI = BreakUpSubtract(BI)) {
349         MadeChange = true;
350         BI = NI;
351       }
352     if (BI->getOpcode() == Instruction::Shl &&
353         isa<ConstantInt>(BI->getOperand(1)))
354       if (Instruction *NI = ConvertShiftToMul(BI)) {
355         MadeChange = true;
356         BI = NI;
357       }
358
359     // If this instruction is a commutative binary operator, process it.
360     if (!BI->isAssociative()) continue;
361     BinaryOperator *I = cast<BinaryOperator>(BI);
362     
363     // If this is an interior node of a reassociable tree, ignore it until we
364     // get to the root of the tree, to avoid N^2 analysis.
365     if (I->hasOneUse() && isReassociableOp(I->use_back(), I->getOpcode()))
366       continue;
367
368     // First, walk the expression tree, linearizing the tree, collecting 
369     std::vector<ValueEntry> Ops;
370     LinearizeExprTree(I, Ops);
371
372     // Now that we have linearized the tree to a list and have gathered all of
373     // the operands and their ranks, sort the operands by their rank.  Use a
374     // stable_sort so that values with equal ranks will have their relative
375     // positions maintained (and so the compiler is deterministic).  Note that
376     // this sorts so that the highest ranking values end up at the beginning of
377     // the vector.
378     std::stable_sort(Ops.begin(), Ops.end());
379
380     // Now that we have the linearized expression tree, try to optimize it.
381     // Start by folding any constants that we found.
382   FoldConstants:
383     if (Ops.size() > 1)
384       if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
385         if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
386           Ops.pop_back();
387           Ops.back().Op = ConstantExpr::get(I->getOpcode(), V1, V2);
388           goto FoldConstants;
389         }
390
391     // FIXME: Handle destructive annihilation here.  Ensure RANK(neg(x)) ==
392     // RANK(x) [and not].  Handle case when Cst = 0 and op = AND f.e.
393
394     // FIXME: Handle +0,*1,&~0,... at end of the list.
395
396
397     if (Ops.size() == 1) {
398       // This expression tree simplified to something that isn't a tree,
399       // eliminate it.
400       I->replaceAllUsesWith(Ops[0].Op);
401     } else {
402       // Now that we ordered and optimized the expressions, splat them back into
403       // the expression tree, removing any unneeded nodes.
404       RewriteExprTree(I, 0, Ops);
405     }
406   }
407 }
408
409
410 bool Reassociate::runOnFunction(Function &F) {
411   // Recalculate the rank map for F
412   BuildRankMap(F);
413
414   MadeChange = false;
415   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
416     ReassociateBB(FI);
417
418   // We are done with the rank map...
419   RankMap.clear();
420   ValueRankMap.clear();
421   return MadeChange;
422 }
423