blob: 631db2cea78368877aaadcd8acab6d4f8bd51b51 [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 Lattnerd8183122001-07-06 16:32:07 +000014#include "llvm/Analysis/Writer.h"
Chris Lattnerb8259dd2001-09-09 22:26:47 +000015#include "llvm/CFG.h"
16#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 //
93 for (cfg::df_iterator BBI = cfg::df_begin(M), BBE = cfg::df_end(M);
94 BBI != BBE; ++BBI) {
95 BasicBlock *BB = *BBI;
96 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
97 Instruction *I = *II;
98
99 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
100 markInstructionLive(I);
101 } else {
102 // Check to see if anything is trivially dead
103 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
104 // Remove the instruction from it's basic block...
105 delete BB->getInstList().remove(II);
106 MadeChanges = true;
107 continue; // Don't increment the iterator past the current slot
108 }
109 }
110
111 ++II; // Increment the inst iterator if the inst wasn't deleted
112 }
113 }
114
115#ifdef DEBUG_ADCE
Chris Lattner02e90d52001-06-30 06:39:11 +0000116 cerr << "Processing work list\n";
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000117#endif
Chris Lattner02e90d52001-06-30 06:39:11 +0000118
Chris Lattner72f1e992001-07-08 18:38:36 +0000119 // AliveBlocks - Set of basic blocks that we know have instructions that are
120 // alive in them...
121 //
122 set<BasicBlock*> AliveBlocks;
123
Chris Lattner02e90d52001-06-30 06:39:11 +0000124 // Process the work list of instructions that just became live... if they
125 // became live, then that means that all of their operands are neccesary as
126 // well... make them live as well.
127 //
128 while (!WorkList.empty()) {
Chris Lattner72f1e992001-07-08 18:38:36 +0000129 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattner02e90d52001-06-30 06:39:11 +0000130 WorkList.pop_back();
131
Chris Lattner72f1e992001-07-08 18:38:36 +0000132 BasicBlock *BB = I->getParent();
133 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
134 // Mark the basic block as being newly ALIVE... and mark all branches that
135 // this block is control dependant on as being alive also...
136 //
137 AliveBlocks.insert(BB); // Block is now ALIVE!
138 cfg::DominanceFrontier::const_iterator It = CDG.find(BB);
139 if (It != CDG.end()) {
140 // Get the blocks that this node is control dependant on...
141 const cfg::DominanceFrontier::DomSetType &CDB = It->second;
142 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
143 bind_obj(this, &ADCE::markTerminatorLive));
144 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000145
146 // If this basic block is live, then the terminator must be as well!
147 markTerminatorLive(BB);
Chris Lattner72f1e992001-07-08 18:38:36 +0000148 }
149
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000150 // Loop over all of the operands of the live instruction, making sure that
151 // they are known to be alive as well...
152 //
Chris Lattner72f1e992001-07-08 18:38:36 +0000153 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000154 if (Instruction *Operand = I->getOperand(op)->castInstruction())
155 markInstructionLive(Operand);
Chris Lattner02e90d52001-06-30 06:39:11 +0000156 }
157 }
158
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000159#ifdef DEBUG_ADCE
160 cerr << "Current Method: X = Live\n";
161 for (Method::inst_iterator IL = M->inst_begin(); IL != M->inst_end(); ++IL) {
162 if (LiveSet.count(*IL)) cerr << "X ";
163 cerr << *IL;
164 }
165#endif
166
167 // After the worklist is processed, recursively walk the CFG in depth first
168 // order, patching up references to dead blocks...
Chris Lattner02e90d52001-06-30 06:39:11 +0000169 //
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000170 set<BasicBlock*> VisitedBlocks;
171 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
172 if (EntryBlock && EntryBlock != M->front()) {
173 if (EntryBlock->front()->isPHINode()) {
174 // Cannot make the first block be a block with a PHI node in it! Instead,
175 // strip the first basic block of the method to contain no instructions,
176 // then add a simple branch to the "real" entry node...
177 //
178 BasicBlock *E = M->front();
179 if (!E->front()->isTerminator() || // Check for an actual change...
180 ((TerminatorInst*)E->front())->getNumSuccessors() != 1 ||
181 ((TerminatorInst*)E->front())->getSuccessor(0) != EntryBlock) {
182 E->getInstList().delete_all(); // Delete all instructions in block
183 E->getInstList().push_back(new BranchInst(EntryBlock));
184 MadeChanges = true;
185 }
186 AliveBlocks.insert(E);
Chris Lattner8a396e52001-09-28 00:06:42 +0000187
188 // Next we need to change any PHI nodes in the entry block to refer to the
189 // new predecessor node...
190
191
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000192 } else {
193 // We need to move the new entry block to be the first bb of the method.
194 Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
195 swap(*EBI, *M->begin()); // Exchange old location with start of method
196 MadeChanges = true;
Chris Lattner02e90d52001-06-30 06:39:11 +0000197 }
Chris Lattner02e90d52001-06-30 06:39:11 +0000198 }
199
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000200 // Now go through and tell dead blocks to drop all of their references so they
201 // can be safely deleted.
202 //
203 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
204 BasicBlock *BB = *BI;
205 if (!AliveBlocks.count(BB)) {
206 BB->dropAllReferences();
207 }
208 }
209
210 // Now loop through all of the blocks and delete them. We can safely do this
211 // now because we know that there are no references to dead blocks (because
212 // they have dropped all of their references...
213 //
214 for (Method::iterator BI = M->begin(); BI != M->end();) {
215 if (!AliveBlocks.count(*BI)) {
216 delete M->getBasicBlocks().remove(BI);
217 MadeChanges = true;
218 continue; // Don't increment iterator
219 }
220 ++BI; // Increment iterator...
221 }
222
223 return MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +0000224}
225
226
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000227// fixupCFG - Walk the CFG in depth first order, eliminating references to
228// dead blocks:
229// If the BB is alive (in AliveBlocks):
230// 1. Eliminate all dead instructions in the BB
231// 2. Recursively traverse all of the successors of the BB:
232// - If the returned successor is non-null, update our terminator to
233// reference the returned BB
234// 3. Return 0 (no update needed)
235//
236// If the BB is dead (not in AliveBlocks):
237// 1. Add the BB to the dead set
238// 2. Recursively traverse all of the successors of the block:
239// - Only one shall return a nonnull value (or else this block should have
240// been in the alive set).
241// 3. Return the nonnull child, or 0 if no non-null children.
242//
243BasicBlock *ADCE::fixupCFG(BasicBlock *BB, set<BasicBlock*> &VisitedBlocks,
244 const set<BasicBlock*> &AliveBlocks) {
245 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
246 VisitedBlocks.insert(BB); // We have now visited this node!
247
248#ifdef DEBUG_ADCE
249 cerr << "Fixing up BB: " << BB;
250#endif
251
252 if (AliveBlocks.count(BB)) { // Is the block alive?
253 // Yes it's alive: loop through and eliminate all dead instructions in block
254 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
255 Instruction *I = *II;
256 if (!LiveSet.count(I)) { // Is this instruction alive?
257 // Nope... remove the instruction from it's basic block...
258 delete BB->getInstList().remove(II);
259 MadeChanges = true;
260 continue; // Don't increment II
261 }
262 ++II;
263 }
264
265 // Recursively traverse successors of this basic block.
266 cfg::succ_iterator SI = cfg::succ_begin(BB), SE = cfg::succ_end(BB);
267 for (; SI != SE; ++SI) {
268 BasicBlock *Succ = *SI;
269 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
270 if (Repl && Repl != Succ) { // We have to replace the successor
271 Succ->replaceAllUsesWith(Repl);
272 MadeChanges = true;
273 }
274 }
275 return BB;
276 } else { // Otherwise the block is dead...
277 BasicBlock *ReturnBB = 0; // Default to nothing live down here
278
279 // Recursively traverse successors of this basic block.
280 cfg::succ_iterator SI = cfg::succ_begin(BB), SE = cfg::succ_end(BB);
281 for (; SI != SE; ++SI) {
282 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
283 if (RetBB) {
284 assert(ReturnBB == 0 && "One one live child allowed!");
285 ReturnBB = RetBB;
286 }
287 }
288 return ReturnBB; // Return the result of traversal
289 }
290}
291
292
293
Chris Lattner02e90d52001-06-30 06:39:11 +0000294// DoADCE - Execute the Agressive Dead Code Elimination Algorithm
295//
296bool opt::DoADCE(Method *M) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000297 if (M->isExternal()) return false;
Chris Lattner02e90d52001-06-30 06:39:11 +0000298 ADCE DCE(M);
299 return DCE.doADCE();
300}