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