blob: df0a64188f3e751def73c3922d8d0f3cb30775a2 [file] [log] [blame]
Chris Lattner4fd56002002-05-08 22:19:27 +00001//===- Reassociate.cpp - Reassociate binary expressions -------------------===//
2//
3// This pass reassociates commutative expressions in an order that is designed
4// to promote better constant propogation, 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//
Chris Lattnere4b73042002-10-31 17:12:59 +000017// This code was originally written by Chris Lattner, and was then cleaned up
18// and perfected by Casey Carter.
19//
Chris Lattner4fd56002002-05-08 22:19:27 +000020//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
23#include "llvm/Function.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000024#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/PostOrderIterator.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000030#include "Support/Statistic.h"
Chris Lattner4fd56002002-05-08 22:19:27 +000031
32namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000033 Statistic<> NumLinear ("reassociate","Number of insts linearized");
34 Statistic<> NumChanged("reassociate","Number of insts reassociated");
35 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
36
Chris Lattner4fd56002002-05-08 22:19:27 +000037 class Reassociate : public FunctionPass {
Chris Lattner0c0edf82002-07-25 06:17:51 +000038 std::map<BasicBlock*, unsigned> RankMap;
Chris Lattner4d0a82d2002-12-15 03:56:00 +000039 std::map<Instruction*, unsigned> InstRankMap;
Chris Lattner4fd56002002-05-08 22:19:27 +000040 public:
Chris Lattner7e708292002-06-25 16:13:24 +000041 bool runOnFunction(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000042
43 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +000044 AU.setPreservesCFG();
Chris Lattner4fd56002002-05-08 22:19:27 +000045 }
46 private:
Chris Lattner7e708292002-06-25 16:13:24 +000047 void BuildRankMap(Function &F);
Chris Lattner4fd56002002-05-08 22:19:27 +000048 unsigned getRank(Value *V);
49 bool ReassociateExpr(BinaryOperator *I);
50 bool ReassociateBB(BasicBlock *BB);
51 };
Chris Lattnerf6293092002-07-23 18:06:35 +000052
Chris Lattnera6275cc2002-07-26 21:12:46 +000053 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
Chris Lattner4fd56002002-05-08 22:19:27 +000054}
55
56Pass *createReassociatePass() { return new Reassociate(); }
57
Chris Lattner7e708292002-06-25 16:13:24 +000058void Reassociate::BuildRankMap(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +000059 unsigned i = 1;
Chris Lattner7e708292002-06-25 16:13:24 +000060 ReversePostOrderTraversal<Function*> RPOT(&F);
Chris Lattner4fd56002002-05-08 22:19:27 +000061 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
62 E = RPOT.end(); I != E; ++I)
63 RankMap[*I] = ++i;
64}
65
66unsigned Reassociate::getRank(Value *V) {
67 if (isa<Argument>(V)) return 1; // Function argument...
68 if (Instruction *I = dyn_cast<Instruction>(V)) {
69 // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
70 // can reassociate expressions for code motion! Since we do not recurse for
71 // PHI nodes, we cannot have infinite recursion here, because there cannot
Chris Lattner680f0c22002-12-15 03:49:50 +000072 // be loops in the value graph that do not go through PHI nodes.
Chris Lattner4fd56002002-05-08 22:19:27 +000073 //
74 if (I->getOpcode() == Instruction::PHINode ||
75 I->getOpcode() == Instruction::Alloca ||
76 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
Chris Lattnerf0a93ed2003-02-24 20:48:32 +000077 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
Chris Lattner4fd56002002-05-08 22:19:27 +000078 return RankMap[I->getParent()];
79
Chris Lattner4d0a82d2002-12-15 03:56:00 +000080 unsigned &CachedRank = InstRankMap[I];
81 if (CachedRank) return CachedRank; // Rank already known?
82
83 // If not, compute it!
Chris Lattnera36e6c82002-05-16 04:37:07 +000084 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
85 for (unsigned i = 0, e = I->getNumOperands();
86 i != e && Rank != MaxRank; ++i)
Chris Lattner4fd56002002-05-08 22:19:27 +000087 Rank = std::max(Rank, getRank(I->getOperand(i)));
88
Chris Lattner4d0a82d2002-12-15 03:56:00 +000089 return CachedRank = Rank;
Chris Lattner4fd56002002-05-08 22:19:27 +000090 }
91
92 // Otherwise it's a global or constant, rank 0.
93 return 0;
94}
95
96
Chris Lattner4fd56002002-05-08 22:19:27 +000097bool Reassociate::ReassociateExpr(BinaryOperator *I) {
98 Value *LHS = I->getOperand(0);
99 Value *RHS = I->getOperand(1);
100 unsigned LHSRank = getRank(LHS);
101 unsigned RHSRank = getRank(RHS);
102
103 bool Changed = false;
104
105 // Make sure the LHS of the operand always has the greater rank...
106 if (LHSRank < RHSRank) {
Chris Lattnere4b73042002-10-31 17:12:59 +0000107 bool Success = !I->swapOperands();
108 assert(Success && "swapOperands failed");
109
Chris Lattner4fd56002002-05-08 22:19:27 +0000110 std::swap(LHS, RHS);
111 std::swap(LHSRank, RHSRank);
112 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000113 ++NumSwapped;
Chris Lattner680f0c22002-12-15 03:49:50 +0000114 DEBUG(std::cerr << "Transposed: " << I
115 /* << " Result BB: " << I->getParent()*/);
Chris Lattner4fd56002002-05-08 22:19:27 +0000116 }
117
118 // If the LHS is the same operator as the current one is, and if we are the
119 // only expression using it...
120 //
121 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
122 if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
123 // If the rank of our current RHS is less than the rank of the LHS's LHS,
124 // then we reassociate the two instructions...
125 if (RHSRank < getRank(LHSI->getOperand(0))) {
126 unsigned TakeOp = 0;
127 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
128 if (IOp->getOpcode() == LHSI->getOpcode())
129 TakeOp = 1; // Hoist out non-tree portion
130
131 // Convert ((a + 12) + 10) into (a + (12 + 10))
132 I->setOperand(0, LHSI->getOperand(TakeOp));
Chris Lattner680f0c22002-12-15 03:49:50 +0000133 LHSI->setOperand(TakeOp, RHS);
134 I->setOperand(1, LHSI);
Chris Lattnere4b73042002-10-31 17:12:59 +0000135
136 // Move the LHS expression forward, to ensure that it is dominated by
137 // its operands.
Chris Lattner680f0c22002-12-15 03:49:50 +0000138 LHSI->getParent()->getInstList().remove(LHSI);
139 I->getParent()->getInstList().insert(I, LHSI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000140
Chris Lattner3dec1f22002-05-10 15:38:35 +0000141 ++NumChanged;
Chris Lattner680f0c22002-12-15 03:49:50 +0000142 DEBUG(std::cerr << "Reassociated: " << I/* << " Result BB: "
143 << I->getParent()*/);
Chris Lattner4fd56002002-05-08 22:19:27 +0000144
145 // Since we modified the RHS instruction, make sure that we recheck it.
Chris Lattner680f0c22002-12-15 03:49:50 +0000146 ReassociateExpr(LHSI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000147 return true;
148 }
149 }
150
151 return Changed;
152}
153
154
Chris Lattnera36e6c82002-05-16 04:37:07 +0000155// NegateValue - Insert instructions before the instruction pointed to by BI,
156// that computes the negative version of the value specified. The negative
157// version of the value is returned, and BI is left pointing at the instruction
158// that should be processed next by the reassociation pass.
159//
Chris Lattnere4b73042002-10-31 17:12:59 +0000160static Value *NegateValue(Value *V, BasicBlock::iterator &BI) {
Chris Lattnera36e6c82002-05-16 04:37:07 +0000161 // We are trying to expose opportunity for reassociation. One of the things
162 // that we want to do to achieve this is to push a negation as deep into an
163 // expression chain as possible, to expose the add instructions. In practice,
164 // this means that we turn this:
165 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
166 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
167 // the constants. We assume that instcombine will clean up the mess later if
168 // we introduce tons of unneccesary negation instructions...
169 //
170 if (Instruction *I = dyn_cast<Instruction>(V))
171 if (I->getOpcode() == Instruction::Add && I->use_size() == 1) {
Chris Lattnere4b73042002-10-31 17:12:59 +0000172 Value *RHS = NegateValue(I->getOperand(1), BI);
173 Value *LHS = NegateValue(I->getOperand(0), BI);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000174
175 // We must actually insert a new add instruction here, because the neg
176 // instructions do not dominate the old add instruction in general. By
177 // adding it now, we are assured that the neg instructions we just
178 // inserted dominate the instruction we are about to insert after them.
179 //
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000180 return BinaryOperator::create(Instruction::Add, LHS, RHS,
181 I->getName()+".neg",
182 cast<Instruction>(RHS)->getNext());
Chris Lattnera36e6c82002-05-16 04:37:07 +0000183 }
184
185 // Insert a 'neg' instruction that subtracts the value from zero to get the
186 // negation.
187 //
Chris Lattnere4b73042002-10-31 17:12:59 +0000188 return BI = BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000189}
190
191
Chris Lattner4fd56002002-05-08 22:19:27 +0000192bool Reassociate::ReassociateBB(BasicBlock *BB) {
193 bool Changed = false;
194 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000195
Chris Lattner680f0c22002-12-15 03:49:50 +0000196 DEBUG(std::cerr << "Processing: " << *BI);
Chris Lattnere4b73042002-10-31 17:12:59 +0000197 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI)) {
198 // Convert a subtract into an add and a neg instruction... so that sub
199 // instructions can be commuted with other add instructions...
200 //
201 // Calculate the negative value of Operand 1 of the sub instruction...
202 // and set it as the RHS of the add instruction we just made...
203 //
204 std::string Name = BI->getName();
205 BI->setName("");
206 Instruction *New =
207 BinaryOperator::create(Instruction::Add, BI->getOperand(0),
208 BI->getOperand(1), Name, BI);
209
210 // Everyone now refers to the add instruction...
211 BI->replaceAllUsesWith(New);
212
213 // Put the new add in the place of the subtract... deleting the subtract
214 BB->getInstList().erase(BI);
215
216 BI = New;
217 New->setOperand(1, NegateValue(New->getOperand(1), BI));
218
219 Changed = true;
Chris Lattner680f0c22002-12-15 03:49:50 +0000220 DEBUG(std::cerr << "Negated: " << New /*<< " Result BB: " << BB*/);
Chris Lattnere4b73042002-10-31 17:12:59 +0000221 }
222
Chris Lattner4fd56002002-05-08 22:19:27 +0000223 // If this instruction is a commutative binary operator, and the ranks of
224 // the two operands are sorted incorrectly, fix it now.
225 //
Chris Lattnere4b73042002-10-31 17:12:59 +0000226 if (BI->isAssociative()) {
227 BinaryOperator *I = cast<BinaryOperator>(&*BI);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000228 if (!I->use_empty()) {
229 // Make sure that we don't have a tree-shaped computation. If we do,
230 // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D
231 //
232 Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
233 Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
234 if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
235 RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
236 RHSI->use_size() == 1) {
237 // Insert a new temporary instruction... (A+B)+C
238 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
239 RHSI->getOperand(0),
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000240 RHSI->getName()+".ra",
241 BI);
242 BI = Tmp;
Chris Lattnera36e6c82002-05-16 04:37:07 +0000243 I->setOperand(0, Tmp);
244 I->setOperand(1, RHSI->getOperand(1));
245
246 // Process the temporary instruction for reassociation now.
247 I = Tmp;
248 ++NumLinear;
249 Changed = true;
Chris Lattner680f0c22002-12-15 03:49:50 +0000250 DEBUG(std::cerr << "Linearized: " << I/* << " Result BB: " << BB*/);
Chris Lattnera36e6c82002-05-16 04:37:07 +0000251 }
252
253 // Make sure that this expression is correctly reassociated with respect
254 // to it's used values...
255 //
256 Changed |= ReassociateExpr(I);
257 }
Chris Lattner4fd56002002-05-08 22:19:27 +0000258 }
259 }
260
261 return Changed;
262}
263
264
Chris Lattner7e708292002-06-25 16:13:24 +0000265bool Reassociate::runOnFunction(Function &F) {
Chris Lattner4fd56002002-05-08 22:19:27 +0000266 // Recalculate the rank map for F
267 BuildRankMap(F);
268
269 bool Changed = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000270 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
271 Changed |= ReassociateBB(FI);
Chris Lattner4fd56002002-05-08 22:19:27 +0000272
273 // We are done with the rank map...
274 RankMap.clear();
Chris Lattner4d0a82d2002-12-15 03:56:00 +0000275 InstRankMap.clear();
Chris Lattner4fd56002002-05-08 22:19:27 +0000276 return Changed;
277}