Put all LLVM code into the llvm namespace, as per bug 109.
[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 // Note that this pass works best if left shifts have been promoted to explicit
16 // multiplies before this pass executes.
17 //
18 // In the implementation of this algorithm, constants are assigned rank = 0,
19 // function arguments are rank = 1, and other values are assigned ranks
20 // corresponding to the reverse post order traversal of current function
21 // (starting at 2), which effectively gives values in deep loops higher rank
22 // than values not in loops.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Function.h"
28 #include "llvm/iOperators.h"
29 #include "llvm/Type.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Constant.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/Debug.h"
34 #include "Support/PostOrderIterator.h"
35 #include "Support/Statistic.h"
36
37 namespace llvm {
38
39 namespace {
40   Statistic<> NumLinear ("reassociate","Number of insts linearized");
41   Statistic<> NumChanged("reassociate","Number of insts reassociated");
42   Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
43
44   class Reassociate : public FunctionPass {
45     std::map<BasicBlock*, unsigned> RankMap;
46     std::map<Value*, unsigned> ValueRankMap;
47   public:
48     bool runOnFunction(Function &F);
49
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.setPreservesCFG();
52     }
53   private:
54     void BuildRankMap(Function &F);
55     unsigned getRank(Value *V);
56     bool ReassociateExpr(BinaryOperator *I);
57     bool ReassociateBB(BasicBlock *BB);
58   };
59
60   RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
61 }
62
63 // Public interface to the Reassociate pass
64 FunctionPass *createReassociatePass() { return new Reassociate(); }
65
66 void Reassociate::BuildRankMap(Function &F) {
67   unsigned i = 2;
68
69   // Assign distinct ranks to function arguments
70   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
71     ValueRankMap[I] = ++i;
72
73   ReversePostOrderTraversal<Function*> RPOT(&F);
74   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
75          E = RPOT.end(); I != E; ++I)
76     RankMap[*I] = ++i << 16;
77 }
78
79 unsigned Reassociate::getRank(Value *V) {
80   if (isa<Argument>(V)) return ValueRankMap[V];   // Function argument...
81
82   if (Instruction *I = dyn_cast<Instruction>(V)) {
83     // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
84     // we can reassociate expressions for code motion!  Since we do not recurse
85     // for PHI nodes, we cannot have infinite recursion here, because there
86     // cannot be loops in the value graph that do not go through PHI nodes.
87     //
88     if (I->getOpcode() == Instruction::PHI ||
89         I->getOpcode() == Instruction::Alloca ||
90         I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
91         I->mayWriteToMemory())  // Cannot move inst if it writes to memory!
92       return RankMap[I->getParent()];
93
94     unsigned &CachedRank = ValueRankMap[I];
95     if (CachedRank) return CachedRank;    // Rank already known?
96
97     // If not, compute it!
98     unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
99     for (unsigned i = 0, e = I->getNumOperands();
100          i != e && Rank != MaxRank; ++i)
101       Rank = std::max(Rank, getRank(I->getOperand(i)));
102
103     DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
104                     << Rank+1 << "\n");
105
106     return CachedRank = Rank+1;
107   }
108
109   // Otherwise it's a global or constant, rank 0.
110   return 0;
111 }
112
113
114 bool Reassociate::ReassociateExpr(BinaryOperator *I) {
115   Value *LHS = I->getOperand(0);
116   Value *RHS = I->getOperand(1);
117   unsigned LHSRank = getRank(LHS);
118   unsigned RHSRank = getRank(RHS);
119   
120   bool Changed = false;
121
122   // Make sure the LHS of the operand always has the greater rank...
123   if (LHSRank < RHSRank) {
124     bool Success = !I->swapOperands();
125     assert(Success && "swapOperands failed");
126
127     std::swap(LHS, RHS);
128     std::swap(LHSRank, RHSRank);
129     Changed = true;
130     ++NumSwapped;
131     DEBUG(std::cerr << "Transposed: " << I
132           /* << " Result BB: " << I->getParent()*/);
133   }
134   
135   // If the LHS is the same operator as the current one is, and if we are the
136   // only expression using it...
137   //
138   if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
139     if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
140       // If the rank of our current RHS is less than the rank of the LHS's LHS,
141       // then we reassociate the two instructions...
142
143       unsigned TakeOp = 0;
144       if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
145         if (IOp->getOpcode() == LHSI->getOpcode())
146           TakeOp = 1;   // Hoist out non-tree portion
147
148       if (RHSRank < getRank(LHSI->getOperand(TakeOp))) {
149         // Convert ((a + 12) + 10) into (a + (12 + 10))
150         I->setOperand(0, LHSI->getOperand(TakeOp));
151         LHSI->setOperand(TakeOp, RHS);
152         I->setOperand(1, LHSI);
153
154         // Move the LHS expression forward, to ensure that it is dominated by
155         // its operands.
156         LHSI->getParent()->getInstList().remove(LHSI);
157         I->getParent()->getInstList().insert(I, LHSI);
158
159         ++NumChanged;
160         DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
161                                                    << I->getParent()*/);
162
163         // Since we modified the RHS instruction, make sure that we recheck it.
164         ReassociateExpr(LHSI);
165         ReassociateExpr(I);
166         return true;
167       }
168     }
169
170   return Changed;
171 }
172
173
174 // NegateValue - Insert instructions before the instruction pointed to by BI,
175 // that computes the negative version of the value specified.  The negative
176 // version of the value is returned, and BI is left pointing at the instruction
177 // that should be processed next by the reassociation pass.
178 //
179 static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
180   // We are trying to expose opportunity for reassociation.  One of the things
181   // that we want to do to achieve this is to push a negation as deep into an
182   // expression chain as possible, to expose the add instructions.  In practice,
183   // this means that we turn this:
184   //   X = -(A+12+C+D)   into    X = -A + -12 + -C + -D = -12 + -A + -C + -D
185   // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
186   // the constants.  We assume that instcombine will clean up the mess later if
187   // we introduce tons of unnecessary negation instructions...
188   //
189   if (Instruction *I = dyn_cast<Instruction>(V))
190     if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
191       Value *RHS = NegateValue(I->getOperand(1), BI);
192       Value *LHS = NegateValue(I->getOperand(0), BI);
193
194       // We must actually insert a new add instruction here, because the neg
195       // instructions do not dominate the old add instruction in general.  By
196       // adding it now, we are assured that the neg instructions we just
197       // inserted dominate the instruction we are about to insert after them.
198       //
199       return BinaryOperator::create(Instruction::Add, LHS, RHS,
200                                     I->getName()+".neg",
201                                     cast<Instruction>(RHS)->getNext());
202     }
203
204   // Insert a 'neg' instruction that subtracts the value from zero to get the
205   // negation.
206   //
207   return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
208 }
209
210
211 bool Reassociate::ReassociateBB(BasicBlock *BB) {
212   bool Changed = false;
213   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
214
215     DEBUG(std::cerr << "Processing: " << *BI);
216     if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) {
217       // Convert a subtract into an add and a neg instruction... so that sub
218       // instructions can be commuted with other add instructions...
219       //
220       // Calculate the negative value of Operand 1 of the sub instruction...
221       // and set it as the RHS of the add instruction we just made...
222       //
223       std::string Name = BI->getName();
224       BI->setName("");
225       Instruction *New =
226         BinaryOperator::create(Instruction::Add, BI->getOperand(0),
227                                BI->getOperand(1), Name, BI);
228
229       // Everyone now refers to the add instruction...
230       BI->replaceAllUsesWith(New);
231
232       // Put the new add in the place of the subtract... deleting the subtract
233       BB->getInstList().erase(BI);
234
235       BI = New;
236       New->setOperand(1, NegateValue(New->getOperand(1), BI));
237       
238       Changed = true;
239       DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
240     }
241
242     // If this instruction is a commutative binary operator, and the ranks of
243     // the two operands are sorted incorrectly, fix it now.
244     //
245     if (BI->isAssociative()) {
246       BinaryOperator *I = cast<BinaryOperator>(BI);
247       if (!I->use_empty()) {
248         // Make sure that we don't have a tree-shaped computation.  If we do,
249         // linearize it.  Convert (A+B)+(C+D) into ((A+B)+C)+D
250         //
251         Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
252         Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
253         if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
254             RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
255             RHSI->hasOneUse()) {
256           // Insert a new temporary instruction... (A+B)+C
257           BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
258                                                        RHSI->getOperand(0),
259                                                        RHSI->getName()+".ra",
260                                                        BI);
261           BI = Tmp;
262           I->setOperand(0, Tmp);
263           I->setOperand(1, RHSI->getOperand(1));
264
265           // Process the temporary instruction for reassociation now.
266           I = Tmp;
267           ++NumLinear;
268           Changed = true;
269           DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
270         }
271
272         // Make sure that this expression is correctly reassociated with respect
273         // to it's used values...
274         //
275         Changed |= ReassociateExpr(I);
276       }
277     }
278   }
279
280   return Changed;
281 }
282
283
284 bool Reassociate::runOnFunction(Function &F) {
285   // Recalculate the rank map for F
286   BuildRankMap(F);
287
288   bool Changed = false;
289   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
290     Changed |= ReassociateBB(FI);
291
292   // We are done with the rank map...
293   RankMap.clear();
294   ValueRankMap.clear();
295   return Changed;
296 }
297
298 } // End llvm namespace