xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/ADCE.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- ADCE.cpp - Code to perform dead code elimination -------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the Aggressive Dead Code Elimination pass.  This pass
100b57cec5SDimitry Andric // optimistically assumes that all instructions are dead until proven otherwise,
110b57cec5SDimitry Andric // allowing it to eliminate dead computations that other DCE passes do not
120b57cec5SDimitry Andric // catch, particularly involving loop computations.
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/ADCE.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
190b57cec5SDimitry Andric #include "llvm/ADT/GraphTraits.h"
200b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
210b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
240b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
250b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/IteratedDominanceFrontier.h"
2906c3fb27SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
300b57cec5SDimitry Andric #include "llvm/Analysis/PostDominators.h"
310b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
320b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
33bdd1243dSDimitry Andric #include "llvm/IR/DebugInfo.h"
340b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
350b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
360b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
370b57cec5SDimitry Andric #include "llvm/IR/Function.h"
380b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
390b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
400b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
410b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
420b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
430b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
440b57cec5SDimitry Andric #include "llvm/IR/Use.h"
450b57cec5SDimitry Andric #include "llvm/IR/Value.h"
460b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
470b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
480b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
490b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
500b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
51fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
520b57cec5SDimitry Andric #include <cassert>
530b57cec5SDimitry Andric #include <cstddef>
540b57cec5SDimitry Andric #include <utility>
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric using namespace llvm;
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric #define DEBUG_TYPE "adce"
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric STATISTIC(NumRemoved, "Number of instructions removed");
610b57cec5SDimitry Andric STATISTIC(NumBranchesRemoved, "Number of branch instructions removed");
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric // This is a temporary option until we change the interface to this pass based
640b57cec5SDimitry Andric // on optimization level.
650b57cec5SDimitry Andric static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow",
660b57cec5SDimitry Andric                                            cl::init(true), cl::Hidden);
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric // This option enables removing of may-be-infinite loops which have no other
690b57cec5SDimitry Andric // effect.
700b57cec5SDimitry Andric static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false),
710b57cec5SDimitry Andric                                  cl::Hidden);
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric namespace {
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric /// Information about Instructions
760b57cec5SDimitry Andric struct InstInfoType {
770b57cec5SDimitry Andric   /// True if the associated instruction is live.
780b57cec5SDimitry Andric   bool Live = false;
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric   /// Quick access to information for block containing associated Instruction.
810b57cec5SDimitry Andric   struct BlockInfoType *Block = nullptr;
820b57cec5SDimitry Andric };
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric /// Information about basic blocks relevant to dead code elimination.
850b57cec5SDimitry Andric struct BlockInfoType {
860b57cec5SDimitry Andric   /// True when this block contains a live instructions.
870b57cec5SDimitry Andric   bool Live = false;
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   /// True when this block ends in an unconditional branch.
900b57cec5SDimitry Andric   bool UnconditionalBranch = false;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   /// True when this block is known to have live PHI nodes.
930b57cec5SDimitry Andric   bool HasLivePhiNodes = false;
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   /// Control dependence sources need to be live for this block.
960b57cec5SDimitry Andric   bool CFLive = false;
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   /// Quick access to the LiveInfo for the terminator,
990b57cec5SDimitry Andric   /// holds the value &InstInfo[Terminator]
1000b57cec5SDimitry Andric   InstInfoType *TerminatorLiveInfo = nullptr;
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   /// Corresponding BasicBlock.
1030b57cec5SDimitry Andric   BasicBlock *BB = nullptr;
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   /// Cache of BB->getTerminator().
1060b57cec5SDimitry Andric   Instruction *Terminator = nullptr;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   /// Post-order numbering of reverse control flow graph.
1090b57cec5SDimitry Andric   unsigned PostOrder;
1100b57cec5SDimitry Andric 
terminatorIsLive__anonf15092a00111::BlockInfoType1110b57cec5SDimitry Andric   bool terminatorIsLive() const { return TerminatorLiveInfo->Live; }
1120b57cec5SDimitry Andric };
1130b57cec5SDimitry Andric 
11406c3fb27SDimitry Andric struct ADCEChanged {
11506c3fb27SDimitry Andric   bool ChangedAnything = false;
11606c3fb27SDimitry Andric   bool ChangedNonDebugInstr = false;
11706c3fb27SDimitry Andric   bool ChangedControlFlow = false;
11806c3fb27SDimitry Andric };
11906c3fb27SDimitry Andric 
1200b57cec5SDimitry Andric class AggressiveDeadCodeElimination {
1210b57cec5SDimitry Andric   Function &F;
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // ADCE does not use DominatorTree per se, but it updates it to preserve the
1240b57cec5SDimitry Andric   // analysis.
1250b57cec5SDimitry Andric   DominatorTree *DT;
1260b57cec5SDimitry Andric   PostDominatorTree &PDT;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric   /// Mapping of blocks to associated information, an element in BlockInfoVec.
1290b57cec5SDimitry Andric   /// Use MapVector to get deterministic iteration order.
1300b57cec5SDimitry Andric   MapVector<BasicBlock *, BlockInfoType> BlockInfo;
isLive(BasicBlock * BB)1310b57cec5SDimitry Andric   bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   /// Mapping of instructions to associated information.
1340b57cec5SDimitry Andric   DenseMap<Instruction *, InstInfoType> InstInfo;
isLive(Instruction * I)1350b57cec5SDimitry Andric   bool isLive(Instruction *I) { return InstInfo[I].Live; }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   /// Instructions known to be live where we need to mark
1380b57cec5SDimitry Andric   /// reaching definitions as live.
1390b57cec5SDimitry Andric   SmallVector<Instruction *, 128> Worklist;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   /// Debug info scopes around a live instruction.
1420b57cec5SDimitry Andric   SmallPtrSet<const Metadata *, 32> AliveScopes;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric   /// Set of blocks with not known to have live terminators.
1450b57cec5SDimitry Andric   SmallSetVector<BasicBlock *, 16> BlocksWithDeadTerminators;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   /// The set of blocks which we have determined whose control
1480b57cec5SDimitry Andric   /// dependence sources must be live and which have not had
1490b57cec5SDimitry Andric   /// those dependences analyzed.
1500b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 16> NewLiveBlocks;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   /// Set up auxiliary data structures for Instructions and BasicBlocks and
1530b57cec5SDimitry Andric   /// initialize the Worklist to the set of must-be-live Instruscions.
1540b57cec5SDimitry Andric   void initialize();
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   /// Return true for operations which are always treated as live.
1570b57cec5SDimitry Andric   bool isAlwaysLive(Instruction &I);
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   /// Return true for instrumentation instructions for value profiling.
1600b57cec5SDimitry Andric   bool isInstrumentsConstant(Instruction &I);
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   /// Propagate liveness to reaching definitions.
1630b57cec5SDimitry Andric   void markLiveInstructions();
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   /// Mark an instruction as live.
1660b57cec5SDimitry Andric   void markLive(Instruction *I);
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   /// Mark a block as live.
1690b57cec5SDimitry Andric   void markLive(BlockInfoType &BB);
markLive(BasicBlock * BB)1700b57cec5SDimitry Andric   void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   /// Mark terminators of control predecessors of a PHI node live.
1730b57cec5SDimitry Andric   void markPhiLive(PHINode *PN);
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   /// Record the Debug Scopes which surround live debug information.
1760b57cec5SDimitry Andric   void collectLiveScopes(const DILocalScope &LS);
1770b57cec5SDimitry Andric   void collectLiveScopes(const DILocation &DL);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   /// Analyze dead branches to find those whose branches are the sources
1800b57cec5SDimitry Andric   /// of control dependences impacting a live block. Those branches are
1810b57cec5SDimitry Andric   /// marked live.
1820b57cec5SDimitry Andric   void markLiveBranchesFromControlDependences();
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   /// Remove instructions not marked live, return if any instruction was
1850b57cec5SDimitry Andric   /// removed.
18606c3fb27SDimitry Andric   ADCEChanged removeDeadInstructions();
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   /// Identify connected sections of the control flow graph which have
1890b57cec5SDimitry Andric   /// dead terminators and rewrite the control flow graph to remove them.
1905ffd83dbSDimitry Andric   bool updateDeadRegions();
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   /// Set the BlockInfo::PostOrder field based on a post-order
1930b57cec5SDimitry Andric   /// numbering of the reverse control flow graph.
1940b57cec5SDimitry Andric   void computeReversePostOrder();
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   /// Make the terminator of this block an unconditional branch to \p Target.
1970b57cec5SDimitry Andric   void makeUnconditional(BasicBlock *BB, BasicBlock *Target);
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric public:
AggressiveDeadCodeElimination(Function & F,DominatorTree * DT,PostDominatorTree & PDT)2000b57cec5SDimitry Andric   AggressiveDeadCodeElimination(Function &F, DominatorTree *DT,
2010b57cec5SDimitry Andric                                 PostDominatorTree &PDT)
2020b57cec5SDimitry Andric       : F(F), DT(DT), PDT(PDT) {}
2030b57cec5SDimitry Andric 
20406c3fb27SDimitry Andric   ADCEChanged performDeadCodeElimination();
2050b57cec5SDimitry Andric };
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric } // end anonymous namespace
2080b57cec5SDimitry Andric 
performDeadCodeElimination()20906c3fb27SDimitry Andric ADCEChanged AggressiveDeadCodeElimination::performDeadCodeElimination() {
2100b57cec5SDimitry Andric   initialize();
2110b57cec5SDimitry Andric   markLiveInstructions();
2120b57cec5SDimitry Andric   return removeDeadInstructions();
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
isUnconditionalBranch(Instruction * Term)2150b57cec5SDimitry Andric static bool isUnconditionalBranch(Instruction *Term) {
2160b57cec5SDimitry Andric   auto *BR = dyn_cast<BranchInst>(Term);
2170b57cec5SDimitry Andric   return BR && BR->isUnconditional();
2180b57cec5SDimitry Andric }
2190b57cec5SDimitry Andric 
initialize()2200b57cec5SDimitry Andric void AggressiveDeadCodeElimination::initialize() {
2210b57cec5SDimitry Andric   auto NumBlocks = F.size();
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   // We will have an entry in the map for each block so we grow the
2240b57cec5SDimitry Andric   // structure to twice that size to keep the load factor low in the hash table.
2250b57cec5SDimitry Andric   BlockInfo.reserve(NumBlocks);
2260b57cec5SDimitry Andric   size_t NumInsts = 0;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   // Iterate over blocks and initialize BlockInfoVec entries, count
2290b57cec5SDimitry Andric   // instructions to size the InstInfo hash table.
2300b57cec5SDimitry Andric   for (auto &BB : F) {
2310b57cec5SDimitry Andric     NumInsts += BB.size();
2320b57cec5SDimitry Andric     auto &Info = BlockInfo[&BB];
2330b57cec5SDimitry Andric     Info.BB = &BB;
2340b57cec5SDimitry Andric     Info.Terminator = BB.getTerminator();
2350b57cec5SDimitry Andric     Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator);
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   // Initialize instruction map and set pointers to block info.
2390b57cec5SDimitry Andric   InstInfo.reserve(NumInsts);
2400b57cec5SDimitry Andric   for (auto &BBInfo : BlockInfo)
2410b57cec5SDimitry Andric     for (Instruction &I : *BBInfo.second.BB)
2420b57cec5SDimitry Andric       InstInfo[&I].Block = &BBInfo.second;
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric   // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not
2450b57cec5SDimitry Andric   // add any more elements to either after this point.
2460b57cec5SDimitry Andric   for (auto &BBInfo : BlockInfo)
2470b57cec5SDimitry Andric     BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator];
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   // Collect the set of "root" instructions that are known live.
2500b57cec5SDimitry Andric   for (Instruction &I : instructions(F))
2510b57cec5SDimitry Andric     if (isAlwaysLive(I))
2520b57cec5SDimitry Andric       markLive(&I);
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   if (!RemoveControlFlowFlag)
2550b57cec5SDimitry Andric     return;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   if (!RemoveLoops) {
2580b57cec5SDimitry Andric     // This stores state for the depth-first iterator. In addition
2590b57cec5SDimitry Andric     // to recording which nodes have been visited we also record whether
2600b57cec5SDimitry Andric     // a node is currently on the "stack" of active ancestors of the current
2610b57cec5SDimitry Andric     // node.
2620b57cec5SDimitry Andric     using StatusMap = DenseMap<BasicBlock *, bool>;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric     class DFState : public StatusMap {
2650b57cec5SDimitry Andric     public:
2660b57cec5SDimitry Andric       std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) {
2670b57cec5SDimitry Andric         return StatusMap::insert(std::make_pair(BB, true));
2680b57cec5SDimitry Andric       }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric       // Invoked after we have visited all children of a node.
2710b57cec5SDimitry Andric       void completed(BasicBlock *BB) { (*this)[BB] = false; }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric       // Return true if \p BB is currently on the active stack
2740b57cec5SDimitry Andric       // of ancestors.
2750b57cec5SDimitry Andric       bool onStack(BasicBlock *BB) {
2760b57cec5SDimitry Andric         auto Iter = find(BB);
2770b57cec5SDimitry Andric         return Iter != end() && Iter->second;
2780b57cec5SDimitry Andric       }
2790b57cec5SDimitry Andric     } State;
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric     State.reserve(F.size());
2820b57cec5SDimitry Andric     // Iterate over blocks in depth-first pre-order and
2830b57cec5SDimitry Andric     // treat all edges to a block already seen as loop back edges
2840b57cec5SDimitry Andric     // and mark the branch live it if there is a back edge.
2850b57cec5SDimitry Andric     for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) {
2860b57cec5SDimitry Andric       Instruction *Term = BB->getTerminator();
2870b57cec5SDimitry Andric       if (isLive(Term))
2880b57cec5SDimitry Andric         continue;
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric       for (auto *Succ : successors(BB))
2910b57cec5SDimitry Andric         if (State.onStack(Succ)) {
2920b57cec5SDimitry Andric           // back edge....
2930b57cec5SDimitry Andric           markLive(Term);
2940b57cec5SDimitry Andric           break;
2950b57cec5SDimitry Andric         }
2960b57cec5SDimitry Andric     }
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // Mark blocks live if there is no path from the block to a
3000b57cec5SDimitry Andric   // return of the function.
3010b57cec5SDimitry Andric   // We do this by seeing which of the postdomtree root children exit the
3020b57cec5SDimitry Andric   // program, and for all others, mark the subtree live.
303bdd1243dSDimitry Andric   for (const auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) {
3040b57cec5SDimitry Andric     auto *BB = PDTChild->getBlock();
3050b57cec5SDimitry Andric     auto &Info = BlockInfo[BB];
3060b57cec5SDimitry Andric     // Real function return
3070b57cec5SDimitry Andric     if (isa<ReturnInst>(Info.Terminator)) {
3080b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName()
3090b57cec5SDimitry Andric                         << '\n';);
3100b57cec5SDimitry Andric       continue;
3110b57cec5SDimitry Andric     }
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric     // This child is something else, like an infinite loop.
314bdd1243dSDimitry Andric     for (auto *DFNode : depth_first(PDTChild))
3150b57cec5SDimitry Andric       markLive(BlockInfo[DFNode->getBlock()].Terminator);
3160b57cec5SDimitry Andric   }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   // Treat the entry block as always live
3190b57cec5SDimitry Andric   auto *BB = &F.getEntryBlock();
3200b57cec5SDimitry Andric   auto &EntryInfo = BlockInfo[BB];
3210b57cec5SDimitry Andric   EntryInfo.Live = true;
3220b57cec5SDimitry Andric   if (EntryInfo.UnconditionalBranch)
3230b57cec5SDimitry Andric     markLive(EntryInfo.Terminator);
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   // Build initial collection of blocks with dead terminators
3260b57cec5SDimitry Andric   for (auto &BBInfo : BlockInfo)
3270b57cec5SDimitry Andric     if (!BBInfo.second.terminatorIsLive())
3280b57cec5SDimitry Andric       BlocksWithDeadTerminators.insert(BBInfo.second.BB);
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
isAlwaysLive(Instruction & I)3310b57cec5SDimitry Andric bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) {
3320b57cec5SDimitry Andric   // TODO -- use llvm::isInstructionTriviallyDead
33328a41182SDimitry Andric   if (I.isEHPad() || I.mayHaveSideEffects()) {
3340b57cec5SDimitry Andric     // Skip any value profile instrumentation calls if they are
3350b57cec5SDimitry Andric     // instrumenting constants.
3360b57cec5SDimitry Andric     if (isInstrumentsConstant(I))
3370b57cec5SDimitry Andric       return false;
3380b57cec5SDimitry Andric     return true;
3390b57cec5SDimitry Andric   }
3400b57cec5SDimitry Andric   if (!I.isTerminator())
3410b57cec5SDimitry Andric     return false;
3420b57cec5SDimitry Andric   if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I)))
3430b57cec5SDimitry Andric     return false;
3440b57cec5SDimitry Andric   return true;
3450b57cec5SDimitry Andric }
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric // Check if this instruction is a runtime call for value profiling and
3480b57cec5SDimitry Andric // if it's instrumenting a constant.
isInstrumentsConstant(Instruction & I)3490b57cec5SDimitry Andric bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) {
3500b57cec5SDimitry Andric   // TODO -- move this test into llvm::isInstructionTriviallyDead
3510b57cec5SDimitry Andric   if (CallInst *CI = dyn_cast<CallInst>(&I))
3520b57cec5SDimitry Andric     if (Function *Callee = CI->getCalledFunction())
353*0fca6ea1SDimitry Andric       if (Callee->getName() == getInstrProfValueProfFuncName())
3540b57cec5SDimitry Andric         if (isa<Constant>(CI->getArgOperand(0)))
3550b57cec5SDimitry Andric           return true;
3560b57cec5SDimitry Andric   return false;
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
markLiveInstructions()3590b57cec5SDimitry Andric void AggressiveDeadCodeElimination::markLiveInstructions() {
3600b57cec5SDimitry Andric   // Propagate liveness backwards to operands.
3610b57cec5SDimitry Andric   do {
3620b57cec5SDimitry Andric     // Worklist holds newly discovered live instructions
3630b57cec5SDimitry Andric     // where we need to mark the inputs as live.
3640b57cec5SDimitry Andric     while (!Worklist.empty()) {
3650b57cec5SDimitry Andric       Instruction *LiveInst = Worklist.pop_back_val();
3660b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "work live: "; LiveInst->dump(););
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric       for (Use &OI : LiveInst->operands())
3690b57cec5SDimitry Andric         if (Instruction *Inst = dyn_cast<Instruction>(OI))
3700b57cec5SDimitry Andric           markLive(Inst);
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric       if (auto *PN = dyn_cast<PHINode>(LiveInst))
3730b57cec5SDimitry Andric         markPhiLive(PN);
3740b57cec5SDimitry Andric     }
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric     // After data flow liveness has been identified, examine which branch
3770b57cec5SDimitry Andric     // decisions are required to determine live instructions are executed.
3780b57cec5SDimitry Andric     markLiveBranchesFromControlDependences();
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   } while (!Worklist.empty());
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
markLive(Instruction * I)3830b57cec5SDimitry Andric void AggressiveDeadCodeElimination::markLive(Instruction *I) {
3840b57cec5SDimitry Andric   auto &Info = InstInfo[I];
3850b57cec5SDimitry Andric   if (Info.Live)
3860b57cec5SDimitry Andric     return;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "mark live: "; I->dump());
3890b57cec5SDimitry Andric   Info.Live = true;
3900b57cec5SDimitry Andric   Worklist.push_back(I);
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   // Collect the live debug info scopes attached to this instruction.
3930b57cec5SDimitry Andric   if (const DILocation *DL = I->getDebugLoc())
3940b57cec5SDimitry Andric     collectLiveScopes(*DL);
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   // Mark the containing block live
3970b57cec5SDimitry Andric   auto &BBInfo = *Info.Block;
3980b57cec5SDimitry Andric   if (BBInfo.Terminator == I) {
3990b57cec5SDimitry Andric     BlocksWithDeadTerminators.remove(BBInfo.BB);
4000b57cec5SDimitry Andric     // For live terminators, mark destination blocks
4010b57cec5SDimitry Andric     // live to preserve this control flow edges.
4020b57cec5SDimitry Andric     if (!BBInfo.UnconditionalBranch)
4030b57cec5SDimitry Andric       for (auto *BB : successors(I->getParent()))
4040b57cec5SDimitry Andric         markLive(BB);
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric   markLive(BBInfo);
4070b57cec5SDimitry Andric }
4080b57cec5SDimitry Andric 
markLive(BlockInfoType & BBInfo)4090b57cec5SDimitry Andric void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) {
4100b57cec5SDimitry Andric   if (BBInfo.Live)
4110b57cec5SDimitry Andric     return;
4120b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n');
4130b57cec5SDimitry Andric   BBInfo.Live = true;
4140b57cec5SDimitry Andric   if (!BBInfo.CFLive) {
4150b57cec5SDimitry Andric     BBInfo.CFLive = true;
4160b57cec5SDimitry Andric     NewLiveBlocks.insert(BBInfo.BB);
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   // Mark unconditional branches at the end of live
4200b57cec5SDimitry Andric   // blocks as live since there is no work to do for them later
4210b57cec5SDimitry Andric   if (BBInfo.UnconditionalBranch)
4220b57cec5SDimitry Andric     markLive(BBInfo.Terminator);
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric 
collectLiveScopes(const DILocalScope & LS)4250b57cec5SDimitry Andric void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) {
4260b57cec5SDimitry Andric   if (!AliveScopes.insert(&LS).second)
4270b57cec5SDimitry Andric     return;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   if (isa<DISubprogram>(LS))
4300b57cec5SDimitry Andric     return;
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   // Tail-recurse through the scope chain.
4330b57cec5SDimitry Andric   collectLiveScopes(cast<DILocalScope>(*LS.getScope()));
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric 
collectLiveScopes(const DILocation & DL)4360b57cec5SDimitry Andric void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) {
4370b57cec5SDimitry Andric   // Even though DILocations are not scopes, shove them into AliveScopes so we
4380b57cec5SDimitry Andric   // don't revisit them.
4390b57cec5SDimitry Andric   if (!AliveScopes.insert(&DL).second)
4400b57cec5SDimitry Andric     return;
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric   // Collect live scopes from the scope chain.
4430b57cec5SDimitry Andric   collectLiveScopes(*DL.getScope());
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   // Tail-recurse through the inlined-at chain.
4460b57cec5SDimitry Andric   if (const DILocation *IA = DL.getInlinedAt())
4470b57cec5SDimitry Andric     collectLiveScopes(*IA);
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
markPhiLive(PHINode * PN)4500b57cec5SDimitry Andric void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) {
4510b57cec5SDimitry Andric   auto &Info = BlockInfo[PN->getParent()];
4520b57cec5SDimitry Andric   // Only need to check this once per block.
4530b57cec5SDimitry Andric   if (Info.HasLivePhiNodes)
4540b57cec5SDimitry Andric     return;
4550b57cec5SDimitry Andric   Info.HasLivePhiNodes = true;
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   // If a predecessor block is not live, mark it as control-flow live
4580b57cec5SDimitry Andric   // which will trigger marking live branches upon which
4590b57cec5SDimitry Andric   // that block is control dependent.
4600b57cec5SDimitry Andric   for (auto *PredBB : predecessors(Info.BB)) {
4610b57cec5SDimitry Andric     auto &Info = BlockInfo[PredBB];
4620b57cec5SDimitry Andric     if (!Info.CFLive) {
4630b57cec5SDimitry Andric       Info.CFLive = true;
4640b57cec5SDimitry Andric       NewLiveBlocks.insert(PredBB);
4650b57cec5SDimitry Andric     }
4660b57cec5SDimitry Andric   }
4670b57cec5SDimitry Andric }
4680b57cec5SDimitry Andric 
markLiveBranchesFromControlDependences()4690b57cec5SDimitry Andric void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() {
4700b57cec5SDimitry Andric   if (BlocksWithDeadTerminators.empty())
4710b57cec5SDimitry Andric     return;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   LLVM_DEBUG({
4740b57cec5SDimitry Andric     dbgs() << "new live blocks:\n";
4750b57cec5SDimitry Andric     for (auto *BB : NewLiveBlocks)
4760b57cec5SDimitry Andric       dbgs() << "\t" << BB->getName() << '\n';
4770b57cec5SDimitry Andric     dbgs() << "dead terminator blocks:\n";
4780b57cec5SDimitry Andric     for (auto *BB : BlocksWithDeadTerminators)
4790b57cec5SDimitry Andric       dbgs() << "\t" << BB->getName() << '\n';
4800b57cec5SDimitry Andric   });
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   // The dominance frontier of a live block X in the reverse
4830b57cec5SDimitry Andric   // control graph is the set of blocks upon which X is control
4840b57cec5SDimitry Andric   // dependent. The following sequence computes the set of blocks
4850b57cec5SDimitry Andric   // which currently have dead terminators that are control
4860b57cec5SDimitry Andric   // dependence sources of a block which is in NewLiveBlocks.
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric   const SmallPtrSet<BasicBlock *, 16> BWDT{
4890b57cec5SDimitry Andric       BlocksWithDeadTerminators.begin(),
4900b57cec5SDimitry Andric       BlocksWithDeadTerminators.end()
4910b57cec5SDimitry Andric   };
4920b57cec5SDimitry Andric   SmallVector<BasicBlock *, 32> IDFBlocks;
4930b57cec5SDimitry Andric   ReverseIDFCalculator IDFs(PDT);
4940b57cec5SDimitry Andric   IDFs.setDefiningBlocks(NewLiveBlocks);
4950b57cec5SDimitry Andric   IDFs.setLiveInBlocks(BWDT);
4960b57cec5SDimitry Andric   IDFs.calculate(IDFBlocks);
4970b57cec5SDimitry Andric   NewLiveBlocks.clear();
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   // Dead terminators which control live blocks are now marked live.
5000b57cec5SDimitry Andric   for (auto *BB : IDFBlocks) {
5010b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "live control in: " << BB->getName() << '\n');
5020b57cec5SDimitry Andric     markLive(BB->getTerminator());
5030b57cec5SDimitry Andric   }
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5070b57cec5SDimitry Andric //
5080b57cec5SDimitry Andric //  Routines to update the CFG and SSA information before removing dead code.
5090b57cec5SDimitry Andric //
5100b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
removeDeadInstructions()51106c3fb27SDimitry Andric ADCEChanged AggressiveDeadCodeElimination::removeDeadInstructions() {
51206c3fb27SDimitry Andric   ADCEChanged Changed;
5130b57cec5SDimitry Andric   // Updates control and dataflow around dead blocks
51406c3fb27SDimitry Andric   Changed.ChangedControlFlow = updateDeadRegions();
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric   LLVM_DEBUG({
5170b57cec5SDimitry Andric     for (Instruction &I : instructions(F)) {
5180b57cec5SDimitry Andric       // Check if the instruction is alive.
5190b57cec5SDimitry Andric       if (isLive(&I))
5200b57cec5SDimitry Andric         continue;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric       if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
5230b57cec5SDimitry Andric         // Check if the scope of this variable location is alive.
5240b57cec5SDimitry Andric         if (AliveScopes.count(DII->getDebugLoc()->getScope()))
5250b57cec5SDimitry Andric           continue;
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric         // If intrinsic is pointing at a live SSA value, there may be an
5280b57cec5SDimitry Andric         // earlier optimization bug: if we know the location of the variable,
5290b57cec5SDimitry Andric         // why isn't the scope of the location alive?
530fe6060f1SDimitry Andric         for (Value *V : DII->location_ops()) {
531fe6060f1SDimitry Andric           if (Instruction *II = dyn_cast<Instruction>(V)) {
532fe6060f1SDimitry Andric             if (isLive(II)) {
5330b57cec5SDimitry Andric               dbgs() << "Dropping debug info for " << *DII << "\n";
534fe6060f1SDimitry Andric               break;
535fe6060f1SDimitry Andric             }
536fe6060f1SDimitry Andric           }
537fe6060f1SDimitry Andric         }
5380b57cec5SDimitry Andric       }
5390b57cec5SDimitry Andric     }
5400b57cec5SDimitry Andric   });
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   // The inverse of the live set is the dead set.  These are those instructions
5430b57cec5SDimitry Andric   // that have no side effects and do not influence the control flow or return
5440b57cec5SDimitry Andric   // value of the function, and may therefore be deleted safely.
5450b57cec5SDimitry Andric   // NOTE: We reuse the Worklist vector here for memory efficiency.
546349cc55cSDimitry Andric   for (Instruction &I : llvm::reverse(instructions(F))) {
547*0fca6ea1SDimitry Andric     // With "RemoveDIs" debug-info stored in DbgVariableRecord objects,
548*0fca6ea1SDimitry Andric     // debug-info attached to this instruction, and drop any for scopes that
549*0fca6ea1SDimitry Andric     // aren't alive, like the rest of this loop does. Extending support to
550*0fca6ea1SDimitry Andric     // assignment tracking is future work.
551*0fca6ea1SDimitry Andric     for (DbgRecord &DR : make_early_inc_range(I.getDbgRecordRange())) {
552*0fca6ea1SDimitry Andric       // Avoid removing a DVR that is linked to instructions because it holds
5537a6dacacSDimitry Andric       // information about an existing store.
554*0fca6ea1SDimitry Andric       if (DbgVariableRecord *DVR = dyn_cast<DbgVariableRecord>(&DR);
555*0fca6ea1SDimitry Andric           DVR && DVR->isDbgAssign())
556*0fca6ea1SDimitry Andric         if (!at::getAssignmentInsts(DVR).empty())
5577a6dacacSDimitry Andric           continue;
558*0fca6ea1SDimitry Andric       if (AliveScopes.count(DR.getDebugLoc()->getScope()))
5595f757f3fSDimitry Andric         continue;
560*0fca6ea1SDimitry Andric       I.dropOneDbgRecord(&DR);
5615f757f3fSDimitry Andric     }
5625f757f3fSDimitry Andric 
5630b57cec5SDimitry Andric     // Check if the instruction is alive.
5640b57cec5SDimitry Andric     if (isLive(&I))
5650b57cec5SDimitry Andric       continue;
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) {
568bdd1243dSDimitry Andric       // Avoid removing a dbg.assign that is linked to instructions because it
569bdd1243dSDimitry Andric       // holds information about an existing store.
570bdd1243dSDimitry Andric       if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII))
571bdd1243dSDimitry Andric         if (!at::getAssignmentInsts(DAI).empty())
572bdd1243dSDimitry Andric           continue;
5730b57cec5SDimitry Andric       // Check if the scope of this variable location is alive.
5740b57cec5SDimitry Andric       if (AliveScopes.count(DII->getDebugLoc()->getScope()))
5750b57cec5SDimitry Andric         continue;
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric       // Fallthrough and drop the intrinsic.
57806c3fb27SDimitry Andric     } else {
57906c3fb27SDimitry Andric       Changed.ChangedNonDebugInstr = true;
5800b57cec5SDimitry Andric     }
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     // Prepare to delete.
5830b57cec5SDimitry Andric     Worklist.push_back(&I);
584fe6060f1SDimitry Andric     salvageDebugInfo(I);
5850b57cec5SDimitry Andric   }
5860b57cec5SDimitry Andric 
587349cc55cSDimitry Andric   for (Instruction *&I : Worklist)
588349cc55cSDimitry Andric     I->dropAllReferences();
589349cc55cSDimitry Andric 
5900b57cec5SDimitry Andric   for (Instruction *&I : Worklist) {
5910b57cec5SDimitry Andric     ++NumRemoved;
5920b57cec5SDimitry Andric     I->eraseFromParent();
5930b57cec5SDimitry Andric   }
5940b57cec5SDimitry Andric 
59506c3fb27SDimitry Andric   Changed.ChangedAnything = Changed.ChangedControlFlow || !Worklist.empty();
59606c3fb27SDimitry Andric 
59706c3fb27SDimitry Andric   return Changed;
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric // A dead region is the set of dead blocks with a common live post-dominator.
updateDeadRegions()6015ffd83dbSDimitry Andric bool AggressiveDeadCodeElimination::updateDeadRegions() {
6020b57cec5SDimitry Andric   LLVM_DEBUG({
6030b57cec5SDimitry Andric     dbgs() << "final dead terminator blocks: " << '\n';
6040b57cec5SDimitry Andric     for (auto *BB : BlocksWithDeadTerminators)
6050b57cec5SDimitry Andric       dbgs() << '\t' << BB->getName()
6060b57cec5SDimitry Andric              << (BlockInfo[BB].Live ? " LIVE\n" : "\n");
6070b57cec5SDimitry Andric   });
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   // Don't compute the post ordering unless we needed it.
6100b57cec5SDimitry Andric   bool HavePostOrder = false;
6115ffd83dbSDimitry Andric   bool Changed = false;
61204eeddc0SDimitry Andric   SmallVector<DominatorTree::UpdateType, 10> DeletedEdges;
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   for (auto *BB : BlocksWithDeadTerminators) {
6150b57cec5SDimitry Andric     auto &Info = BlockInfo[BB];
6160b57cec5SDimitry Andric     if (Info.UnconditionalBranch) {
6170b57cec5SDimitry Andric       InstInfo[Info.Terminator].Live = true;
6180b57cec5SDimitry Andric       continue;
6190b57cec5SDimitry Andric     }
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric     if (!HavePostOrder) {
6220b57cec5SDimitry Andric       computeReversePostOrder();
6230b57cec5SDimitry Andric       HavePostOrder = true;
6240b57cec5SDimitry Andric     }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric     // Add an unconditional branch to the successor closest to the
6270b57cec5SDimitry Andric     // end of the function which insures a path to the exit for each
6280b57cec5SDimitry Andric     // live edge.
6290b57cec5SDimitry Andric     BlockInfoType *PreferredSucc = nullptr;
6300b57cec5SDimitry Andric     for (auto *Succ : successors(BB)) {
6310b57cec5SDimitry Andric       auto *Info = &BlockInfo[Succ];
6320b57cec5SDimitry Andric       if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder)
6330b57cec5SDimitry Andric         PreferredSucc = Info;
6340b57cec5SDimitry Andric     }
6350b57cec5SDimitry Andric     assert((PreferredSucc && PreferredSucc->PostOrder > 0) &&
6360b57cec5SDimitry Andric            "Failed to find safe successor for dead branch");
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     // Collect removed successors to update the (Post)DominatorTrees.
6390b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 4> RemovedSuccessors;
6400b57cec5SDimitry Andric     bool First = true;
6410b57cec5SDimitry Andric     for (auto *Succ : successors(BB)) {
6420b57cec5SDimitry Andric       if (!First || Succ != PreferredSucc->BB) {
6430b57cec5SDimitry Andric         Succ->removePredecessor(BB);
6440b57cec5SDimitry Andric         RemovedSuccessors.insert(Succ);
6450b57cec5SDimitry Andric       } else
6460b57cec5SDimitry Andric         First = false;
6470b57cec5SDimitry Andric     }
6480b57cec5SDimitry Andric     makeUnconditional(BB, PreferredSucc->BB);
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric     // Inform the dominators about the deleted CFG edges.
6510b57cec5SDimitry Andric     for (auto *Succ : RemovedSuccessors) {
6520b57cec5SDimitry Andric       // It might have happened that the same successor appeared multiple times
6530b57cec5SDimitry Andric       // and the CFG edge wasn't really removed.
6540b57cec5SDimitry Andric       if (Succ != PreferredSucc->BB) {
6550b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion"
6560b57cec5SDimitry Andric                           << BB->getName() << " -> " << Succ->getName()
6570b57cec5SDimitry Andric                           << "\n");
6580b57cec5SDimitry Andric         DeletedEdges.push_back({DominatorTree::Delete, BB, Succ});
6590b57cec5SDimitry Andric       }
6600b57cec5SDimitry Andric     }
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric     NumBranchesRemoved += 1;
6635ffd83dbSDimitry Andric     Changed = true;
6640b57cec5SDimitry Andric   }
6655ffd83dbSDimitry Andric 
66604eeddc0SDimitry Andric   if (!DeletedEdges.empty())
66704eeddc0SDimitry Andric     DomTreeUpdater(DT, &PDT, DomTreeUpdater::UpdateStrategy::Eager)
66804eeddc0SDimitry Andric         .applyUpdates(DeletedEdges);
66904eeddc0SDimitry Andric 
6705ffd83dbSDimitry Andric   return Changed;
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric // reverse top-sort order
computeReversePostOrder()6740b57cec5SDimitry Andric void AggressiveDeadCodeElimination::computeReversePostOrder() {
6750b57cec5SDimitry Andric   // This provides a post-order numbering of the reverse control flow graph
6760b57cec5SDimitry Andric   // Note that it is incomplete in the presence of infinite loops but we don't
6770b57cec5SDimitry Andric   // need numbers blocks which don't reach the end of the functions since
6780b57cec5SDimitry Andric   // all branches in those blocks are forced live.
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric   // For each block without successors, extend the DFS from the block
6810b57cec5SDimitry Andric   // backward through the graph
6820b57cec5SDimitry Andric   SmallPtrSet<BasicBlock*, 16> Visited;
6830b57cec5SDimitry Andric   unsigned PostOrder = 0;
6840b57cec5SDimitry Andric   for (auto &BB : F) {
685e8d8bef9SDimitry Andric     if (!succ_empty(&BB))
6860b57cec5SDimitry Andric       continue;
6870b57cec5SDimitry Andric     for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited))
6880b57cec5SDimitry Andric       BlockInfo[Block].PostOrder = PostOrder++;
6890b57cec5SDimitry Andric   }
6900b57cec5SDimitry Andric }
6910b57cec5SDimitry Andric 
makeUnconditional(BasicBlock * BB,BasicBlock * Target)6920b57cec5SDimitry Andric void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB,
6930b57cec5SDimitry Andric                                                       BasicBlock *Target) {
6940b57cec5SDimitry Andric   Instruction *PredTerm = BB->getTerminator();
6950b57cec5SDimitry Andric   // Collect the live debug info scopes attached to this instruction.
6960b57cec5SDimitry Andric   if (const DILocation *DL = PredTerm->getDebugLoc())
6970b57cec5SDimitry Andric     collectLiveScopes(*DL);
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   // Just mark live an existing unconditional branch
7000b57cec5SDimitry Andric   if (isUnconditionalBranch(PredTerm)) {
7010b57cec5SDimitry Andric     PredTerm->setSuccessor(0, Target);
7020b57cec5SDimitry Andric     InstInfo[PredTerm].Live = true;
7030b57cec5SDimitry Andric     return;
7040b57cec5SDimitry Andric   }
7050b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n');
7060b57cec5SDimitry Andric   NumBranchesRemoved += 1;
7070b57cec5SDimitry Andric   IRBuilder<> Builder(PredTerm);
7080b57cec5SDimitry Andric   auto *NewTerm = Builder.CreateBr(Target);
7090b57cec5SDimitry Andric   InstInfo[NewTerm].Live = true;
7100b57cec5SDimitry Andric   if (const DILocation *DL = PredTerm->getDebugLoc())
7110b57cec5SDimitry Andric     NewTerm->setDebugLoc(DL);
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   InstInfo.erase(PredTerm);
7140b57cec5SDimitry Andric   PredTerm->eraseFromParent();
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7180b57cec5SDimitry Andric //
7190b57cec5SDimitry Andric // Pass Manager integration code
7200b57cec5SDimitry Andric //
7210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
run(Function & F,FunctionAnalysisManager & FAM)7220b57cec5SDimitry Andric PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &FAM) {
7230b57cec5SDimitry Andric   // ADCE does not need DominatorTree, but require DominatorTree here
7240b57cec5SDimitry Andric   // to update analysis if it is already available.
7250b57cec5SDimitry Andric   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
7260b57cec5SDimitry Andric   auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F);
72706c3fb27SDimitry Andric   ADCEChanged Changed =
72806c3fb27SDimitry Andric       AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination();
72906c3fb27SDimitry Andric   if (!Changed.ChangedAnything)
7300b57cec5SDimitry Andric     return PreservedAnalyses::all();
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   PreservedAnalyses PA;
73306c3fb27SDimitry Andric   if (!Changed.ChangedControlFlow) {
7340b57cec5SDimitry Andric     PA.preserveSet<CFGAnalyses>();
73506c3fb27SDimitry Andric     if (!Changed.ChangedNonDebugInstr) {
73606c3fb27SDimitry Andric       // Only removing debug instructions does not affect MemorySSA.
73706c3fb27SDimitry Andric       //
73806c3fb27SDimitry Andric       // Therefore we preserve MemorySSA when only removing debug instructions
73906c3fb27SDimitry Andric       // since otherwise later passes may behave differently which then makes
74006c3fb27SDimitry Andric       // the presence of debug info affect code generation.
74106c3fb27SDimitry Andric       PA.preserve<MemorySSAAnalysis>();
74206c3fb27SDimitry Andric     }
74306c3fb27SDimitry Andric   }
7440b57cec5SDimitry Andric   PA.preserve<DominatorTreeAnalysis>();
7450b57cec5SDimitry Andric   PA.preserve<PostDominatorTreeAnalysis>();
74606c3fb27SDimitry Andric 
7470b57cec5SDimitry Andric   return PA;
7480b57cec5SDimitry Andric }
749