Add support for printing out statistics information when -stats is added to
[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 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 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Function.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/iOperators.h"
23 #include "llvm/Type.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Support/CFG.h"
27 #include "Support/PostOrderIterator.h"
28 #include "Support/StatisticReporter.h"
29
30 static Statistic<> NumChanged("reassociate\t- Number of insts reassociated");
31 static Statistic<> NumSwapped("reassociate\t- Number of insts with operands swapped");
32
33 namespace {
34   class Reassociate : public FunctionPass {
35     map<BasicBlock*, unsigned> RankMap;
36   public:
37     const char *getPassName() const {
38       return "Expression Reassociation";
39     }
40
41     bool runOnFunction(Function *F);
42
43     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44       AU.preservesCFG();
45     }
46   private:
47     void BuildRankMap(Function *F);
48     unsigned getRank(Value *V);
49     bool ReassociateExpr(BinaryOperator *I);
50     bool ReassociateBB(BasicBlock *BB);
51   };
52 }
53
54 Pass *createReassociatePass() { return new Reassociate(); }
55
56 void Reassociate::BuildRankMap(Function *F) {
57   unsigned i = 1;
58   ReversePostOrderTraversal<Function*> RPOT(F);
59   for (ReversePostOrderTraversal<Function*>::rpo_iterator I = RPOT.begin(),
60          E = RPOT.end(); I != E; ++I)
61     RankMap[*I] = ++i;
62 }
63
64 unsigned Reassociate::getRank(Value *V) {
65   if (isa<Argument>(V)) return 1;   // Function argument...
66   if (Instruction *I = dyn_cast<Instruction>(V)) {
67     // If this is an expression, return the MAX(rank(LHS), rank(RHS)) so that we
68     // can reassociate expressions for code motion!  Since we do not recurse for
69     // PHI nodes, we cannot have infinite recursion here, because there cannot
70     // be loops in the value graph (except for PHI nodes).
71     //
72     if (I->getOpcode() == Instruction::PHINode ||
73         I->getOpcode() == Instruction::Alloca ||
74         I->getOpcode() == Instruction::Malloc || isa<TerminatorInst>(I) ||
75         I->hasSideEffects())
76       return RankMap[I->getParent()];
77
78     unsigned Rank = 0;
79     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
80       Rank = std::max(Rank, getRank(I->getOperand(i)));
81
82     return Rank;
83   }
84
85   // Otherwise it's a global or constant, rank 0.
86   return 0;
87 }
88
89
90 // isCommutativeOperator - Return true if the specified instruction is
91 // commutative and associative.  If the instruction is not commutative and
92 // associative, we can not reorder its operands!
93 //
94 static inline BinaryOperator *isCommutativeOperator(Instruction *I) {
95   // Floating point operations do not commute!
96   if (I->getType()->isFloatingPoint()) return 0;
97
98   if (I->getOpcode() == Instruction::Add || 
99       I->getOpcode() == Instruction::Mul ||
100       I->getOpcode() == Instruction::And || 
101       I->getOpcode() == Instruction::Or  ||
102       I->getOpcode() == Instruction::Xor)
103     return cast<BinaryOperator>(I);
104   return 0;    
105 }
106
107
108 bool Reassociate::ReassociateExpr(BinaryOperator *I) {
109   Value *LHS = I->getOperand(0);
110   Value *RHS = I->getOperand(1);
111   unsigned LHSRank = getRank(LHS);
112   unsigned RHSRank = getRank(RHS);
113   
114   bool Changed = false;
115
116   // Make sure the LHS of the operand always has the greater rank...
117   if (LHSRank < RHSRank) {
118     I->swapOperands();
119     std::swap(LHS, RHS);
120     std::swap(LHSRank, RHSRank);
121     Changed = true;
122     ++NumSwapped;
123     //cerr << "Transposed: " << I << " Result BB: " << I->getParent();
124   }
125   
126   // If the LHS is the same operator as the current one is, and if we are the
127   // only expression using it...
128   //
129   if (BinaryOperator *LHSI = dyn_cast<BinaryOperator>(LHS))
130     if (LHSI->getOpcode() == I->getOpcode() && LHSI->use_size() == 1) {
131       // If the rank of our current RHS is less than the rank of the LHS's LHS,
132       // then we reassociate the two instructions...
133       if (RHSRank < getRank(LHSI->getOperand(0))) {
134         unsigned TakeOp = 0;
135         if (BinaryOperator *IOp = dyn_cast<BinaryOperator>(LHSI->getOperand(0)))
136           if (IOp->getOpcode() == LHSI->getOpcode())
137             TakeOp = 1;   // Hoist out non-tree portion
138
139         // Convert ((a + 12) + 10) into (a + (12 + 10))
140         I->setOperand(0, LHSI->getOperand(TakeOp));
141         LHSI->setOperand(TakeOp, RHS);
142         I->setOperand(1, LHSI);
143
144         ++NumChanged;
145         //cerr << "Reassociated: " << I << " Result BB: " << I->getParent();
146
147         // Since we modified the RHS instruction, make sure that we recheck it.
148         ReassociateExpr(LHSI);
149         return true;
150       }
151     }
152
153   return Changed;
154 }
155
156
157 bool Reassociate::ReassociateBB(BasicBlock *BB) {
158   bool Changed = false;
159   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end(); ++BI) {
160     Instruction *Inst = *BI;
161
162     // If this instruction is a commutative binary operator, and the ranks of
163     // the two operands are sorted incorrectly, fix it now.
164     //
165     if (BinaryOperator *I = isCommutativeOperator(Inst)) {
166       // Make sure that this expression is correctly reassociated with respect
167       // to it's used values...
168       //
169       Changed |= ReassociateExpr(I);
170
171     } else if (Inst->getOpcode() == Instruction::Sub &&
172                Inst->getOperand(0) != Constant::getNullValue(Inst->getType())) {
173       // Convert a subtract into an add and a neg instruction... so that sub
174       // instructions can be commuted with other add instructions...
175       //
176       Instruction *New = BinaryOperator::create(Instruction::Add,
177                                                 Inst->getOperand(0), Inst,
178                                                 Inst->getName());
179       // Everyone now refers to the add instruction...
180       Inst->replaceAllUsesWith(New);
181       Inst->setName(Inst->getOperand(1)->getName()+".neg");
182       New->setOperand(1, Inst);        // Except for the add inst itself!
183
184       BI = BB->getInstList().insert(BI+1, New)-1;  // Add to the basic block...
185       Inst->setOperand(0, Constant::getNullValue(Inst->getType()));
186       Changed = true;
187     }
188   }
189
190   return Changed;
191 }
192
193
194 bool Reassociate::runOnFunction(Function *F) {
195   // Recalculate the rank map for F
196   BuildRankMap(F);
197
198   bool Changed = false;
199   for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
200     Changed |= ReassociateBB(*FI);
201
202   // We are done with the rank map...
203   RankMap.clear();
204   return Changed;
205 }