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/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Type.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Constant.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"
37 Statistic<> NumLinear ("reassociate","Number of insts linearized");
38 Statistic<> NumChanged("reassociate","Number of insts reassociated");
39 Statistic<> NumSwapped("reassociate","Number of insts with operands swapped");
41 class Reassociate : public FunctionPass {
42 std::map<BasicBlock*, unsigned> RankMap;
43 std::map<Value*, unsigned> ValueRankMap;
45 bool runOnFunction(Function &F);
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 void BuildRankMap(Function &F);
52 unsigned getRank(Value *V);
53 bool ReassociateExpr(BinaryOperator *I);
54 bool ReassociateBB(BasicBlock *BB);
57 RegisterOpt<Reassociate> X("reassociate", "Reassociate expressions");
60 // Public interface to the Reassociate pass
61 FunctionPass *llvm::createReassociatePass() { return new Reassociate(); }
63 void Reassociate::BuildRankMap(Function &F) {
66 // Assign distinct ranks to function arguments
67 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
68 ValueRankMap[I] = ++i;
70 ReversePostOrderTraversal<Function*> RPOT(&F);
71 for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
72 E = RPOT.end(); I != E; ++I)
73 RankMap[*I] = ++i << 16;
76 unsigned Reassociate::getRank(Value *V) {
77 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument...
79 Instruction *I = dyn_cast<Instruction>(V);
80 if (I == 0) return 0; // Otherwise it's a global or constant, rank 0.
82 unsigned &CachedRank = ValueRankMap[I];
83 if (CachedRank) return CachedRank; // Rank already known?
85 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
86 // we can reassociate expressions for code motion! Since we do not recurse
87 // for PHI nodes, we cannot have infinite recursion here, because there
88 // cannot be loops in the value graph that do not go through PHI nodes.
90 if (I->getOpcode() == Instruction::PHI ||
91 I->getOpcode() == Instruction::Alloca ||
92 I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
93 I->mayWriteToMemory()) // Cannot move inst if it writes to memory!
94 return RankMap[I->getParent()];
96 // If not, compute it!
97 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
98 for (unsigned i = 0, e = I->getNumOperands();
99 i != e && Rank != MaxRank; ++i)
100 Rank = std::max(Rank, getRank(I->getOperand(i)));
102 DEBUG(std::cerr << "Calculated Rank[" << V->getName() << "] = "
105 return CachedRank = Rank+1;
109 bool Reassociate::ReassociateExpr(BinaryOperator *I) {
110 Value *LHS = I->getOperand(0);
111 Value *RHS = I->getOperand(1);
112 unsigned LHSRank = getRank(LHS);
113 unsigned RHSRank = getRank(RHS);
115 bool Changed = false;
117 // Make sure the LHS of the operand always has the greater rank...
118 if (LHSRank < RHSRank) {
119 bool Success = !I->swapOperands();
120 assert(Success && "swapOperands failed");
123 std::swap(LHSRank, RHSRank);
126 DEBUG(std::cerr << "Transposed: " << *I
127 /* << " Result BB: " << I->getParent()*/);
130 // If the LHS is the same operator as the current one is, and if we are the
131 // only expression using it...
133 if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
134 if (LHSI->getOpcode() == I->getOpcode() && LHSI->hasOneUse()) {
135 // If the rank of our current RHS is less than the rank of the LHS's LHS,
136 // then we reassociate the two instructions...
139 if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
140 if (IOp->getOpcode() == LHSI->getOpcode())
141 TakeOp = 1; // Hoist out non-tree portion
143 if (RHSRank < getRank(LHSI->getOperand(TakeOp))) {
144 // Convert ((a + 12) + 10) into (a + (12 + 10))
145 I->setOperand(0, LHSI->getOperand(TakeOp));
146 LHSI->setOperand(TakeOp, RHS);
147 I->setOperand(1, LHSI);
149 // Move the LHS expression forward, to ensure that it is dominated by
151 LHSI->getParent()->getInstList().remove(LHSI);
152 I->getParent()->getInstList().insert(I, LHSI);
155 DEBUG(std::cerr << "Reassociated: " << *I/* << " Result BB: "
156 << I->getParent()*/);
158 // Since we modified the RHS instruction, make sure that we recheck it.
159 ReassociateExpr(LHSI);
169 // NegateValue - Insert instructions before the instruction pointed to by BI,
170 // that computes the negative version of the value specified. The negative
171 // version of the value is returned, and BI is left pointing at the instruction
172 // that should be processed next by the reassociation pass.
174 static Value *NegateValue(Value *V, Instruction *BI) {
175 // We are trying to expose opportunity for reassociation. One of the things
176 // that we want to do to achieve this is to push a negation as deep into an
177 // expression chain as possible, to expose the add instructions. In practice,
178 // this means that we turn this:
179 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
180 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
181 // the constants. We assume that instcombine will clean up the mess later if
182 // we introduce tons of unnecessary negation instructions...
184 if (Instruction *I = dyn_cast<Instruction>(V))
185 if (I->getOpcode() == Instruction::Add && I->hasOneUse()) {
186 Value *RHS = NegateValue(I->getOperand(1), BI);
187 Value *LHS = NegateValue(I->getOperand(0), BI);
189 // We must actually insert a new add instruction here, because the neg
190 // instructions do not dominate the old add instruction in general. By
191 // adding it now, we are assured that the neg instructions we just
192 // inserted dominate the instruction we are about to insert after them.
194 return BinaryOperator::create(Instruction::Add, LHS, RHS,
195 I->getName()+".neg", BI);
198 // Insert a 'neg' instruction that subtracts the value from zero to get the
201 return BinaryOperator::createNeg(V, V->getName() + ".neg", BI);
204 /// isReassociableOp - Return true if V is an instruction of the specified
205 /// opcode and if it only has one use.
206 static bool isReassociableOp(Value *V, unsigned Opcode) {
207 return V->hasOneUse() && isa<Instruction>(V) &&
208 cast<Instruction>(V)->getOpcode() == Opcode;
211 /// BreakUpSubtract - If we have (X-Y), and if either X is an add, or if this is
212 /// only used by an add, transform this into (X+(0-Y)) to promote better
214 static Instruction *BreakUpSubtract(Instruction *Sub) {
215 // Reject cases where it is pointless to do this.
216 if (Sub->getType()->isFloatingPoint())
217 return 0; // Floating point adds are not associative.
219 // Don't bother to break this up unless either the LHS is an associable add or
220 // if this is only used by one.
221 if (!isReassociableOp(Sub->getOperand(0), Instruction::Add) &&
222 !isReassociableOp(Sub->getOperand(1), Instruction::Add) &&
223 !(Sub->hasOneUse() &&isReassociableOp(Sub->use_back(), Instruction::Add)))
226 // Convert a subtract into an add and a neg instruction... so that sub
227 // instructions can be commuted with other add instructions...
229 // Calculate the negative value of Operand 1 of the sub instruction...
230 // and set it as the RHS of the add instruction we just made...
232 std::string Name = Sub->getName();
234 Value *NegVal = NegateValue(Sub->getOperand(1), Sub);
236 BinaryOperator::createAdd(Sub->getOperand(0), NegVal, Name, Sub);
238 // Everyone now refers to the add instruction.
239 Sub->replaceAllUsesWith(New);
240 Sub->eraseFromParent();
242 DEBUG(std::cerr << "Negated: " << *New);
247 /// ReassociateBB - Inspect all of the instructions in this basic block,
248 /// reassociating them as we go.
249 bool Reassociate::ReassociateBB(BasicBlock *BB) {
250 bool Changed = false;
251 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
252 // If this is a subtract instruction which is not already in negate form,
253 // see if we can convert it to X+-Y.
254 if (BI->getOpcode() == Instruction::Sub && !BinaryOperator::isNeg(BI))
255 if (Instruction *NI = BreakUpSubtract(BI)) {
260 // If this instruction is a commutative binary operator, and the ranks of
261 // the two operands are sorted incorrectly, fix it now.
263 if (BI->isAssociative()) {
264 DEBUG(std::cerr << "Reassociating: " << *BI);
265 BinaryOperator *I = cast<BinaryOperator>(BI);
266 if (!I->use_empty()) {
267 // Make sure that we don't have a tree-shaped computation. If we do,
268 // linearize it. Convert (A+B)+(C+D) into ((A+B)+C)+D
270 Instruction *LHSI = dyn_cast<Instruction>(I->getOperand(0));
271 Instruction *RHSI = dyn_cast<Instruction>(I->getOperand(1));
272 if (LHSI && (int)LHSI->getOpcode() == I->getOpcode() &&
273 RHSI && (int)RHSI->getOpcode() == I->getOpcode() &&
275 // Insert a new temporary instruction... (A+B)+C
276 BinaryOperator *Tmp = BinaryOperator::create(I->getOpcode(), LHSI,
278 RHSI->getName()+".ra",
281 I->setOperand(0, Tmp);
282 I->setOperand(1, RHSI->getOperand(1));
284 // Process the temporary instruction for reassociation now.
288 DEBUG(std::cerr << "Linearized: " << *I/* << " Result BB: " << BB*/);
291 // Make sure that this expression is correctly reassociated with respect
292 // to it's used values...
294 Changed |= ReassociateExpr(I);
303 bool Reassociate::runOnFunction(Function &F) {
304 // Recalculate the rank map for F
307 bool Changed = false;
308 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
309 Changed |= ReassociateBB(FI);
311 // We are done with the rank map...
313 ValueRankMap.clear();