1 //===- ADCE.cpp - Code to perform agressive dead code elimination ---------===//
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.
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/Scalar/DCE.h"
10 #include "llvm/Type.h"
11 #include "llvm/Analysis/Dominators.h"
12 #include "llvm/Analysis/Writer.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Support/CFG.h"
16 #include "Support/STLExtras.h"
17 #include "Support/DepthFirstIterator.h"
26 //===----------------------------------------------------------------------===//
29 // This class does all of the work of Agressive Dead Code Elimination.
30 // It's public interface consists of a constructor and a doADCE() method.
32 class ADCE : public FunctionPass {
33 Function *Func; // The function that we are working on
34 std::vector<Instruction*> WorkList; // Instructions that just became live
35 std::set<Instruction*> LiveSet; // The set of live instructions
38 //===--------------------------------------------------------------------===//
39 // The public interface for this class
42 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
44 // doADCE - Execute the Agressive Dead Code Elimination Algorithm
46 virtual bool runOnFunction(Function *F) {
47 Func = F; MadeChanges = false;
48 doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
49 assert(WorkList.empty());
53 // getAnalysisUsage - We require post dominance frontiers (aka Control
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired(DominanceFrontier::PostDomID);
60 //===--------------------------------------------------------------------===//
61 // The implementation of this class
64 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
65 // true if the function was modified.
67 void doADCE(DominanceFrontier &CDG);
69 inline void markInstructionLive(Instruction *I) {
70 if (LiveSet.count(I)) return;
72 cerr << "Insn Live: " << I;
75 WorkList.push_back(I);
78 inline void markTerminatorLive(const BasicBlock *BB) {
80 cerr << "Terminat Live: " << BB->getTerminator();
82 markInstructionLive((Instruction*)BB->getTerminator());
85 // fixupCFG - Walk the CFG in depth first order, eliminating references to
88 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
89 const std::set<BasicBlock*> &AliveBlocks);
92 } // End of anonymous namespace
94 Pass *createAgressiveDCEPass() {
99 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
100 // true if the function was modified.
102 void ADCE::doADCE(DominanceFrontier &CDG) {
104 cerr << "Function: " << Func;
107 // Iterate over all of the instructions in the function, eliminating trivially
108 // dead instructions, and marking instructions live that are known to be
109 // needed. Perform the walk in depth first order so that we avoid marking any
110 // instructions live in basic blocks that are unreachable. These blocks will
111 // be eliminated later, along with the instructions inside.
113 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
115 BasicBlock *BB = *BBI;
116 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
117 Instruction *I = *II;
119 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
120 markInstructionLive(I);
122 // Check to see if anything is trivially dead
123 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
124 // Remove the instruction from it's basic block...
125 delete BB->getInstList().remove(II);
127 continue; // Don't increment the iterator past the current slot
131 ++II; // Increment the inst iterator if the inst wasn't deleted
136 cerr << "Processing work list\n";
139 // AliveBlocks - Set of basic blocks that we know have instructions that are
142 std::set<BasicBlock*> AliveBlocks;
144 // Process the work list of instructions that just became live... if they
145 // became live, then that means that all of their operands are neccesary as
146 // well... make them live as well.
148 while (!WorkList.empty()) {
149 Instruction *I = WorkList.back(); // Get an instruction that became live...
152 BasicBlock *BB = I->getParent();
153 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
154 // Mark the basic block as being newly ALIVE... and mark all branches that
155 // this block is control dependant on as being alive also...
157 AliveBlocks.insert(BB); // Block is now ALIVE!
158 DominanceFrontier::const_iterator It = CDG.find(BB);
159 if (It != CDG.end()) {
160 // Get the blocks that this node is control dependant on...
161 const DominanceFrontier::DomSetType &CDB = It->second;
162 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
163 bind_obj(this, &ADCE::markTerminatorLive));
166 // If this basic block is live, then the terminator must be as well!
167 markTerminatorLive(BB);
170 // Loop over all of the operands of the live instruction, making sure that
171 // they are known to be alive as well...
173 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
174 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
175 markInstructionLive(Operand);
180 cerr << "Current Function: X = Live\n";
181 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
182 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
184 if (LiveSet.count(*BI)) cerr << "X ";
189 // After the worklist is processed, recursively walk the CFG in depth first
190 // order, patching up references to dead blocks...
192 std::set<BasicBlock*> VisitedBlocks;
193 BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
194 if (EntryBlock && EntryBlock != Func->front()) {
195 if (isa<PHINode>(EntryBlock->front())) {
196 // Cannot make the first block be a block with a PHI node in it! Instead,
197 // strip the first basic block of the function to contain no instructions,
198 // then add a simple branch to the "real" entry node...
200 BasicBlock *E = Func->front();
201 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
202 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
203 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
204 E->getInstList().delete_all(); // Delete all instructions in block
205 E->getInstList().push_back(new BranchInst(EntryBlock));
208 AliveBlocks.insert(E);
210 // Next we need to change any PHI nodes in the entry block to refer to the
211 // new predecessor node...
215 // We need to move the new entry block to be the first bb of the function
216 Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
217 std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
222 // Now go through and tell dead blocks to drop all of their references so they
223 // can be safely deleted.
225 for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
226 BasicBlock *BB = *BI;
227 if (!AliveBlocks.count(BB)) {
228 BB->dropAllReferences();
232 // Now loop through all of the blocks and delete them. We can safely do this
233 // now because we know that there are no references to dead blocks (because
234 // they have dropped all of their references...
236 for (Function::iterator BI = Func->begin(); BI != Func->end();) {
237 if (!AliveBlocks.count(*BI)) {
238 delete Func->getBasicBlocks().remove(BI);
240 continue; // Don't increment iterator
242 ++BI; // Increment iterator...
247 // fixupCFG - Walk the CFG in depth first order, eliminating references to
249 // If the BB is alive (in AliveBlocks):
250 // 1. Eliminate all dead instructions in the BB
251 // 2. Recursively traverse all of the successors of the BB:
252 // - If the returned successor is non-null, update our terminator to
253 // reference the returned BB
254 // 3. Return 0 (no update needed)
256 // If the BB is dead (not in AliveBlocks):
257 // 1. Add the BB to the dead set
258 // 2. Recursively traverse all of the successors of the block:
259 // - Only one shall return a nonnull value (or else this block should have
260 // been in the alive set).
261 // 3. Return the nonnull child, or 0 if no non-null children.
263 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
264 const std::set<BasicBlock*> &AliveBlocks) {
265 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
266 VisitedBlocks.insert(BB); // We have now visited this node!
269 cerr << "Fixing up BB: " << BB;
272 if (AliveBlocks.count(BB)) { // Is the block alive?
273 // Yes it's alive: loop through and eliminate all dead instructions in block
274 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
275 Instruction *I = *II;
276 if (!LiveSet.count(I)) { // Is this instruction alive?
277 // Nope... remove the instruction from it's basic block...
278 delete BB->getInstList().remove(II);
280 continue; // Don't increment II
285 // Recursively traverse successors of this basic block.
286 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
287 BasicBlock *Succ = *SI;
288 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
289 if (Repl && Repl != Succ) { // We have to replace the successor
290 Succ->replaceAllUsesWith(Repl);
295 } else { // Otherwise the block is dead...
296 BasicBlock *ReturnBB = 0; // Default to nothing live down here
298 // Recursively traverse successors of this basic block.
299 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
300 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
302 assert(ReturnBB == 0 && "One one live child allowed!");
306 return ReturnBB; // Return the result of traversal