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/Constant.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/STLExtras.h"
19 #include "Support/DepthFirstIterator.h"
20 #include "Support/StatisticReporter.h"
25 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
26 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
30 //===----------------------------------------------------------------------===//
33 // This class does all of the work of Aggressive Dead Code Elimination.
34 // It's public interface consists of a constructor and a doADCE() method.
36 class ADCE : public FunctionPass {
37 Function *Func; // The function that we are working on
38 std::vector<Instruction*> WorkList; // Instructions that just became live
39 std::set<Instruction*> LiveSet; // The set of live instructions
41 //===--------------------------------------------------------------------===//
42 // The public interface for this class
45 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
47 // Execute the Aggressive Dead Code Elimination Algorithm
49 virtual bool runOnFunction(Function &F) {
51 bool Changed = doADCE();
52 assert(WorkList.empty());
56 // getAnalysisUsage - We require post dominance frontiers (aka Control
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired(DominatorTree::PostDomID);
60 AU.addRequired(DominanceFrontier::PostDomID);
64 //===--------------------------------------------------------------------===//
65 // The implementation of this class
68 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
69 // true if the function was modified.
73 void markBlockAlive(BasicBlock *BB);
75 inline void markInstructionLive(Instruction *I) {
76 if (LiveSet.count(I)) return;
77 DEBUG(cerr << "Insn Live: " << I);
79 WorkList.push_back(I);
82 inline void markTerminatorLive(const BasicBlock *BB) {
83 DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
84 markInstructionLive((Instruction*)BB->getTerminator());
88 } // End of anonymous namespace
90 Pass *createAggressiveDCEPass() { return new ADCE(); }
93 void ADCE::markBlockAlive(BasicBlock *BB) {
94 // Mark the basic block as being newly ALIVE... and mark all branches that
95 // this block is control dependant on as being alive also...
97 DominanceFrontier &CDG =
98 getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID);
100 DominanceFrontier::const_iterator It = CDG.find(BB);
101 if (It != CDG.end()) {
102 // Get the blocks that this node is control dependant on...
103 const DominanceFrontier::DomSetType &CDB = It->second;
104 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
105 bind_obj(this, &ADCE::markTerminatorLive));
108 // If this basic block is live, then the terminator must be as well!
109 markTerminatorLive(BB);
113 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
114 // true if the function was modified.
116 bool ADCE::doADCE() {
117 bool MadeChanges = false;
119 // Iterate over all of the instructions in the function, eliminating trivially
120 // dead instructions, and marking instructions live that are known to be
121 // needed. Perform the walk in depth first order so that we avoid marking any
122 // instructions live in basic blocks that are unreachable. These blocks will
123 // be eliminated later, along with the instructions inside.
125 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
127 BasicBlock *BB = *BBI;
128 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
129 if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
130 markInstructionLive(II);
131 ++II; // Increment the inst iterator if the inst wasn't deleted
132 } else if (isInstructionTriviallyDead(II)) {
133 // Remove the instruction from it's basic block...
134 II = BB->getInstList().erase(II);
138 ++II; // Increment the inst iterator if the inst wasn't deleted
143 DEBUG(cerr << "Processing work list\n");
145 // AliveBlocks - Set of basic blocks that we know have instructions that are
148 std::set<BasicBlock*> AliveBlocks;
150 // Process the work list of instructions that just became live... if they
151 // became live, then that means that all of their operands are neccesary as
152 // well... make them live as well.
154 while (!WorkList.empty()) {
155 Instruction *I = WorkList.back(); // Get an instruction that became live...
158 BasicBlock *BB = I->getParent();
159 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
160 AliveBlocks.insert(BB); // Block is now ALIVE!
161 markBlockAlive(BB); // Make it so now!
164 // PHI nodes are a special case, because the incoming values are actually
165 // defined in the predecessor nodes of this block, meaning that the PHI
166 // makes the predecessors alive.
168 if (PHINode *PN = dyn_cast<PHINode>(I))
169 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
170 if (!AliveBlocks.count(*PI)) {
171 AliveBlocks.insert(BB); // Block is now ALIVE!
175 // Loop over all of the operands of the live instruction, making sure that
176 // they are known to be alive as well...
178 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
179 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
180 markInstructionLive(Operand);
184 cerr << "Current Function: X = Live\n";
185 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
186 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
187 if (LiveSet.count(BI)) cerr << "X ";
192 // Find the first postdominator of the entry node that is alive. Make it the
195 DominatorTree &DT = getAnalysis<DominatorTree>(DominatorTree::PostDomID);
197 // If there are some blocks dead...
198 if (AliveBlocks.size() != Func->size()) {
199 // Insert a new entry node to eliminate the entry node as a special case.
200 BasicBlock *NewEntry = new BasicBlock();
201 NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
202 Func->getBasicBlockList().push_front(NewEntry);
203 AliveBlocks.insert(NewEntry); // This block is always alive!
205 // Loop over all of the alive blocks in the function. If any successor
206 // blocks are not alive, we adjust the outgoing branches to branch to the
207 // first live postdominator of the live block, adjusting any PHI nodes in
208 // the block to reflect this.
210 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
211 if (AliveBlocks.count(I)) {
213 TerminatorInst *TI = BB->getTerminator();
215 // Loop over all of the successors, looking for ones that are not alive
216 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
217 if (!AliveBlocks.count(TI->getSuccessor(i))) {
218 // Scan up the postdominator tree, looking for the first
219 // postdominator that is alive, and the last postdominator that is
222 DominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
223 DominatorTree::Node *NextNode = LastNode->getIDom();
224 while (!AliveBlocks.count(NextNode->getNode())) {
226 NextNode = NextNode->getIDom();
229 // Get the basic blocks that we need...
230 BasicBlock *LastDead = LastNode->getNode();
231 BasicBlock *NextAlive = NextNode->getNode();
233 // Make the conditional branch now go to the next alive block...
234 TI->getSuccessor(i)->removePredecessor(BB);
235 TI->setSuccessor(i, NextAlive);
237 // If there are PHI nodes in NextAlive, we need to add entries to
238 // the PHI nodes for the new incoming edge. The incoming values
239 // should be identical to the incoming values for LastDead.
241 for (BasicBlock::iterator II = NextAlive->begin();
242 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
243 // Get the incoming value for LastDead...
244 int OldIdx = PN->getBasicBlockIndex(LastDead);
245 assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
246 Value *InVal = PN->getIncomingValue(OldIdx);
248 // Add an incoming value for BB now...
249 PN->addIncoming(InVal, BB);
253 // Now loop over all of the instructions in the basic block, telling
254 // dead instructions to drop their references. This is so that the next
255 // sweep over the program can safely delete dead instructions without
256 // other dead instructions still refering to them.
258 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
259 if (!LiveSet.count(I)) // Is this instruction alive?
260 I->dropAllReferences(); // Nope, drop references...
264 // Loop over all of the basic blocks in the function, dropping references of
265 // the dead basic blocks
267 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
268 if (!AliveBlocks.count(BB)) {
269 // Remove all outgoing edges from this basic block and convert the
270 // terminator into a return instruction.
271 vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
273 if (!Succs.empty()) {
274 // Loop over all of the successors, removing this block from PHI node
275 // entries that might be in the block...
276 while (!Succs.empty()) {
277 Succs.back()->removePredecessor(BB);
281 // Delete the old terminator instruction...
282 BB->getInstList().pop_back();
283 const Type *RetTy = Func->getReturnType();
284 Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
285 Constant::getNullValue(RetTy) : 0);
286 BB->getInstList().push_back(New);
289 BB->dropAllReferences();
295 // Now loop through all of the blocks and delete the dead ones. We can safely
296 // do this now because we know that there are no references to dead blocks
297 // (because they have dropped all of their references... we also remove dead
298 // instructions from alive blocks.
300 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
301 if (!AliveBlocks.count(BI))
302 BI = Func->getBasicBlockList().erase(BI);
304 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
305 if (!LiveSet.count(II)) { // Is this instruction alive?
306 // Nope... remove the instruction from it's basic block...
307 II = BI->getInstList().erase(II);
314 ++BI; // Increment iterator...