blob: 480a2696b5630bf7ce7a9de2e90f8c5605abb1ea [file] [log] [blame]
Chris Lattner02e90d52001-06-30 06:39:11 +00001//===- ADCE.cpp - Code to perform agressive dead code elimination ---------===//
2//
3// This file implements "agressive" dead code elimination. ADCE is DCe where
4// values are assumed to be dead until proven otherwise. This is similar to
5// SCCP, except applied to the liveness of values.
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Optimizations/DCE.h"
10#include "llvm/Instruction.h"
11#include "llvm/Type.h"
Chris Lattnerd8183122001-07-06 16:32:07 +000012#include "llvm/Analysis/Dominators.h"
Chris Lattner57dbb3a2001-07-23 17:46:59 +000013#include "llvm/Support/STLExtras.h"
Chris Lattner3ff43872001-09-28 22:56:31 +000014#include "llvm/Support/DepthFirstIterator.h"
Chris Lattnerd8183122001-07-06 16:32:07 +000015#include "llvm/Analysis/Writer.h"
Chris Lattnerb8259dd2001-09-09 22:26:47 +000016#include "llvm/iTerminators.h"
Chris Lattner72f1e992001-07-08 18:38:36 +000017#include <set>
18#include <algorithm>
Chris Lattner02e90d52001-06-30 06:39:11 +000019
Chris Lattner8a396e52001-09-28 00:06:42 +000020#define DEBUG_ADCE 1
Chris Lattnerb8259dd2001-09-09 22:26:47 +000021
Chris Lattner02e90d52001-06-30 06:39:11 +000022//===----------------------------------------------------------------------===//
23// ADCE Class
24//
25// This class does all of the work of Agressive Dead Code Elimination.
26// It's public interface consists of a constructor and a doADCE() method.
27//
28class ADCE {
29 Method *M; // The method that we are working on...
30 vector<Instruction*> WorkList; // Instructions that just became live
31 set<Instruction*> LiveSet; // The set of live instructions
Chris Lattnerb8259dd2001-09-09 22:26:47 +000032 bool MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +000033
34 //===--------------------------------------------------------------------===//
35 // The public interface for this class
36 //
37public:
38 // ADCE Ctor - Save the method to operate on...
Chris Lattnerb8259dd2001-09-09 22:26:47 +000039 inline ADCE(Method *m) : M(m), MadeChanges(false) {}
Chris Lattner02e90d52001-06-30 06:39:11 +000040
41 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
42 // true if the method was modified.
43 bool doADCE();
44
45 //===--------------------------------------------------------------------===//
46 // The implementation of this class
47 //
48private:
49 inline void markInstructionLive(Instruction *I) {
50 if (LiveSet.count(I)) return;
Chris Lattnerb8259dd2001-09-09 22:26:47 +000051#ifdef DEBUG_ADCE
Chris Lattner02e90d52001-06-30 06:39:11 +000052 cerr << "Insn Live: " << I;
Chris Lattnerb8259dd2001-09-09 22:26:47 +000053#endif
Chris Lattner02e90d52001-06-30 06:39:11 +000054 LiveSet.insert(I);
55 WorkList.push_back(I);
56 }
57
Chris Lattner72f1e992001-07-08 18:38:36 +000058 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +000059#ifdef DEBUG_ADCE
60 cerr << "Terminat Live: " << BB->getTerminator();
61#endif
62 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattner72f1e992001-07-08 18:38:36 +000063 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +000064
65 // fixupCFG - Walk the CFG in depth first order, eliminating references to
66 // dead blocks.
67 //
68 BasicBlock *fixupCFG(BasicBlock *Head, set<BasicBlock*> &VisitedBlocks,
69 const set<BasicBlock*> &AliveBlocks);
Chris Lattner02e90d52001-06-30 06:39:11 +000070};
71
72
73
74// doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
75// true if the method was modified.
76//
77bool ADCE::doADCE() {
Chris Lattnerb8259dd2001-09-09 22:26:47 +000078 // Compute the control dependence graph... Note that this has a side effect
79 // on the CFG: a new return bb is added and all returns are merged here.
Chris Lattner02e90d52001-06-30 06:39:11 +000080 //
Chris Lattner72f1e992001-07-08 18:38:36 +000081 cfg::DominanceFrontier CDG(cfg::DominatorSet(M, true));
Chris Lattner02e90d52001-06-30 06:39:11 +000082
Chris Lattnerb8259dd2001-09-09 22:26:47 +000083#ifdef DEBUG_ADCE
84 cerr << "Method: " << M;
85#endif
86
87 // Iterate over all of the instructions in the method, eliminating trivially
88 // dead instructions, and marking instructions live that are known to be
89 // needed. Perform the walk in depth first order so that we avoid marking any
90 // instructions live in basic blocks that are unreachable. These blocks will
91 // be eliminated later, along with the instructions inside.
92 //
Chris Lattner3ff43872001-09-28 22:56:31 +000093 for (df_iterator<Method*> BBI = df_begin(M),
94 BBE = df_end(M);
Chris Lattnerb8259dd2001-09-09 22:26:47 +000095 BBI != BBE; ++BBI) {
96 BasicBlock *BB = *BBI;
97 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
98 Instruction *I = *II;
99
100 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
101 markInstructionLive(I);
102 } else {
103 // Check to see if anything is trivially dead
104 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
105 // Remove the instruction from it's basic block...
106 delete BB->getInstList().remove(II);
107 MadeChanges = true;
108 continue; // Don't increment the iterator past the current slot
109 }
110 }
111
112 ++II; // Increment the inst iterator if the inst wasn't deleted
113 }
114 }
115
116#ifdef DEBUG_ADCE
Chris Lattner02e90d52001-06-30 06:39:11 +0000117 cerr << "Processing work list\n";
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000118#endif
Chris Lattner02e90d52001-06-30 06:39:11 +0000119
Chris Lattner72f1e992001-07-08 18:38:36 +0000120 // AliveBlocks - Set of basic blocks that we know have instructions that are
121 // alive in them...
122 //
123 set<BasicBlock*> AliveBlocks;
124
Chris Lattner02e90d52001-06-30 06:39:11 +0000125 // Process the work list of instructions that just became live... if they
126 // became live, then that means that all of their operands are neccesary as
127 // well... make them live as well.
128 //
129 while (!WorkList.empty()) {
Chris Lattner72f1e992001-07-08 18:38:36 +0000130 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattner02e90d52001-06-30 06:39:11 +0000131 WorkList.pop_back();
132
Chris Lattner72f1e992001-07-08 18:38:36 +0000133 BasicBlock *BB = I->getParent();
134 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
135 // Mark the basic block as being newly ALIVE... and mark all branches that
136 // this block is control dependant on as being alive also...
137 //
138 AliveBlocks.insert(BB); // Block is now ALIVE!
139 cfg::DominanceFrontier::const_iterator It = CDG.find(BB);
140 if (It != CDG.end()) {
141 // Get the blocks that this node is control dependant on...
142 const cfg::DominanceFrontier::DomSetType &CDB = It->second;
143 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
144 bind_obj(this, &ADCE::markTerminatorLive));
145 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000146
147 // If this basic block is live, then the terminator must be as well!
148 markTerminatorLive(BB);
Chris Lattner72f1e992001-07-08 18:38:36 +0000149 }
150
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000151 // Loop over all of the operands of the live instruction, making sure that
152 // they are known to be alive as well...
153 //
Chris Lattner72f1e992001-07-08 18:38:36 +0000154 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000155 if (Instruction *Operand = I->getOperand(op)->castInstruction())
156 markInstructionLive(Operand);
Chris Lattner02e90d52001-06-30 06:39:11 +0000157 }
158 }
159
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000160#ifdef DEBUG_ADCE
161 cerr << "Current Method: X = Live\n";
162 for (Method::inst_iterator IL = M->inst_begin(); IL != M->inst_end(); ++IL) {
163 if (LiveSet.count(*IL)) cerr << "X ";
164 cerr << *IL;
165 }
166#endif
167
168 // After the worklist is processed, recursively walk the CFG in depth first
169 // order, patching up references to dead blocks...
Chris Lattner02e90d52001-06-30 06:39:11 +0000170 //
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000171 set<BasicBlock*> VisitedBlocks;
172 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
173 if (EntryBlock && EntryBlock != M->front()) {
174 if (EntryBlock->front()->isPHINode()) {
175 // Cannot make the first block be a block with a PHI node in it! Instead,
176 // strip the first basic block of the method to contain no instructions,
177 // then add a simple branch to the "real" entry node...
178 //
179 BasicBlock *E = M->front();
180 if (!E->front()->isTerminator() || // Check for an actual change...
181 ((TerminatorInst*)E->front())->getNumSuccessors() != 1 ||
182 ((TerminatorInst*)E->front())->getSuccessor(0) != EntryBlock) {
183 E->getInstList().delete_all(); // Delete all instructions in block
184 E->getInstList().push_back(new BranchInst(EntryBlock));
185 MadeChanges = true;
186 }
187 AliveBlocks.insert(E);
Chris Lattner8a396e52001-09-28 00:06:42 +0000188
189 // Next we need to change any PHI nodes in the entry block to refer to the
190 // new predecessor node...
191
192
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000193 } else {
194 // We need to move the new entry block to be the first bb of the method.
195 Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
196 swap(*EBI, *M->begin()); // Exchange old location with start of method
197 MadeChanges = true;
Chris Lattner02e90d52001-06-30 06:39:11 +0000198 }
Chris Lattner02e90d52001-06-30 06:39:11 +0000199 }
200
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000201 // Now go through and tell dead blocks to drop all of their references so they
202 // can be safely deleted.
203 //
204 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
205 BasicBlock *BB = *BI;
206 if (!AliveBlocks.count(BB)) {
207 BB->dropAllReferences();
208 }
209 }
210
211 // Now loop through all of the blocks and delete them. We can safely do this
212 // now because we know that there are no references to dead blocks (because
213 // they have dropped all of their references...
214 //
215 for (Method::iterator BI = M->begin(); BI != M->end();) {
216 if (!AliveBlocks.count(*BI)) {
217 delete M->getBasicBlocks().remove(BI);
218 MadeChanges = true;
219 continue; // Don't increment iterator
220 }
221 ++BI; // Increment iterator...
222 }
223
224 return MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +0000225}
226
227
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000228// fixupCFG - Walk the CFG in depth first order, eliminating references to
229// dead blocks:
230// If the BB is alive (in AliveBlocks):
231// 1. Eliminate all dead instructions in the BB
232// 2. Recursively traverse all of the successors of the BB:
233// - If the returned successor is non-null, update our terminator to
234// reference the returned BB
235// 3. Return 0 (no update needed)
236//
237// If the BB is dead (not in AliveBlocks):
238// 1. Add the BB to the dead set
239// 2. Recursively traverse all of the successors of the block:
240// - Only one shall return a nonnull value (or else this block should have
241// been in the alive set).
242// 3. Return the nonnull child, or 0 if no non-null children.
243//
244BasicBlock *ADCE::fixupCFG(BasicBlock *BB, set<BasicBlock*> &VisitedBlocks,
245 const set<BasicBlock*> &AliveBlocks) {
246 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
247 VisitedBlocks.insert(BB); // We have now visited this node!
248
249#ifdef DEBUG_ADCE
250 cerr << "Fixing up BB: " << BB;
251#endif
252
253 if (AliveBlocks.count(BB)) { // Is the block alive?
254 // Yes it's alive: loop through and eliminate all dead instructions in block
255 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
256 Instruction *I = *II;
257 if (!LiveSet.count(I)) { // Is this instruction alive?
258 // Nope... remove the instruction from it's basic block...
259 delete BB->getInstList().remove(II);
260 MadeChanges = true;
261 continue; // Don't increment II
262 }
263 ++II;
264 }
265
266 // Recursively traverse successors of this basic block.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000267 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000268 for (; SI != SE; ++SI) {
269 BasicBlock *Succ = *SI;
270 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
271 if (Repl && Repl != Succ) { // We have to replace the successor
272 Succ->replaceAllUsesWith(Repl);
273 MadeChanges = true;
274 }
275 }
276 return BB;
277 } else { // Otherwise the block is dead...
278 BasicBlock *ReturnBB = 0; // Default to nothing live down here
279
280 // Recursively traverse successors of this basic block.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000281 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000282 for (; SI != SE; ++SI) {
283 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
284 if (RetBB) {
285 assert(ReturnBB == 0 && "One one live child allowed!");
286 ReturnBB = RetBB;
287 }
288 }
289 return ReturnBB; // Return the result of traversal
290 }
291}
292
293
294
Chris Lattner02e90d52001-06-30 06:39:11 +0000295// DoADCE - Execute the Agressive Dead Code Elimination Algorithm
296//
297bool opt::DoADCE(Method *M) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000298 if (M->isExternal()) return false;
Chris Lattner02e90d52001-06-30 06:39:11 +0000299 ADCE DCE(M);
300 return DCE.doADCE();
301}