blob: e0f5287937028f79c17a3686570d72bd4c2a3a70 [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:
Chris Lattnerc560f882002-01-23 05:48:24 +00006// * removes definitions with no uses
Chris Lattner00950542001-06-06 20:29:01 +00007// * 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 Lattner59b6b8e2002-01-21 23:17:48 +000026#include "llvm/Transforms/Scalar/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 Lattner79df7c02002-03-26 18:01:55 +000029#include "llvm/Function.h"
Chris Lattner00950542001-06-06 20:29:01 +000030#include "llvm/BasicBlock.h"
31#include "llvm/iTerminators.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000032#include "llvm/iPHINode.h"
Chris Lattner455889a2002-02-12 22:39:50 +000033#include "llvm/Support/CFG.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000034#include "llvm/Pass.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000035#include "Support/STLExtras.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000036#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000037
Chris Lattnera1f6e642001-11-01 07:00:27 +000038// dceInstruction - Inspect the instruction at *BBI and figure out if it's
39// [trivially] dead. If so, remove the instruction and update the iterator
40// to point to the instruction that immediately succeeded the original
41// instruction.
42//
Chris Lattnerbd0ef772002-02-26 21:46:54 +000043bool dceInstruction(BasicBlock::InstListType &BBIL,
44 BasicBlock::iterator &BBI) {
Chris Lattnera1f6e642001-11-01 07:00:27 +000045 // Look for un"used" definitions...
46 if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() &&
47 !isa<TerminatorInst>(*BBI)) {
48 delete BBIL.remove(BBI); // Bye bye
49 return true;
50 }
51 return false;
52}
53
54static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000055 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000056 for (BasicBlock::InstListType::iterator DI = Vals.begin();
Chris Lattnera1f6e642001-11-01 07:00:27 +000057 DI != Vals.end(); )
Chris Lattnerbd0ef772002-02-26 21:46:54 +000058 if (dceInstruction(Vals, DI))
Chris Lattner00950542001-06-06 20:29:01 +000059 Changed = true;
Chris Lattnera1f6e642001-11-01 07:00:27 +000060 else
Chris Lattner7fc9fe32001-06-27 23:41:11 +000061 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000062 return Changed;
63}
64
Chris Lattnerbd0ef772002-02-26 21:46:54 +000065struct DeadInstElimination : public BasicBlockPass {
66 virtual bool runOnBasicBlock(BasicBlock *BB) {
67 return RemoveUnusedDefs(BB->getInstList());
68 }
69};
70
71Pass *createDeadInstEliminationPass() {
72 return new DeadInstElimination();
Chris Lattnerc560f882002-01-23 05:48:24 +000073}
74
Chris Lattnerf155e132001-06-07 16:59:26 +000075// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
76// a single predecessor. This means that the PHI node must only have a single
77// RHS value and can be eliminated.
78//
79// This routine is very simple because we know that PHI nodes must be the first
80// things in a basic block, if they are present.
81//
82static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattner455889a2002-02-12 22:39:50 +000083 pred_iterator PI(pred_begin(BB));
84 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000085 return false; // More than one predecessor...
86
Chris Lattner7fc9fe32001-06-27 23:41:11 +000087 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000088 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000089
Chris Lattneree976f32001-06-11 15:04:40 +000090 //cerr << "Killing PHIs from " << BB;
Chris Lattner455889a2002-02-12 22:39:50 +000091 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000092
Chris Lattner79df7c02002-03-26 18:01:55 +000093 //cerr << "Function == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000094
95 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000096 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000097 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000098 Value *V = PN->getOperand(0);
99
100 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000101 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +0000102
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000103 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000104 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +0000105
106 return true; // Yes, we nuked at least one phi node
107}
Chris Lattner00950542001-06-06 20:29:01 +0000108
Chris Lattner00950542001-06-06 20:29:01 +0000109static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000110 Constant *CPV = Constant::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000111
112 // Make all users of this instruction reference the constant instead
113 I->replaceAllUsesWith(CPV);
114}
115
Chris Lattnerf155e132001-06-07 16:59:26 +0000116// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
117// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
118// have extra slots added to them to hold the merge edges from BB's
Chris Lattner081431a2001-11-03 21:30:22 +0000119// predecessors. This function returns true (failure) if the Succ BB already
120// has a predecessor that is a predecessor of BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000121//
Chris Lattner081431a2001-11-03 21:30:22 +0000122// Assumption: Succ is the single successor for BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000123//
Chris Lattner081431a2001-11-03 21:30:22 +0000124static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner455889a2002-02-12 22:39:50 +0000125 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000126 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000127
128 // If there is more than one predecessor, and there are PHI nodes in
129 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000130 //
Chris Lattner455889a2002-02-12 22:39:50 +0000131 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000132
Chris Lattner081431a2001-11-03 21:30:22 +0000133 // Check to see if one of the predecessors of BB is already a predecessor of
134 // Succ. If so, we cannot do the transformation!
135 //
Chris Lattner455889a2002-02-12 22:39:50 +0000136 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
137 PI != PE; ++PI) {
Chris Lattner081431a2001-11-03 21:30:22 +0000138 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
139 return true;
140 }
141
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000142 BasicBlock::iterator I = Succ->begin();
143 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000144 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000145 Value *OldVal = PN->removeIncomingValue(BB);
146 assert(OldVal && "No entry in PHI for Pred BB!");
147
Chris Lattner697954c2002-01-20 22:54:45 +0000148 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000149 End = BBPreds.end(); PredI != End; ++PredI) {
150 // Add an incoming value for each of the new incoming values...
151 PN->addIncoming(OldVal, *PredI);
152 }
153
154 ++I;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000155 } while (isa<PHINode>(*I));
Chris Lattner081431a2001-11-03 21:30:22 +0000156 return false;
Chris Lattnerf155e132001-06-07 16:59:26 +0000157}
158
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000159
160// SimplifyCFG - This function is used to do simplification of a CFG. For
161// example, it adjusts branches to branches to eliminate the extra hop, it
162// eliminates unreachable basic blocks, and does other "peephole" optimization
163// of the CFG. It returns true if a modification was made, and returns an
164// iterator that designates the first element remaining after the block that
165// was deleted.
166//
167// WARNING: The entry node of a method may not be simplified.
168//
Chris Lattner79df7c02002-03-26 18:01:55 +0000169bool SimplifyCFG(Function::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000170 BasicBlock *BB = *BBIt;
Chris Lattner79df7c02002-03-26 18:01:55 +0000171 Function *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000172
173 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000174 assert(BB->getTerminator() && "Degenerate basic block encountered!");
175 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
176
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000177
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000178 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattner455889a2002-02-12 22:39:50 +0000179 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000180 !BB->hasConstantReferences()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000181 //cerr << "Removing BB: \n" << BB;
182
183 // Loop through all of our successors and make sure they know that one
184 // of their predecessors is going away.
Chris Lattner455889a2002-02-12 22:39:50 +0000185 for_each(succ_begin(BB), succ_end(BB),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000186 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
187
188 while (!BB->empty()) {
189 Instruction *I = BB->back();
190 // If this instruction is used, replace uses with an arbitrary
191 // constant value. Because control flow can't get here, we don't care
192 // what we replace the value with. Note that since this block is
193 // unreachable, and all values contained within it must dominate their
194 // uses, that all uses will eventually be removed.
195 if (!I->use_empty()) ReplaceUsesWithConstant(I);
196
197 // Remove the instruction from the basic block
198 delete BB->getInstList().pop_back();
199 }
200 delete M->getBasicBlocks().remove(BBIt);
201 return true;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000202 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000203
204 // Check to see if this block has no instructions and only a single
205 // successor. If so, replace block references with successor.
Chris Lattner455889a2002-02-12 22:39:50 +0000206 succ_iterator SI(succ_begin(BB));
207 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner081431a2001-11-03 21:30:22 +0000208 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
Chris Lattner455889a2002-02-12 22:39:50 +0000209 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000210 //cerr << "Killing Trivial BB: \n" << BB;
211
212 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattner081431a2001-11-03 21:30:22 +0000213 // If our successor has PHI nodes, then we need to update them to
214 // include entries for BB's predecessors, not for BB itself.
215 // Be careful though, if this transformation fails (returns true) then
216 // we cannot do this transformation!
217 //
218 if (!isa<PHINode>(Succ->front()) ||
219 !PropogatePredecessorsForPHIs(BB, Succ)) {
220
221 BB->replaceAllUsesWith(Succ);
222 BB = M->getBasicBlocks().remove(BBIt);
223
224 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
225 Succ->setName(BB->getName());
226 delete BB; // Delete basic block
227
Chris Lattner79df7c02002-03-26 18:01:55 +0000228 //cerr << "Function after removal: \n" << M;
Chris Lattner081431a2001-11-03 21:30:22 +0000229 return true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000230 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000231 }
232 }
233 }
234
235 // Merge basic blocks into their predecessor if there is only one pred,
236 // and if there is only one successor of the predecessor.
Chris Lattner455889a2002-02-12 22:39:50 +0000237 pred_iterator PI(pred_begin(BB));
238 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
239 ++PI == pred_end(BB) && !BB->hasConstantReferences()) {
240 BasicBlock *Pred = *pred_begin(BB);
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000241 TerminatorInst *Term = Pred->getTerminator();
242 assert(Term != 0 && "malformed basic block without terminator!");
243
244 // Does the predecessor block only have a single successor?
Chris Lattner455889a2002-02-12 22:39:50 +0000245 succ_iterator SI(succ_begin(Pred));
246 if (++SI == succ_end(Pred)) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000247 //cerr << "Merging: " << BB << "into: " << Pred;
248
249 // Delete the unconditianal branch from the predecessor...
250 BasicBlock::iterator DI = Pred->end();
251 assert(Pred->getTerminator() &&
252 "Degenerate basic block encountered!"); // Empty bb???
253 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
254
255 // Move all definitions in the succecessor to the predecessor...
256 while (!BB->empty()) {
257 DI = BB->begin();
258 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
259 Pred->getInstList().push_back(Def); // Add to end...
260 }
261
262 // Remove basic block from the method... and advance iterator to the
263 // next valid block...
264 BB = M->getBasicBlocks().remove(BBIt);
265
266 // Make all PHI nodes that refered to BB now refer to Pred as their
267 // source...
268 BB->replaceAllUsesWith(Pred);
269
270 // Inherit predecessors name if it exists...
271 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
272
273 delete BB; // You ARE the weakest link... goodbye
274 return true;
275 }
276 }
277
278 return false;
279}
280
Chris Lattner79df7c02002-03-26 18:01:55 +0000281static bool DoDCEPass(Function *F) {
282 Function::iterator BBIt, BBEnd = F->end();
283 if (F->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000284 bool Changed = false;
285
286 // Loop through now and remove instructions that have no uses...
Chris Lattner79df7c02002-03-26 18:01:55 +0000287 for (BBIt = F->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000288 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000289 Changed |= RemoveSingularPHIs(*BBIt);
290 }
Chris Lattner00950542001-06-06 20:29:01 +0000291
Chris Lattnerf155e132001-06-07 16:59:26 +0000292 // Loop over all of the basic blocks (except the first one) and remove them
293 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000294 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000295 for (BBIt = F->begin(), ++BBIt; BBIt != F->end(); ) {
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000296 if (SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000297 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000298 } else {
299 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000300 }
301 }
302
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000303 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000304}
305
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000306// Remove unused global values - This removes unused global values of no
307// possible value. This currently includes unused method prototypes and
308// unitialized global variables.
Chris Lattner00950542001-06-06 20:29:01 +0000309//
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000310static bool RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000311 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000312
Chris Lattneree7cb292001-07-28 17:51:49 +0000313 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
Chris Lattner79df7c02002-03-26 18:01:55 +0000314 Function *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000315 if (Meth->isExternal() && Meth->use_size() == 0) {
316 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000317 //cerr << "Removing method proto: " << Meth->getName() << endl;
Chris Lattner79df7c02002-03-26 18:01:55 +0000318 delete Mod->getFunctionList().remove(MI); // Remove prototype
Chris Lattneree7cb292001-07-28 17:51:49 +0000319 // Remove moves iterator to point to the next one automatically
Chris Lattner5680ee62001-10-18 01:32:34 +0000320 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000321 } else {
322 ++MI; // Skip prototype in use.
323 }
324 }
325
Chris Lattner5680ee62001-10-18 01:32:34 +0000326 for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
327 GlobalVariable *GV = *GI;
328 if (!GV->hasInitializer() && GV->use_size() == 0) {
329 // No references to uninitialized global variable?
330 //cerr << "Removing global var: " << GV->getName() << endl;
331 delete Mod->getGlobalList().remove(GI);
332 // Remove moves iterator to point to the next one automatically
333 Changed = true;
334 } else {
335 ++GI;
336 }
337 }
338
Chris Lattneree7cb292001-07-28 17:51:49 +0000339 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000340}
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000341
342namespace {
343 struct DeadCodeElimination : public MethodPass {
344
345 // Pass Interface...
346 virtual bool doInitialization(Module *M) {
347 return RemoveUnusedGlobalValues(M);
348 }
349
350 // It is possible that we may require multiple passes over the code to fully
351 // eliminate dead code. Iterate until we are done.
352 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000353 virtual bool runOnMethod(Function *F) {
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000354 bool Changed = false;
Chris Lattner79df7c02002-03-26 18:01:55 +0000355 while (DoDCEPass(F)) Changed = true;
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000356 return Changed;
357 }
358
359 virtual bool doFinalization(Module *M) {
360 return RemoveUnusedGlobalValues(M);
361 }
362 };
363}
364
365Pass *createDeadCodeEliminationPass() {
366 return new DeadCodeElimination();
367}