1 //===- 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/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" 18 #include <algorithm> 19 #include <iostream> 20 using std::cerr; 21 22 #define DEBUG_ADCE 1 23 24 namespace { 25 26 //===----------------------------------------------------------------------===// 27 // ADCE Class 28 // 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. 31 // 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 36 bool MadeChanges; 37 38 //===--------------------------------------------------------------------===// 39 // The public interface for this class 40 // 41 public: 42 const char *getPassName() const { return "Aggressive Dead Code Elimination"; } 43 44 // doADCE - Execute the Agressive Dead Code Elimination Algorithm 45 // 46 virtual bool runOnFunction(Function *F) { 47 Func = F; MadeChanges = false; 48 doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID)); 49 assert(WorkList.empty()); 50 LiveSet.clear(); 51 return MadeChanges; 52 } 53 // getAnalysisUsage - We require post dominance frontiers (aka Control 54 // Dependence Graph) 55 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 56 AU.addRequired(DominanceFrontier::PostDomID); 57 } 58 59 60 //===--------------------------------------------------------------------===// 61 // The implementation of this class 62 // 63 private: 64 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning 65 // true if the function was modified. 66 // 67 void doADCE(DominanceFrontier &CDG); 68 69 inline void markInstructionLive(Instruction *I) { 70 if (LiveSet.count(I)) return; 71 #ifdef DEBUG_ADCE 72 cerr << "Insn Live: " << I; 73 #endif 74 LiveSet.insert(I); 75 WorkList.push_back(I); 76 } 77 78 inline void markTerminatorLive(const BasicBlock *BB) { 79 #ifdef DEBUG_ADCE 80 cerr << "Terminat Live: " << BB->getTerminator(); 81 #endif 82 markInstructionLive((Instruction*)BB->getTerminator()); 83 } 84 85 // fixupCFG - Walk the CFG in depth first order, eliminating references to 86 // dead blocks. 87 // 88 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks, 89 const std::set<BasicBlock*> &AliveBlocks); 90 }; 91 92 } // End of anonymous namespace 93 94 Pass *createAgressiveDCEPass() { 95 return new ADCE(); 96 } 97 98 99 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning 100 // true if the function was modified. 101 // 102 void ADCE::doADCE(DominanceFrontier &CDG) { 103 #ifdef DEBUG_ADCE 104 cerr << "Function: " << Func; 105 #endif 106 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. 112 // 113 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func); 114 BBI != BBE; ++BBI) { 115 BasicBlock *BB = *BBI; 116 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) { 117 Instruction *I = *II; 118 119 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) { 120 markInstructionLive(I); 121 } else { 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); 126 MadeChanges = true; 127 continue; // Don't increment the iterator past the current slot 128 } 129 } 130 131 ++II; // Increment the inst iterator if the inst wasn't deleted 132 } 133 } 134 135 #ifdef DEBUG_ADCE 136 cerr << "Processing work list\n"; 137 #endif 138 139 // AliveBlocks - Set of basic blocks that we know have instructions that are 140 // alive in them... 141 // 142 std::set<BasicBlock*> AliveBlocks; 143 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. 147 // 148 while (!WorkList.empty()) { 149 Instruction *I = WorkList.back(); // Get an instruction that became live... 150 WorkList.pop_back(); 151 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... 156 // 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)); 164 } 165 166 // If this basic block is live, then the terminator must be as well! 167 markTerminatorLive(BB); 168 } 169 170 // Loop over all of the operands of the live instruction, making sure that 171 // they are known to be alive as well... 172 // 173 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) { 174 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op))) 175 markInstructionLive(Operand); 176 } 177 } 178 179 #ifdef DEBUG_ADCE 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(); 183 BI != BE; ++BI) { 184 if (LiveSet.count(*BI)) cerr << "X "; 185 cerr << *BI; 186 } 187 #endif 188 189 // After the worklist is processed, recursively walk the CFG in depth first 190 // order, patching up references to dead blocks... 191 // 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... 199 // 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)); 206 MadeChanges = true; 207 } 208 AliveBlocks.insert(E); 209 210 // Next we need to change any PHI nodes in the entry block to refer to the 211 // new predecessor node... 212 213 214 } else { 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 218 MadeChanges = true; 219 } 220 } 221 222 // Now go through and tell dead blocks to drop all of their references so they 223 // can be safely deleted. 224 // 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(); 229 } 230 } 231 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... 235 // 236 for (Function::iterator BI = Func->begin(); BI != Func->end();) { 237 if (!AliveBlocks.count(*BI)) { 238 delete Func->getBasicBlocks().remove(BI); 239 MadeChanges = true; 240 continue; // Don't increment iterator 241 } 242 ++BI; // Increment iterator... 243 } 244 } 245 246 247 // fixupCFG - Walk the CFG in depth first order, eliminating references to 248 // dead blocks: 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) 255 // 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. 262 // 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! 267 268 #ifdef DEBUG_ADCE 269 cerr << "Fixing up BB: " << BB; 270 #endif 271 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); 279 MadeChanges = true; 280 continue; // Don't increment II 281 } 282 ++II; 283 } 284 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); 291 MadeChanges = true; 292 } 293 } 294 return BB; 295 } else { // Otherwise the block is dead... 296 BasicBlock *ReturnBB = 0; // Default to nothing live down here 297 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); 301 if (RetBB) { 302 assert(ReturnBB == 0 && "One one live child allowed!"); 303 ReturnBB = RetBB; 304 } 305 } 306 return ReturnBB; // Return the result of traversal 307 } 308 } 309 310