1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass reassociates commutative expressions in an order that is designed
11 // to promote better constant propagation, GCSE, LICM, PRE...
13 // For example: 4 + (x + 5) -> x + (4 + 5)
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.
21 //===----------------------------------------------------------------------===//
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"
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");
45 ValueEntry(unsigned R, Value *O) : Rank(R), Op(O) {}
47 inline bool operator<(const ValueEntry &LHS, const ValueEntry &RHS) {
48 return LHS.Rank > RHS.Rank; // Sort so that highest rank goes to start.
51 class Reassociate : public FunctionPass {
52 std::map<BasicBlock*, unsigned> RankMap;
53 std::map<Value*, unsigned> ValueRankMap;
56 bool runOnFunction(Function &F);
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
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);
71 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
74 // Public interface to the Reassociate pass
75 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
77 void Reassociate::BuildRankMap(Function &F) {
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;
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;
90 unsigned Reassociate::getRank(Value *V) {
91 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
93 Instruction *I = dyn_cast<Instruction>(V);
94 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
96 unsigned &CachedRank = ValueRankMap[I];
97 if (CachedRank) return CachedRank; // Rank already known?
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.
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()];
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)));
116 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
119 return CachedRank = Rank+1;
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);
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
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?");
142 DEBUG(std::cerr << "Linear" << *LHS << *RHS << *I);
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);
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);
155 DEBUG(std::cerr << "Linearized: " << *I);
157 // If D is part of this expression tree, tail recurse.
158 if (isReassociableOp(I->getOperand(1), I->getOpcode()))
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.
168 /// This returns the rank of the RHS operand, which is known to be the highest
169 /// rank value in the expression tree.
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();
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);
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));
188 // Turn X+(Y+Z) -> (Y+Z)+X
189 std::swap(LHSBO, RHSBO);
191 bool Success = !I->swapOperands();
192 assert(Success && "swapOperands failed");
196 // Turn (A+B)+(C+D) -> (((A+B)+C)+D). This guarantees the the RHS is not
197 // part of the expression tree.
199 LHS = LHSBO = cast<BinaryOperator>(I->getOperand(0));
200 RHS = I->getOperand(1);
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!");
208 // Move LHS right before I to make sure that the tree expression dominates all
210 I->getParent()->getInstList().splice(I,
211 LHSBO->getParent()->getInstList(), LHSBO);
213 // Linearize the expression tree on the LHS.
214 LinearizeExprTree(LHSBO, Ops);
216 // Remember the RHS operand and its rank.
217 Ops.push_back(ValueEntry(getRank(RHS), RHS));
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
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);
237 assert(i+2 < Ops.size() && "Ops index out of range!");
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);
246 RewriteExprTree(cast<BinaryOperator>(I->getOperand(0)), i+1, Ops);
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.
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...
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);
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.
276 return BinaryOperator::create(Instruction::Add, LHS, RHS,
277 I->getName()+".neg", BI);
280 // Insert a 'neg' instruction that subtracts the value from zero to get the
283 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
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
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.
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)))
301 // Convert a subtract into an add and a neg instruction... so that sub
302 // instructions can be commuted with other add instructions...
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...
307 std::string Name = Sub->getName();
309 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
311 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
313 // Everyone now refers to the add instruction.
314 Sub->replaceAllUsesWith(New);
315 Sub->eraseFromParent();
317 DEBUG(std::cerr << "Negated: " << *New);
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
324 static Instruction *ConvertShiftToMul(Instruction *Shl) {
325 if (!isReassociableOp(Shl->getOperand(0), Instruction::Mul) &&
326 !(Shl->hasOneUse() && isReassociableOp(Shl->use_back(),Instruction::Mul)))
329 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
330 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
332 std::string Name = Shl->getName(); Shl->setName("");
333 Instruction *Mul = BinaryOperator::createMul(Shl->getOperand(0), MulCst,
335 Shl->replaceAllUsesWith(Mul);
336 Shl->eraseFromParent();
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)) {
352 if (BI->getOpcode() == Instruction::Shl &&
353 isa<ConstantInt>(BI->getOperand(1)))
354 if (Instruction *NI = ConvertShiftToMul(BI)) {
359 // If this instruction is a commutative binary operator, process it.
360 if (!BI->isAssociative()) continue;
361 BinaryOperator *I = cast<BinaryOperator>(BI);
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()))
368 // First, walk the expression tree, linearizing the tree, collecting
369 std::vector<ValueEntry> Ops;
370 LinearizeExprTree(I, Ops);
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
378 std::stable_sort(Ops.begin(), Ops.end());
380 // Now that we have the linearized expression tree, try to optimize it.
381 // Start by folding any constants that we found.
384 if (Constant *V1 = dyn_cast<Constant>(Ops[Ops.size()-2].Op))
385 if (Constant *V2 = dyn_cast<Constant>(Ops.back().Op)) {
387 Ops.back().Op = ConstantExpr::get(I->getOpcode(), V1, V2);
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.
394 // FIXME: Handle +0,*1,&~0,... at end of the list.
397 if (Ops.size() == 1) {
398 // This expression tree simplified to something that isn't a tree,
400 I->replaceAllUsesWith(Ops[0].Op);
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);
410 bool Reassociate::runOnFunction(Function &F) {
411 // Recalculate the rank map for F
415 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
418 // We are done with the rank map...
420 ValueRankMap.clear();