1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements "aggressive" dead code elimination. ADCE is DCe where
11 // values are assumed to be dead until proven otherwise. This is similar to
12 // SCCP, except applied to the liveness of values.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/PostDominators.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
26 #include "Support/Debug.h"
27 #include "Support/DepthFirstIterator.h"
28 #include "Support/Statistic.h"
29 #include "Support/STLExtras.h"
34 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
35 Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
36 Statistic<> NumCallRemoved ("adce", "Number of calls and invokes removed");
38 //===----------------------------------------------------------------------===//
41 // This class does all of the work of Aggressive Dead Code Elimination.
42 // It's public interface consists of a constructor and a doADCE() method.
44 class ADCE : public FunctionPass {
45 Function *Func; // The function that we are working on
46 AliasAnalysis *AA; // Current AliasAnalysis object
47 std::vector<Instruction*> WorkList; // Instructions that just became live
48 std::set<Instruction*> LiveSet; // The set of live instructions
50 //===--------------------------------------------------------------------===//
51 // The public interface for this class
54 // Execute the Aggressive Dead Code Elimination Algorithm
56 virtual bool runOnFunction(Function &F) {
58 AA = &getAnalysis<AliasAnalysis>();
59 bool Changed = doADCE();
60 assert(WorkList.empty());
64 // getAnalysisUsage - We require post dominance frontiers (aka Control
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 // We require that all function nodes are unified, because otherwise code
68 // can be marked live that wouldn't necessarily be otherwise.
69 AU.addRequired<UnifyFunctionExitNodes>();
70 AU.addRequired<AliasAnalysis>();
71 AU.addRequired<PostDominatorTree>();
72 AU.addRequired<PostDominanceFrontier>();
76 //===--------------------------------------------------------------------===//
77 // The implementation of this class
80 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
81 // true if the function was modified.
85 void markBlockAlive(BasicBlock *BB);
88 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
89 // instructions in the specified basic block, dropping references on
90 // instructions that are dead according to LiveSet.
91 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB);
93 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
95 inline void markInstructionLive(Instruction *I) {
96 if (LiveSet.count(I)) return;
97 DEBUG(std::cerr << "Insn Live: " << I);
99 WorkList.push_back(I);
102 inline void markTerminatorLive(const BasicBlock *BB) {
103 DEBUG(std::cerr << "Terminator Live: " << BB->getTerminator());
104 markInstructionLive(const_cast<TerminatorInst*>(BB->getTerminator()));
108 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
109 } // End of anonymous namespace
111 Pass *llvm::createAggressiveDCEPass() { return new ADCE(); }
113 void ADCE::markBlockAlive(BasicBlock *BB) {
114 // Mark the basic block as being newly ALIVE... and mark all branches that
115 // this block is control dependent on as being alive also...
117 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
119 PostDominanceFrontier::const_iterator It = CDG.find(BB);
120 if (It != CDG.end()) {
121 // Get the blocks that this node is control dependent on...
122 const PostDominanceFrontier::DomSetType &CDB = It->second;
123 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
124 bind_obj(this, &ADCE::markTerminatorLive));
127 // If this basic block is live, and it ends in an unconditional branch, then
128 // the branch is alive as well...
129 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
130 if (BI->isUnconditional())
131 markTerminatorLive(BB);
134 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
135 // instructions in the specified basic block, dropping references on
136 // instructions that are dead according to LiveSet.
137 bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) {
138 bool Changed = false;
139 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
140 if (!LiveSet.count(I)) { // Is this instruction alive?
141 I->dropAllReferences(); // Nope, drop references...
142 if (PHINode *PN = dyn_cast<PHINode>(I)) {
143 // We don't want to leave PHI nodes in the program that have
144 // #arguments != #predecessors, so we remove them now.
146 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
149 if (isa<CallInst>(I))
154 // Delete the instruction...
155 BB->getInstList().erase(I++);
165 /// convertToUnconditionalBranch - Transform this conditional terminator
166 /// instruction into an unconditional branch because we don't care which of the
167 /// successors it goes to. This eliminate a use of the condition as well.
169 TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
170 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
171 BasicBlock *BB = TI->getParent();
173 // Remove entries from PHI nodes to avoid confusing ourself later...
174 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
175 TI->getSuccessor(i)->removePredecessor(BB);
177 // Delete the old branch itself...
178 BB->getInstList().erase(TI);
183 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
184 // true if the function was modified.
186 bool ADCE::doADCE() {
187 bool MadeChanges = false;
189 // Iterate over all of the instructions in the function, eliminating trivially
190 // dead instructions, and marking instructions live that are known to be
191 // needed. Perform the walk in depth first order so that we avoid marking any
192 // instructions live in basic blocks that are unreachable. These blocks will
193 // be eliminated later, along with the instructions inside.
195 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
197 BasicBlock *BB = *BBI;
198 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
199 Instruction *I = II++;
200 if (CallInst *CI = dyn_cast<CallInst>(I)) {
201 Function *F = CI->getCalledFunction();
202 if (F && AA->onlyReadsMemory(F)) {
203 if (CI->use_empty()) {
204 BB->getInstList().erase(CI);
208 markInstructionLive(I);
210 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
211 Function *F = II->getCalledFunction();
212 if (F && AA->onlyReadsMemory(F)) {
213 // The function cannot unwind. Convert it to a call with a branch
214 // after it to the normal destination.
215 std::vector<Value*> Args(II->op_begin()+1, II->op_end());
216 std::string Name = II->getName(); II->setName("");
217 Instruction *NewCall = new CallInst(F, Args, Name, II);
218 II->replaceAllUsesWith(NewCall);
219 new BranchInst(II->getNormalDest(), II);
220 BB->getInstList().erase(II);
222 if (NewCall->use_empty()) {
223 BB->getInstList().erase(NewCall);
227 markInstructionLive(I);
229 } else if (I->mayWriteToMemory() || isa<ReturnInst>(I) ||
230 isa<UnwindInst>(I)) {
231 markInstructionLive(I);
232 } else if (isInstructionTriviallyDead(I)) {
233 // Remove the instruction from it's basic block...
234 BB->getInstList().erase(I);
240 // Check to ensure we have an exit node for this CFG. If we don't, we won't
241 // have any post-dominance information, thus we cannot perform our
242 // transformations safely.
244 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
245 if (DT[&Func->getEntryBlock()] == 0) {
250 // Scan the function marking blocks without post-dominance information as
251 // live. Blocks without post-dominance information occur when there is an
252 // infinite loop in the program. Because the infinite loop could contain a
253 // function which unwinds, exits or has side-effects, we don't want to delete
254 // the infinite loop or those blocks leading up to it.
255 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
257 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI)
258 markInstructionLive((*PI)->getTerminator());
262 DEBUG(std::cerr << "Processing work list\n");
264 // AliveBlocks - Set of basic blocks that we know have instructions that are
267 std::set<BasicBlock*> AliveBlocks;
269 // Process the work list of instructions that just became live... if they
270 // became live, then that means that all of their operands are necessary as
271 // well... make them live as well.
273 while (!WorkList.empty()) {
274 Instruction *I = WorkList.back(); // Get an instruction that became live...
277 BasicBlock *BB = I->getParent();
278 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
279 AliveBlocks.insert(BB); // Block is now ALIVE!
280 markBlockAlive(BB); // Make it so now!
283 // PHI nodes are a special case, because the incoming values are actually
284 // defined in the predecessor nodes of this block, meaning that the PHI
285 // makes the predecessors alive.
287 if (PHINode *PN = dyn_cast<PHINode>(I))
288 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
289 if (!AliveBlocks.count(*PI)) {
290 AliveBlocks.insert(BB); // Block is now ALIVE!
294 // Loop over all of the operands of the live instruction, making sure that
295 // they are known to be alive as well...
297 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
298 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
299 markInstructionLive(Operand);
303 std::cerr << "Current Function: X = Live\n";
304 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
305 std::cerr << I->getName() << ":\t"
306 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
307 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
308 if (LiveSet.count(BI)) std::cerr << "X ";
313 // Find the first postdominator of the entry node that is alive. Make it the
316 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
317 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
318 // Loop over all of the instructions in the function, telling dead
319 // instructions to drop their references. This is so that the next sweep
320 // over the program can safely delete dead instructions without other dead
321 // instructions still referring to them.
323 dropReferencesOfDeadInstructionsInLiveBlock(I);
325 // Check to make sure the terminator instruction is live. If it isn't,
326 // this means that the condition that it branches on (we know it is not an
327 // unconditional branch), is not needed to make the decision of where to
328 // go to, because all outgoing edges go to the same place. We must remove
329 // the use of the condition (because it's probably dead), so we convert
330 // the terminator to a conditional branch.
332 TerminatorInst *TI = I->getTerminator();
333 if (!LiveSet.count(TI))
334 convertToUnconditionalBranch(TI);
337 } else { // If there are some blocks dead...
338 // If the entry node is dead, insert a new entry node to eliminate the entry
339 // node as a special case.
341 if (!AliveBlocks.count(&Func->front())) {
342 BasicBlock *NewEntry = new BasicBlock();
343 new BranchInst(&Func->front(), NewEntry);
344 Func->getBasicBlockList().push_front(NewEntry);
345 AliveBlocks.insert(NewEntry); // This block is always alive!
346 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
349 // Loop over all of the alive blocks in the function. If any successor
350 // blocks are not alive, we adjust the outgoing branches to branch to the
351 // first live postdominator of the live block, adjusting any PHI nodes in
352 // the block to reflect this.
354 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
355 if (AliveBlocks.count(I)) {
357 TerminatorInst *TI = BB->getTerminator();
359 // If the terminator instruction is alive, but the block it is contained
360 // in IS alive, this means that this terminator is a conditional branch
361 // on a condition that doesn't matter. Make it an unconditional branch
362 // to ONE of the successors. This has the side effect of dropping a use
363 // of the conditional value, which may also be dead.
364 if (!LiveSet.count(TI))
365 TI = convertToUnconditionalBranch(TI);
367 // Loop over all of the successors, looking for ones that are not alive.
368 // We cannot save the number of successors in the terminator instruction
369 // here because we may remove them if we don't have a postdominator...
371 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
372 if (!AliveBlocks.count(TI->getSuccessor(i))) {
373 // Scan up the postdominator tree, looking for the first
374 // postdominator that is alive, and the last postdominator that is
377 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
379 // There is a special case here... if there IS no post-dominator for
380 // the block we have no owhere to point our branch to. Instead,
381 // convert it to a return. This can only happen if the code
382 // branched into an infinite loop. Note that this may not be
383 // desirable, because we _are_ altering the behavior of the code.
384 // This is a well known drawback of ADCE, so in the future if we
385 // choose to revisit the decision, this is where it should be.
387 if (LastNode == 0) { // No postdominator!
388 // Call RemoveSuccessor to transmogrify the terminator instruction
389 // to not contain the outgoing branch, or to create a new
390 // terminator if the form fundamentally changes (i.e.,
391 // unconditional branch to return). Note that this will change a
392 // branch into an infinite loop into a return instruction!
394 RemoveSuccessor(TI, i);
396 // RemoveSuccessor may replace TI... make sure we have a fresh
397 // pointer... and e variable.
399 TI = BB->getTerminator();
401 // Rescan this successor...
404 PostDominatorTree::Node *NextNode = LastNode->getIDom();
406 while (!AliveBlocks.count(NextNode->getBlock())) {
408 NextNode = NextNode->getIDom();
411 // Get the basic blocks that we need...
412 BasicBlock *LastDead = LastNode->getBlock();
413 BasicBlock *NextAlive = NextNode->getBlock();
415 // Make the conditional branch now go to the next alive block...
416 TI->getSuccessor(i)->removePredecessor(BB);
417 TI->setSuccessor(i, NextAlive);
419 // If there are PHI nodes in NextAlive, we need to add entries to
420 // the PHI nodes for the new incoming edge. The incoming values
421 // should be identical to the incoming values for LastDead.
423 for (BasicBlock::iterator II = NextAlive->begin();
424 PHINode *PN = dyn_cast<PHINode>(II); ++II)
425 if (LiveSet.count(PN)) { // Only modify live phi nodes
426 // Get the incoming value for LastDead...
427 int OldIdx = PN->getBasicBlockIndex(LastDead);
428 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
429 Value *InVal = PN->getIncomingValue(OldIdx);
431 // Add an incoming value for BB now...
432 PN->addIncoming(InVal, BB);
437 // Now loop over all of the instructions in the basic block, telling
438 // dead instructions to drop their references. This is so that the next
439 // sweep over the program can safely delete dead instructions without
440 // other dead instructions still referring to them.
442 dropReferencesOfDeadInstructionsInLiveBlock(BB);
446 // We make changes if there are any dead blocks in the function...
447 if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) {
449 NumBlockRemoved += NumDeadBlocks;
452 // Loop over all of the basic blocks in the function, removing control flow
453 // edges to live blocks (also eliminating any entries in PHI functions in
454 // referenced blocks).
456 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
457 if (!AliveBlocks.count(BB)) {
458 // Remove all outgoing edges from this basic block and convert the
459 // terminator into a return instruction.
460 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
462 if (!Succs.empty()) {
463 // Loop over all of the successors, removing this block from PHI node
464 // entries that might be in the block...
465 while (!Succs.empty()) {
466 Succs.back()->removePredecessor(BB);
470 // Delete the old terminator instruction...
471 const Type *TermTy = BB->getTerminator()->getType();
472 if (TermTy != Type::VoidTy)
473 BB->getTerminator()->replaceAllUsesWith(
474 Constant::getNullValue(TermTy));
475 BB->getInstList().pop_back();
476 const Type *RetTy = Func->getReturnType();
477 new ReturnInst(RetTy != Type::VoidTy ?
478 Constant::getNullValue(RetTy) : 0, BB);
483 // Loop over all of the basic blocks in the function, dropping references of
484 // the dead basic blocks. We must do this after the previous step to avoid
485 // dropping references to PHIs which still have entries...
487 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
488 if (!AliveBlocks.count(BB))
489 BB->dropAllReferences();
491 // Now loop through all of the blocks and delete the dead ones. We can safely
492 // do this now because we know that there are no references to dead blocks
493 // (because they have dropped all of their references... we also remove dead
494 // instructions from alive blocks.
496 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
497 if (!AliveBlocks.count(BI)) { // Delete dead blocks...
498 BI = Func->getBasicBlockList().erase(BI);
499 } else { // Scan alive blocks...
500 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
501 if (!LiveSet.count(II)) { // Is this instruction alive?
502 // Nope... remove the instruction from it's basic block...
503 if (isa<CallInst>(II))
507 II = BI->getInstList().erase(II);
513 ++BI; // Increment iterator...