Home | History | Annotate | Line # | Download | only in CodeGen
      1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
      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 pass is an extremely simple version of the SimplifyCFG pass.  Its sole
     10 // job is to delete LLVM basic blocks that are not reachable from the entry
     11 // node.  To do this, it performs a simple depth first traversal of the CFG,
     12 // then deletes any unvisited nodes.
     13 //
     14 // Note that this pass is really a hack.  In particular, the instruction
     15 // selectors for various targets should just not generate code for unreachable
     16 // blocks.  Until LLVM has a more systematic way of defining instruction
     17 // selectors, however, we cannot really expect them to handle additional
     18 // complexity.
     19 //
     20 //===----------------------------------------------------------------------===//
     21 
     22 #include "llvm/CodeGen/UnreachableBlockElim.h"
     23 #include "llvm/ADT/DepthFirstIterator.h"
     24 #include "llvm/ADT/SmallPtrSet.h"
     25 #include "llvm/CodeGen/MachineDominators.h"
     26 #include "llvm/CodeGen/MachineFunctionPass.h"
     27 #include "llvm/CodeGen/MachineInstrBuilder.h"
     28 #include "llvm/CodeGen/MachineLoopInfo.h"
     29 #include "llvm/CodeGen/MachineModuleInfo.h"
     30 #include "llvm/CodeGen/MachineRegisterInfo.h"
     31 #include "llvm/CodeGen/Passes.h"
     32 #include "llvm/CodeGen/TargetInstrInfo.h"
     33 #include "llvm/IR/CFG.h"
     34 #include "llvm/IR/Constant.h"
     35 #include "llvm/IR/Dominators.h"
     36 #include "llvm/IR/Function.h"
     37 #include "llvm/IR/Instructions.h"
     38 #include "llvm/IR/Type.h"
     39 #include "llvm/InitializePasses.h"
     40 #include "llvm/Pass.h"
     41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     42 using namespace llvm;
     43 
     44 namespace {
     45 class UnreachableBlockElimLegacyPass : public FunctionPass {
     46   bool runOnFunction(Function &F) override {
     47     return llvm::EliminateUnreachableBlocks(F);
     48   }
     49 
     50 public:
     51   static char ID; // Pass identification, replacement for typeid
     52   UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
     53     initializeUnreachableBlockElimLegacyPassPass(
     54         *PassRegistry::getPassRegistry());
     55   }
     56 
     57   void getAnalysisUsage(AnalysisUsage &AU) const override {
     58     AU.addPreserved<DominatorTreeWrapperPass>();
     59   }
     60 };
     61 }
     62 char UnreachableBlockElimLegacyPass::ID = 0;
     63 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
     64                 "Remove unreachable blocks from the CFG", false, false)
     65 
     66 FunctionPass *llvm::createUnreachableBlockEliminationPass() {
     67   return new UnreachableBlockElimLegacyPass();
     68 }
     69 
     70 PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
     71                                                 FunctionAnalysisManager &AM) {
     72   bool Changed = llvm::EliminateUnreachableBlocks(F);
     73   if (!Changed)
     74     return PreservedAnalyses::all();
     75   PreservedAnalyses PA;
     76   PA.preserve<DominatorTreeAnalysis>();
     77   return PA;
     78 }
     79 
     80 namespace {
     81   class UnreachableMachineBlockElim : public MachineFunctionPass {
     82     bool runOnMachineFunction(MachineFunction &F) override;
     83     void getAnalysisUsage(AnalysisUsage &AU) const override;
     84 
     85   public:
     86     static char ID; // Pass identification, replacement for typeid
     87     UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
     88   };
     89 }
     90 char UnreachableMachineBlockElim::ID = 0;
     91 
     92 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
     93   "Remove unreachable machine basic blocks", false, false)
     94 
     95 char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
     96 
     97 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
     98   AU.addPreserved<MachineLoopInfo>();
     99   AU.addPreserved<MachineDominatorTree>();
    100   MachineFunctionPass::getAnalysisUsage(AU);
    101 }
    102 
    103 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
    104   df_iterator_default_set<MachineBasicBlock*> Reachable;
    105   bool ModifiedPHI = false;
    106 
    107   MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
    108   MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
    109 
    110   // Mark all reachable blocks.
    111   for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
    112     (void)BB/* Mark all reachable blocks */;
    113 
    114   // Loop over all dead blocks, remembering them and deleting all instructions
    115   // in them.
    116   std::vector<MachineBasicBlock*> DeadBlocks;
    117   for (MachineBasicBlock &BB : F) {
    118     // Test for deadness.
    119     if (!Reachable.count(&BB)) {
    120       DeadBlocks.push_back(&BB);
    121 
    122       // Update dominator and loop info.
    123       if (MLI) MLI->removeBlock(&BB);
    124       if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
    125 
    126       while (BB.succ_begin() != BB.succ_end()) {
    127         MachineBasicBlock* succ = *BB.succ_begin();
    128 
    129         MachineBasicBlock::iterator start = succ->begin();
    130         while (start != succ->end() && start->isPHI()) {
    131           for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
    132             if (start->getOperand(i).isMBB() &&
    133                 start->getOperand(i).getMBB() == &BB) {
    134               start->RemoveOperand(i);
    135               start->RemoveOperand(i-1);
    136             }
    137 
    138           start++;
    139         }
    140 
    141         BB.removeSuccessor(BB.succ_begin());
    142       }
    143     }
    144   }
    145 
    146   // Actually remove the blocks now.
    147   for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) {
    148     // Remove any call site information for calls in the block.
    149     for (auto &I : DeadBlocks[i]->instrs())
    150       if (I.shouldUpdateCallSiteInfo())
    151         DeadBlocks[i]->getParent()->eraseCallSiteInfo(&I);
    152 
    153     DeadBlocks[i]->eraseFromParent();
    154   }
    155 
    156   // Cleanup PHI nodes.
    157   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
    158     MachineBasicBlock *BB = &*I;
    159     // Prune unneeded PHI entries.
    160     SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
    161                                              BB->pred_end());
    162     MachineBasicBlock::iterator phi = BB->begin();
    163     while (phi != BB->end() && phi->isPHI()) {
    164       for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
    165         if (!preds.count(phi->getOperand(i).getMBB())) {
    166           phi->RemoveOperand(i);
    167           phi->RemoveOperand(i-1);
    168           ModifiedPHI = true;
    169         }
    170 
    171       if (phi->getNumOperands() == 3) {
    172         const MachineOperand &Input = phi->getOperand(1);
    173         const MachineOperand &Output = phi->getOperand(0);
    174         Register InputReg = Input.getReg();
    175         Register OutputReg = Output.getReg();
    176         assert(Output.getSubReg() == 0 && "Cannot have output subregister");
    177         ModifiedPHI = true;
    178 
    179         if (InputReg != OutputReg) {
    180           MachineRegisterInfo &MRI = F.getRegInfo();
    181           unsigned InputSub = Input.getSubReg();
    182           if (InputSub == 0 &&
    183               MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
    184               !Input.isUndef()) {
    185             MRI.replaceRegWith(OutputReg, InputReg);
    186           } else {
    187             // The input register to the PHI has a subregister or it can't be
    188             // constrained to the proper register class or it is undef:
    189             // insert a COPY instead of simply replacing the output
    190             // with the input.
    191             const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
    192             BuildMI(*BB, BB->getFirstNonPHI(), phi->getDebugLoc(),
    193                     TII->get(TargetOpcode::COPY), OutputReg)
    194                 .addReg(InputReg, getRegState(Input), InputSub);
    195           }
    196           phi++->eraseFromParent();
    197         }
    198         continue;
    199       }
    200 
    201       ++phi;
    202     }
    203   }
    204 
    205   F.RenumberBlocks();
    206 
    207   return (!DeadBlocks.empty() || ModifiedPHI);
    208 }
    209