LiveRangeShrink.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //===- LiveRangeShrink.cpp - Move instructions to shrink live range -------===//
  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. /// \file
  10. /// This pass moves instructions close to the definition of its operands to
  11. /// shrink live range of the def instruction. The code motion is limited within
  12. /// the basic block. The moved instruction should have 1 def, and more than one
  13. /// uses, all of which are the only use of the def.
  14. ///
  15. ///===---------------------------------------------------------------------===//
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/iterator_range.h"
  19. #include "llvm/CodeGen/MachineBasicBlock.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineFunctionPass.h"
  22. #include "llvm/CodeGen/MachineInstr.h"
  23. #include "llvm/CodeGen/MachineOperand.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/InitializePasses.h"
  26. #include "llvm/Pass.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <iterator>
  30. #include <utility>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "lrshrink"
  33. STATISTIC(NumInstrsHoistedToShrinkLiveRange,
  34. "Number of insructions hoisted to shrink live range.");
  35. namespace {
  36. class LiveRangeShrink : public MachineFunctionPass {
  37. public:
  38. static char ID;
  39. LiveRangeShrink() : MachineFunctionPass(ID) {
  40. initializeLiveRangeShrinkPass(*PassRegistry::getPassRegistry());
  41. }
  42. void getAnalysisUsage(AnalysisUsage &AU) const override {
  43. AU.setPreservesCFG();
  44. MachineFunctionPass::getAnalysisUsage(AU);
  45. }
  46. StringRef getPassName() const override { return "Live Range Shrink"; }
  47. bool runOnMachineFunction(MachineFunction &MF) override;
  48. };
  49. } // end anonymous namespace
  50. char LiveRangeShrink::ID = 0;
  51. char &llvm::LiveRangeShrinkID = LiveRangeShrink::ID;
  52. INITIALIZE_PASS(LiveRangeShrink, "lrshrink", "Live Range Shrink Pass", false,
  53. false)
  54. using InstOrderMap = DenseMap<MachineInstr *, unsigned>;
  55. /// Returns \p New if it's dominated by \p Old, otherwise return \p Old.
  56. /// \p M maintains a map from instruction to its dominating order that satisfies
  57. /// M[A] > M[B] guarantees that A is dominated by B.
  58. /// If \p New is not in \p M, return \p Old. Otherwise if \p Old is null, return
  59. /// \p New.
  60. static MachineInstr *FindDominatedInstruction(MachineInstr &New,
  61. MachineInstr *Old,
  62. const InstOrderMap &M) {
  63. auto NewIter = M.find(&New);
  64. if (NewIter == M.end())
  65. return Old;
  66. if (Old == nullptr)
  67. return &New;
  68. unsigned OrderOld = M.find(Old)->second;
  69. unsigned OrderNew = NewIter->second;
  70. if (OrderOld != OrderNew)
  71. return OrderOld < OrderNew ? &New : Old;
  72. // OrderOld == OrderNew, we need to iterate down from Old to see if it
  73. // can reach New, if yes, New is dominated by Old.
  74. for (MachineInstr *I = Old->getNextNode(); M.find(I)->second == OrderNew;
  75. I = I->getNextNode())
  76. if (I == &New)
  77. return &New;
  78. return Old;
  79. }
  80. /// Builds Instruction to its dominating order number map \p M by traversing
  81. /// from instruction \p Start.
  82. static void BuildInstOrderMap(MachineBasicBlock::iterator Start,
  83. InstOrderMap &M) {
  84. M.clear();
  85. unsigned i = 0;
  86. for (MachineInstr &I : make_range(Start, Start->getParent()->end()))
  87. M[&I] = i++;
  88. }
  89. bool LiveRangeShrink::runOnMachineFunction(MachineFunction &MF) {
  90. if (skipFunction(MF.getFunction()))
  91. return false;
  92. MachineRegisterInfo &MRI = MF.getRegInfo();
  93. LLVM_DEBUG(dbgs() << "**** Analysing " << MF.getName() << '\n');
  94. InstOrderMap IOM;
  95. // Map from register to instruction order (value of IOM) where the
  96. // register is used last. When moving instructions up, we need to
  97. // make sure all its defs (including dead def) will not cross its
  98. // last use when moving up.
  99. DenseMap<unsigned, std::pair<unsigned, MachineInstr *>> UseMap;
  100. for (MachineBasicBlock &MBB : MF) {
  101. if (MBB.empty())
  102. continue;
  103. bool SawStore = false;
  104. BuildInstOrderMap(MBB.begin(), IOM);
  105. UseMap.clear();
  106. for (MachineBasicBlock::iterator Next = MBB.begin(); Next != MBB.end();) {
  107. MachineInstr &MI = *Next;
  108. ++Next;
  109. if (MI.isPHI() || MI.isDebugOrPseudoInstr())
  110. continue;
  111. if (MI.mayStore())
  112. SawStore = true;
  113. unsigned CurrentOrder = IOM[&MI];
  114. unsigned Barrier = 0;
  115. MachineInstr *BarrierMI = nullptr;
  116. for (const MachineOperand &MO : MI.operands()) {
  117. if (!MO.isReg() || MO.isDebug())
  118. continue;
  119. if (MO.isUse())
  120. UseMap[MO.getReg()] = std::make_pair(CurrentOrder, &MI);
  121. else if (MO.isDead() && UseMap.count(MO.getReg()))
  122. // Barrier is the last instruction where MO get used. MI should not
  123. // be moved above Barrier.
  124. if (Barrier < UseMap[MO.getReg()].first) {
  125. Barrier = UseMap[MO.getReg()].first;
  126. BarrierMI = UseMap[MO.getReg()].second;
  127. }
  128. }
  129. if (!MI.isSafeToMove(nullptr, SawStore)) {
  130. // If MI has side effects, it should become a barrier for code motion.
  131. // IOM is rebuild from the next instruction to prevent later
  132. // instructions from being moved before this MI.
  133. if (MI.hasUnmodeledSideEffects() && !MI.isPseudoProbe() &&
  134. Next != MBB.end()) {
  135. BuildInstOrderMap(Next, IOM);
  136. SawStore = false;
  137. }
  138. continue;
  139. }
  140. const MachineOperand *DefMO = nullptr;
  141. MachineInstr *Insert = nullptr;
  142. // Number of live-ranges that will be shortened. We do not count
  143. // live-ranges that are defined by a COPY as it could be coalesced later.
  144. unsigned NumEligibleUse = 0;
  145. for (const MachineOperand &MO : MI.operands()) {
  146. if (!MO.isReg() || MO.isDead() || MO.isDebug())
  147. continue;
  148. Register Reg = MO.getReg();
  149. // Do not move the instruction if it def/uses a physical register,
  150. // unless it is a constant physical register or a noreg.
  151. if (!Reg.isVirtual()) {
  152. if (!Reg || MRI.isConstantPhysReg(Reg))
  153. continue;
  154. Insert = nullptr;
  155. break;
  156. }
  157. if (MO.isDef()) {
  158. // Do not move if there is more than one def.
  159. if (DefMO) {
  160. Insert = nullptr;
  161. break;
  162. }
  163. DefMO = &MO;
  164. } else if (MRI.hasOneNonDBGUse(Reg) && MRI.hasOneDef(Reg) && DefMO &&
  165. MRI.getRegClass(DefMO->getReg()) ==
  166. MRI.getRegClass(MO.getReg())) {
  167. // The heuristic does not handle different register classes yet
  168. // (registers of different sizes, looser/tighter constraints). This
  169. // is because it needs more accurate model to handle register
  170. // pressure correctly.
  171. MachineInstr &DefInstr = *MRI.def_instr_begin(Reg);
  172. if (!DefInstr.isCopy())
  173. NumEligibleUse++;
  174. Insert = FindDominatedInstruction(DefInstr, Insert, IOM);
  175. } else {
  176. Insert = nullptr;
  177. break;
  178. }
  179. }
  180. // If Barrier equals IOM[I], traverse forward to find if BarrierMI is
  181. // after Insert, if yes, then we should not hoist.
  182. for (MachineInstr *I = Insert; I && IOM[I] == Barrier;
  183. I = I->getNextNode())
  184. if (I == BarrierMI) {
  185. Insert = nullptr;
  186. break;
  187. }
  188. // Move the instruction when # of shrunk live range > 1.
  189. if (DefMO && Insert && NumEligibleUse > 1 && Barrier <= IOM[Insert]) {
  190. MachineBasicBlock::iterator I = std::next(Insert->getIterator());
  191. // Skip all the PHI and debug instructions.
  192. while (I != MBB.end() && (I->isPHI() || I->isDebugOrPseudoInstr()))
  193. I = std::next(I);
  194. if (I == MI.getIterator())
  195. continue;
  196. // Update the dominator order to be the same as the insertion point.
  197. // We do this to maintain a non-decreasing order without need to update
  198. // all instruction orders after the insertion point.
  199. unsigned NewOrder = IOM[&*I];
  200. IOM[&MI] = NewOrder;
  201. NumInstrsHoistedToShrinkLiveRange++;
  202. // Find MI's debug value following MI.
  203. MachineBasicBlock::iterator EndIter = std::next(MI.getIterator());
  204. if (MI.getOperand(0).isReg())
  205. for (; EndIter != MBB.end() && EndIter->isDebugValue() &&
  206. EndIter->hasDebugOperandForReg(MI.getOperand(0).getReg());
  207. ++EndIter, ++Next)
  208. IOM[&*EndIter] = NewOrder;
  209. MBB.splice(I, &MBB, MI.getIterator(), EndIter);
  210. }
  211. }
  212. }
  213. return false;
  214. }