1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
3 // This file implements "aggressive" 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.h"
10 #include "llvm/Transforms/Utils/Local.h"
11 #include "llvm/Type.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/Analysis/Writer.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/Support/CFG.h"
17 #include "Support/STLExtras.h"
18 #include "Support/DepthFirstIterator.h"
27 //===----------------------------------------------------------------------===//
30 // This class does all of the work of Aggressive Dead Code Elimination.
31 // It's public interface consists of a constructor and a doADCE() method.
33 class ADCE : public FunctionPass {
34 Function *Func; // The function that we are working on
35 std::vector<Instruction*> WorkList; // Instructions that just became live
36 std::set<Instruction*> LiveSet; // The set of live instructions
39 //===--------------------------------------------------------------------===//
40 // The public interface for this class
43 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
45 // doADCE - Execute the Aggressive Dead Code Elimination Algorithm
47 virtual bool runOnFunction(Function *F) {
48 Func = F; MadeChanges = false;
49 doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
50 assert(WorkList.empty());
54 // getAnalysisUsage - We require post dominance frontiers (aka Control
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired(DominanceFrontier::PostDomID);
61 //===--------------------------------------------------------------------===//
62 // The implementation of this class
65 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
66 // true if the function was modified.
68 void doADCE(DominanceFrontier &CDG);
70 inline void markInstructionLive(Instruction *I) {
71 if (LiveSet.count(I)) return;
73 cerr << "Insn Live: " << I;
76 WorkList.push_back(I);
79 inline void markTerminatorLive(const BasicBlock *BB) {
81 cerr << "Terminat Live: " << BB->getTerminator();
83 markInstructionLive((Instruction*)BB->getTerminator());
86 // fixupCFG - Walk the CFG in depth first order, eliminating references to
89 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
90 const std::set<BasicBlock*> &AliveBlocks);
93 } // End of anonymous namespace
95 Pass *createAggressiveDCEPass() {
100 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
101 // true if the function was modified.
103 void ADCE::doADCE(DominanceFrontier &CDG) {
105 cerr << "Function: " << Func;
108 // Iterate over all of the instructions in the function, eliminating trivially
109 // 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.
114 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
116 BasicBlock *BB = *BBI;
117 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
118 Instruction *I = *II;
120 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
121 markInstructionLive(I);
122 ++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);
128 ++II; // Increment the inst iterator if the inst wasn't deleted
134 cerr << "Processing work list\n";
137 // AliveBlocks - Set of basic blocks that we know have instructions that are
140 std::set<BasicBlock*> AliveBlocks;
142 // 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.
146 while (!WorkList.empty()) {
147 Instruction *I = WorkList.back(); // Get an instruction that became live...
150 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...
155 AliveBlocks.insert(BB); // Block is now ALIVE!
156 DominanceFrontier::const_iterator It = CDG.find(BB);
157 if (It != CDG.end()) {
158 // Get the blocks that this node is control dependant on...
159 const DominanceFrontier::DomSetType &CDB = It->second;
160 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
161 bind_obj(this, &ADCE::markTerminatorLive));
164 // If this basic block is live, then the terminator must be as well!
165 markTerminatorLive(BB);
168 // Loop over all of the operands of the live instruction, making sure that
169 // they are known to be alive as well...
171 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
172 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
173 markInstructionLive(Operand);
177 cerr << "Current Function: X = Live\n";
178 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
179 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
181 if (LiveSet.count(*BI)) cerr << "X ";
186 // After the worklist is processed, recursively walk the CFG in depth first
187 // order, patching up references to dead blocks...
189 std::set<BasicBlock*> VisitedBlocks;
190 BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
192 // Now go through and tell dead blocks to drop all of their references so they
193 // 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.
197 for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
198 BasicBlock *BB = *BI;
199 if (!AliveBlocks.count(BB)) {
200 // 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
209 BB->dropAllReferences();
213 cerr << "Before Deleting Blocks: " << Func;
215 // 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...
219 for (Function::iterator BI = Func->begin(); BI != Func->end();) {
220 if (!AliveBlocks.count(*BI)) {
221 delete Func->getBasicBlocks().remove(BI);
223 continue; // Don't increment iterator
225 ++BI; // Increment iterator...
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
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...
240 PN->replaceAllUsesWith(PN->getIncomingValue(0));
242 // Nuke the phi node...
243 delete EntryBlock->getInstList().remove(EntryBlock->begin());
248 // fixupCFG - Walk the CFG in depth first order, eliminating references to
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)
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.
264 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
265 const std::set<BasicBlock*> &AliveBlocks) {
266 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
267 VisitedBlocks.insert(BB); // We have now visited this node!
270 cerr << "Fixing up BB: " << BB;
273 if (AliveBlocks.count(BB)) { // Is the block alive?
274 // Yes it's alive: loop through and eliminate all dead instructions in block
275 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
276 if (!LiveSet.count(*II)) { // Is this instruction alive?
277 // Nope... remove the instruction from it's basic block...
278 delete BB->getInstList().remove(II);
284 // Recursively traverse successors of this basic block.
285 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
286 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);
294 } else { // Otherwise the block is dead...
295 BasicBlock *ReturnBB = 0; // Default to nothing live down here
297 // Recursively traverse successors of this basic block.
298 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
299 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
301 assert(ReturnBB == 0 && "At most one live child allowed!");
305 return ReturnBB; // Return the result of traversal