llvm.org GIT mirror llvm / 038a874
Replace the old ADCE implementation with a new one that more simply solves the one case that ADCE catches that normal DCE doesn't: non-induction variable loop computations. This implementation handles this problem without using postdominators. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@51668 91177308-0d34-0410-b5e6-96231b3b80d8 Owen Anderson 11 years ago
3 changed file(s) with 66 addition(s) and 505 deletion(s). Raw diff Collapse all Expand all
None //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
0 //===- DCE.cpp - Code to perform dead code elimination --------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file implements "aggressive" dead code elimination. ADCE is DCe where
10 // values are assumed to be dead until proven otherwise. This is similar to
11 // SCCP, except applied to the liveness of values.
9 // This file implements the Aggressive Dead Code Elimination pass. This pass
10 // optimistically assumes that all instructions are dead until proven otherwise,
11 // allowing it to eliminate dead computations that other DCE passes do not
12 // catch, particularly involving loop computations.
1213 //
1314 //===----------------------------------------------------------------------===//
1415
1516 #define DEBUG_TYPE "adce"
1617 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
1818 #include "llvm/Instructions.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/PostDominators.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/InstIterator.h"
2822 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/Compiler.h"
31 #include
23 #include "llvm/ADT/SmallPtrSet.h"
24
3225 using namespace llvm;
3326
34 STATISTIC(NumBlockRemoved, "Number of basic blocks removed");
35 STATISTIC(NumInstRemoved , "Number of instructions removed");
36 STATISTIC(NumCallRemoved , "Number of calls removed");
27 STATISTIC(NumRemoved, "Number of instructions removed");
3728
3829 namespace {
39 //===----------------------------------------------------------------------===//
40 // ADCE Class
41 //
42 // This class does all of the work of Aggressive Dead Code Elimination.
43 // It's public interface consists of a constructor and a doADCE() method.
44 //
45 class VISIBILITY_HIDDEN ADCE : public FunctionPass {
46 Function *Func; // The function that we are working on
47 std::vector WorkList; // Instructions that just became live
48 std::set LiveSet; // The set of live instructions
49
50 //===--------------------------------------------------------------------===//
51 // The public interface for this class
52 //
53 public:
54 static char ID; // Pass identification, replacement for typeid
55 ADCE() : FunctionPass((intptr_t)&ID) {}
56
57 // Execute the Aggressive Dead Code Elimination Algorithm
58 //
59 virtual bool runOnFunction(Function &F) {
60 Func = &F;
61 bool Changed = doADCE();
62 assert(WorkList.empty());
63 LiveSet.clear();
64 return Changed;
65 }
66 // getAnalysisUsage - We require post dominance frontiers (aka Control
67 // Dependence Graph)
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 // We require that all function nodes are unified, because otherwise code
70 // can be marked live that wouldn't necessarily be otherwise.
71 AU.addRequired();
72 AU.addRequired();
73 AU.addRequired();
74 AU.addRequired();
75 }
76
77
78 //===--------------------------------------------------------------------===//
79 // The implementation of this class
80 //
81 private:
82 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
83 // true if the function was modified.
84 //
85 bool doADCE();
86
87 void markBlockAlive(BasicBlock *BB);
88
89
90 // deleteDeadInstructionsInLiveBlock - Loop over all of the instructions in
91 // the specified basic block, deleting ones that are dead according to
92 // LiveSet.
93 bool deleteDeadInstructionsInLiveBlock(BasicBlock *BB);
94
95 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
96
97 inline void markInstructionLive(Instruction *I) {
98 if (!LiveSet.insert(I).second) return;
99 DOUT << "Insn Live: " << *I;
100 WorkList.push_back(I);
101 }
102
103 inline void markTerminatorLive(const BasicBlock *BB) {
104 DOUT << "Terminator Live: " << *BB->getTerminator();
105 markInstructionLive(const_cast(BB->getTerminator()));
106 }
107 };
108 } // End of anonymous namespace
30 struct VISIBILITY_HIDDEN ADCE : public FunctionPass {
31 static char ID; // Pass identification, replacement for typeid
32 ADCE() : FunctionPass((intptr_t)&ID) {}
33
34 virtual bool runOnFunction(Function& F);
35
36 virtual void getAnalysisUsage(AnalysisUsage& AU) const {
37 AU.setPreservesCFG();
38 }
39
40 };
41 }
10942
11043 char ADCE::ID = 0;
11144 static RegisterPass X("adce", "Aggressive Dead Code Elimination");
11245
113 FunctionPass *llvm::createAggressiveDCEPass() { return new ADCE(); }
114
115 void ADCE::markBlockAlive(BasicBlock *BB) {
116 // Mark the basic block as being newly ALIVE... and mark all branches that
117 // this block is control dependent on as being alive also...
118 //
119 PostDominanceFrontier &CDG = getAnalysis();
120
121 PostDominanceFrontier::const_iterator It = CDG.find(BB);
122 if (It != CDG.end()) {
123 // Get the blocks that this node is control dependent on...
124 const PostDominanceFrontier::DomSetType &CDB = It->second;
125 for (PostDominanceFrontier::DomSetType::const_iterator I =
126 CDB.begin(), E = CDB.end(); I != E; ++I)
127 markTerminatorLive(*I); // Mark all their terminators as live
46 bool ADCE::runOnFunction(Function& F) {
47 SmallPtrSet alive;
48 std::vector worklist;
49
50 // Collect the set of "root" instructions that are known live.
51 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
52 if (isa(I.getInstructionIterator()) ||
53 I->mayWriteToMemory()) {
54 alive.insert(I.getInstructionIterator());
55 worklist.push_back(I.getInstructionIterator());
56 }
57
58 // Propagate liveness backwards to operands.
59 while (!worklist.empty()) {
60 Instruction* curr = worklist.back();
61 worklist.pop_back();
62
63 for (Instruction::op_iterator OI = curr->op_begin(), OE = curr->op_end();
64 OI != OE; ++OI)
65 if (Instruction* Inst = dyn_cast(OI))
66 if (alive.insert(Inst))
67 worklist.push_back(Inst);
12868 }
129
130 // If this basic block is live, and it ends in an unconditional branch, then
131 // the branch is alive as well...
132 if (BranchInst *BI = dyn_cast(BB->getTerminator()))
133 if (BI->isUnconditional())
134 markTerminatorLive(BB);
69
70 // The inverse of the live set is the dead set. These are those instructions
71 // which have no side effects and do not influence the control flow or return
72 // value of the function, and may therefore be deleted safely.
73 SmallPtrSet dead;
74 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
75 if (!alive.count(I.getInstructionIterator())) {
76 dead.insert(I.getInstructionIterator());
77 I->dropAllReferences();
78 }
79
80 for (SmallPtrSet::iterator I = dead.begin(),
81 E = dead.end(); I != E; ++I) {
82 NumRemoved++;
83 (*I)->eraseFromParent();
84 }
85
86 return !dead.empty();
13587 }
13688
137 // deleteDeadInstructionsInLiveBlock - Loop over all of the instructions in the
138 // specified basic block, deleting ones that are dead according to LiveSet.
139 bool ADCE::deleteDeadInstructionsInLiveBlock(BasicBlock *BB) {
140 bool Changed = false;
141 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ) {
142 Instruction *I = II++;
143 if (!LiveSet.count(I)) { // Is this instruction alive?
144 if (!I->use_empty())
145 I->replaceAllUsesWith(UndefValue::get(I->getType()));
146
147 // Nope... remove the instruction from it's basic block...
148 if (isa(I))
149 ++NumCallRemoved;
150 else
151 ++NumInstRemoved;
152 BB->getInstList().erase(I);
153 Changed = true;
154 }
155 }
156 return Changed;
157 }
158
159
160 /// convertToUnconditionalBranch - Transform this conditional terminator
161 /// instruction into an unconditional branch because we don't care which of the
162 /// successors it goes to. This eliminate a use of the condition as well.
163 ///
164 TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
165 BranchInst *NB = BranchInst::Create(TI->getSuccessor(0), TI);
166 BasicBlock *BB = TI->getParent();
167
168 // Remove entries from PHI nodes to avoid confusing ourself later...
169 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
170 TI->getSuccessor(i)->removePredecessor(BB);
171
172 // Delete the old branch itself...
173 BB->getInstList().erase(TI);
174 return NB;
175 }
176
177
178 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
179 // true if the function was modified.
180 //
181 bool ADCE::doADCE() {
182 bool MadeChanges = false;
183
184 AliasAnalysis &AA = getAnalysis();
185
186 // Iterate over all of the instructions in the function, eliminating trivially
187 // dead instructions, and marking instructions live that are known to be
188 // needed. Perform the walk in depth first order so that we avoid marking any
189 // instructions live in basic blocks that are unreachable. These blocks will
190 // be eliminated later, along with the instructions inside.
191 //
192 std::set ReachableBBs;
193 std::vector Stack;
194 Stack.push_back(&Func->getEntryBlock());
195
196 while (!Stack.empty()) {
197 BasicBlock* BB = Stack.back();
198 if (ReachableBBs.count(BB)) {
199 Stack.pop_back();
200 continue;
201 } else {
202 ReachableBBs.insert(BB);
203 }
204
205 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
206 Instruction *I = II++;
207 if (CallInst *CI = dyn_cast(I)) {
208 if (AA.onlyReadsMemory(CI)) {
209 if (CI->use_empty()) {
210 BB->getInstList().erase(CI);
211 ++NumCallRemoved;
212 }
213 } else {
214 markInstructionLive(I);
215 }
216 } else if (I->mayWriteToMemory() || isa(I) ||
217 isa(I) || isa(I)) {
218 // FIXME: Unreachable instructions should not be marked intrinsically
219 // live here.
220 markInstructionLive(I);
221 } else if (isInstructionTriviallyDead(I)) {
222 // Remove the instruction from it's basic block...
223 BB->getInstList().erase(I);
224 ++NumInstRemoved;
225 }
226 }
227
228 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
229 // Back edges (as opposed to cross edges) indicate loops, so implicitly
230 // mark them live.
231 if (std::find(Stack.begin(), Stack.end(), *SI) != Stack.end())
232 markInstructionLive(BB->getTerminator());
233 if (!ReachableBBs.count(*SI))
234 Stack.push_back(*SI);
235 }
236 }
237
238 // Check to ensure we have an exit node for this CFG. If we don't, we won't
239 // have any post-dominance information, thus we cannot perform our
240 // transformations safely.
241 //
242 PostDominatorTree &DT = getAnalysis();
243 if (DT[&Func->getEntryBlock()] == 0) {
244 WorkList.clear();
245 return MadeChanges;
246 }
247
248 // Scan the function marking blocks without post-dominance information as
249 // live. Blocks without post-dominance information occur when there is an
250 // infinite loop in the program. Because the infinite loop could contain a
251 // function which unwinds, exits or has side-effects, we don't want to delete
252 // the infinite loop or those blocks leading up to it.
253 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
254 if (DT[I] == 0 && ReachableBBs.count(I))
255 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI)
256 markInstructionLive((*PI)->getTerminator());
257
258 DOUT << "Processing work list\n";
259
260 // AliveBlocks - Set of basic blocks that we know have instructions that are
261 // alive in them...
262 //
263 std::set AliveBlocks;
264
265 // Process the work list of instructions that just became live... if they
266 // became live, then that means that all of their operands are necessary as
267 // well... make them live as well.
268 //
269 while (!WorkList.empty()) {
270 Instruction *I = WorkList.back(); // Get an instruction that became live...
271 WorkList.pop_back();
272
273 BasicBlock *BB = I->getParent();
274 if (!ReachableBBs.count(BB)) continue;
275 if (AliveBlocks.insert(BB).second) // Basic block not alive yet.
276 markBlockAlive(BB); // Make it so now!
277
278 // PHI nodes are a special case, because the incoming values are actually
279 // defined in the predecessor nodes of this block, meaning that the PHI
280 // makes the predecessors alive.
281 //
282 if (PHINode *PN = dyn_cast(I)) {
283 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
284 // If the incoming edge is clearly dead, it won't have control
285 // dependence information. Do not mark it live.
286 BasicBlock *PredBB = PN->getIncomingBlock(i);
287 if (ReachableBBs.count(PredBB)) {
288 // FIXME: This should mark the control dependent edge as live, not
289 // necessarily the predecessor itself!
290 if (AliveBlocks.insert(PredBB).second)
291 markBlockAlive(PN->getIncomingBlock(i)); // Block is newly ALIVE!
292 if (Instruction *Op = dyn_cast(PN->getIncomingValue(i)))
293 markInstructionLive(Op);
294 }
295 }
296 } else {
297 // Loop over all of the operands of the live instruction, making sure that
298 // they are known to be alive as well.
299 //
300 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
301 if (Instruction *Operand = dyn_cast(I->getOperand(op)))
302 markInstructionLive(Operand);
303 }
304 }
305
306 DEBUG(
307 DOUT << "Current Function: X = Live\n";
308 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
309 DOUT << I->getName() << ":\t"
310 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
311 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
312 if (LiveSet.count(BI)) DOUT << "X ";
313 DOUT << *BI;
314 }
315 });
316
317 // All blocks being live is a common case, handle it specially.
318 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
319 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
320 // Loop over all of the instructions in the function deleting instructions
321 // to drop their references.
322 deleteDeadInstructionsInLiveBlock(I);
323
324 // Check to make sure the terminator instruction is live. If it isn't,
325 // this means that the condition that it branches on (we know it is not an
326 // unconditional branch), is not needed to make the decision of where to
327 // go to, because all outgoing edges go to the same place. We must remove
328 // the use of the condition (because it's probably dead), so we convert
329 // the terminator to an unconditional branch.
330 //
331 TerminatorInst *TI = I->getTerminator();
332 if (!LiveSet.count(TI))
333 convertToUnconditionalBranch(TI);
334 }
335
336 return MadeChanges;
337 }
338
339
340 // If the entry node is dead, insert a new entry node to eliminate the entry
341 // node as a special case.
342 //
343 if (!AliveBlocks.count(&Func->front())) {
344 BasicBlock *NewEntry = BasicBlock::Create();
345 BranchInst::Create(&Func->front(), NewEntry);
346 Func->getBasicBlockList().push_front(NewEntry);
347 AliveBlocks.insert(NewEntry); // This block is always alive!
348 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
349 }
350
351 // Loop over all of the alive blocks in the function. If any successor
352 // blocks are not alive, we adjust the outgoing branches to branch to the
353 // first live postdominator of the live block, adjusting any PHI nodes in
354 // the block to reflect this.
355 //
356 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
357 if (AliveBlocks.count(I)) {
358 BasicBlock *BB = I;
359 TerminatorInst *TI = BB->getTerminator();
360
361 // If the terminator instruction is alive, but the block it is contained
362 // in IS alive, this means that this terminator is a conditional branch on
363 // a condition that doesn't matter. Make it an unconditional branch to
364 // ONE of the successors. This has the side effect of dropping a use of
365 // the conditional value, which may also be dead.
366 if (!LiveSet.count(TI))
367 TI = convertToUnconditionalBranch(TI);
368
369 // Loop over all of the successors, looking for ones that are not alive.
370 // We cannot save the number of successors in the terminator instruction
371 // here because we may remove them if we don't have a postdominator.
372 //
373 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
374 if (!AliveBlocks.count(TI->getSuccessor(i))) {
375 // Scan up the postdominator tree, looking for the first
376 // postdominator that is alive, and the last postdominator that is
377 // dead...
378 //
379 DomTreeNode *LastNode = DT[TI->getSuccessor(i)];
380 DomTreeNode *NextNode = 0;
381
382 if (LastNode) {
383 NextNode = LastNode->getIDom();
384 while (!AliveBlocks.count(NextNode->getBlock())) {
385 LastNode = NextNode;
386 NextNode = NextNode->getIDom();
387 if (NextNode == 0) {
388 LastNode = 0;
389 break;
390 }
391 }
392 }
393
394 // There is a special case here... if there IS no post-dominator for
395 // the block we have nowhere to point our branch to. Instead, convert
396 // it to a return. This can only happen if the code branched into an
397 // infinite loop. Note that this may not be desirable, because we
398 // _are_ altering the behavior of the code. This is a well known
399 // drawback of ADCE, so in the future if we choose to revisit the
400 // decision, this is where it should be.
401 //
402 if (LastNode == 0) { // No postdominator!
403 if (!isa(TI)) {
404 // Call RemoveSuccessor to transmogrify the terminator instruction
405 // to not contain the outgoing branch, or to create a new
406 // terminator if the form fundamentally changes (i.e.,
407 // unconditional branch to return). Note that this will change a
408 // branch into an infinite loop into a return instruction!
409 //
410 RemoveSuccessor(TI, i);
411
412 // RemoveSuccessor may replace TI... make sure we have a fresh
413 // pointer.
414 //
415 TI = BB->getTerminator();
416
417 // Rescan this successor...
418 --i;
419 } else {
420
421 }
422 } else {
423 // Get the basic blocks that we need...
424 BasicBlock *LastDead = LastNode->getBlock();
425 BasicBlock *NextAlive = NextNode->getBlock();
426
427 // Make the conditional branch now go to the next alive block...
428 TI->getSuccessor(i)->removePredecessor(BB);
429 TI->setSuccessor(i, NextAlive);
430
431 // If there are PHI nodes in NextAlive, we need to add entries to
432 // the PHI nodes for the new incoming edge. The incoming values
433 // should be identical to the incoming values for LastDead.
434 //
435 for (BasicBlock::iterator II = NextAlive->begin();
436 isa(II); ++II) {
437 PHINode *PN = cast(II);
438 if (LiveSet.count(PN)) { // Only modify live phi nodes
439 // Get the incoming value for LastDead...
440 int OldIdx = PN->getBasicBlockIndex(LastDead);
441 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
442 Value *InVal = PN->getIncomingValue(OldIdx);
443
444 // Add an incoming value for BB now...
445 PN->addIncoming(InVal, BB);
446 }
447 }
448 }
449 }
450
451 // Now loop over all of the instructions in the basic block, deleting
452 // dead instructions. This is so that the next sweep over the program
453 // can safely delete dead instructions without other dead instructions
454 // still referring to them.
455 //
456 deleteDeadInstructionsInLiveBlock(BB);
457 }
458
459 // Loop over all of the basic blocks in the function, dropping references of
460 // the dead basic blocks. We must do this after the previous step to avoid
461 // dropping references to PHIs which still have entries...
462 //
463 std::vector DeadBlocks;
464 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
465 if (!AliveBlocks.count(BB)) {
466 // Remove PHI node entries for this block in live successor blocks.
467 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
468 if (!SI->empty() && isa(SI->front()) && AliveBlocks.count(*SI))
469 (*SI)->removePredecessor(BB);
470
471 BB->dropAllReferences();
472 MadeChanges = true;
473 DeadBlocks.push_back(BB);
474 }
475
476 NumBlockRemoved += DeadBlocks.size();
477
478 // Now loop through all of the blocks and delete the dead ones. We can safely
479 // do this now because we know that there are no references to dead blocks
480 // (because they have dropped all of their references).
481 for (std::vector::iterator I = DeadBlocks.begin(),
482 E = DeadBlocks.end(); I != E; ++I)
483 Func->getBasicBlockList().erase(*I);
484
485 return MadeChanges;
486 }
89 FunctionPass *llvm::createAggressiveDCEPass() {
90 return new ADCE();
91 }
+0
-27
test/Transforms/ADCE/2003-12-19-MergeReturn.ll less more
None ; This testcase was failing because without merging the return blocks, ADCE
1 ; didn't know that it could get rid of the then.0 block.
2
3 ; RUN: llvm-as < %s | opt -adce | llvm-dis | not grep load
4
5
6 define void @main(i32 %argc, i8** %argv) {
7 entry:
8 call void @__main( )
9 %tmp.1 = icmp ule i32 %argc, 5 ; [#uses=1]
10 br i1 %tmp.1, label %then.0, label %return
11
12 then.0: ; preds = %entry
13 %tmp.8 = load i8** %argv ; [#uses=1]
14 %tmp.10 = load i8* %tmp.8 ; [#uses=1]
15 %tmp.11 = icmp eq i8 %tmp.10, 98 ; [#uses=1]
16 br i1 %tmp.11, label %then.1, label %return
17
18 then.1: ; preds = %then.0
19 ret void
20
21 return: ; preds = %then.0, %entry
22 ret void
23 }
24
25 declare void @__main()
26
+0
-17
test/Transforms/ADCE/dead-phi-edge.ll less more
None ; RUN: llvm-as < %s | opt -adce | llvm-dis | not grep call
1
2 ; The call is not live just because the PHI uses the call retval!
3
4 define i32 @test(i32 %X) {
5 ;
6 br label %Done
7
8 DeadBlock: ; No predecessors!
9 %Y = call i32 @test( i32 0 ) ; [#uses=1]
10 br label %Done
11
12 Done: ; preds = %DeadBlock, %0
13 %Z = phi i32 [ %X, %0 ], [ %Y, %DeadBlock ] ; [#uses=1]
14 ret i32 %Z
15 }
16