Simplify DCE code a lot
[oota-llvm.git] / lib / Transforms / Scalar / DCE.cpp
1 //===- DCE.cpp - Code to perform dead code elimination --------------------===//
2 //
3 // This file implements dead code elimination and basic block merging.
4 //
5 // Specifically, this:
6 //   * removes definitions with no uses (including unused constants)
7 //   * removes basic blocks with no predecessors
8 //   * merges a basic block into its predecessor if there is only one and the
9 //     predecessor only has one successor.
10 //   * Eliminates PHI nodes for basic blocks with a single predecessor
11 //   * Eliminates a basic block that only contains an unconditional branch
12 //   * Eliminates method prototypes that are not referenced
13 //
14 // TODO: This should REALLY be worklist driven instead of iterative.  Right now,
15 // we scan linearly through values, removing unused ones as we go.  The problem
16 // is that this may cause other earlier values to become unused.  To make sure
17 // that we get them all, we iterate until things stop changing.  Instead, when 
18 // removing a value, recheck all of its operands to see if they are now unused.
19 // Piece of cake, and more efficient as well.  
20 //
21 // Note, this is not trivial, because we have to worry about invalidating 
22 // iterators.  :(
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Optimizations/DCE.h"
27 #include "llvm/Support/STLExtras.h"
28 #include "llvm/Module.h"
29 #include "llvm/GlobalVariable.h"
30 #include "llvm/Method.h"
31 #include "llvm/BasicBlock.h"
32 #include "llvm/iTerminators.h"
33 #include "llvm/iOther.h"
34 #include "llvm/Assembly/Writer.h"
35 #include <algorithm>
36
37 static bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
38   bool Changed = false;
39   for (BasicBlock::InstListType::iterator DI = Vals.begin(); 
40        DI != Vals.end()-1; ) {
41     // Look for un"used" definitions...
42     if ((*DI)->use_empty() && !(*DI)->hasSideEffects()) {
43       // Bye bye
44       //cerr << "Removing: " << *DI;
45       delete Vals.remove(DI);
46       Changed = true;
47     } else {
48       ++DI;
49     }
50   }
51   return Changed;
52 }
53
54 // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
55 // a single predecessor.  This means that the PHI node must only have a single
56 // RHS value and can be eliminated.
57 //
58 // This routine is very simple because we know that PHI nodes must be the first
59 // things in a basic block, if they are present.
60 //
61 static bool RemoveSingularPHIs(BasicBlock *BB) {
62   BasicBlock::pred_iterator PI(BB->pred_begin());
63   if (PI == BB->pred_end() || ++PI != BB->pred_end()) 
64     return false;   // More than one predecessor...
65
66   Instruction *I = BB->front();
67   if (!isa<PHINode>(I)) return false;  // No PHI nodes
68
69   //cerr << "Killing PHIs from " << BB;
70   //cerr << "Pred #0 = " << *BB->pred_begin();
71
72   //cerr << "Method == " << BB->getParent();
73
74   do {
75     PHINode *PN = cast<PHINode>(I);
76     assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
77     Value *V = PN->getOperand(0);
78
79     PN->replaceAllUsesWith(V);      // Replace PHI node with its single value.
80     delete BB->getInstList().remove(BB->begin());
81
82     I = BB->front();
83   } while (isa<PHINode>(I));
84         
85   return true;  // Yes, we nuked at least one phi node
86 }
87
88 static void ReplaceUsesWithConstant(Instruction *I) {
89   ConstPoolVal *CPV = ConstPoolVal::getNullConstant(I->getType());
90   
91   // Make all users of this instruction reference the constant instead
92   I->replaceAllUsesWith(CPV);
93 }
94
95 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from
96 // "BB".  This is a little tricky because "Succ" has PHI nodes, which need to
97 // have extra slots added to them to hold the merge edges from BB's
98 // predecessors.
99 //
100 // Assumption: BB is the single predecessor of Succ.
101 //
102 static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
103   assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
104
105   // If there is more than one predecessor, and there are PHI nodes in
106   // the successor, then we need to add incoming edges for the PHI nodes
107   //
108   const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
109
110   BasicBlock::iterator I = Succ->begin();
111   do {                     // Loop over all of the PHI nodes in the successor BB
112     PHINode *PN = cast<PHINode>(*I);
113     Value *OldVal = PN->removeIncomingValue(BB);
114     assert(OldVal && "No entry in PHI for Pred BB!");
115
116     for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
117            End = BBPreds.end(); PredI != End; ++PredI) {
118       // Add an incoming value for each of the new incoming values...
119       PN->addIncoming(OldVal, *PredI);
120     }
121
122     ++I;
123   } while (isa<PHINode>(*I));
124 }
125
126
127 // SimplifyCFG - This function is used to do simplification of a CFG.  For
128 // example, it adjusts branches to branches to eliminate the extra hop, it
129 // eliminates unreachable basic blocks, and does other "peephole" optimization
130 // of the CFG.  It returns true if a modification was made, and returns an 
131 // iterator that designates the first element remaining after the block that
132 // was deleted.
133 //
134 // WARNING:  The entry node of a method may not be simplified.
135 //
136 bool opt::SimplifyCFG(Method::iterator &BBIt) {
137   BasicBlock *BB = *BBIt;
138   Method *M = BB->getParent();
139
140   assert(BB && BB->getParent() && "Block not embedded in method!");
141   assert(BB->getTerminator() && "Degenerate basic block encountered!");
142   assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
143
144
145   // Remove basic blocks that have no predecessors... which are unreachable.
146   if (BB->pred_begin() == BB->pred_end() &&
147       !BB->hasConstantPoolReferences()) {
148     //cerr << "Removing BB: \n" << BB;
149
150     // Loop through all of our successors and make sure they know that one
151     // of their predecessors is going away.
152     for_each(BB->succ_begin(), BB->succ_end(),
153              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
154
155     while (!BB->empty()) {
156       Instruction *I = BB->back();
157       // If this instruction is used, replace uses with an arbitrary
158       // constant value.  Because control flow can't get here, we don't care
159       // what we replace the value with.  Note that since this block is 
160       // unreachable, and all values contained within it must dominate their
161       // uses, that all uses will eventually be removed.
162       if (!I->use_empty()) ReplaceUsesWithConstant(I);
163       
164       // Remove the instruction from the basic block
165       delete BB->getInstList().pop_back();
166     }
167     delete M->getBasicBlocks().remove(BBIt);
168     return true;
169   }
170
171   // Check to see if this block has no instructions and only a single 
172   // successor.  If so, replace block references with successor.
173   BasicBlock::succ_iterator SI(BB->succ_begin());
174   if (SI != BB->succ_end() && ++SI == BB->succ_end()) {  // One succ?
175     Instruction *I = BB->front();
176     if (I->isTerminator()) {   // Terminator is the only instruction!
177       BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
178       //cerr << "Killing Trivial BB: \n" << BB;
179       
180       if (Succ != BB) {   // Arg, don't hurt infinite loops!
181         if (isa<PHINode>(Succ->front())) {
182           // If our successor has PHI nodes, then we need to update them to
183           // include entries for BB's predecessors, not for BB itself.
184           //
185           PropogatePredecessorsForPHIs(BB, Succ);
186         }
187         
188         BB->replaceAllUsesWith(Succ);
189         BB = M->getBasicBlocks().remove(BBIt);
190         
191         if (BB->hasName() && !Succ->hasName())  // Transfer name if we can
192           Succ->setName(BB->getName());
193         delete BB;                              // Delete basic block
194         
195         //cerr << "Method after removal: \n" << M;
196         return true;
197       }
198     }
199   }
200
201   // Merge basic blocks into their predecessor if there is only one pred, 
202   // and if there is only one successor of the predecessor. 
203   BasicBlock::pred_iterator PI(BB->pred_begin());
204   if (PI != BB->pred_end() && *PI != BB &&    // Not empty?  Not same BB?
205       ++PI == BB->pred_end() && !BB->hasConstantPoolReferences()) {
206     BasicBlock *Pred = *BB->pred_begin();
207     TerminatorInst *Term = Pred->getTerminator();
208     assert(Term != 0 && "malformed basic block without terminator!");
209     
210     // Does the predecessor block only have a single successor?
211     BasicBlock::succ_iterator SI(Pred->succ_begin());
212     if (++SI == Pred->succ_end()) {
213       //cerr << "Merging: " << BB << "into: " << Pred;
214       
215       // Delete the unconditianal branch from the predecessor...
216       BasicBlock::iterator DI = Pred->end();
217       assert(Pred->getTerminator() && 
218              "Degenerate basic block encountered!");  // Empty bb???      
219       delete Pred->getInstList().remove(--DI);        // Destroy uncond branch
220       
221       // Move all definitions in the succecessor to the predecessor...
222       while (!BB->empty()) {
223         DI = BB->begin();
224         Instruction *Def = BB->getInstList().remove(DI); // Remove from front
225         Pred->getInstList().push_back(Def);              // Add to end...
226       }
227       
228       // Remove basic block from the method... and advance iterator to the
229       // next valid block...
230       BB = M->getBasicBlocks().remove(BBIt);
231
232       // Make all PHI nodes that refered to BB now refer to Pred as their
233       // source...
234       BB->replaceAllUsesWith(Pred);
235       
236       // Inherit predecessors name if it exists...
237       if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
238       
239       delete BB; // You ARE the weakest link... goodbye
240       return true;
241     }
242   }
243   
244   return false;
245 }
246
247 static bool DoDCEPass(Method *M) {
248   Method::iterator BBIt, BBEnd = M->end();
249   if (M->begin() == BBEnd) return false;  // Nothing to do
250   bool Changed = false;
251
252   // Loop through now and remove instructions that have no uses...
253   for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
254     Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
255     Changed |= RemoveSingularPHIs(*BBIt);
256   }
257
258   // Loop over all of the basic blocks (except the first one) and remove them
259   // if they are unneeded...
260   //
261   for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
262     if (opt::SimplifyCFG(BBIt)) {
263       Changed = true;
264     } else {
265       ++BBIt;
266     }
267   }
268
269   return Changed;
270 }
271
272
273 // It is possible that we may require multiple passes over the code to fully
274 // eliminate dead code.  Iterate until we are done.
275 //
276 bool opt::DeadCodeElimination::doDCE(Method *M) {
277   bool Changed = false;
278   while (DoDCEPass(M)) Changed = true;
279   return Changed;
280 }
281
282 bool opt::DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
283   bool Changed = false;
284
285   for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
286     Method *Meth = *MI;
287     if (Meth->isExternal() && Meth->use_size() == 0) {
288       // No references to prototype?
289       //cerr << "Removing method proto: " << Meth->getName() << endl;
290       delete Mod->getMethodList().remove(MI);  // Remove prototype
291       // Remove moves iterator to point to the next one automatically
292       Changed = true;
293     } else {
294       ++MI;                                    // Skip prototype in use.
295     }
296   }
297
298   for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
299     GlobalVariable *GV = *GI;
300     if (!GV->hasInitializer() && GV->use_size() == 0) {
301       // No references to uninitialized global variable?
302       //cerr << "Removing global var: " << GV->getName() << endl;
303       delete Mod->getGlobalList().remove(GI);
304       // Remove moves iterator to point to the next one automatically
305       Changed = true;
306     } else {
307       ++GI;
308     }
309   }
310
311   return Changed;
312 }