blob: 9e22ec4e7e5cb302ef399816285bdee5c38aceb1 [file] [log] [blame]
Chris Lattnerc0f58002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattnerc0f58002002-05-08 22:19:27 +00009//
10// This pass reassociates commutative expressions in an order that is designed
Chris Lattner36663782003-05-02 19:26:34 +000011// to promote better constant propagation, GCSE, LICM, PRE...
Chris Lattnerc0f58002002-05-08 22:19:27 +000012//
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"
Chris Lattnerc0f58002002-05-08 22:19:27 +000028#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"
Chris Lattner8abcd562003-08-01 22:15:03 +000033#include "Support/Debug.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000034#include "Support/PostOrderIterator.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000035#include "Support/Statistic.h"
Chris Lattnerc0f58002002-05-08 22:19:27 +000036
Brian Gaeke960707c2003-11-11 22:41:34 +000037namespace llvm {
38
Chris Lattnerc0f58002002-05-08 22:19:27 +000039namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000040 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
Chris Lattnerc0f58002002-05-08 22:19:27 +000044 class Reassociate : public FunctionPass {
Chris Lattner10073a92002-07-25 06:17:51 +000045 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner8ac196d2003-08-13 16:16:26 +000046 std::map<Value*, unsigned> ValueRankMap;
Chris Lattnerc0f58002002-05-08 22:19:27 +000047 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000048 bool runOnFunction(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000049
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000051 AU.setPreservesCFG();
Chris Lattnerc0f58002002-05-08 22:19:27 +000052 }
53 private:
Chris Lattner113f4f42002-06-25 16:13:24 +000054 void BuildRankMap(Function &F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000055 unsigned getRank(Value *V);
56 bool ReassociateExpr(BinaryOperator *I);
57 bool ReassociateBB(BasicBlock *BB);
58 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000059
Chris Lattnerc8b70922002-07-26 21:12:46 +000060 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattnerc0f58002002-05-08 22:19:27 +000061}
62
Brian Gaeke960707c2003-11-11 22:41:34 +000063// Public interface to the Reassociate pass
Misha Brukmanad03afc2003-11-07 17:20:18 +000064FunctionPass *createReassociatePass() { return new Reassociate(); }
Chris Lattnerc0f58002002-05-08 22:19:27 +000065
Chris Lattner113f4f42002-06-25 16:13:24 +000066void Reassociate::BuildRankMap(Function &F) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000067 unsigned i = 2;
Chris Lattner8ac196d2003-08-13 16:16:26 +000068
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
Chris Lattner113f4f42002-06-25 16:13:24 +000073 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattnerc0f58002002-05-08 22:19:27 +000074 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
75 E = RPOT.end(); I != E; ++I)
Chris Lattner58c7eb62003-08-12 20:14:27 +000076 RankMap[*I] = ++i << 16;
Chris Lattnerc0f58002002-05-08 22:19:27 +000077}
78
79unsigned Reassociate::getRank(Value *V) {
Chris Lattner8ac196d2003-08-13 16:16:26 +000080 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
81
Chris Lattnerc0f58002002-05-08 22:19:27 +000082 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner58c7eb62003-08-12 20:14:27 +000083 // 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.
Chris Lattnerc0f58002002-05-08 22:19:27 +000087 //
Chris Lattnerb94550e2003-10-19 21:34:28 +000088 if (I->getOpcode() == Instruction::PHI ||
Chris Lattnerc0f58002002-05-08 22:19:27 +000089 I->getOpcode() == Instruction::Alloca ||
90 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
Chris Lattner4869f372003-02-24 20:48:32 +000091 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
Chris Lattnerc0f58002002-05-08 22:19:27 +000092 return RankMap[I->getParent()];
93
Chris Lattner8ac196d2003-08-13 16:16:26 +000094 unsigned &CachedRank = ValueRankMap[I];
Chris Lattner3aa77672002-12-15 03:56:00 +000095 if (CachedRank) return CachedRank; // Rank already known?
96
97 // If not, compute it!
Chris Lattner7bc532d2002-05-16 04:37:07 +000098 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
99 for (unsigned i = 0, e = I->getNumOperands();
100 i != e && Rank != MaxRank; ++i)
Chris Lattnerc0f58002002-05-08 22:19:27 +0000101 Rank = std::max(Rank, getRank(I->getOperand(i)));
102
Chris Lattner58c7eb62003-08-12 20:14:27 +0000103 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
104 << Rank+1 << "\n");
105
106 return CachedRank = Rank+1;
Chris Lattnerc0f58002002-05-08 22:19:27 +0000107 }
108
109 // Otherwise it's a global or constant, rank 0.
110 return 0;
111}
112
113
Chris Lattnerc0f58002002-05-08 22:19:27 +0000114bool 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) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000124 bool Success = !I->swapOperands();
125 assert(Success && "swapOperands failed");
126
Chris Lattnerc0f58002002-05-08 22:19:27 +0000127 std::swap(LHS, RHS);
128 std::swap(LHSRank, RHSRank);
129 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000130 ++NumSwapped;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000131 DEBUG(std::cerr << "Transposed: " << I
132 /* << " Result BB: " << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000133 }
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))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000139 if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000140 // If the rank of our current RHS is less than the rank of the LHS's LHS,
141 // then we reassociate the two instructions...
Chris Lattnerc0f58002002-05-08 22:19:27 +0000142
Chris Lattner98b3ecd2003-08-12 21:45:24 +0000143 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))) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000149 // Convert ((a + 12) + 10) into (a + (12 + 10))
150 I->setOperand(0, LHSI->getOperand(TakeOp));
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000151 LHSI->setOperand(TakeOp, RHS);
152 I->setOperand(1, LHSI);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000153
154 // Move the LHS expression forward, to ensure that it is dominated by
155 // its operands.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000156 LHSI->getParent()->getInstList().remove(LHSI);
157 I->getParent()->getInstList().insert(I, LHSI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000158
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000159 ++NumChanged;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000160 DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
161 << I->getParent()*/);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000162
163 // Since we modified the RHS instruction, make sure that we recheck it.
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000164 ReassociateExpr(LHSI);
Chris Lattner58c7eb62003-08-12 20:14:27 +0000165 ReassociateExpr(I);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000166 return true;
167 }
168 }
169
170 return Changed;
171}
172
173
Chris Lattner7bc532d2002-05-16 04:37:07 +0000174// 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//
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000179static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000180 // 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
Misha Brukman7eb05a12003-08-18 14:43:39 +0000187 // we introduce tons of unnecessary negation instructions...
Chris Lattner7bc532d2002-05-16 04:37:07 +0000188 //
189 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000190 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000191 Value *RHS = NegateValue(I->getOperand(1), BI);
192 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000193
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 //
Chris Lattner28a8d242002-09-10 17:04:02 +0000199 return BinaryOperator::create(Instruction::Add, LHS, RHS,
200 I->getName()+".neg",
201 cast<Instruction>(RHS)->getNext());
Chris Lattner7bc532d2002-05-16 04:37:07 +0000202 }
203
204 // Insert a 'neg' instruction that subtracts the value from zero to get the
205 // negation.
206 //
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000207 return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000208}
209
210
Chris Lattnerc0f58002002-05-08 22:19:27 +0000211bool Reassociate::ReassociateBB(BasicBlock *BB) {
212 bool Changed = false;
213 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000214
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000215 DEBUG(std::cerr << "Processing: " << *BI);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000216 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;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000239 DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000240 }
241
Chris Lattnerc0f58002002-05-08 22:19:27 +0000242 // If this instruction is a commutative binary operator, and the ranks of
243 // the two operands are sorted incorrectly, fix it now.
244 //
Chris Lattner8fdf75c2002-10-31 17:12:59 +0000245 if (BI->isAssociative()) {
Chris Lattner889f6202003-04-23 16:37:45 +0000246 BinaryOperator *I = cast<BinaryOperator>(BI);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000247 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() &&
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000255 RHSI->hasOneUse()) {
Chris Lattner7bc532d2002-05-16 04:37:07 +0000256 // Insert a new temporary instruction... (A+B)+C
257 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
258 RHSI->getOperand(0),
Chris Lattner28a8d242002-09-10 17:04:02 +0000259 RHSI->getName()+".ra",
260 BI);
261 BI = Tmp;
Chris Lattner7bc532d2002-05-16 04:37:07 +0000262 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;
Chris Lattnerf96c8be2002-12-15 03:49:50 +0000269 DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
Chris Lattner7bc532d2002-05-16 04:37:07 +0000270 }
271
272 // Make sure that this expression is correctly reassociated with respect
273 // to it's used values...
274 //
275 Changed |= ReassociateExpr(I);
276 }
Chris Lattnerc0f58002002-05-08 22:19:27 +0000277 }
278 }
279
280 return Changed;
281}
282
283
Chris Lattner113f4f42002-06-25 16:13:24 +0000284bool Reassociate::runOnFunction(Function &F) {
Chris Lattnerc0f58002002-05-08 22:19:27 +0000285 // Recalculate the rank map for F
286 BuildRankMap(F);
287
288 bool Changed = false;
Chris Lattner113f4f42002-06-25 16:13:24 +0000289 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
290 Changed |= ReassociateBB(FI);
Chris Lattnerc0f58002002-05-08 22:19:27 +0000291
292 // We are done with the rank map...
293 RankMap.clear();
Chris Lattner8ac196d2003-08-13 16:16:26 +0000294 ValueRankMap.clear();
Chris Lattnerc0f58002002-05-08 22:19:27 +0000295 return Changed;
296}
Brian Gaeke960707c2003-11-11 22:41:34 +0000297
298} // End llvm namespace