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