blob: 4452b4061ceb09a438981cb853ef2acb20546156 [file] [log] [blame]
Chris Lattnerea54ab92002-05-07 22:11:39 +00001//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner02e90d52001-06-30 06:39:11 +00009//
Chris Lattnerea54ab92002-05-07 22:11:39 +000010// This file implements "aggressive" dead code elimination. ADCE is DCe where
Misha Brukmanfd939082005-04-21 23:48:37 +000011// values are assumed to be dead until proven otherwise. This is similar to
Chris Lattner02e90d52001-06-30 06:39:11 +000012// SCCP, except applied to the liveness of values.
13//
14//===----------------------------------------------------------------------===//
15
Chris Lattner022103b2002-05-07 20:03:00 +000016#include "llvm/Transforms/Scalar.h"
Chris Lattner387bc132004-12-12 23:40:17 +000017#include "llvm/Constants.h"
Chris Lattnerede6ac62004-04-10 06:53:09 +000018#include "llvm/Instructions.h"
Chris Lattnerede6ac62004-04-10 06:53:09 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Analysis/PostDominators.h"
Chris Lattner221d6882002-02-12 21:07:25 +000021#include "llvm/Support/CFG.h"
Chris Lattnerbd1a90e2003-12-19 09:08:34 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
24#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/STLExtras.h"
Chris Lattner72f1e992001-07-08 18:38:36 +000029#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000030#include <iostream>
Chris Lattnerbd1a90e2003-12-19 09:08:34 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner492d4a92005-10-24 01:40:23 +000033static IncludeFile X((void*)createUnifyFunctionExitNodesPass);
34
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000035namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000036 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
37 Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
Chris Lattnerede6ac62004-04-10 06:53:09 +000038 Statistic<> NumCallRemoved ("adce", "Number of calls and invokes removed");
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000039
Chris Lattner02e90d52001-06-30 06:39:11 +000040//===----------------------------------------------------------------------===//
41// ADCE Class
42//
Chris Lattnerea54ab92002-05-07 22:11:39 +000043// This class does all of the work of Aggressive Dead Code Elimination.
Chris Lattner02e90d52001-06-30 06:39:11 +000044// It's public interface consists of a constructor and a doADCE() method.
45//
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000046class ADCE : public FunctionPass {
47 Function *Func; // The function that we are working on
Chris Lattner697954c2002-01-20 22:54:45 +000048 std::vector<Instruction*> WorkList; // Instructions that just became live
49 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattner02e90d52001-06-30 06:39:11 +000050
51 //===--------------------------------------------------------------------===//
52 // The public interface for this class
53 //
54public:
Chris Lattnerd9036a12002-05-22 21:32:16 +000055 // Execute the Aggressive Dead Code Elimination Algorithm
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000056 //
Chris Lattner7e708292002-06-25 16:13:24 +000057 virtual bool runOnFunction(Function &F) {
58 Func = &F;
Chris Lattnerd9036a12002-05-22 21:32:16 +000059 bool Changed = doADCE();
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000060 assert(WorkList.empty());
61 LiveSet.clear();
Chris Lattnerd9036a12002-05-22 21:32:16 +000062 return Changed;
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000063 }
64 // getAnalysisUsage - We require post dominance frontiers (aka Control
65 // Dependence Graph)
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbd1a90e2003-12-19 09:08:34 +000067 // 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>();
Chris Lattnerede6ac62004-04-10 06:53:09 +000070 AU.addRequired<AliasAnalysis>();
Chris Lattner5f0eb8d2002-08-08 19:01:30 +000071 AU.addRequired<PostDominatorTree>();
72 AU.addRequired<PostDominanceFrontier>();
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000073 }
Chris Lattner02e90d52001-06-30 06:39:11 +000074
Chris Lattner02e90d52001-06-30 06:39:11 +000075
76 //===--------------------------------------------------------------------===//
77 // The implementation of this class
78 //
79private:
Chris Lattnerea54ab92002-05-07 22:11:39 +000080 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000081 // true if the function was modified.
82 //
Chris Lattnerd9036a12002-05-22 21:32:16 +000083 bool doADCE();
84
85 void markBlockAlive(BasicBlock *BB);
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000086
Chris Lattner446698b2002-07-30 00:22:34 +000087
Chris Lattner387bc132004-12-12 23:40:17 +000088 // deleteDeadInstructionsInLiveBlock - Loop over all of the instructions in
89 // the specified basic block, deleting ones that are dead according to
90 // LiveSet.
91 bool deleteDeadInstructionsInLiveBlock(BasicBlock *BB);
Chris Lattner446698b2002-07-30 00:22:34 +000092
Chris Lattner837e42c2003-06-24 23:02:45 +000093 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
94
Chris Lattner02e90d52001-06-30 06:39:11 +000095 inline void markInstructionLive(Instruction *I) {
Chris Lattner188839a2004-12-12 22:16:13 +000096 if (!LiveSet.insert(I).second) return;
Chris Lattner2fc12302004-07-15 01:50:47 +000097 DEBUG(std::cerr << "Insn Live: " << *I);
Chris Lattner02e90d52001-06-30 06:39:11 +000098 WorkList.push_back(I);
99 }
100
Chris Lattner72f1e992001-07-08 18:38:36 +0000101 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattner2fc12302004-07-15 01:50:47 +0000102 DEBUG(std::cerr << "Terminator Live: " << *BB->getTerminator());
Chris Lattner545a76c2003-09-10 20:38:14 +0000103 markInstructionLive(const_cast<TerminatorInst*>(BB->getTerminator()));
Chris Lattner72f1e992001-07-08 18:38:36 +0000104 }
Chris Lattner02e90d52001-06-30 06:39:11 +0000105};
106
Chris Lattnera6275cc2002-07-26 21:12:46 +0000107 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
Chris Lattnerdfe81ab2002-05-06 17:27:57 +0000108} // End of anonymous namespace
109
Chris Lattner4b501562004-09-20 04:43:15 +0000110FunctionPass *llvm::createAggressiveDCEPass() { return new ADCE(); }
Chris Lattnerd9036a12002-05-22 21:32:16 +0000111
Chris Lattnerd9036a12002-05-22 21:32:16 +0000112void ADCE::markBlockAlive(BasicBlock *BB) {
113 // Mark the basic block as being newly ALIVE... and mark all branches that
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000114 // this block is control dependent on as being alive also...
Chris Lattnerd9036a12002-05-22 21:32:16 +0000115 //
Chris Lattnerce6ef112002-07-26 18:40:14 +0000116 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
Chris Lattnerd9036a12002-05-22 21:32:16 +0000117
Chris Lattnerce6ef112002-07-26 18:40:14 +0000118 PostDominanceFrontier::const_iterator It = CDG.find(BB);
Chris Lattnerd9036a12002-05-22 21:32:16 +0000119 if (It != CDG.end()) {
Misha Brukmanef6a6a62003-08-21 22:14:26 +0000120 // Get the blocks that this node is control dependent on...
Chris Lattnerce6ef112002-07-26 18:40:14 +0000121 const PostDominanceFrontier::DomSetType &CDB = It->second;
Misha Brukmanfd939082005-04-21 23:48:37 +0000122 for (PostDominanceFrontier::DomSetType::const_iterator I =
Chris Lattnercfa2f8e2005-02-22 23:22:58 +0000123 CDB.begin(), E = CDB.end(); I != E; ++I)
124 markTerminatorLive(*I); // Mark all their terminators as live
Chris Lattnerd9036a12002-05-22 21:32:16 +0000125 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000126
Chris Lattner99c91e02003-06-24 21:49:45 +0000127 // 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);
Chris Lattnerdfe81ab2002-05-06 17:27:57 +0000132}
Chris Lattner02e90d52001-06-30 06:39:11 +0000133
Chris Lattner387bc132004-12-12 23:40:17 +0000134// deleteDeadInstructionsInLiveBlock - Loop over all of the instructions in the
135// specified basic block, deleting ones that are dead according to LiveSet.
136bool ADCE::deleteDeadInstructionsInLiveBlock(BasicBlock *BB) {
Chris Lattner446698b2002-07-30 00:22:34 +0000137 bool Changed = false;
Chris Lattner387bc132004-12-12 23:40:17 +0000138 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ) {
139 Instruction *I = II++;
Chris Lattner446698b2002-07-30 00:22:34 +0000140 if (!LiveSet.count(I)) { // Is this instruction alive?
Chris Lattner387bc132004-12-12 23:40:17 +0000141 if (!I->use_empty())
142 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner17177602004-04-10 07:02:02 +0000143
Chris Lattner387bc132004-12-12 23:40:17 +0000144 // Nope... remove the instruction from it's basic block...
145 if (isa<CallInst>(I))
146 ++NumCallRemoved;
147 else
Chris Lattner27c694b2004-04-10 07:27:48 +0000148 ++NumInstRemoved;
Chris Lattner387bc132004-12-12 23:40:17 +0000149 BB->getInstList().erase(I);
150 Changed = true;
Chris Lattner446698b2002-07-30 00:22:34 +0000151 }
Chris Lattner387bc132004-12-12 23:40:17 +0000152 }
Chris Lattner446698b2002-07-30 00:22:34 +0000153 return Changed;
154}
155
Chris Lattner02e90d52001-06-30 06:39:11 +0000156
Chris Lattner837e42c2003-06-24 23:02:45 +0000157/// convertToUnconditionalBranch - Transform this conditional terminator
158/// instruction into an unconditional branch because we don't care which of the
159/// successors it goes to. This eliminate a use of the condition as well.
160///
161TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
162 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
163 BasicBlock *BB = TI->getParent();
164
165 // Remove entries from PHI nodes to avoid confusing ourself later...
166 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
167 TI->getSuccessor(i)->removePredecessor(BB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Chris Lattner837e42c2003-06-24 23:02:45 +0000169 // Delete the old branch itself...
170 BB->getInstList().erase(TI);
171 return NB;
172}
173
174
Chris Lattnerea54ab92002-05-07 22:11:39 +0000175// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerf57b8452002-04-27 06:56:12 +0000176// true if the function was modified.
Chris Lattner02e90d52001-06-30 06:39:11 +0000177//
Chris Lattnerd9036a12002-05-22 21:32:16 +0000178bool ADCE::doADCE() {
179 bool MadeChanges = false;
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000180
Chris Lattnera5f41032004-04-10 18:06:21 +0000181 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
182
183
184 // Iterate over all invokes in the function, turning invokes into calls if
185 // they cannot throw.
186 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
187 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
188 if (Function *F = II->getCalledFunction())
189 if (AA.onlyReadsMemory(F)) {
190 // The function cannot unwind. Convert it to a call with a branch
191 // after it to the normal destination.
192 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
193 std::string Name = II->getName(); II->setName("");
Chris Lattnere4370262005-05-14 12:25:32 +0000194 CallInst *NewCall = new CallInst(F, Args, Name, II);
195 NewCall->setCallingConv(II->getCallingConv());
Chris Lattnera5f41032004-04-10 18:06:21 +0000196 II->replaceAllUsesWith(NewCall);
197 new BranchInst(II->getNormalDest(), II);
198
199 // Update PHI nodes in the unwind destination
200 II->getUnwindDest()->removePredecessor(BB);
201 BB->getInstList().erase(II);
202
203 if (NewCall->use_empty()) {
204 BB->getInstList().erase(NewCall);
205 ++NumCallRemoved;
206 }
207 }
208
Chris Lattnerf57b8452002-04-27 06:56:12 +0000209 // Iterate over all of the instructions in the function, eliminating trivially
Misha Brukmanfd939082005-04-21 23:48:37 +0000210 // dead instructions, and marking instructions live that are known to be
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000211 // needed. Perform the walk in depth first order so that we avoid marking any
212 // instructions live in basic blocks that are unreachable. These blocks will
213 // be eliminated later, along with the instructions inside.
214 //
Chris Lattnerb9110c62004-05-04 17:00:46 +0000215 std::set<BasicBlock*> ReachableBBs;
216 for (df_ext_iterator<BasicBlock*>
217 BBI = df_ext_begin(&Func->front(), ReachableBBs),
218 BBE = df_ext_end(&Func->front(), ReachableBBs); BBI != BBE; ++BBI) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000219 BasicBlock *BB = *BBI;
220 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Chris Lattnerede6ac62004-04-10 06:53:09 +0000221 Instruction *I = II++;
222 if (CallInst *CI = dyn_cast<CallInst>(I)) {
223 Function *F = CI->getCalledFunction();
Chris Lattnera5f41032004-04-10 18:06:21 +0000224 if (F && AA.onlyReadsMemory(F)) {
Chris Lattnerede6ac62004-04-10 06:53:09 +0000225 if (CI->use_empty()) {
226 BB->getInstList().erase(CI);
227 ++NumCallRemoved;
228 }
229 } else {
230 markInstructionLive(I);
231 }
Chris Lattnerede6ac62004-04-10 06:53:09 +0000232 } else if (I->mayWriteToMemory() || isa<ReturnInst>(I) ||
Chris Lattnerc7ff6c82004-10-17 23:45:06 +0000233 isa<UnwindInst>(I) || isa<UnreachableInst>(I)) {
234 // FIXME: Unreachable instructions should not be marked intrinsically
235 // live here.
Jeff Cohen9d809302005-04-23 21:38:35 +0000236 markInstructionLive(I);
Chris Lattnerede6ac62004-04-10 06:53:09 +0000237 } else if (isInstructionTriviallyDead(I)) {
Chris Lattnerea54ab92002-05-07 22:11:39 +0000238 // Remove the instruction from it's basic block...
Chris Lattnerede6ac62004-04-10 06:53:09 +0000239 BB->getInstList().erase(I);
Chris Lattnerd9036a12002-05-22 21:32:16 +0000240 ++NumInstRemoved;
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000241 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000242 }
243 }
244
Chris Lattner34e353e2003-06-16 12:10:45 +0000245 // Check to ensure we have an exit node for this CFG. If we don't, we won't
246 // have any post-dominance information, thus we cannot perform our
247 // transformations safely.
248 //
249 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
Chris Lattner02a3be02003-09-20 14:39:18 +0000250 if (DT[&Func->getEntryBlock()] == 0) {
Chris Lattner34e353e2003-06-16 12:10:45 +0000251 WorkList.clear();
252 return MadeChanges;
253 }
254
Chris Lattnerfaa45ce2003-11-16 21:39:27 +0000255 // Scan the function marking blocks without post-dominance information as
256 // live. Blocks without post-dominance information occur when there is an
257 // infinite loop in the program. Because the infinite loop could contain a
258 // function which unwinds, exits or has side-effects, we don't want to delete
259 // the infinite loop or those blocks leading up to it.
260 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner1a84bd32005-02-17 19:28:49 +0000261 if (DT[I] == 0 && ReachableBBs.count(I))
Chris Lattnerfaa45ce2003-11-16 21:39:27 +0000262 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI)
263 markInstructionLive((*PI)->getTerminator());
264
Chris Lattnerde579f12003-05-22 22:00:07 +0000265 DEBUG(std::cerr << "Processing work list\n");
Chris Lattner02e90d52001-06-30 06:39:11 +0000266
Chris Lattner72f1e992001-07-08 18:38:36 +0000267 // AliveBlocks - Set of basic blocks that we know have instructions that are
268 // alive in them...
269 //
Chris Lattner697954c2002-01-20 22:54:45 +0000270 std::set<BasicBlock*> AliveBlocks;
Chris Lattner72f1e992001-07-08 18:38:36 +0000271
Chris Lattner02e90d52001-06-30 06:39:11 +0000272 // Process the work list of instructions that just became live... if they
Misha Brukman5560c9d2003-08-18 14:43:39 +0000273 // became live, then that means that all of their operands are necessary as
Chris Lattner02e90d52001-06-30 06:39:11 +0000274 // well... make them live as well.
275 //
276 while (!WorkList.empty()) {
Chris Lattner72f1e992001-07-08 18:38:36 +0000277 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattner02e90d52001-06-30 06:39:11 +0000278 WorkList.pop_back();
279
Chris Lattner72f1e992001-07-08 18:38:36 +0000280 BasicBlock *BB = I->getParent();
Chris Lattnerb9110c62004-05-04 17:00:46 +0000281 if (!ReachableBBs.count(BB)) continue;
Chris Lattner4e51ccd2004-12-12 22:22:18 +0000282 if (AliveBlocks.insert(BB).second) // Basic block not alive yet.
Chris Lattnerd9036a12002-05-22 21:32:16 +0000283 markBlockAlive(BB); // Make it so now!
Chris Lattner72f1e992001-07-08 18:38:36 +0000284
Chris Lattnerd9036a12002-05-22 21:32:16 +0000285 // PHI nodes are a special case, because the incoming values are actually
286 // defined in the predecessor nodes of this block, meaning that the PHI
287 // makes the predecessors alive.
288 //
Chris Lattner1a84bd32005-02-17 19:28:49 +0000289 if (PHINode *PN = dyn_cast<PHINode>(I)) {
290 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
291 // If the incoming edge is clearly dead, it won't have control
292 // dependence information. Do not mark it live.
293 BasicBlock *PredBB = PN->getIncomingBlock(i);
294 if (ReachableBBs.count(PredBB)) {
295 // FIXME: This should mark the control dependent edge as live, not
296 // necessarily the predecessor itself!
297 if (AliveBlocks.insert(PredBB).second)
298 markBlockAlive(PN->getIncomingBlock(i)); // Block is newly ALIVE!
299 if (Instruction *Op = dyn_cast<Instruction>(PN->getIncomingValue(i)))
300 markInstructionLive(Op);
301 }
302 }
303 } else {
304 // Loop over all of the operands of the live instruction, making sure that
305 // they are known to be alive as well.
306 //
307 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
308 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
309 markInstructionLive(Operand);
310 }
Chris Lattner02e90d52001-06-30 06:39:11 +0000311 }
312
Chris Lattnerde579f12003-05-22 22:00:07 +0000313 DEBUG(
314 std::cerr << "Current Function: X = Live\n";
Chris Lattner34e353e2003-06-16 12:10:45 +0000315 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
316 std::cerr << I->getName() << ":\t"
317 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000318 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
Chris Lattnerde579f12003-05-22 22:00:07 +0000319 if (LiveSet.count(BI)) std::cerr << "X ";
320 std::cerr << *BI;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000321 }
Chris Lattner34e353e2003-06-16 12:10:45 +0000322 });
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000323
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000324 // All blocks being live is a common case, handle it specially.
Chris Lattner446698b2002-07-30 00:22:34 +0000325 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
Chris Lattner837e42c2003-06-24 23:02:45 +0000326 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
Chris Lattner387bc132004-12-12 23:40:17 +0000327 // Loop over all of the instructions in the function deleting instructions
328 // to drop their references.
329 deleteDeadInstructionsInLiveBlock(I);
Chris Lattner837e42c2003-06-24 23:02:45 +0000330
331 // Check to make sure the terminator instruction is live. If it isn't,
332 // this means that the condition that it branches on (we know it is not an
333 // unconditional branch), is not needed to make the decision of where to
334 // go to, because all outgoing edges go to the same place. We must remove
335 // the use of the condition (because it's probably dead), so we convert
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000336 // the terminator to an unconditional branch.
Chris Lattner837e42c2003-06-24 23:02:45 +0000337 //
338 TerminatorInst *TI = I->getTerminator();
339 if (!LiveSet.count(TI))
340 convertToUnconditionalBranch(TI);
341 }
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000342
343 return MadeChanges;
344 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000345
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000346
347 // If the entry node is dead, insert a new entry node to eliminate the entry
348 // node as a special case.
349 //
350 if (!AliveBlocks.count(&Func->front())) {
351 BasicBlock *NewEntry = new BasicBlock();
352 new BranchInst(&Func->front(), NewEntry);
353 Func->getBasicBlockList().push_front(NewEntry);
354 AliveBlocks.insert(NewEntry); // This block is always alive!
355 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
356 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000357
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000358 // Loop over all of the alive blocks in the function. If any successor
359 // blocks are not alive, we adjust the outgoing branches to branch to the
360 // first live postdominator of the live block, adjusting any PHI nodes in
361 // the block to reflect this.
362 //
363 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
364 if (AliveBlocks.count(I)) {
365 BasicBlock *BB = I;
366 TerminatorInst *TI = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000367
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000368 // If the terminator instruction is alive, but the block it is contained
369 // in IS alive, this means that this terminator is a conditional branch on
370 // a condition that doesn't matter. Make it an unconditional branch to
371 // ONE of the successors. This has the side effect of dropping a use of
372 // the conditional value, which may also be dead.
373 if (!LiveSet.count(TI))
374 TI = convertToUnconditionalBranch(TI);
Chris Lattner99c91e02003-06-24 21:49:45 +0000375
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000376 // Loop over all of the successors, looking for ones that are not alive.
377 // We cannot save the number of successors in the terminator instruction
Chris Lattner1a84bd32005-02-17 19:28:49 +0000378 // here because we may remove them if we don't have a postdominator.
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000379 //
380 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
381 if (!AliveBlocks.count(TI->getSuccessor(i))) {
382 // Scan up the postdominator tree, looking for the first
383 // postdominator that is alive, and the last postdominator that is
384 // dead...
385 //
386 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
Chris Lattner1a84bd32005-02-17 19:28:49 +0000387 PostDominatorTree::Node *NextNode = 0;
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000388
Chris Lattner1a84bd32005-02-17 19:28:49 +0000389 if (LastNode) {
390 NextNode = LastNode->getIDom();
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000391 while (!AliveBlocks.count(NextNode->getBlock())) {
392 LastNode = NextNode;
393 NextNode = NextNode->getIDom();
Chris Lattner1a84bd32005-02-17 19:28:49 +0000394 if (NextNode == 0) {
395 LastNode = 0;
396 break;
397 }
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000398 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000399 }
Chris Lattner1a84bd32005-02-17 19:28:49 +0000400
401 // There is a special case here... if there IS no post-dominator for
402 // the block we have nowhere to point our branch to. Instead, convert
403 // it to a return. This can only happen if the code branched into an
404 // infinite loop. Note that this may not be desirable, because we
405 // _are_ altering the behavior of the code. This is a well known
406 // drawback of ADCE, so in the future if we choose to revisit the
407 // decision, this is where it should be.
408 //
409 if (LastNode == 0) { // No postdominator!
410 if (!isa<InvokeInst>(TI)) {
411 // Call RemoveSuccessor to transmogrify the terminator instruction
412 // to not contain the outgoing branch, or to create a new
413 // terminator if the form fundamentally changes (i.e.,
414 // unconditional branch to return). Note that this will change a
415 // branch into an infinite loop into a return instruction!
416 //
417 RemoveSuccessor(TI, i);
Misha Brukmanfd939082005-04-21 23:48:37 +0000418
Chris Lattner1a84bd32005-02-17 19:28:49 +0000419 // RemoveSuccessor may replace TI... make sure we have a fresh
420 // pointer.
421 //
422 TI = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000423
Chris Lattner1a84bd32005-02-17 19:28:49 +0000424 // Rescan this successor...
425 --i;
426 } else {
427
428 }
429 } else {
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000430 // Get the basic blocks that we need...
431 BasicBlock *LastDead = LastNode->getBlock();
432 BasicBlock *NextAlive = NextNode->getBlock();
Chris Lattner011de072002-07-29 22:31:39 +0000433
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000434 // Make the conditional branch now go to the next alive block...
435 TI->getSuccessor(i)->removePredecessor(BB);
436 TI->setSuccessor(i, NextAlive);
Chris Lattner011de072002-07-29 22:31:39 +0000437
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000438 // If there are PHI nodes in NextAlive, we need to add entries to
439 // the PHI nodes for the new incoming edge. The incoming values
440 // should be identical to the incoming values for LastDead.
441 //
442 for (BasicBlock::iterator II = NextAlive->begin();
443 isa<PHINode>(II); ++II) {
444 PHINode *PN = cast<PHINode>(II);
445 if (LiveSet.count(PN)) { // Only modify live phi nodes
446 // Get the incoming value for LastDead...
447 int OldIdx = PN->getBasicBlockIndex(LastDead);
448 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
449 Value *InVal = PN->getIncomingValue(OldIdx);
Misha Brukmanfd939082005-04-21 23:48:37 +0000450
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000451 // Add an incoming value for BB now...
452 PN->addIncoming(InVal, BB);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000453 }
Chris Lattnerd9036a12002-05-22 21:32:16 +0000454 }
455 }
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000456 }
Chris Lattner55547272002-05-10 15:37:35 +0000457
Chris Lattner6b8efcd2004-12-12 23:49:37 +0000458 // Now loop over all of the instructions in the basic block, deleting
459 // dead instructions. This is so that the next sweep over the program
460 // can safely delete dead instructions without other dead instructions
461 // still referring to them.
462 //
463 deleteDeadInstructionsInLiveBlock(BB);
464 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000465
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000466 // Loop over all of the basic blocks in the function, dropping references of
467 // the dead basic blocks. We must do this after the previous step to avoid
468 // dropping references to PHIs which still have entries...
469 //
Chris Lattner387bc132004-12-12 23:40:17 +0000470 std::vector<BasicBlock*> DeadBlocks;
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000471 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
Chris Lattner387bc132004-12-12 23:40:17 +0000472 if (!AliveBlocks.count(BB)) {
473 // Remove PHI node entries for this block in live successor blocks.
474 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
475 if (!SI->empty() && isa<PHINode>(SI->front()) && AliveBlocks.count(*SI))
476 (*SI)->removePredecessor(BB);
477
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000478 BB->dropAllReferences();
Chris Lattner387bc132004-12-12 23:40:17 +0000479 MadeChanges = true;
480 DeadBlocks.push_back(BB);
481 }
482
483 NumBlockRemoved += DeadBlocks.size();
Chris Lattner55547272002-05-10 15:37:35 +0000484
Chris Lattner84369b32002-05-28 21:38:16 +0000485 // Now loop through all of the blocks and delete the dead ones. We can safely
486 // do this now because we know that there are no references to dead blocks
Chris Lattner387bc132004-12-12 23:40:17 +0000487 // (because they have dropped all of their references).
488 for (std::vector<BasicBlock*>::iterator I = DeadBlocks.begin(),
489 E = DeadBlocks.end(); I != E; ++I)
490 Func->getBasicBlockList().erase(*I);
Chris Lattner55547272002-05-10 15:37:35 +0000491
Chris Lattnerd9036a12002-05-22 21:32:16 +0000492 return MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +0000493}