blob: 5bc3c5b0895f7c6941ab3dde43759c984d012d49 [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 Lattner00950542001-06-06 20:29:01 +000012//
13// TODO: This should REALLY be recursive instead of iterative. Right now, we
14// scan linearly through values, removing unused ones as we go. The problem is
15// that this may cause other earlier values to become unused. To make sure that
16// we get them all, we iterate until things stop changing. Instead, when
17// removing a value, recheck all of its operands to see if they are now unused.
Chris Lattnerd36c91c2001-06-13 19:55:22 +000018// Piece of cake, and more efficient as well.
19//
20// Note, this is not trivial, because we have to worry about invalidating
21// iterators. :(
Chris Lattner00950542001-06-06 20:29:01 +000022//
23//===----------------------------------------------------------------------===//
24
25#include "llvm/Module.h"
26#include "llvm/Method.h"
27#include "llvm/BasicBlock.h"
28#include "llvm/iTerminators.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000029#include "llvm/iOther.h"
Chris Lattner00950542001-06-06 20:29:01 +000030#include "llvm/Opt/AllOpts.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000031#include "llvm/Assembly/Writer.h"
Chris Lattnerdac6dda2001-06-07 21:18:45 +000032#include "llvm/CFG.h"
Chris Lattner00950542001-06-06 20:29:01 +000033
Chris Lattnerd36c91c2001-06-13 19:55:22 +000034using namespace cfg;
35
Chris Lattner00950542001-06-06 20:29:01 +000036struct ConstPoolDCE {
37 enum { EndOffs = 0 };
38 static bool isDCEable(const Value *) { return true; }
39};
40
41struct BasicBlockDCE {
42 enum { EndOffs = 1 };
43 static bool isDCEable(const Instruction *I) {
44 return !I->hasSideEffects();
45 }
46};
47
Chris Lattnerf155e132001-06-07 16:59:26 +000048
Chris Lattner00950542001-06-06 20:29:01 +000049template<class ValueSubclass, class ItemParentType, class DCEController>
50static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals,
51 DCEController DCEControl) {
52 bool Changed = false;
53 typedef ValueHolder<ValueSubclass, ItemParentType> Container;
54
55 int Offset = DCEController::EndOffs;
56 for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) {
57 // Look for un"used" definitions...
58 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
59 // Bye bye
Chris Lattnerf155e132001-06-07 16:59:26 +000060 //cerr << "Removing: " << *DI;
Chris Lattner00950542001-06-06 20:29:01 +000061 delete Vals.remove(DI);
62 Changed = true;
63 } else {
Chris Lattner7fc9fe32001-06-27 23:41:11 +000064 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000065 }
66 }
67 return Changed;
68}
69
Chris Lattnerf155e132001-06-07 16:59:26 +000070// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
71// a single predecessor. This means that the PHI node must only have a single
72// RHS value and can be eliminated.
73//
74// This routine is very simple because we know that PHI nodes must be the first
75// things in a basic block, if they are present.
76//
77static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +000078 pred_iterator PI(pred_begin(BB));
79 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000080 return false; // More than one predecessor...
81
Chris Lattner7fc9fe32001-06-27 23:41:11 +000082 Instruction *I = BB->front();
83 if (!I->isPHINode()) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000084
Chris Lattneree976f32001-06-11 15:04:40 +000085 //cerr << "Killing PHIs from " << BB;
86 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000087
Chris Lattneree976f32001-06-11 15:04:40 +000088 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000089
90 do {
91 PHINode *PN = (PHINode*)I;
Chris Lattneree976f32001-06-11 15:04:40 +000092 assert(PN->getOperand(2) == 0 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000093 Value *V = PN->getOperand(0);
94
95 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +000096 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +000097
Chris Lattner7fc9fe32001-06-27 23:41:11 +000098 I = BB->front();
99 } while (I->isPHINode());
Chris Lattnerf155e132001-06-07 16:59:26 +0000100
101 return true; // Yes, we nuked at least one phi node
102}
Chris Lattner00950542001-06-06 20:29:01 +0000103
104bool DoRemoveUnusedConstants(SymTabValue *S) {
105 bool Changed = false;
106 ConstantPool &CP = S->getConstantPool();
107 for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)
108 Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());
109 return Changed;
110}
111
Chris Lattner00950542001-06-06 20:29:01 +0000112static void ReplaceUsesWithConstant(Instruction *I) {
113 // Get the method level constant pool
114 ConstantPool &CP = I->getParent()->getParent()->getConstantPool();
115
116 ConstPoolVal *CPV = 0;
117 ConstantPool::PlaneType *P;
118 if (!CP.getPlane(I->getType(), P)) { // Does plane exist?
119 // Yes, is it empty?
120 if (!P->empty()) CPV = P->front();
121 }
122
123 if (CPV == 0) { // We don't have an existing constant to reuse. Just add one.
124 CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant
125
126 // Add the new value to the constant pool...
127 CP.insert(CPV);
128 }
129
130 // Make all users of this instruction reference the constant instead
131 I->replaceAllUsesWith(CPV);
132}
133
Chris Lattnerf155e132001-06-07 16:59:26 +0000134// RemovePredecessorFromBlock - This function is called when we are about
135// to remove a predecessor from a basic block. This function takes care of
136// removing the predecessor from the PHI nodes in BB so that after the pred
137// is removed, the number of PHI slots per bb is equal to the number of
138// predecessors.
139//
140static void RemovePredecessorFromBlock(BasicBlock *BB, BasicBlock *Pred) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000141 pred_iterator PI(pred_begin(BB)), EI(pred_end(BB));
Chris Lattneree976f32001-06-11 15:04:40 +0000142 unsigned max_idx;
Chris Lattnerf155e132001-06-07 16:59:26 +0000143
Chris Lattneree976f32001-06-11 15:04:40 +0000144 //cerr << "RPFB: " << Pred << "From Block: " << BB;
Chris Lattnerf155e132001-06-07 16:59:26 +0000145
Chris Lattnerf155e132001-06-07 16:59:26 +0000146 // Loop over the rest of the predecssors until we run out, or until we find
147 // out that there are more than 2 predecessors.
Chris Lattneree976f32001-06-11 15:04:40 +0000148 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
Chris Lattnerf155e132001-06-07 16:59:26 +0000149
150 // If there are exactly two predecessors, then we want to nuke the PHI nodes
151 // altogether.
Chris Lattneree976f32001-06-11 15:04:40 +0000152 bool NukePHIs = max_idx == 2;
153 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000154
155 // Okay, now we know that we need to remove predecessor #pred_idx from all
156 // PHI nodes. Iterate over each PHI node fixing them up
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000157 BasicBlock::iterator II(BB->begin());
158 for (; (*II)->isPHINode(); ++II) {
Chris Lattnerf155e132001-06-07 16:59:26 +0000159 PHINode *PN = (PHINode*)*II;
Chris Lattneree976f32001-06-11 15:04:40 +0000160 PN->removeIncomingValue(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +0000161
162 if (NukePHIs) { // Destroy the PHI altogether??
163 assert(PN->getOperand(1) == 0 && "PHI node should only have one value!");
164 Value *V = PN->getOperand(0);
165
166 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
167 delete BB->getInstList().remove(II);
168 }
169 }
170}
171
172// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
173// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
174// have extra slots added to them to hold the merge edges from BB's
175// predecessors.
176//
177// Assumption: BB is the single predecessor of Succ.
178//
179static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000180 assert(Succ->front()->isPHINode() && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000181
182 // If there is more than one predecessor, and there are PHI nodes in
183 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000184 //
185 const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
186
187 BasicBlock::iterator I = Succ->begin();
188 do { // Loop over all of the PHI nodes in the successor BB
189 PHINode *PN = (PHINode*)*I;
190 Value *OldVal = PN->removeIncomingValue(BB);
191 assert(OldVal && "No entry in PHI for Pred BB!");
192
193 for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
194 End = BBPreds.end(); PredI != End; ++PredI) {
195 // Add an incoming value for each of the new incoming values...
196 PN->addIncoming(OldVal, *PredI);
197 }
198
199 ++I;
200 } while ((*I)->isPHINode());
Chris Lattnerf155e132001-06-07 16:59:26 +0000201}
202
Chris Lattner00950542001-06-06 20:29:01 +0000203static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000204 Method::iterator BBIt, BBEnd = M->end();
205 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000206 bool Changed = false;
207
208 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000209 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattner00950542001-06-06 20:29:01 +0000210 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
Chris Lattnerf155e132001-06-07 16:59:26 +0000211 Changed |= RemoveSingularPHIs(*BBIt);
212 }
Chris Lattner00950542001-06-06 20:29:01 +0000213
Chris Lattnerf155e132001-06-07 16:59:26 +0000214 // Loop over all of the basic blocks (except the first one) and remove them
215 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000216 //
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000217 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ++BBIt) {
Chris Lattner00950542001-06-06 20:29:01 +0000218 BasicBlock *BB = *BBIt;
Chris Lattnerf155e132001-06-07 16:59:26 +0000219 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner00950542001-06-06 20:29:01 +0000220
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000221#if 0 // This is know to basically work?
Chris Lattnerf155e132001-06-07 16:59:26 +0000222 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000223 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattnerf155e132001-06-07 16:59:26 +0000224 !BB->hasConstantPoolReferences() && 0) {
225 cerr << "Removing BB: \n" << BB;
226
227 // Loop through all of our successors and make sure they know that one
228 // of their predecessors is going away.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000229 for_each(succ_begin(BB), succ_end(BB),
230 bind_2nd(RemovePredecessorFromBlock, BB));
Chris Lattner00950542001-06-06 20:29:01 +0000231
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000232 while (!BB->empty()) {
233 Instruction *I = BB->front();
Chris Lattner00950542001-06-06 20:29:01 +0000234 // If this instruction is used, replace uses with an arbitrary
235 // constant value. Because control flow can't get here, we don't care
236 // what we replace the value with.
237 if (!I->use_empty()) ReplaceUsesWithConstant(I);
238
239 // Remove the instruction from the basic block
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000240 delete BB->getInstList().remove(BB->begin());
Chris Lattner00950542001-06-06 20:29:01 +0000241 }
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000242 delete M->getBasicBlocks().remove(BBIt);
Chris Lattnerf155e132001-06-07 16:59:26 +0000243 --BBIt; // remove puts use on the next block, we want the previous one
Chris Lattner00950542001-06-06 20:29:01 +0000244 Changed = true;
Chris Lattnerf155e132001-06-07 16:59:26 +0000245 continue;
246 }
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000247#endif
Chris Lattnerf155e132001-06-07 16:59:26 +0000248
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000249#if 0 // This has problems
Chris Lattnerf155e132001-06-07 16:59:26 +0000250 // Check to see if this block has no instructions and only a single
251 // successor. If so, replace block references with successor.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000252 succ_iterator SI(succ_begin(BB));
253 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000254 Instruction *I = BB->front();
Chris Lattnerf155e132001-06-07 16:59:26 +0000255 if (I->isTerminator()) { // Terminator is the only instruction!
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000256 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
257 cerr << "Killing Trivial BB: \n" << BB;
Chris Lattnerf155e132001-06-07 16:59:26 +0000258
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000259 if (Succ->front()->isPHINode()) {
260 // If our successor has PHI nodes, then we need to update them to
261 // include entries for BB's predecessors, not for BB itself.
262 //
Chris Lattnerf155e132001-06-07 16:59:26 +0000263 PropogatePredecessorsForPHIs(BB, Succ);
264 }
265
Chris Lattnerf155e132001-06-07 16:59:26 +0000266 BB->replaceAllUsesWith(Succ);
Chris Lattnerf155e132001-06-07 16:59:26 +0000267
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000268 BB = M->getBasicBlocks().remove(BBIt);
Chris Lattnerf155e132001-06-07 16:59:26 +0000269 --BBIt; // remove puts use on the next block, we want the previous one
270
271 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
272 Succ->setName(BB->getName());
273 delete BB; // Delete basic block
274
275 cerr << "Method after removal: \n" << M;
276 Changed = true;
277 continue;
278 }
Chris Lattner00950542001-06-06 20:29:01 +0000279 }
Chris Lattnerf155e132001-06-07 16:59:26 +0000280#endif
Chris Lattner00950542001-06-06 20:29:01 +0000281
Chris Lattnerf155e132001-06-07 16:59:26 +0000282 // Merge basic blocks into their predecessor if there is only one pred,
283 // and if there is only one successor of the predecessor.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000284 pred_iterator PI(pred_begin(BB));
285 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
286 ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {
287 BasicBlock *Pred = *pred_begin(BB);
Chris Lattner00950542001-06-06 20:29:01 +0000288 TerminatorInst *Term = Pred->getTerminator();
Chris Lattnerf155e132001-06-07 16:59:26 +0000289 assert(Term != 0 && "malformed basic block without terminator!");
Chris Lattner00950542001-06-06 20:29:01 +0000290
Chris Lattnerf155e132001-06-07 16:59:26 +0000291 // Does the predecessor block only have a single successor?
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000292 succ_iterator SI(succ_begin(Pred));
293 if (++SI == succ_end(Pred)) {
Chris Lattnerf155e132001-06-07 16:59:26 +0000294 //cerr << "Merging: " << BB << "into: " << Pred;
Chris Lattner00950542001-06-06 20:29:01 +0000295
Chris Lattnerf155e132001-06-07 16:59:26 +0000296 // Delete the unconditianal branch from the predecessor...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000297 BasicBlock::iterator DI = Pred->end();
Chris Lattnerf155e132001-06-07 16:59:26 +0000298 assert(Pred->getTerminator() &&
299 "Degenerate basic block encountered!"); // Empty bb???
Chris Lattneree976f32001-06-11 15:04:40 +0000300 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
Chris Lattnerf155e132001-06-07 16:59:26 +0000301
302 // Move all definitions in the succecessor to the predecessor...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000303 while (!BB->empty()) {
304 DI = BB->begin();
Chris Lattnerf155e132001-06-07 16:59:26 +0000305 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
306 Pred->getInstList().push_back(Def); // Add to end...
307 }
Chris Lattneree976f32001-06-11 15:04:40 +0000308
Chris Lattnerf155e132001-06-07 16:59:26 +0000309 // Remove basic block from the method... and advance iterator to the
310 // next valid block...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000311 BB = M->getBasicBlocks().remove(BBIt);
Chris Lattnerf155e132001-06-07 16:59:26 +0000312 --BBIt; // remove puts us on the NEXT bb. We want the prev BB
313 Changed = true;
Chris Lattneree976f32001-06-11 15:04:40 +0000314
315 // Make all PHI nodes that refered to BB now refer to Pred as their
316 // source...
317 BB->replaceAllUsesWith(Pred);
Chris Lattnerf155e132001-06-07 16:59:26 +0000318
319 // Inherit predecessors name if it exists...
320 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
321
322 // You ARE the weakest link... goodbye
323 delete BB;
Chris Lattnerd36c91c2001-06-13 19:55:22 +0000324
Chris Lattner5ef7afb2001-06-20 23:09:39 +0000325 //WriteToVCG(M, "MergedInto");
Chris Lattner00950542001-06-06 20:29:01 +0000326 }
Chris Lattner00950542001-06-06 20:29:01 +0000327 }
328 }
329
330 // Remove unused constants
331 Changed |= DoRemoveUnusedConstants(M);
332 return Changed;
333}
334
335
336// It is possible that we may require multiple passes over the code to fully
337// eliminate dead code. Iterate until we are done.
338//
339bool DoDeadCodeElimination(Method *M) {
340 bool Changed = false;
341 while (DoDCEPass(M)) Changed = true;
342 return Changed;
343}
344
345bool DoDeadCodeElimination(Module *C) {
346 bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination);
347 while (DoRemoveUnusedConstants(C)) Val = true;
348 return Val;
349}