blob: 4c0169171b245f0c5ea571f31f5273b30491454b [file] [log] [blame]
Chris Lattnerc1496bda2002-05-07 22:11:39 +00001//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
Chris Lattnerb28986f2001-06-30 06:39:11 +00002//
Chris Lattnerc1496bda2002-05-07 22:11:39 +00003// This file implements "aggressive" dead code elimination. ADCE is DCe where
Chris Lattnerb28986f2001-06-30 06:39:11 +00004// 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
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +00009#include "llvm/Transforms/Scalar.h"
Chris Lattnerc1496bda2002-05-07 22:11:39 +000010#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb28986f2001-06-30 06:39:11 +000011#include "llvm/Type.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000012#include "llvm/Analysis/Dominators.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000013#include "llvm/Analysis/Writer.h"
Chris Lattneracfd27d2001-09-09 22:26:47 +000014#include "llvm/iTerminators.h"
Chris Lattnerfb5ae022001-12-03 18:02:31 +000015#include "llvm/iPHINode.h"
Chris Lattner60a65912002-02-12 21:07:25 +000016#include "llvm/Support/CFG.h"
Chris Lattner5de22042001-11-27 00:03:19 +000017#include "Support/STLExtras.h"
18#include "Support/DepthFirstIterator.h"
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000019#include <algorithm>
Chris Lattner7f74a562002-01-20 22:54:45 +000020#include <iostream>
21using std::cerr;
Chris Lattnerb28986f2001-06-30 06:39:11 +000022
Chris Lattnerb271be32001-09-28 00:06:42 +000023#define DEBUG_ADCE 1
Chris Lattneracfd27d2001-09-09 22:26:47 +000024
Chris Lattner019f3642002-05-06 17:27:57 +000025namespace {
26
Chris Lattnerb28986f2001-06-30 06:39:11 +000027//===----------------------------------------------------------------------===//
28// ADCE Class
29//
Chris Lattnerc1496bda2002-05-07 22:11:39 +000030// This class does all of the work of Aggressive Dead Code Elimination.
Chris Lattnerb28986f2001-06-30 06:39:11 +000031// It's public interface consists of a constructor and a doADCE() method.
32//
Chris Lattner019f3642002-05-06 17:27:57 +000033class ADCE : public FunctionPass {
34 Function *Func; // The function that we are working on
Chris Lattner7f74a562002-01-20 22:54:45 +000035 std::vector<Instruction*> WorkList; // Instructions that just became live
36 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattneracfd27d2001-09-09 22:26:47 +000037 bool MadeChanges;
Chris Lattnerb28986f2001-06-30 06:39:11 +000038
39 //===--------------------------------------------------------------------===//
40 // The public interface for this class
41 //
42public:
Chris Lattner019f3642002-05-06 17:27:57 +000043 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
44
Chris Lattnerc1496bda2002-05-07 22:11:39 +000045 // doADCE - Execute the Aggressive Dead Code Elimination Algorithm
Chris Lattner019f3642002-05-06 17:27:57 +000046 //
47 virtual bool runOnFunction(Function *F) {
48 Func = F; MadeChanges = false;
49 doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
50 assert(WorkList.empty());
51 LiveSet.clear();
52 return MadeChanges;
53 }
54 // getAnalysisUsage - We require post dominance frontiers (aka Control
55 // Dependence Graph)
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired(DominanceFrontier::PostDomID);
58 }
Chris Lattnerb28986f2001-06-30 06:39:11 +000059
Chris Lattnerb28986f2001-06-30 06:39:11 +000060
61 //===--------------------------------------------------------------------===//
62 // The implementation of this class
63 //
64private:
Chris Lattnerc1496bda2002-05-07 22:11:39 +000065 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattner019f3642002-05-06 17:27:57 +000066 // true if the function was modified.
67 //
68 void doADCE(DominanceFrontier &CDG);
69
Chris Lattnerb28986f2001-06-30 06:39:11 +000070 inline void markInstructionLive(Instruction *I) {
71 if (LiveSet.count(I)) return;
Chris Lattneracfd27d2001-09-09 22:26:47 +000072#ifdef DEBUG_ADCE
Chris Lattnerb28986f2001-06-30 06:39:11 +000073 cerr << "Insn Live: " << I;
Chris Lattneracfd27d2001-09-09 22:26:47 +000074#endif
Chris Lattnerb28986f2001-06-30 06:39:11 +000075 LiveSet.insert(I);
76 WorkList.push_back(I);
77 }
78
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000079 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattneracfd27d2001-09-09 22:26:47 +000080#ifdef DEBUG_ADCE
81 cerr << "Terminat Live: " << BB->getTerminator();
82#endif
83 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000084 }
Chris Lattneracfd27d2001-09-09 22:26:47 +000085
86 // fixupCFG - Walk the CFG in depth first order, eliminating references to
87 // dead blocks.
88 //
Chris Lattner7f74a562002-01-20 22:54:45 +000089 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
90 const std::set<BasicBlock*> &AliveBlocks);
Chris Lattnerb28986f2001-06-30 06:39:11 +000091};
92
Chris Lattner019f3642002-05-06 17:27:57 +000093} // End of anonymous namespace
94
Chris Lattnerc1496bda2002-05-07 22:11:39 +000095Pass *createAggressiveDCEPass() {
Chris Lattner019f3642002-05-06 17:27:57 +000096 return new ADCE();
97}
Chris Lattnerb28986f2001-06-30 06:39:11 +000098
99
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000100// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerc8e66542002-04-27 06:56:12 +0000101// true if the function was modified.
Chris Lattnerb28986f2001-06-30 06:39:11 +0000102//
Chris Lattner019f3642002-05-06 17:27:57 +0000103void ADCE::doADCE(DominanceFrontier &CDG) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000104#ifdef DEBUG_ADCE
Chris Lattner019f3642002-05-06 17:27:57 +0000105 cerr << "Function: " << Func;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000106#endif
107
Chris Lattnerc8e66542002-04-27 06:56:12 +0000108 // Iterate over all of the instructions in the function, eliminating trivially
Chris Lattneracfd27d2001-09-09 22:26:47 +0000109 // dead instructions, and marking instructions live that are known to be
110 // needed. Perform the walk in depth first order so that we avoid marking any
111 // instructions live in basic blocks that are unreachable. These blocks will
112 // be eliminated later, along with the instructions inside.
113 //
Chris Lattner019f3642002-05-06 17:27:57 +0000114 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000115 BBI != BBE; ++BBI) {
116 BasicBlock *BB = *BBI;
117 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
118 Instruction *I = *II;
119
120 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
121 markInstructionLive(I);
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000122 ++II; // Increment the inst iterator if the inst wasn't deleted
123 } else if (isInstructionTriviallyDead(I)) {
124 // Remove the instruction from it's basic block...
125 delete BB->getInstList().remove(II);
126 MadeChanges = true;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000127 } else {
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000128 ++II; // Increment the inst iterator if the inst wasn't deleted
Chris Lattneracfd27d2001-09-09 22:26:47 +0000129 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000130 }
131 }
132
133#ifdef DEBUG_ADCE
Chris Lattnerb28986f2001-06-30 06:39:11 +0000134 cerr << "Processing work list\n";
Chris Lattneracfd27d2001-09-09 22:26:47 +0000135#endif
Chris Lattnerb28986f2001-06-30 06:39:11 +0000136
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000137 // AliveBlocks - Set of basic blocks that we know have instructions that are
138 // alive in them...
139 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000140 std::set<BasicBlock*> AliveBlocks;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000141
Chris Lattnerb28986f2001-06-30 06:39:11 +0000142 // Process the work list of instructions that just became live... if they
143 // became live, then that means that all of their operands are neccesary as
144 // well... make them live as well.
145 //
146 while (!WorkList.empty()) {
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000147 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000148 WorkList.pop_back();
149
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000150 BasicBlock *BB = I->getParent();
151 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
152 // Mark the basic block as being newly ALIVE... and mark all branches that
153 // this block is control dependant on as being alive also...
154 //
155 AliveBlocks.insert(BB); // Block is now ALIVE!
Chris Lattner78dd56f2002-04-28 16:21:30 +0000156 DominanceFrontier::const_iterator It = CDG.find(BB);
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000157 if (It != CDG.end()) {
158 // Get the blocks that this node is control dependant on...
Chris Lattner78dd56f2002-04-28 16:21:30 +0000159 const DominanceFrontier::DomSetType &CDB = It->second;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000160 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
161 bind_obj(this, &ADCE::markTerminatorLive));
162 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000163
164 // If this basic block is live, then the terminator must be as well!
165 markTerminatorLive(BB);
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000166 }
167
Chris Lattneracfd27d2001-09-09 22:26:47 +0000168 // Loop over all of the operands of the live instruction, making sure that
169 // they are known to be alive as well...
170 //
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000171 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
Chris Lattner4b717c02001-10-01 16:18:37 +0000172 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattneracfd27d2001-09-09 22:26:47 +0000173 markInstructionLive(Operand);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000174 }
175
Chris Lattneracfd27d2001-09-09 22:26:47 +0000176#ifdef DEBUG_ADCE
Chris Lattnerf8e4dc32002-04-08 22:03:00 +0000177 cerr << "Current Function: X = Live\n";
Chris Lattner019f3642002-05-06 17:27:57 +0000178 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner60a65912002-02-12 21:07:25 +0000179 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
180 BI != BE; ++BI) {
181 if (LiveSet.count(*BI)) cerr << "X ";
182 cerr << *BI;
183 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000184#endif
185
186 // After the worklist is processed, recursively walk the CFG in depth first
187 // order, patching up references to dead blocks...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000188 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000189 std::set<BasicBlock*> VisitedBlocks;
Chris Lattner019f3642002-05-06 17:27:57 +0000190 BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000191
Chris Lattneracfd27d2001-09-09 22:26:47 +0000192 // Now go through and tell dead blocks to drop all of their references so they
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000193 // can be safely deleted. Also, as we are doing so, if the block has
194 // successors that are still live (and that have PHI nodes in them), remove
195 // the entry for this block from the phi nodes.
Chris Lattneracfd27d2001-09-09 22:26:47 +0000196 //
Chris Lattner019f3642002-05-06 17:27:57 +0000197 for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
Chris Lattneracfd27d2001-09-09 22:26:47 +0000198 BasicBlock *BB = *BI;
199 if (!AliveBlocks.count(BB)) {
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000200 // Remove entries from successors PHI nodes if they are still alive...
201 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
202 if (AliveBlocks.count(*SI)) { // Only if the successor is alive...
203 BasicBlock *Succ = *SI;
204 for (BasicBlock::iterator I = Succ->begin();// Loop over all PHI nodes
205 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
206 PN->removeIncomingValue(BB); // Remove value for this block
207 }
208
Chris Lattneracfd27d2001-09-09 22:26:47 +0000209 BB->dropAllReferences();
210 }
211 }
212
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000213 cerr << "Before Deleting Blocks: " << Func;
214
Chris Lattneracfd27d2001-09-09 22:26:47 +0000215 // Now loop through all of the blocks and delete them. We can safely do this
216 // now because we know that there are no references to dead blocks (because
217 // they have dropped all of their references...
218 //
Chris Lattner019f3642002-05-06 17:27:57 +0000219 for (Function::iterator BI = Func->begin(); BI != Func->end();) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000220 if (!AliveBlocks.count(*BI)) {
Chris Lattner019f3642002-05-06 17:27:57 +0000221 delete Func->getBasicBlocks().remove(BI);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000222 MadeChanges = true;
223 continue; // Don't increment iterator
224 }
225 ++BI; // Increment iterator...
226 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000227
228 if (EntryBlock && EntryBlock != Func->front()) {
229 // We need to move the new entry block to be the first bb of the function
230 Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
231 std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
232 }
233
234 while (PHINode *PN = dyn_cast<PHINode>(EntryBlock->front())) {
235 assert(PN->getNumIncomingValues() == 1 &&
236 "Can only have a single incoming value at this point...");
237 // The incoming value must be outside of the scope of the function, a
238 // global variable, constant or parameter maybe...
239 //
240 PN->replaceAllUsesWith(PN->getIncomingValue(0));
241
242 // Nuke the phi node...
243 delete EntryBlock->getInstList().remove(EntryBlock->begin());
244 }
Chris Lattnerb28986f2001-06-30 06:39:11 +0000245}
246
247
Chris Lattneracfd27d2001-09-09 22:26:47 +0000248// fixupCFG - Walk the CFG in depth first order, eliminating references to
249// dead blocks:
250// If the BB is alive (in AliveBlocks):
251// 1. Eliminate all dead instructions in the BB
252// 2. Recursively traverse all of the successors of the BB:
253// - If the returned successor is non-null, update our terminator to
254// reference the returned BB
255// 3. Return 0 (no update needed)
256//
257// If the BB is dead (not in AliveBlocks):
258// 1. Add the BB to the dead set
259// 2. Recursively traverse all of the successors of the block:
260// - Only one shall return a nonnull value (or else this block should have
261// been in the alive set).
262// 3. Return the nonnull child, or 0 if no non-null children.
263//
Chris Lattner7f74a562002-01-20 22:54:45 +0000264BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
265 const std::set<BasicBlock*> &AliveBlocks) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000266 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
267 VisitedBlocks.insert(BB); // We have now visited this node!
268
269#ifdef DEBUG_ADCE
270 cerr << "Fixing up BB: " << BB;
271#endif
272
273 if (AliveBlocks.count(BB)) { // Is the block alive?
274 // Yes it's alive: loop through and eliminate all dead instructions in block
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000275 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
276 if (!LiveSet.count(*II)) { // Is this instruction alive?
Chris Lattneracfd27d2001-09-09 22:26:47 +0000277 // Nope... remove the instruction from it's basic block...
278 delete BB->getInstList().remove(II);
279 MadeChanges = true;
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000280 } else {
281 ++II;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000282 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000283
284 // Recursively traverse successors of this basic block.
Chris Lattner83d485b2002-02-12 22:39:50 +0000285 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000286 BasicBlock *Succ = *SI;
287 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
288 if (Repl && Repl != Succ) { // We have to replace the successor
289 Succ->replaceAllUsesWith(Repl);
290 MadeChanges = true;
291 }
292 }
293 return BB;
294 } else { // Otherwise the block is dead...
295 BasicBlock *ReturnBB = 0; // Default to nothing live down here
296
297 // Recursively traverse successors of this basic block.
Chris Lattner83d485b2002-02-12 22:39:50 +0000298 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000299 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
300 if (RetBB) {
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000301 assert(ReturnBB == 0 && "At most one live child allowed!");
Chris Lattneracfd27d2001-09-09 22:26:47 +0000302 ReturnBB = RetBB;
303 }
304 }
305 return ReturnBB; // Return the result of traversal
306 }
307}
308