xref: /llvm-project/llvm/lib/Transforms/Scalar/ADCE.cpp (revision db7d8678bcdc440ffd0529f0d970cf10cbcbe984)
1 //===- ADCE.cpp - Code to perform dead code elimination -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Scalar/ADCE.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/DomTreeUpdater.h"
27 #include "llvm/Analysis/GlobalsModRef.h"
28 #include "llvm/Analysis/IteratedDominanceFrontier.h"
29 #include "llvm/Analysis/MemorySSA.h"
30 #include "llvm/Analysis/PostDominators.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/InstIterator.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/PassManager.h"
44 #include "llvm/IR/Use.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Pass.h"
48 #include "llvm/ProfileData/InstrProf.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Transforms/Scalar.h"
54 #include "llvm/Transforms/Utils/Local.h"
55 #include <cassert>
56 #include <cstddef>
57 #include <utility>
58 
59 using namespace llvm;
60 
61 #define DEBUG_TYPE "adce"
62 
63 STATISTIC(NumRemoved, "Number of instructions removed");
64 STATISTIC(NumBranchesRemoved, "Number of branch instructions removed");
65 
66 // This is a temporary option until we change the interface to this pass based
67 // on optimization level.
68 static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow",
69                                            cl::init(true), cl::Hidden);
70 
71 // This option enables removing of may-be-infinite loops which have no other
72 // effect.
73 static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false),
74                                  cl::Hidden);
75 
76 namespace {
77 
78 /// Information about Instructions
79 struct InstInfoType {
80   /// True if the associated instruction is live.
81   bool Live = false;
82 
83   /// Quick access to information for block containing associated Instruction.
84   struct BlockInfoType *Block = nullptr;
85 };
86 
87 /// Information about basic blocks relevant to dead code elimination.
88 struct BlockInfoType {
89   /// True when this block contains a live instructions.
90   bool Live = false;
91 
92   /// True when this block ends in an unconditional branch.
93   bool UnconditionalBranch = false;
94 
95   /// True when this block is known to have live PHI nodes.
96   bool HasLivePhiNodes = false;
97 
98   /// Control dependence sources need to be live for this block.
99   bool CFLive = false;
100 
101   /// Quick access to the LiveInfo for the terminator,
102   /// holds the value &InstInfo[Terminator]
103   InstInfoType *TerminatorLiveInfo = nullptr;
104 
105   /// Corresponding BasicBlock.
106   BasicBlock *BB = nullptr;
107 
108   /// Cache of BB->getTerminator().
109   Instruction *Terminator = nullptr;
110 
111   /// Post-order numbering of reverse control flow graph.
112   unsigned PostOrder;
113 
114   bool terminatorIsLive() const { return TerminatorLiveInfo->Live; }
115 };
116 
117 struct ADCEChanged {
118   bool ChangedAnything = false;
119   bool ChangedNonDebugInstr = false;
120   bool ChangedControlFlow = false;
121 };
122 
123 class AggressiveDeadCodeElimination {
124   Function &F;
125 
126   // ADCE does not use DominatorTree per se, but it updates it to preserve the
127   // analysis.
128   DominatorTree *DT;
129   PostDominatorTree &PDT;
130 
131   /// Mapping of blocks to associated information, an element in BlockInfoVec.
132   /// Use MapVector to get deterministic iteration order.
133   MapVector<BasicBlock *, BlockInfoType> BlockInfo;
134   bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; }
135 
136   /// Mapping of instructions to associated information.
137   DenseMap<Instruction *, InstInfoType> InstInfo;
138   bool isLive(Instruction *I) { return InstInfo[I].Live; }
139 
140   /// Instructions known to be live where we need to mark
141   /// reaching definitions as live.
142   SmallVector<Instruction *, 128> Worklist;
143 
144   /// Debug info scopes around a live instruction.
145   SmallPtrSet<const Metadata *, 32> AliveScopes;
146 
147   /// Set of blocks with not known to have live terminators.
148   SmallSetVector<BasicBlock *, 16> BlocksWithDeadTerminators;
149 
150   /// The set of blocks which we have determined whose control
151   /// dependence sources must be live and which have not had
152   /// those dependences analyzed.
153   SmallPtrSet<BasicBlock *, 16> NewLiveBlocks;
154 
155   /// Set up auxiliary data structures for Instructions and BasicBlocks and
156   /// initialize the Worklist to the set of must-be-live Instruscions.
157   void initialize();
158 
159   /// Return true for operations which are always treated as live.
160   bool isAlwaysLive(Instruction &I);
161 
162   /// Return true for instrumentation instructions for value profiling.
163   bool isInstrumentsConstant(Instruction &I);
164 
165   /// Propagate liveness to reaching definitions.
166   void markLiveInstructions();
167 
168   /// Mark an instruction as live.
169   void markLive(Instruction *I);
170 
171   /// Mark a block as live.
172   void markLive(BlockInfoType &BB);
173   void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); }
174 
175   /// Mark terminators of control predecessors of a PHI node live.
176   void markPhiLive(PHINode *PN);
177 
178   /// Record the Debug Scopes which surround live debug information.
179   void collectLiveScopes(const DILocalScope &LS);
180   void collectLiveScopes(const DILocation &DL);
181 
182   /// Analyze dead branches to find those whose branches are the sources
183   /// of control dependences impacting a live block. Those branches are
184   /// marked live.
185   void markLiveBranchesFromControlDependences();
186 
187   /// Remove instructions not marked live, return if any instruction was
188   /// removed.
189   ADCEChanged removeDeadInstructions();
190 
191   /// Identify connected sections of the control flow graph which have
192   /// dead terminators and rewrite the control flow graph to remove them.
193   bool updateDeadRegions();
194 
195   /// Set the BlockInfo::PostOrder field based on a post-order
196   /// numbering of the reverse control flow graph.
197   void computeReversePostOrder();
198 
199   /// Make the terminator of this block an unconditional branch to \p Target.
200   void makeUnconditional(BasicBlock *BB, BasicBlock *Target);
201 
202 public:
203   AggressiveDeadCodeElimination(Function &F, DominatorTree *DT,
204                                 PostDominatorTree &PDT)
205       : F(F), DT(DT), PDT(PDT) {}
206 
207   ADCEChanged performDeadCodeElimination();
208 };
209 
210 } // end anonymous namespace
211 
212 ADCEChanged AggressiveDeadCodeElimination::performDeadCodeElimination() {
213   initialize();
214   markLiveInstructions();
215   return removeDeadInstructions();
216 }
217 
218 static bool isUnconditionalBranch(Instruction *Term) {
219   auto *BR = dyn_cast<BranchInst>(Term);
220   return BR && BR->isUnconditional();
221 }
222 
223 void AggressiveDeadCodeElimination::initialize() {
224   auto NumBlocks = F.size();
225 
226   // We will have an entry in the map for each block so we grow the
227   // structure to twice that size to keep the load factor low in the hash table.
228   BlockInfo.reserve(NumBlocks);
229   size_t NumInsts = 0;
230 
231   // Iterate over blocks and initialize BlockInfoVec entries, count
232   // instructions to size the InstInfo hash table.
233   for (auto &BB : F) {
234     NumInsts += BB.size();
235     auto &Info = BlockInfo[&BB];
236     Info.BB = &BB;
237     Info.Terminator = BB.getTerminator();
238     Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator);
239   }
240 
241   // Initialize instruction map and set pointers to block info.
242   InstInfo.reserve(NumInsts);
243   for (auto &BBInfo : BlockInfo)
244     for (Instruction &I : *BBInfo.second.BB)
245       InstInfo[&I].Block = &BBInfo.second;
246 
247   // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not
248   // add any more elements to either after this point.
249   for (auto &BBInfo : BlockInfo)
250     BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator];
251 
252   // Collect the set of "root" instructions that are known live.
253   for (Instruction &I : instructions(F))
254     if (isAlwaysLive(I))
255       markLive(&I);
256 
257   if (!RemoveControlFlowFlag)
258     return;
259 
260   if (!RemoveLoops) {
261     // This stores state for the depth-first iterator. In addition
262     // to recording which nodes have been visited we also record whether
263     // a node is currently on the "stack" of active ancestors of the current
264     // node.
265     using StatusMap = DenseMap<BasicBlock *, bool>;
266 
267     class DFState : public StatusMap {
268     public:
269       std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) {
270         return StatusMap::insert(std::make_pair(BB, true));
271       }
272 
273       // Invoked after we have visited all children of a node.
274       void completed(BasicBlock *BB) { (*this)[BB] = false; }
275 
276       // Return true if \p BB is currently on the active stack
277       // of ancestors.
278       bool onStack(BasicBlock *BB) {
279         auto Iter = find(BB);
280         return Iter != end() && Iter->second;
281       }
282     } State;
283 
284     State.reserve(F.size());
285     // Iterate over blocks in depth-first pre-order and
286     // treat all edges to a block already seen as loop back edges
287     // and mark the branch live it if there is a back edge.
288     for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) {
289       Instruction *Term = BB->getTerminator();
290       if (isLive(Term))
291         continue;
292 
293       for (auto *Succ : successors(BB))
294         if (State.onStack(Succ)) {
295           // back edge....
296           markLive(Term);
297           break;
298         }
299     }
300   }
301 
302   // Mark blocks live if there is no path from the block to a
303   // return of the function.
304   // We do this by seeing which of the postdomtree root children exit the
305   // program, and for all others, mark the subtree live.
306   for (const auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) {
307     auto *BB = PDTChild->getBlock();
308     auto &Info = BlockInfo[BB];
309     // Real function return
310     if (isa<ReturnInst>(Info.Terminator)) {
311       LLVM_DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName()
312                         << '\n';);
313       continue;
314     }
315 
316     // This child is something else, like an infinite loop.
317     for (auto *DFNode : depth_first(PDTChild))
318       markLive(BlockInfo[DFNode->getBlock()].Terminator);
319   }
320 
321   // Treat the entry block as always live
322   auto *BB = &F.getEntryBlock();
323   auto &EntryInfo = BlockInfo[BB];
324   EntryInfo.Live = true;
325   if (EntryInfo.UnconditionalBranch)
326     markLive(EntryInfo.Terminator);
327 
328   // Build initial collection of blocks with dead terminators
329   for (auto &BBInfo : BlockInfo)
330     if (!BBInfo.second.terminatorIsLive())
331       BlocksWithDeadTerminators.insert(BBInfo.second.BB);
332 }
333 
334 bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) {
335   // TODO -- use llvm::isInstructionTriviallyDead
336   if (I.isEHPad() || I.mayHaveSideEffects()) {
337     // Skip any value profile instrumentation calls if they are
338     // instrumenting constants.
339     if (isInstrumentsConstant(I))
340       return false;
341     return true;
342   }
343   if (!I.isTerminator())
344     return false;
345   if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I)))
346     return false;
347   return true;
348 }
349 
350 // Check if this instruction is a runtime call for value profiling and
351 // if it's instrumenting a constant.
352 bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) {
353   // TODO -- move this test into llvm::isInstructionTriviallyDead
354   if (CallInst *CI = dyn_cast<CallInst>(&I))
355     if (Function *Callee = CI->getCalledFunction())
356       if (Callee->getName().equals(getInstrProfValueProfFuncName()))
357         if (isa<Constant>(CI->getArgOperand(0)))
358           return true;
359   return false;
360 }
361 
362 void AggressiveDeadCodeElimination::markLiveInstructions() {
363   // Propagate liveness backwards to operands.
364   do {
365     // Worklist holds newly discovered live instructions
366     // where we need to mark the inputs as live.
367     while (!Worklist.empty()) {
368       Instruction *LiveInst = Worklist.pop_back_val();
369       LLVM_DEBUG(dbgs() << "work live: "; LiveInst->dump(););
370 
371       for (Use &OI : LiveInst->operands())
372         if (Instruction *Inst = dyn_cast<Instruction>(OI))
373           markLive(Inst);
374 
375       if (auto *PN = dyn_cast<PHINode>(LiveInst))
376         markPhiLive(PN);
377     }
378 
379     // After data flow liveness has been identified, examine which branch
380     // decisions are required to determine live instructions are executed.
381     markLiveBranchesFromControlDependences();
382 
383   } while (!Worklist.empty());
384 }
385 
386 void AggressiveDeadCodeElimination::markLive(Instruction *I) {
387   auto &Info = InstInfo[I];
388   if (Info.Live)
389     return;
390 
391   LLVM_DEBUG(dbgs() << "mark live: "; I->dump());
392   Info.Live = true;
393   Worklist.push_back(I);
394 
395   // Collect the live debug info scopes attached to this instruction.
396   if (const DILocation *DL = I->getDebugLoc())
397     collectLiveScopes(*DL);
398 
399   // Mark the containing block live
400   auto &BBInfo = *Info.Block;
401   if (BBInfo.Terminator == I) {
402     BlocksWithDeadTerminators.remove(BBInfo.BB);
403     // For live terminators, mark destination blocks
404     // live to preserve this control flow edges.
405     if (!BBInfo.UnconditionalBranch)
406       for (auto *BB : successors(I->getParent()))
407         markLive(BB);
408   }
409   markLive(BBInfo);
410 }
411 
412 void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) {
413   if (BBInfo.Live)
414     return;
415   LLVM_DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n');
416   BBInfo.Live = true;
417   if (!BBInfo.CFLive) {
418     BBInfo.CFLive = true;
419     NewLiveBlocks.insert(BBInfo.BB);
420   }
421 
422   // Mark unconditional branches at the end of live
423   // blocks as live since there is no work to do for them later
424   if (BBInfo.UnconditionalBranch)
425     markLive(BBInfo.Terminator);
426 }
427 
428 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) {
429   if (!AliveScopes.insert(&LS).second)
430     return;
431 
432   if (isa<DISubprogram>(LS))
433     return;
434 
435   // Tail-recurse through the scope chain.
436   collectLiveScopes(cast<DILocalScope>(*LS.getScope()));
437 }
438 
439 void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) {
440   // Even though DILocations are not scopes, shove them into AliveScopes so we
441   // don't revisit them.
442   if (!AliveScopes.insert(&DL).second)
443     return;
444 
445   // Collect live scopes from the scope chain.
446   collectLiveScopes(*DL.getScope());
447 
448   // Tail-recurse through the inlined-at chain.
449   if (const DILocation *IA = DL.getInlinedAt())
450     collectLiveScopes(*IA);
451 }
452 
453 void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) {
454   auto &Info = BlockInfo[PN->getParent()];
455   // Only need to check this once per block.
456   if (Info.HasLivePhiNodes)
457     return;
458   Info.HasLivePhiNodes = true;
459 
460   // If a predecessor block is not live, mark it as control-flow live
461   // which will trigger marking live branches upon which
462   // that block is control dependent.
463   for (auto *PredBB : predecessors(Info.BB)) {
464     auto &Info = BlockInfo[PredBB];
465     if (!Info.CFLive) {
466       Info.CFLive = true;
467       NewLiveBlocks.insert(PredBB);
468     }
469   }
470 }
471 
472 void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() {
473   if (BlocksWithDeadTerminators.empty())
474     return;
475 
476   LLVM_DEBUG({
477     dbgs() << "new live blocks:\n";
478     for (auto *BB : NewLiveBlocks)
479       dbgs() << "\t" << BB->getName() << '\n';
480     dbgs() << "dead terminator blocks:\n";
481     for (auto *BB : BlocksWithDeadTerminators)
482       dbgs() << "\t" << BB->getName() << '\n';
483   });
484 
485   // The dominance frontier of a live block X in the reverse
486   // control graph is the set of blocks upon which X is control
487   // dependent. The following sequence computes the set of blocks
488   // which currently have dead terminators that are control
489   // dependence sources of a block which is in NewLiveBlocks.
490 
491   const SmallPtrSet<BasicBlock *, 16> BWDT{
492       BlocksWithDeadTerminators.begin(),
493       BlocksWithDeadTerminators.end()
494   };
495   SmallVector<BasicBlock *, 32> IDFBlocks;
496   ReverseIDFCalculator IDFs(PDT);
497   IDFs.setDefiningBlocks(NewLiveBlocks);
498   IDFs.setLiveInBlocks(BWDT);
499   IDFs.calculate(IDFBlocks);
500   NewLiveBlocks.clear();
501 
502   // Dead terminators which control live blocks are now marked live.
503   for (auto *BB : IDFBlocks) {
504     LLVM_DEBUG(dbgs() << "live control in: " << BB->getName() << '\n');
505     markLive(BB->getTerminator());
506   }
507 }
508 
509 //===----------------------------------------------------------------------===//
510 //
511 //  Routines to update the CFG and SSA information before removing dead code.
512 //
513 //===----------------------------------------------------------------------===//
514 ADCEChanged AggressiveDeadCodeElimination::removeDeadInstructions() {
515   ADCEChanged Changed;
516   // Updates control and dataflow around dead blocks
517   Changed.ChangedControlFlow = updateDeadRegions();
518 
519   LLVM_DEBUG({
520     for (Instruction &I : instructions(F)) {
521       // Check if the instruction is alive.
522       if (isLive(&I))
523         continue;
524 
525       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
526         // Check if the scope of this variable location is alive.
527         if (AliveScopes.count(DII->getDebugLoc()->getScope()))
528           continue;
529 
530         // If intrinsic is pointing at a live SSA value, there may be an
531         // earlier optimization bug: if we know the location of the variable,
532         // why isn't the scope of the location alive?
533         for (Value *V : DII->location_ops()) {
534           if (Instruction *II = dyn_cast<Instruction>(V)) {
535             if (isLive(II)) {
536               dbgs() << "Dropping debug info for " << *DII << "\n";
537               break;
538             }
539           }
540         }
541       }
542     }
543   });
544 
545   // The inverse of the live set is the dead set.  These are those instructions
546   // that have no side effects and do not influence the control flow or return
547   // value of the function, and may therefore be deleted safely.
548   // NOTE: We reuse the Worklist vector here for memory efficiency.
549   for (Instruction &I : llvm::reverse(instructions(F))) {
550     // Check if the instruction is alive.
551     if (isLive(&I))
552       continue;
553 
554     if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) {
555       // Avoid removing a dbg.assign that is linked to instructions because it
556       // holds information about an existing store.
557       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII))
558         if (!at::getAssignmentInsts(DAI).empty())
559           continue;
560       // Check if the scope of this variable location is alive.
561       if (AliveScopes.count(DII->getDebugLoc()->getScope()))
562         continue;
563 
564       // Fallthrough and drop the intrinsic.
565     } else {
566       Changed.ChangedNonDebugInstr = true;
567     }
568 
569     // Prepare to delete.
570     Worklist.push_back(&I);
571     salvageDebugInfo(I);
572   }
573 
574   for (Instruction *&I : Worklist)
575     I->dropAllReferences();
576 
577   for (Instruction *&I : Worklist) {
578     ++NumRemoved;
579     I->eraseFromParent();
580   }
581 
582   Changed.ChangedAnything = Changed.ChangedControlFlow || !Worklist.empty();
583 
584   return Changed;
585 }
586 
587 // A dead region is the set of dead blocks with a common live post-dominator.
588 bool AggressiveDeadCodeElimination::updateDeadRegions() {
589   LLVM_DEBUG({
590     dbgs() << "final dead terminator blocks: " << '\n';
591     for (auto *BB : BlocksWithDeadTerminators)
592       dbgs() << '\t' << BB->getName()
593              << (BlockInfo[BB].Live ? " LIVE\n" : "\n");
594   });
595 
596   // Don't compute the post ordering unless we needed it.
597   bool HavePostOrder = false;
598   bool Changed = false;
599   SmallVector<DominatorTree::UpdateType, 10> DeletedEdges;
600 
601   for (auto *BB : BlocksWithDeadTerminators) {
602     auto &Info = BlockInfo[BB];
603     if (Info.UnconditionalBranch) {
604       InstInfo[Info.Terminator].Live = true;
605       continue;
606     }
607 
608     if (!HavePostOrder) {
609       computeReversePostOrder();
610       HavePostOrder = true;
611     }
612 
613     // Add an unconditional branch to the successor closest to the
614     // end of the function which insures a path to the exit for each
615     // live edge.
616     BlockInfoType *PreferredSucc = nullptr;
617     for (auto *Succ : successors(BB)) {
618       auto *Info = &BlockInfo[Succ];
619       if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder)
620         PreferredSucc = Info;
621     }
622     assert((PreferredSucc && PreferredSucc->PostOrder > 0) &&
623            "Failed to find safe successor for dead branch");
624 
625     // Collect removed successors to update the (Post)DominatorTrees.
626     SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
627     bool First = true;
628     for (auto *Succ : successors(BB)) {
629       if (!First || Succ != PreferredSucc->BB) {
630         Succ->removePredecessor(BB);
631         RemovedSuccessors.insert(Succ);
632       } else
633         First = false;
634     }
635     makeUnconditional(BB, PreferredSucc->BB);
636 
637     // Inform the dominators about the deleted CFG edges.
638     for (auto *Succ : RemovedSuccessors) {
639       // It might have happened that the same successor appeared multiple times
640       // and the CFG edge wasn't really removed.
641       if (Succ != PreferredSucc->BB) {
642         LLVM_DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion"
643                           << BB->getName() << " -> " << Succ->getName()
644                           << "\n");
645         DeletedEdges.push_back({DominatorTree::Delete, BB, Succ});
646       }
647     }
648 
649     NumBranchesRemoved += 1;
650     Changed = true;
651   }
652 
653   if (!DeletedEdges.empty())
654     DomTreeUpdater(DT, &PDT, DomTreeUpdater::UpdateStrategy::Eager)
655         .applyUpdates(DeletedEdges);
656 
657   return Changed;
658 }
659 
660 // reverse top-sort order
661 void AggressiveDeadCodeElimination::computeReversePostOrder() {
662   // This provides a post-order numbering of the reverse control flow graph
663   // Note that it is incomplete in the presence of infinite loops but we don't
664   // need numbers blocks which don't reach the end of the functions since
665   // all branches in those blocks are forced live.
666 
667   // For each block without successors, extend the DFS from the block
668   // backward through the graph
669   SmallPtrSet<BasicBlock*, 16> Visited;
670   unsigned PostOrder = 0;
671   for (auto &BB : F) {
672     if (!succ_empty(&BB))
673       continue;
674     for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited))
675       BlockInfo[Block].PostOrder = PostOrder++;
676   }
677 }
678 
679 void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB,
680                                                       BasicBlock *Target) {
681   Instruction *PredTerm = BB->getTerminator();
682   // Collect the live debug info scopes attached to this instruction.
683   if (const DILocation *DL = PredTerm->getDebugLoc())
684     collectLiveScopes(*DL);
685 
686   // Just mark live an existing unconditional branch
687   if (isUnconditionalBranch(PredTerm)) {
688     PredTerm->setSuccessor(0, Target);
689     InstInfo[PredTerm].Live = true;
690     return;
691   }
692   LLVM_DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n');
693   NumBranchesRemoved += 1;
694   IRBuilder<> Builder(PredTerm);
695   auto *NewTerm = Builder.CreateBr(Target);
696   InstInfo[NewTerm].Live = true;
697   if (const DILocation *DL = PredTerm->getDebugLoc())
698     NewTerm->setDebugLoc(DL);
699 
700   InstInfo.erase(PredTerm);
701   PredTerm->eraseFromParent();
702 }
703 
704 //===----------------------------------------------------------------------===//
705 //
706 // Pass Manager integration code
707 //
708 //===----------------------------------------------------------------------===//
709 PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &FAM) {
710   // ADCE does not need DominatorTree, but require DominatorTree here
711   // to update analysis if it is already available.
712   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
713   auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F);
714   ADCEChanged Changed =
715       AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination();
716   if (!Changed.ChangedAnything)
717     return PreservedAnalyses::all();
718 
719   PreservedAnalyses PA;
720   if (!Changed.ChangedControlFlow) {
721     PA.preserveSet<CFGAnalyses>();
722     if (!Changed.ChangedNonDebugInstr) {
723       // Only removing debug instructions does not affect MemorySSA.
724       //
725       // Therefore we preserve MemorySSA when only removing debug instructions
726       // since otherwise later passes may behave differently which then makes
727       // the presence of debug info affect code generation.
728       PA.preserve<MemorySSAAnalysis>();
729     }
730   }
731   PA.preserve<DominatorTreeAnalysis>();
732   PA.preserve<PostDominatorTreeAnalysis>();
733 
734   return PA;
735 }
736 
737 namespace {
738 
739 struct ADCELegacyPass : public FunctionPass {
740   static char ID; // Pass identification, replacement for typeid
741 
742   ADCELegacyPass() : FunctionPass(ID) {
743     initializeADCELegacyPassPass(*PassRegistry::getPassRegistry());
744   }
745 
746   bool runOnFunction(Function &F) override {
747     if (skipFunction(F))
748       return false;
749 
750     // ADCE does not need DominatorTree, but require DominatorTree here
751     // to update analysis if it is already available.
752     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
753     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
754     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
755     ADCEChanged Changed =
756         AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination();
757     return Changed.ChangedAnything;
758   }
759 
760   void getAnalysisUsage(AnalysisUsage &AU) const override {
761     AU.addRequired<PostDominatorTreeWrapperPass>();
762     if (!RemoveControlFlowFlag)
763       AU.setPreservesCFG();
764     else {
765       AU.addPreserved<DominatorTreeWrapperPass>();
766       AU.addPreserved<PostDominatorTreeWrapperPass>();
767     }
768     AU.addPreserved<GlobalsAAWrapperPass>();
769   }
770 };
771 
772 } // end anonymous namespace
773 
774 char ADCELegacyPass::ID = 0;
775 
776 INITIALIZE_PASS_BEGIN(ADCELegacyPass, "adce",
777                       "Aggressive Dead Code Elimination", false, false)
778 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
779 INITIALIZE_PASS_END(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination",
780                     false, false)
781 
782 FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); }
783