blob: e1bda22b8b90721bbbc3ded364453ee33f71a20e [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===- 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.
Chris Lattnerf155e132001-06-07 16:59:26 +000010// * Eliminates PHI nodes for basic blocks with a single predecessor
11// * Eliminates a basic block that only contains an unconditional branch
Chris Lattneree7cb292001-07-28 17:51:49 +000012// * Eliminates method prototypes that are not referenced
Chris Lattner00950542001-06-06 20:29:01 +000013//
Chris Lattner25d17a52001-06-29 05:24:28 +000014// 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
Chris Lattner00950542001-06-06 20:29:01 +000018// removing a value, recheck all of its operands to see if they are now unused.
Chris Lattnerd36c91c2001-06-13 19:55:22 +000019// Piece of cake, and more efficient as well.
20//
21// Note, this is not trivial, because we have to worry about invalidating
22// iterators. :(
Chris Lattner00950542001-06-06 20:29:01 +000023//
24//===----------------------------------------------------------------------===//
25
Chris Lattner7e02b7e2001-06-30 04:36:40 +000026#include "llvm/Optimizations/DCE.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner5680ee62001-10-18 01:32:34 +000028#include "llvm/GlobalVariable.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/Method.h"
30#include "llvm/BasicBlock.h"
31#include "llvm/iTerminators.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000032#include "llvm/iPHINode.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000033#include "llvm/Assembly/Writer.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000034#include "Support/STLExtras.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000035#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000036
Chris Lattnera1f6e642001-11-01 07:00:27 +000037// dceInstruction - Inspect the instruction at *BBI and figure out if it's
38// [trivially] dead. If so, remove the instruction and update the iterator
39// to point to the instruction that immediately succeeded the original
40// instruction.
41//
42bool opt::DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL,
43 BasicBlock::iterator &BBI) {
44 // Look for un"used" definitions...
45 if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() &&
46 !isa<TerminatorInst>(*BBI)) {
47 delete BBIL.remove(BBI); // Bye bye
48 return true;
49 }
50 return false;
51}
52
53static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000054 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000055 for (BasicBlock::InstListType::iterator DI = Vals.begin();
Chris Lattnera1f6e642001-11-01 07:00:27 +000056 DI != Vals.end(); )
57 if (opt::DeadCodeElimination::dceInstruction(Vals, DI))
Chris Lattner00950542001-06-06 20:29:01 +000058 Changed = true;
Chris Lattnera1f6e642001-11-01 07:00:27 +000059 else
Chris Lattner7fc9fe32001-06-27 23:41:11 +000060 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000061 return Changed;
62}
63
Chris Lattnerf155e132001-06-07 16:59:26 +000064// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
65// a single predecessor. This means that the PHI node must only have a single
66// RHS value and can be eliminated.
67//
68// This routine is very simple because we know that PHI nodes must be the first
69// things in a basic block, if they are present.
70//
71static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerf0604b82001-10-01 13:19:53 +000072 BasicBlock::pred_iterator PI(BB->pred_begin());
73 if (PI == BB->pred_end() || ++PI != BB->pred_end())
Chris Lattnerf155e132001-06-07 16:59:26 +000074 return false; // More than one predecessor...
75
Chris Lattner7fc9fe32001-06-27 23:41:11 +000076 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000077 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000078
Chris Lattneree976f32001-06-11 15:04:40 +000079 //cerr << "Killing PHIs from " << BB;
Chris Lattnerf0604b82001-10-01 13:19:53 +000080 //cerr << "Pred #0 = " << *BB->pred_begin();
Chris Lattnerf155e132001-06-07 16:59:26 +000081
Chris Lattneree976f32001-06-11 15:04:40 +000082 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000083
84 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000085 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000086 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000087 Value *V = PN->getOperand(0);
88
89 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +000090 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +000091
Chris Lattner7fc9fe32001-06-27 23:41:11 +000092 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000093 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +000094
95 return true; // Yes, we nuked at least one phi node
96}
Chris Lattner00950542001-06-06 20:29:01 +000097
Chris Lattner00950542001-06-06 20:29:01 +000098static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattner2f11a9d2001-09-07 16:42:08 +000099 ConstPoolVal *CPV = ConstPoolVal::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000100
101 // Make all users of this instruction reference the constant instead
102 I->replaceAllUsesWith(CPV);
103}
104
Chris Lattnerf155e132001-06-07 16:59:26 +0000105// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
106// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
107// have extra slots added to them to hold the merge edges from BB's
Chris Lattner081431a2001-11-03 21:30:22 +0000108// predecessors. This function returns true (failure) if the Succ BB already
109// has a predecessor that is a predecessor of BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000110//
Chris Lattner081431a2001-11-03 21:30:22 +0000111// Assumption: Succ is the single successor for BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000112//
Chris Lattner081431a2001-11-03 21:30:22 +0000113static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
114 assert(*BB->succ_begin() == Succ && "Succ is not successor of BB!");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000115 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000116
117 // If there is more than one predecessor, and there are PHI nodes in
118 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000119 //
Chris Lattnerf0604b82001-10-01 13:19:53 +0000120 const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000121
Chris Lattner081431a2001-11-03 21:30:22 +0000122 // Check to see if one of the predecessors of BB is already a predecessor of
123 // Succ. If so, we cannot do the transformation!
124 //
125 for (BasicBlock::pred_iterator PI = Succ->pred_begin(), PE = Succ->pred_end();
126 PI != PE; ++PI) {
127 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
128 return true;
129 }
130
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000131 BasicBlock::iterator I = Succ->begin();
132 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000133 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000134 Value *OldVal = PN->removeIncomingValue(BB);
135 assert(OldVal && "No entry in PHI for Pred BB!");
136
137 for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
138 End = BBPreds.end(); PredI != End; ++PredI) {
139 // Add an incoming value for each of the new incoming values...
140 PN->addIncoming(OldVal, *PredI);
141 }
142
143 ++I;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000144 } while (isa<PHINode>(*I));
Chris Lattner081431a2001-11-03 21:30:22 +0000145 return false;
Chris Lattnerf155e132001-06-07 16:59:26 +0000146}
147
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000148
149// SimplifyCFG - This function is used to do simplification of a CFG. For
150// example, it adjusts branches to branches to eliminate the extra hop, it
151// eliminates unreachable basic blocks, and does other "peephole" optimization
152// of the CFG. It returns true if a modification was made, and returns an
153// iterator that designates the first element remaining after the block that
154// was deleted.
155//
156// WARNING: The entry node of a method may not be simplified.
157//
158bool opt::SimplifyCFG(Method::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000159 BasicBlock *BB = *BBIt;
160 Method *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000161
162 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000163 assert(BB->getTerminator() && "Degenerate basic block encountered!");
164 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
165
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000166
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000167 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000168 if (BB->pred_begin() == BB->pred_end() &&
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000169 !BB->hasConstantPoolReferences()) {
170 //cerr << "Removing BB: \n" << BB;
171
172 // Loop through all of our successors and make sure they know that one
173 // of their predecessors is going away.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000174 for_each(BB->succ_begin(), BB->succ_end(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000175 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
176
177 while (!BB->empty()) {
178 Instruction *I = BB->back();
179 // If this instruction is used, replace uses with an arbitrary
180 // constant value. Because control flow can't get here, we don't care
181 // what we replace the value with. Note that since this block is
182 // unreachable, and all values contained within it must dominate their
183 // uses, that all uses will eventually be removed.
184 if (!I->use_empty()) ReplaceUsesWithConstant(I);
185
186 // Remove the instruction from the basic block
187 delete BB->getInstList().pop_back();
188 }
189 delete M->getBasicBlocks().remove(BBIt);
190 return true;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000191 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000192
193 // Check to see if this block has no instructions and only a single
194 // successor. If so, replace block references with successor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000195 BasicBlock::succ_iterator SI(BB->succ_begin());
196 if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ?
Chris Lattner081431a2001-11-03 21:30:22 +0000197 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
Chris Lattnerf0604b82001-10-01 13:19:53 +0000198 BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000199 //cerr << "Killing Trivial BB: \n" << BB;
200
201 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattner081431a2001-11-03 21:30:22 +0000202 // If our successor has PHI nodes, then we need to update them to
203 // include entries for BB's predecessors, not for BB itself.
204 // Be careful though, if this transformation fails (returns true) then
205 // we cannot do this transformation!
206 //
207 if (!isa<PHINode>(Succ->front()) ||
208 !PropogatePredecessorsForPHIs(BB, Succ)) {
209
210 BB->replaceAllUsesWith(Succ);
211 BB = M->getBasicBlocks().remove(BBIt);
212
213 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
214 Succ->setName(BB->getName());
215 delete BB; // Delete basic block
216
217 //cerr << "Method after removal: \n" << M;
218 return true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000219 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000220 }
221 }
222 }
223
224 // Merge basic blocks into their predecessor if there is only one pred,
225 // and if there is only one successor of the predecessor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000226 BasicBlock::pred_iterator PI(BB->pred_begin());
227 if (PI != BB->pred_end() && *PI != BB && // Not empty? Not same BB?
228 ++PI == BB->pred_end() && !BB->hasConstantPoolReferences()) {
229 BasicBlock *Pred = *BB->pred_begin();
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000230 TerminatorInst *Term = Pred->getTerminator();
231 assert(Term != 0 && "malformed basic block without terminator!");
232
233 // Does the predecessor block only have a single successor?
Chris Lattnerf0604b82001-10-01 13:19:53 +0000234 BasicBlock::succ_iterator SI(Pred->succ_begin());
235 if (++SI == Pred->succ_end()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000236 //cerr << "Merging: " << BB << "into: " << Pred;
237
238 // Delete the unconditianal branch from the predecessor...
239 BasicBlock::iterator DI = Pred->end();
240 assert(Pred->getTerminator() &&
241 "Degenerate basic block encountered!"); // Empty bb???
242 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
243
244 // Move all definitions in the succecessor to the predecessor...
245 while (!BB->empty()) {
246 DI = BB->begin();
247 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
248 Pred->getInstList().push_back(Def); // Add to end...
249 }
250
251 // Remove basic block from the method... and advance iterator to the
252 // next valid block...
253 BB = M->getBasicBlocks().remove(BBIt);
254
255 // Make all PHI nodes that refered to BB now refer to Pred as their
256 // source...
257 BB->replaceAllUsesWith(Pred);
258
259 // Inherit predecessors name if it exists...
260 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
261
262 delete BB; // You ARE the weakest link... goodbye
263 return true;
264 }
265 }
266
267 return false;
268}
269
Chris Lattner00950542001-06-06 20:29:01 +0000270static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000271 Method::iterator BBIt, BBEnd = M->end();
272 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000273 bool Changed = false;
274
275 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000276 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000277 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000278 Changed |= RemoveSingularPHIs(*BBIt);
279 }
Chris Lattner00950542001-06-06 20:29:01 +0000280
Chris Lattnerf155e132001-06-07 16:59:26 +0000281 // Loop over all of the basic blocks (except the first one) and remove them
282 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000283 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000284 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
285 if (opt::SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000286 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000287 } else {
288 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000289 }
290 }
291
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000292 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000293}
294
295
296// It is possible that we may require multiple passes over the code to fully
297// eliminate dead code. Iterate until we are done.
298//
Chris Lattner5680ee62001-10-18 01:32:34 +0000299bool opt::DeadCodeElimination::doDCE(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000300 bool Changed = false;
301 while (DoDCEPass(M)) Changed = true;
302 return Changed;
303}
304
Chris Lattner5680ee62001-10-18 01:32:34 +0000305bool opt::DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000306 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000307
Chris Lattneree7cb292001-07-28 17:51:49 +0000308 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
309 Method *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000310 if (Meth->isExternal() && Meth->use_size() == 0) {
311 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000312 //cerr << "Removing method proto: " << Meth->getName() << endl;
313 delete Mod->getMethodList().remove(MI); // Remove prototype
314 // Remove moves iterator to point to the next one automatically
Chris Lattner5680ee62001-10-18 01:32:34 +0000315 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000316 } else {
317 ++MI; // Skip prototype in use.
318 }
319 }
320
Chris Lattner5680ee62001-10-18 01:32:34 +0000321 for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
322 GlobalVariable *GV = *GI;
323 if (!GV->hasInitializer() && GV->use_size() == 0) {
324 // No references to uninitialized global variable?
325 //cerr << "Removing global var: " << GV->getName() << endl;
326 delete Mod->getGlobalList().remove(GI);
327 // Remove moves iterator to point to the next one automatically
328 Changed = true;
329 } else {
330 ++GI;
331 }
332 }
333
Chris Lattneree7cb292001-07-28 17:51:49 +0000334 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000335}