LiveRangeEdit.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. //===-- LiveRangeEdit.cpp - Basic tools for editing a register 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. // The LiveRangeEdit class represents changes done to a virtual register when it
  10. // is spilled or split.
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/LiveRangeEdit.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/CodeGen/CalcSpillWeights.h"
  15. #include "llvm/CodeGen/LiveIntervals.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/TargetInstrInfo.h"
  18. #include "llvm/CodeGen/VirtRegMap.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace llvm;
  22. #define DEBUG_TYPE "regalloc"
  23. STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
  24. STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
  25. STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
  26. STATISTIC(NumReMaterialization, "Number of instructions rematerialized");
  27. void LiveRangeEdit::Delegate::anchor() { }
  28. LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(Register OldReg,
  29. bool createSubRanges) {
  30. Register VReg = MRI.cloneVirtualRegister(OldReg);
  31. if (VRM)
  32. VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
  33. LiveInterval &LI = LIS.createEmptyInterval(VReg);
  34. if (Parent && !Parent->isSpillable())
  35. LI.markNotSpillable();
  36. if (createSubRanges) {
  37. // Create empty subranges if the OldReg's interval has them. Do not create
  38. // the main range here---it will be constructed later after the subranges
  39. // have been finalized.
  40. LiveInterval &OldLI = LIS.getInterval(OldReg);
  41. VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
  42. for (LiveInterval::SubRange &S : OldLI.subranges())
  43. LI.createSubRange(Alloc, S.LaneMask);
  44. }
  45. return LI;
  46. }
  47. Register LiveRangeEdit::createFrom(Register OldReg) {
  48. Register VReg = MRI.cloneVirtualRegister(OldReg);
  49. if (VRM) {
  50. VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
  51. }
  52. // FIXME: Getting the interval here actually computes it.
  53. // In theory, this may not be what we want, but in practice
  54. // the createEmptyIntervalFrom API is used when this is not
  55. // the case. Generally speaking we just want to annotate the
  56. // LiveInterval when it gets created but we cannot do that at
  57. // the moment.
  58. if (Parent && !Parent->isSpillable())
  59. LIS.getInterval(VReg).markNotSpillable();
  60. return VReg;
  61. }
  62. bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
  63. const MachineInstr *DefMI) {
  64. assert(DefMI && "Missing instruction");
  65. ScannedRemattable = true;
  66. if (!TII.isTriviallyReMaterializable(*DefMI))
  67. return false;
  68. Remattable.insert(VNI);
  69. return true;
  70. }
  71. void LiveRangeEdit::scanRemattable() {
  72. for (VNInfo *VNI : getParent().valnos) {
  73. if (VNI->isUnused())
  74. continue;
  75. unsigned Original = VRM->getOriginal(getReg());
  76. LiveInterval &OrigLI = LIS.getInterval(Original);
  77. VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
  78. if (!OrigVNI)
  79. continue;
  80. MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
  81. if (!DefMI)
  82. continue;
  83. checkRematerializable(OrigVNI, DefMI);
  84. }
  85. ScannedRemattable = true;
  86. }
  87. bool LiveRangeEdit::anyRematerializable() {
  88. if (!ScannedRemattable)
  89. scanRemattable();
  90. return !Remattable.empty();
  91. }
  92. /// allUsesAvailableAt - Return true if all registers used by OrigMI at
  93. /// OrigIdx are also available with the same value at UseIdx.
  94. bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
  95. SlotIndex OrigIdx,
  96. SlotIndex UseIdx) const {
  97. OrigIdx = OrigIdx.getRegSlot(true);
  98. UseIdx = std::max(UseIdx, UseIdx.getRegSlot(true));
  99. for (const MachineOperand &MO : OrigMI->operands()) {
  100. if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
  101. continue;
  102. // We can't remat physreg uses, unless it is a constant or target wants
  103. // to ignore this use.
  104. if (MO.getReg().isPhysical()) {
  105. if (MRI.isConstantPhysReg(MO.getReg()) || TII.isIgnorableUse(MO))
  106. continue;
  107. return false;
  108. }
  109. LiveInterval &li = LIS.getInterval(MO.getReg());
  110. const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
  111. if (!OVNI)
  112. continue;
  113. // Don't allow rematerialization immediately after the original def.
  114. // It would be incorrect if OrigMI redefines the register.
  115. // See PR14098.
  116. if (SlotIndex::isSameInstr(OrigIdx, UseIdx))
  117. return false;
  118. if (OVNI != li.getVNInfoAt(UseIdx))
  119. return false;
  120. // Check that subrange is live at UseIdx.
  121. if (li.hasSubRanges()) {
  122. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  123. unsigned SubReg = MO.getSubReg();
  124. LaneBitmask LM = SubReg ? TRI->getSubRegIndexLaneMask(SubReg)
  125. : MRI.getMaxLaneMaskForVReg(MO.getReg());
  126. for (LiveInterval::SubRange &SR : li.subranges()) {
  127. if ((SR.LaneMask & LM).none())
  128. continue;
  129. if (!SR.liveAt(UseIdx))
  130. return false;
  131. // Early exit if all used lanes are checked. No need to continue.
  132. LM &= ~SR.LaneMask;
  133. if (LM.none())
  134. break;
  135. }
  136. }
  137. }
  138. return true;
  139. }
  140. bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI,
  141. SlotIndex UseIdx, bool cheapAsAMove) {
  142. assert(ScannedRemattable && "Call anyRematerializable first");
  143. // Use scanRemattable info.
  144. if (!Remattable.count(OrigVNI))
  145. return false;
  146. // No defining instruction provided.
  147. SlotIndex DefIdx;
  148. assert(RM.OrigMI && "No defining instruction for remattable value");
  149. DefIdx = LIS.getInstructionIndex(*RM.OrigMI);
  150. // If only cheap remats were requested, bail out early.
  151. if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI))
  152. return false;
  153. // Verify that all used registers are available with the same values.
  154. if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
  155. return false;
  156. return true;
  157. }
  158. SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
  159. MachineBasicBlock::iterator MI,
  160. unsigned DestReg,
  161. const Remat &RM,
  162. const TargetRegisterInfo &tri,
  163. bool Late,
  164. unsigned SubIdx,
  165. MachineInstr *ReplaceIndexMI) {
  166. assert(RM.OrigMI && "Invalid remat");
  167. TII.reMaterialize(MBB, MI, DestReg, SubIdx, *RM.OrigMI, tri);
  168. // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg
  169. // to false anyway in case the isDead flag of RM.OrigMI's dest register
  170. // is true.
  171. (*--MI).getOperand(0).setIsDead(false);
  172. Rematted.insert(RM.ParentVNI);
  173. ++NumReMaterialization;
  174. if (ReplaceIndexMI)
  175. return LIS.ReplaceMachineInstrInMaps(*ReplaceIndexMI, *MI).getRegSlot();
  176. return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot();
  177. }
  178. void LiveRangeEdit::eraseVirtReg(Register Reg) {
  179. if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
  180. LIS.removeInterval(Reg);
  181. }
  182. bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
  183. SmallVectorImpl<MachineInstr*> &Dead) {
  184. MachineInstr *DefMI = nullptr, *UseMI = nullptr;
  185. // Check that there is a single def and a single use.
  186. for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg())) {
  187. MachineInstr *MI = MO.getParent();
  188. if (MO.isDef()) {
  189. if (DefMI && DefMI != MI)
  190. return false;
  191. if (!MI->canFoldAsLoad())
  192. return false;
  193. DefMI = MI;
  194. } else if (!MO.isUndef()) {
  195. if (UseMI && UseMI != MI)
  196. return false;
  197. // FIXME: Targets don't know how to fold subreg uses.
  198. if (MO.getSubReg())
  199. return false;
  200. UseMI = MI;
  201. }
  202. }
  203. if (!DefMI || !UseMI)
  204. return false;
  205. // Since we're moving the DefMI load, make sure we're not extending any live
  206. // ranges.
  207. if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI),
  208. LIS.getInstructionIndex(*UseMI)))
  209. return false;
  210. // We also need to make sure it is safe to move the load.
  211. // Assume there are stores between DefMI and UseMI.
  212. bool SawStore = true;
  213. if (!DefMI->isSafeToMove(nullptr, SawStore))
  214. return false;
  215. LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI
  216. << " into single use: " << *UseMI);
  217. SmallVector<unsigned, 8> Ops;
  218. if (UseMI->readsWritesVirtualRegister(LI->reg(), &Ops).second)
  219. return false;
  220. MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS);
  221. if (!FoldMI)
  222. return false;
  223. LLVM_DEBUG(dbgs() << " folded: " << *FoldMI);
  224. LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI);
  225. // Update the call site info.
  226. if (UseMI->shouldUpdateCallSiteInfo())
  227. UseMI->getMF()->moveCallSiteInfo(UseMI, FoldMI);
  228. UseMI->eraseFromParent();
  229. DefMI->addRegisterDead(LI->reg(), nullptr);
  230. Dead.push_back(DefMI);
  231. ++NumDCEFoldedLoads;
  232. return true;
  233. }
  234. bool LiveRangeEdit::useIsKill(const LiveInterval &LI,
  235. const MachineOperand &MO) const {
  236. const MachineInstr &MI = *MO.getParent();
  237. SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
  238. if (LI.Query(Idx).isKill())
  239. return true;
  240. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  241. unsigned SubReg = MO.getSubReg();
  242. LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg);
  243. for (const LiveInterval::SubRange &S : LI.subranges()) {
  244. if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill())
  245. return true;
  246. }
  247. return false;
  248. }
  249. /// Find all live intervals that need to shrink, then remove the instruction.
  250. void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) {
  251. assert(MI->allDefsAreDead() && "Def isn't really dead");
  252. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
  253. // Never delete a bundled instruction.
  254. if (MI->isBundled()) {
  255. return;
  256. }
  257. // Never delete inline asm.
  258. if (MI->isInlineAsm()) {
  259. LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
  260. return;
  261. }
  262. // Use the same criteria as DeadMachineInstructionElim.
  263. bool SawStore = false;
  264. if (!MI->isSafeToMove(nullptr, SawStore)) {
  265. LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
  266. return;
  267. }
  268. LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
  269. // Collect virtual registers to be erased after MI is gone.
  270. SmallVector<unsigned, 8> RegsToErase;
  271. bool ReadsPhysRegs = false;
  272. bool isOrigDef = false;
  273. Register Dest;
  274. unsigned DestSubReg;
  275. // Only optimize rematerialize case when the instruction has one def, since
  276. // otherwise we could leave some dead defs in the code. This case is
  277. // extremely rare.
  278. if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  279. MI->getDesc().getNumDefs() == 1) {
  280. Dest = MI->getOperand(0).getReg();
  281. DestSubReg = MI->getOperand(0).getSubReg();
  282. Register Original = VRM->getOriginal(Dest);
  283. LiveInterval &OrigLI = LIS.getInterval(Original);
  284. VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
  285. // The original live-range may have been shrunk to
  286. // an empty live-range. It happens when it is dead, but
  287. // we still keep it around to be able to rematerialize
  288. // other values that depend on it.
  289. if (OrigVNI)
  290. isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx);
  291. }
  292. bool HasLiveVRegUses = false;
  293. // Check for live intervals that may shrink
  294. for (const MachineOperand &MO : MI->operands()) {
  295. if (!MO.isReg())
  296. continue;
  297. Register Reg = MO.getReg();
  298. if (!Reg.isVirtual()) {
  299. // Check if MI reads any unreserved physregs.
  300. if (Reg && MO.readsReg() && !MRI.isReserved(Reg))
  301. ReadsPhysRegs = true;
  302. else if (MO.isDef())
  303. LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
  304. continue;
  305. }
  306. LiveInterval &LI = LIS.getInterval(Reg);
  307. // Shrink read registers, unless it is likely to be expensive and
  308. // unlikely to change anything. We typically don't want to shrink the
  309. // PIC base register that has lots of uses everywhere.
  310. // Always shrink COPY uses that probably come from live range splitting.
  311. if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MO.isDef())) ||
  312. (MO.readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, MO))))
  313. ToShrink.insert(&LI);
  314. else if (MO.readsReg())
  315. HasLiveVRegUses = true;
  316. // Remove defined value.
  317. if (MO.isDef()) {
  318. if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr)
  319. TheDelegate->LRE_WillShrinkVirtReg(LI.reg());
  320. LIS.removeVRegDefAt(LI, Idx);
  321. if (LI.empty())
  322. RegsToErase.push_back(Reg);
  323. }
  324. }
  325. // Currently, we don't support DCE of physreg live ranges. If MI reads
  326. // any unreserved physregs, don't erase the instruction, but turn it into
  327. // a KILL instead. This way, the physreg live ranges don't end up
  328. // dangling.
  329. // FIXME: It would be better to have something like shrinkToUses() for
  330. // physregs. That could potentially enable more DCE and it would free up
  331. // the physreg. It would not happen often, though.
  332. if (ReadsPhysRegs) {
  333. MI->setDesc(TII.get(TargetOpcode::KILL));
  334. // Remove all operands that aren't physregs.
  335. for (unsigned i = MI->getNumOperands(); i; --i) {
  336. const MachineOperand &MO = MI->getOperand(i-1);
  337. if (MO.isReg() && MO.getReg().isPhysical())
  338. continue;
  339. MI->removeOperand(i-1);
  340. }
  341. LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
  342. } else {
  343. // If the dest of MI is an original reg and MI is reMaterializable,
  344. // don't delete the inst. Replace the dest with a new reg, and keep
  345. // the inst for remat of other siblings. The inst is saved in
  346. // LiveRangeEdit::DeadRemats and will be deleted after all the
  347. // allocations of the func are done.
  348. // However, immediately delete instructions which have unshrunk virtual
  349. // register uses. That may provoke RA to split an interval at the KILL
  350. // and later result in an invalid live segment end.
  351. if (isOrigDef && DeadRemats && !HasLiveVRegUses &&
  352. TII.isTriviallyReMaterializable(*MI)) {
  353. LiveInterval &NewLI = createEmptyIntervalFrom(Dest, false);
  354. VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator();
  355. VNInfo *VNI = NewLI.getNextValue(Idx, Alloc);
  356. NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI));
  357. if (DestSubReg) {
  358. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  359. auto *SR = NewLI.createSubRange(
  360. Alloc, TRI->getSubRegIndexLaneMask(DestSubReg));
  361. SR->addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(),
  362. SR->getNextValue(Idx, Alloc)));
  363. }
  364. pop_back();
  365. DeadRemats->insert(MI);
  366. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  367. MI->substituteRegister(Dest, NewLI.reg(), 0, TRI);
  368. MI->getOperand(0).setIsDead(true);
  369. } else {
  370. if (TheDelegate)
  371. TheDelegate->LRE_WillEraseInstruction(MI);
  372. LIS.RemoveMachineInstrFromMaps(*MI);
  373. MI->eraseFromParent();
  374. ++NumDCEDeleted;
  375. }
  376. }
  377. // Erase any virtregs that are now empty and unused. There may be <undef>
  378. // uses around. Keep the empty live range in that case.
  379. for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
  380. Register Reg = RegsToErase[i];
  381. if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
  382. ToShrink.remove(&LIS.getInterval(Reg));
  383. eraseVirtReg(Reg);
  384. }
  385. }
  386. }
  387. void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead,
  388. ArrayRef<Register> RegsBeingSpilled) {
  389. ToShrinkSet ToShrink;
  390. for (;;) {
  391. // Erase all dead defs.
  392. while (!Dead.empty())
  393. eliminateDeadDef(Dead.pop_back_val(), ToShrink);
  394. if (ToShrink.empty())
  395. break;
  396. // Shrink just one live interval. Then delete new dead defs.
  397. LiveInterval *LI = ToShrink.pop_back_val();
  398. if (foldAsLoad(LI, Dead))
  399. continue;
  400. Register VReg = LI->reg();
  401. if (TheDelegate)
  402. TheDelegate->LRE_WillShrinkVirtReg(VReg);
  403. if (!LIS.shrinkToUses(LI, &Dead))
  404. continue;
  405. // Don't create new intervals for a register being spilled.
  406. // The new intervals would have to be spilled anyway so its not worth it.
  407. // Also they currently aren't spilled so creating them and not spilling
  408. // them results in incorrect code.
  409. if (llvm::is_contained(RegsBeingSpilled, VReg))
  410. continue;
  411. // LI may have been separated, create new intervals.
  412. LI->RenumberValues();
  413. SmallVector<LiveInterval*, 8> SplitLIs;
  414. LIS.splitSeparateComponents(*LI, SplitLIs);
  415. if (!SplitLIs.empty())
  416. ++NumFracRanges;
  417. Register Original = VRM ? VRM->getOriginal(VReg) : Register();
  418. for (const LiveInterval *SplitLI : SplitLIs) {
  419. // If LI is an original interval that hasn't been split yet, make the new
  420. // intervals their own originals instead of referring to LI. The original
  421. // interval must contain all the split products, and LI doesn't.
  422. if (Original != VReg && Original != 0)
  423. VRM->setIsSplitFromReg(SplitLI->reg(), Original);
  424. if (TheDelegate)
  425. TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg(), VReg);
  426. }
  427. }
  428. }
  429. // Keep track of new virtual registers created via
  430. // MachineRegisterInfo::createVirtualRegister.
  431. void
  432. LiveRangeEdit::MRI_NoteNewVirtualRegister(Register VReg) {
  433. if (VRM)
  434. VRM->grow();
  435. NewRegs.push_back(VReg);
  436. }
  437. void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
  438. VirtRegAuxInfo &VRAI) {
  439. for (unsigned I = 0, Size = size(); I < Size; ++I) {
  440. LiveInterval &LI = LIS.getInterval(get(I));
  441. if (MRI.recomputeRegClass(LI.reg()))
  442. LLVM_DEBUG({
  443. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  444. dbgs() << "Inflated " << printReg(LI.reg()) << " to "
  445. << TRI->getRegClassName(MRI.getRegClass(LI.reg())) << '\n';
  446. });
  447. VRAI.calculateSpillWeightAndHint(LI);
  448. }
  449. }