Add counters for the number of calls elimianted
[oota-llvm.git] / lib / Transforms / Scalar / GCSE.cpp
1 //===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
10 // This pass is designed to be a very quick global transformation that
11 // eliminates global common subexpressions from a function.  It does this by
12 // using an existing value numbering implementation to identify the common
13 // subexpressions, eliminating them when possible.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/iMemory.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/ValueNumbering.h"
23 #include "llvm/Support/InstIterator.h"
24 #include "Support/Statistic.h"
25 #include "Support/Debug.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 namespace {
30   Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
31   Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
32   Statistic<> NumCallRemoved("gcse", "Number of calls removed");
33   Statistic<> NumNonInsts   ("gcse", "Number of instructions removed due "
34                              "to non-instruction values");
35
36   class GCSE : public FunctionPass {
37     std::set<Instruction*>  WorkList;
38     DominatorSet           *DomSetInfo;
39     ValueNumbering         *VN;
40   public:
41     virtual bool runOnFunction(Function &F);
42
43   private:
44     bool EliminateRedundancies(Instruction *I,std::vector<Value*> &EqualValues);
45     Instruction *EliminateCSE(Instruction *I, Instruction *Other);
46     void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
47
48     // This transformation requires dominator and immediate dominator info
49     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50       AU.setPreservesCFG();
51       AU.addRequired<DominatorSet>();
52       AU.addRequired<ImmediateDominators>();
53       AU.addRequired<ValueNumbering>();
54     }
55   };
56
57   RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
58 }
59
60 // createGCSEPass - The public interface to this file...
61 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
62
63 // GCSE::runOnFunction - This is the main transformation entry point for a
64 // function.
65 //
66 bool GCSE::runOnFunction(Function &F) {
67   bool Changed = false;
68
69   // Get pointers to the analysis results that we will be using...
70   DomSetInfo = &getAnalysis<DominatorSet>();
71   VN = &getAnalysis<ValueNumbering>();
72
73   // Step #1: Add all instructions in the function to the worklist for
74   // processing.  All of the instructions are considered to be our
75   // subexpressions to eliminate if possible.
76   //
77   WorkList.insert(inst_begin(F), inst_end(F));
78
79   // Step #2: WorkList processing.  Iterate through all of the instructions,
80   // checking to see if there are any additionally defined subexpressions in the
81   // program.  If so, eliminate them!
82   //
83   while (!WorkList.empty()) {
84     Instruction &I = **WorkList.begin(); // Get an instruction from the worklist
85     WorkList.erase(WorkList.begin());
86
87     // If this instruction computes a value, try to fold together common
88     // instructions that compute it.
89     //
90     if (I.getType() != Type::VoidTy) {
91       std::vector<Value*> EqualValues;
92       VN->getEqualNumberNodes(&I, EqualValues);
93
94       if (!EqualValues.empty())
95         Changed |= EliminateRedundancies(&I, EqualValues);
96     }
97   }
98
99   // When the worklist is empty, return whether or not we changed anything...
100   return Changed;
101 }
102
103 bool GCSE::EliminateRedundancies(Instruction *I,
104                                  std::vector<Value*> &EqualValues) {
105   // If the EqualValues set contains any non-instruction values, then we know
106   // that all of the instructions can be replaced with the non-instruction value
107   // because it is guaranteed to dominate all of the instructions in the
108   // function.  We only have to do hard work if all we have are instructions.
109   //
110   for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
111     if (!isa<Instruction>(EqualValues[i])) {
112       // Found a non-instruction.  Replace all instructions with the
113       // non-instruction.
114       //
115       Value *Replacement = EqualValues[i];
116
117       // Make sure we get I as well...
118       EqualValues[i] = I;
119
120       // Replace all instructions with the Replacement value.
121       for (i = 0; i != e; ++i)
122         if (Instruction *I = dyn_cast<Instruction>(EqualValues[i])) {
123           // Change all users of I to use Replacement.
124           I->replaceAllUsesWith(Replacement);
125
126           if (isa<LoadInst>(I))
127             ++NumLoadRemoved; // Keep track of loads eliminated
128           if (isa<CallInst>(I))
129             ++NumCallRemoved; // Keep track of calls eliminated
130           ++NumInstRemoved;   // Keep track of number of instructions eliminated
131           ++NumNonInsts;      // Keep track of number of insts repl with values
132
133           // Erase the instruction from the program.
134           I->getParent()->getInstList().erase(I);
135           WorkList.erase(I);
136         }
137       
138       return true;
139     }
140   
141   // Remove duplicate entries from EqualValues...
142   std::sort(EqualValues.begin(), EqualValues.end());
143   EqualValues.erase(std::unique(EqualValues.begin(), EqualValues.end()),
144                     EqualValues.end());
145
146   // From this point on, EqualValues is logically a vector of instructions.
147   //
148   bool Changed = false;
149   EqualValues.push_back(I); // Make sure I is included...
150   while (EqualValues.size() > 1) {
151     // FIXME, this could be done better than simple iteration!
152     Instruction *Test = cast<Instruction>(EqualValues.back());
153     EqualValues.pop_back();
154     
155     for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
156       if (Instruction *Ret = EliminateCSE(Test,
157                                           cast<Instruction>(EqualValues[i]))) {
158         if (Ret == Test)          // Eliminated EqualValues[i]
159           EqualValues[i] = Test;  // Make sure that we reprocess I at some point
160         Changed = true;
161         break;
162       }
163   }
164   return Changed;
165 }
166
167
168 // ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
169 // uses of the instruction use First now instead.
170 //
171 void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
172   Instruction &Second = *SI;
173
174   DEBUG(std::cerr << "GCSE: Substituting %" << First->getName() << " for: "
175                   << Second);
176   
177   //cerr << "DEL " << (void*)Second << Second;
178
179   // Add the first instruction back to the worklist
180   WorkList.insert(First);
181
182   // Add all uses of the second instruction to the worklist
183   for (Value::use_iterator UI = Second.use_begin(), UE = Second.use_end();
184        UI != UE; ++UI)
185     WorkList.insert(cast<Instruction>(*UI));
186     
187   // Make all users of 'Second' now use 'First'
188   Second.replaceAllUsesWith(First);
189
190   // Erase the second instruction from the program
191   Second.getParent()->getInstList().erase(SI);
192 }
193
194 // EliminateCSE - The two instruction I & Other have been found to be common
195 // subexpressions.  This function is responsible for eliminating one of them,
196 // and for fixing the worklist to be correct.  The instruction that is preserved
197 // is returned from the function if the other is eliminated, otherwise null is
198 // returned.
199 //
200 Instruction *GCSE::EliminateCSE(Instruction *I, Instruction *Other) {
201   assert(I != Other);
202
203   WorkList.erase(I);
204   WorkList.erase(Other); // Other may not actually be on the worklist anymore...
205
206   // Handle the easy case, where both instructions are in the same basic block
207   BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
208   Instruction *Ret = 0;
209
210   if (BB1 == BB2) {
211     // Eliminate the second occurring instruction.  Add all uses of the second
212     // instruction to the worklist.
213     //
214     // Scan the basic block looking for the "first" instruction
215     BasicBlock::iterator BI = BB1->begin();
216     while (&*BI != I && &*BI != Other) {
217       ++BI;
218       assert(BI != BB1->end() && "Instructions not found in parent BB!");
219     }
220
221     // Keep track of which instructions occurred first & second
222     Instruction *First = BI;
223     Instruction *Second = I != First ? I : Other; // Get iterator to second inst
224     BI = Second;
225
226     // Destroy Second, using First instead.
227     ReplaceInstWithInst(First, BI);
228     Ret = First;
229
230     // Otherwise, the two instructions are in different basic blocks.  If one
231     // dominates the other instruction, we can simply use it
232     //
233   } else if (DomSetInfo->dominates(BB1, BB2)) {    // I dom Other?
234     ReplaceInstWithInst(I, Other);
235     Ret = I;
236   } else if (DomSetInfo->dominates(BB2, BB1)) {    // Other dom I?
237     ReplaceInstWithInst(Other, I);
238     Ret = Other;
239   } else {
240     // This code is disabled because it has several problems:
241     // One, the actual assumption is wrong, as shown by this code:
242     // int "test"(int %X, int %Y) {
243     //         %Z = add int %X, %Y
244     //         ret int %Z
245     // Unreachable:
246     //         %Q = add int %X, %Y
247     //         ret int %Q
248     // }
249     //
250     // Here there are no shared dominators.  Additionally, this had the habit of
251     // moving computations where they were not always computed.  For example, in
252     // a case like this:
253     //  if (c) {
254     //    if (d)  ...
255     //    else ... X+Y ...
256     //  } else {
257     //    ... X+Y ...
258     //  }
259     // 
260     // In this case, the expression would be hoisted to outside the 'if' stmt,
261     // causing the expression to be evaluated, even for the if (d) path, which
262     // could cause problems, if, for example, it caused a divide by zero.  In
263     // general the problem this case is trying to solve is better addressed with
264     // PRE than GCSE.
265     //
266     return 0;
267   }
268
269   if (isa<LoadInst>(Ret))
270     ++NumLoadRemoved;  // Keep track of loads eliminated
271   if (isa<CallInst>(Ret))
272     ++NumCallRemoved;  // Keep track of calls eliminated
273   ++NumInstRemoved;   // Keep track of number of instructions eliminated
274
275   // Add all users of Ret to the worklist...
276   for (Value::use_iterator I = Ret->use_begin(), E = Ret->use_end(); I != E;++I)
277     if (Instruction *Inst = dyn_cast<Instruction>(*I))
278       WorkList.insert(Inst);
279
280   return Ret;
281 }