UnreachableBlockElim.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. #include "llvm/CodeGen/UnreachableBlockElim.h"
  22. #include "llvm/ADT/DepthFirstIterator.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/CodeGen/MachineDominators.h"
  25. #include "llvm/CodeGen/MachineFunctionPass.h"
  26. #include "llvm/CodeGen/MachineInstrBuilder.h"
  27. #include "llvm/CodeGen/MachineLoopInfo.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/CodeGen/TargetInstrInfo.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/InitializePasses.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  35. using namespace llvm;
  36. namespace {
  37. class UnreachableBlockElimLegacyPass : public FunctionPass {
  38. bool runOnFunction(Function &F) override {
  39. return llvm::EliminateUnreachableBlocks(F);
  40. }
  41. public:
  42. static char ID; // Pass identification, replacement for typeid
  43. UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
  44. initializeUnreachableBlockElimLegacyPassPass(
  45. *PassRegistry::getPassRegistry());
  46. }
  47. void getAnalysisUsage(AnalysisUsage &AU) const override {
  48. AU.addPreserved<DominatorTreeWrapperPass>();
  49. }
  50. };
  51. }
  52. char UnreachableBlockElimLegacyPass::ID = 0;
  53. INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
  54. "Remove unreachable blocks from the CFG", false, false)
  55. FunctionPass *llvm::createUnreachableBlockEliminationPass() {
  56. return new UnreachableBlockElimLegacyPass();
  57. }
  58. PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
  59. FunctionAnalysisManager &AM) {
  60. bool Changed = llvm::EliminateUnreachableBlocks(F);
  61. if (!Changed)
  62. return PreservedAnalyses::all();
  63. PreservedAnalyses PA;
  64. PA.preserve<DominatorTreeAnalysis>();
  65. return PA;
  66. }
  67. namespace {
  68. class UnreachableMachineBlockElim : public MachineFunctionPass {
  69. bool runOnMachineFunction(MachineFunction &F) override;
  70. void getAnalysisUsage(AnalysisUsage &AU) const override;
  71. public:
  72. static char ID; // Pass identification, replacement for typeid
  73. UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
  74. };
  75. }
  76. char UnreachableMachineBlockElim::ID = 0;
  77. INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
  78. "Remove unreachable machine basic blocks", false, false)
  79. char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
  80. void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
  81. AU.addPreserved<MachineLoopInfo>();
  82. AU.addPreserved<MachineDominatorTree>();
  83. MachineFunctionPass::getAnalysisUsage(AU);
  84. }
  85. bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
  86. df_iterator_default_set<MachineBasicBlock*> Reachable;
  87. bool ModifiedPHI = false;
  88. MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
  89. MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
  90. // Mark all reachable blocks.
  91. for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
  92. (void)BB/* Mark all reachable blocks */;
  93. // Loop over all dead blocks, remembering them and deleting all instructions
  94. // in them.
  95. std::vector<MachineBasicBlock*> DeadBlocks;
  96. for (MachineBasicBlock &BB : F) {
  97. // Test for deadness.
  98. if (!Reachable.count(&BB)) {
  99. DeadBlocks.push_back(&BB);
  100. // Update dominator and loop info.
  101. if (MLI) MLI->removeBlock(&BB);
  102. if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
  103. while (BB.succ_begin() != BB.succ_end()) {
  104. MachineBasicBlock* succ = *BB.succ_begin();
  105. MachineBasicBlock::iterator start = succ->begin();
  106. while (start != succ->end() && start->isPHI()) {
  107. for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
  108. if (start->getOperand(i).isMBB() &&
  109. start->getOperand(i).getMBB() == &BB) {
  110. start->removeOperand(i);
  111. start->removeOperand(i-1);
  112. }
  113. start++;
  114. }
  115. BB.removeSuccessor(BB.succ_begin());
  116. }
  117. }
  118. }
  119. // Actually remove the blocks now.
  120. for (MachineBasicBlock *BB : DeadBlocks) {
  121. // Remove any call site information for calls in the block.
  122. for (auto &I : BB->instrs())
  123. if (I.shouldUpdateCallSiteInfo())
  124. BB->getParent()->eraseCallSiteInfo(&I);
  125. BB->eraseFromParent();
  126. }
  127. // Cleanup PHI nodes.
  128. for (MachineBasicBlock &BB : F) {
  129. // Prune unneeded PHI entries.
  130. SmallPtrSet<MachineBasicBlock*, 8> preds(BB.pred_begin(),
  131. BB.pred_end());
  132. MachineBasicBlock::iterator phi = BB.begin();
  133. while (phi != BB.end() && phi->isPHI()) {
  134. for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
  135. if (!preds.count(phi->getOperand(i).getMBB())) {
  136. phi->removeOperand(i);
  137. phi->removeOperand(i-1);
  138. ModifiedPHI = true;
  139. }
  140. if (phi->getNumOperands() == 3) {
  141. const MachineOperand &Input = phi->getOperand(1);
  142. const MachineOperand &Output = phi->getOperand(0);
  143. Register InputReg = Input.getReg();
  144. Register OutputReg = Output.getReg();
  145. assert(Output.getSubReg() == 0 && "Cannot have output subregister");
  146. ModifiedPHI = true;
  147. if (InputReg != OutputReg) {
  148. MachineRegisterInfo &MRI = F.getRegInfo();
  149. unsigned InputSub = Input.getSubReg();
  150. if (InputSub == 0 &&
  151. MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
  152. !Input.isUndef()) {
  153. MRI.replaceRegWith(OutputReg, InputReg);
  154. } else {
  155. // The input register to the PHI has a subregister or it can't be
  156. // constrained to the proper register class or it is undef:
  157. // insert a COPY instead of simply replacing the output
  158. // with the input.
  159. const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
  160. BuildMI(BB, BB.getFirstNonPHI(), phi->getDebugLoc(),
  161. TII->get(TargetOpcode::COPY), OutputReg)
  162. .addReg(InputReg, getRegState(Input), InputSub);
  163. }
  164. phi++->eraseFromParent();
  165. }
  166. continue;
  167. }
  168. ++phi;
  169. }
  170. }
  171. F.RenumberBlocks();
  172. return (!DeadBlocks.empty() || ModifiedPHI);
  173. }