1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===// 2 // 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. 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Transforms/Scalar.h" 10 #include "llvm/Transforms/Utils/Local.h" 11 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 12 #include "llvm/Type.h" 13 #include "llvm/Analysis/PostDominators.h" 14 #include "llvm/iTerminators.h" 15 #include "llvm/iPHINode.h" 16 #include "llvm/Constant.h" 17 #include "llvm/Support/CFG.h" 18 #include "Support/STLExtras.h" 19 #include "Support/DepthFirstIterator.h" 20 #include "Support/StatisticReporter.h" 21 #include <algorithm> 22 #include <iostream> 23 using std::cerr; 24 using std::vector; 25 26 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed"); 27 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed"); 28 29 namespace { 30 31 //===----------------------------------------------------------------------===// 32 // ADCE Class 33 // 34 // This class does all of the work of Aggressive Dead Code Elimination. 35 // It's public interface consists of a constructor and a doADCE() method. 36 // 37 class ADCE : public FunctionPass { 38 Function *Func; // The function that we are working on 39 std::vector<Instruction*> WorkList; // Instructions that just became live 40 std::set<Instruction*> LiveSet; // The set of live instructions 41 42 //===--------------------------------------------------------------------===// 43 // The public interface for this class 44 // 45 public: 46 // Execute the Aggressive Dead Code Elimination Algorithm 47 // 48 virtual bool runOnFunction(Function &F) { 49 Func = &F; 50 bool Changed = doADCE(); 51 assert(WorkList.empty()); 52 LiveSet.clear(); 53 return Changed; 54 } 55 // getAnalysisUsage - We require post dominance frontiers (aka Control 56 // Dependence Graph) 57 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 58 AU.addRequired<PostDominatorTree>(); 59 AU.addRequired<PostDominanceFrontier>(); 60 } 61 62 63 //===--------------------------------------------------------------------===// 64 // The implementation of this class 65 // 66 private: 67 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 68 // true if the function was modified. 69 // 70 bool doADCE(); 71 72 void markBlockAlive(BasicBlock *BB); 73 74 75 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the 76 // instructions in the specified basic block, dropping references on 77 // instructions that are dead according to LiveSet. 78 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB); 79 80 inline void markInstructionLive(Instruction *I) { 81 if (LiveSet.count(I)) return; 82 DEBUG(cerr << "Insn Live: " << I); 83 LiveSet.insert(I); 84 WorkList.push_back(I); 85 } 86 87 inline void markTerminatorLive(const BasicBlock *BB) { 88 DEBUG(cerr << "Terminat Live: " << BB->getTerminator()); 89 markInstructionLive((Instruction*)BB->getTerminator()); 90 } 91 }; 92 93 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination"); 94 } // End of anonymous namespace 95 96 Pass *createAggressiveDCEPass() { return new ADCE(); } 97 98 void ADCE::markBlockAlive(BasicBlock *BB) { 99 // Mark the basic block as being newly ALIVE... and mark all branches that 100 // this block is control dependant on as being alive also... 101 // 102 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>(); 103 104 PostDominanceFrontier::const_iterator It = CDG.find(BB); 105 if (It != CDG.end()) { 106 // Get the blocks that this node is control dependant on... 107 const PostDominanceFrontier::DomSetType &CDB = It->second; 108 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live 109 bind_obj(this, &ADCE::markTerminatorLive)); 110 } 111 112 // If this basic block is live, then the terminator must be as well! 113 markTerminatorLive(BB); 114 } 115 116 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the 117 // instructions in the specified basic block, dropping references on 118 // instructions that are dead according to LiveSet. 119 bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) { 120 bool Changed = false; 121 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ) 122 if (!LiveSet.count(I)) { // Is this instruction alive? 123 I->dropAllReferences(); // Nope, drop references... 124 if (PHINode *PN = dyn_cast<PHINode>(&*I)) { 125 // We don't want to leave PHI nodes in the program that have 126 // #arguments != #predecessors, so we remove them now. 127 // 128 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); 129 130 // Delete the instruction... 131 I = BB->getInstList().erase(I); 132 Changed = true; 133 } else { 134 ++I; 135 } 136 } else { 137 ++I; 138 } 139 return Changed; 140 } 141 142 143 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 144 // true if the function was modified. 145 // 146 bool ADCE::doADCE() { 147 bool MadeChanges = false; 148 149 // Iterate over all of the instructions in the function, eliminating trivially 150 // dead instructions, and marking instructions live that are known to be 151 // needed. Perform the walk in depth first order so that we avoid marking any 152 // instructions live in basic blocks that are unreachable. These blocks will 153 // be eliminated later, along with the instructions inside. 154 // 155 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func); 156 BBI != BBE; ++BBI) { 157 BasicBlock *BB = *BBI; 158 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) { 159 if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) { 160 markInstructionLive(II); 161 ++II; // Increment the inst iterator if the inst wasn't deleted 162 } else if (isInstructionTriviallyDead(II)) { 163 // Remove the instruction from it's basic block... 164 II = BB->getInstList().erase(II); 165 ++NumInstRemoved; 166 MadeChanges = true; 167 } else { 168 ++II; // Increment the inst iterator if the inst wasn't deleted 169 } 170 } 171 } 172 173 DEBUG(cerr << "Processing work list\n"); 174 175 // AliveBlocks - Set of basic blocks that we know have instructions that are 176 // alive in them... 177 // 178 std::set<BasicBlock*> AliveBlocks; 179 180 // Process the work list of instructions that just became live... if they 181 // became live, then that means that all of their operands are neccesary as 182 // well... make them live as well. 183 // 184 while (!WorkList.empty()) { 185 Instruction *I = WorkList.back(); // Get an instruction that became live... 186 WorkList.pop_back(); 187 188 BasicBlock *BB = I->getParent(); 189 if (!AliveBlocks.count(BB)) { // Basic block not alive yet... 190 AliveBlocks.insert(BB); // Block is now ALIVE! 191 markBlockAlive(BB); // Make it so now! 192 } 193 194 // PHI nodes are a special case, because the incoming values are actually 195 // defined in the predecessor nodes of this block, meaning that the PHI 196 // makes the predecessors alive. 197 // 198 if (PHINode *PN = dyn_cast<PHINode>(I)) 199 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) 200 if (!AliveBlocks.count(*PI)) { 201 AliveBlocks.insert(BB); // Block is now ALIVE! 202 markBlockAlive(*PI); 203 } 204 205 // Loop over all of the operands of the live instruction, making sure that 206 // they are known to be alive as well... 207 // 208 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) 209 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op))) 210 markInstructionLive(Operand); 211 } 212 213 if (DebugFlag) { 214 cerr << "Current Function: X = Live\n"; 215 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 216 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){ 217 if (LiveSet.count(BI)) cerr << "X "; 218 cerr << *BI; 219 } 220 } 221 222 // Find the first postdominator of the entry node that is alive. Make it the 223 // new entry node... 224 // 225 PostDominatorTree &DT = getAnalysis<PostDominatorTree>(); 226 227 228 if (AliveBlocks.size() == Func->size()) { // No dead blocks? 229 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 230 // Loop over all of the instructions in the function, telling dead 231 // instructions to drop their references. This is so that the next sweep 232 // over the program can safely delete dead instructions without other dead 233 // instructions still refering to them. 234 // 235 dropReferencesOfDeadInstructionsInLiveBlock(I); 236 237 } else { // If there are some blocks dead... 238 // If the entry node is dead, insert a new entry node to eliminate the entry 239 // node as a special case. 240 // 241 if (!AliveBlocks.count(&Func->front())) { 242 BasicBlock *NewEntry = new BasicBlock(); 243 new BranchInst(&Func->front(), NewEntry->end()); 244 Func->getBasicBlockList().push_front(NewEntry); 245 AliveBlocks.insert(NewEntry); // This block is always alive! 246 } 247 248 // Loop over all of the alive blocks in the function. If any successor 249 // blocks are not alive, we adjust the outgoing branches to branch to the 250 // first live postdominator of the live block, adjusting any PHI nodes in 251 // the block to reflect this. 252 // 253 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 254 if (AliveBlocks.count(I)) { 255 BasicBlock *BB = I; 256 TerminatorInst *TI = BB->getTerminator(); 257 258 // Loop over all of the successors, looking for ones that are not alive. 259 // We cannot save the number of successors in the terminator instruction 260 // here because we may remove them if we don't have a postdominator... 261 // 262 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i) 263 if (!AliveBlocks.count(TI->getSuccessor(i))) { 264 // Scan up the postdominator tree, looking for the first 265 // postdominator that is alive, and the last postdominator that is 266 // dead... 267 // 268 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)]; 269 270 // There is a special case here... if there IS no post-dominator for 271 // the block we have no owhere to point our branch to. Instead, 272 // convert it to a return. This can only happen if the code 273 // branched into an infinite loop. Note that this may not be 274 // desirable, because we _are_ altering the behavior of the code. 275 // This is a well known drawback of ADCE, so in the future if we 276 // choose to revisit the decision, this is where it should be. 277 // 278 if (LastNode == 0) { // No postdominator! 279 // Call RemoveSuccessor to transmogrify the terminator instruction 280 // to not contain the outgoing branch, or to create a new 281 // terminator if the form fundementally changes (ie unconditional 282 // branch to return). Note that this will change a branch into an 283 // infinite loop into a return instruction! 284 // 285 RemoveSuccessor(TI, i); 286 287 // RemoveSuccessor may replace TI... make sure we have a fresh 288 // pointer... and e variable. 289 // 290 TI = BB->getTerminator(); 291 292 // Rescan this successor... 293 --i; 294 } else { 295 PostDominatorTree::Node *NextNode = LastNode->getIDom(); 296 297 while (!AliveBlocks.count(NextNode->getNode())) { 298 LastNode = NextNode; 299 NextNode = NextNode->getIDom(); 300 } 301 302 // Get the basic blocks that we need... 303 BasicBlock *LastDead = LastNode->getNode(); 304 BasicBlock *NextAlive = NextNode->getNode(); 305 306 // Make the conditional branch now go to the next alive block... 307 TI->getSuccessor(i)->removePredecessor(BB); 308 TI->setSuccessor(i, NextAlive); 309 310 // If there are PHI nodes in NextAlive, we need to add entries to 311 // the PHI nodes for the new incoming edge. The incoming values 312 // should be identical to the incoming values for LastDead. 313 // 314 for (BasicBlock::iterator II = NextAlive->begin(); 315 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) { 316 // Get the incoming value for LastDead... 317 int OldIdx = PN->getBasicBlockIndex(LastDead); 318 assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!"); 319 Value *InVal = PN->getIncomingValue(OldIdx); 320 321 // Add an incoming value for BB now... 322 PN->addIncoming(InVal, BB); 323 } 324 } 325 } 326 327 // Now loop over all of the instructions in the basic block, telling 328 // dead instructions to drop their references. This is so that the next 329 // sweep over the program can safely delete dead instructions without 330 // other dead instructions still refering to them. 331 // 332 dropReferencesOfDeadInstructionsInLiveBlock(BB); 333 } 334 } 335 336 // Loop over all of the basic blocks in the function, dropping references of 337 // the dead basic blocks 338 // 339 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) { 340 if (!AliveBlocks.count(BB)) { 341 // Remove all outgoing edges from this basic block and convert the 342 // terminator into a return instruction. 343 vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB)); 344 345 if (!Succs.empty()) { 346 // Loop over all of the successors, removing this block from PHI node 347 // entries that might be in the block... 348 while (!Succs.empty()) { 349 Succs.back()->removePredecessor(BB); 350 Succs.pop_back(); 351 } 352 353 // Delete the old terminator instruction... 354 BB->getInstList().pop_back(); 355 const Type *RetTy = Func->getReturnType(); 356 new ReturnInst(RetTy != Type::VoidTy ? Constant::getNullValue(RetTy) :0, 357 BB->end()); 358 } 359 360 BB->dropAllReferences(); 361 ++NumBlockRemoved; 362 MadeChanges = true; 363 } 364 } 365 366 // Now loop through all of the blocks and delete the dead ones. We can safely 367 // do this now because we know that there are no references to dead blocks 368 // (because they have dropped all of their references... we also remove dead 369 // instructions from alive blocks. 370 // 371 for (Function::iterator BI = Func->begin(); BI != Func->end(); ) 372 if (!AliveBlocks.count(BI)) { // Delete dead blocks... 373 BI = Func->getBasicBlockList().erase(BI); 374 } else { // Scan alive blocks... 375 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); ) 376 if (!LiveSet.count(II)) { // Is this instruction alive? 377 // Nope... remove the instruction from it's basic block... 378 II = BI->getInstList().erase(II); 379 ++NumInstRemoved; 380 MadeChanges = true; 381 } else { 382 ++II; 383 } 384 385 ++BI; // Increment iterator... 386 } 387 388 return MadeChanges; 389 } 390