VirtRegMap.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. //===- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map -----------------===//
  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 file implements the VirtRegMap class.
  10. //
  11. // It also contains implementations of the Spiller interface, which, given a
  12. // virtual register map and a machine function, eliminates all virtual
  13. // references by replacing them with physical register references - adding spill
  14. // code as necessary.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/CodeGen/VirtRegMap.h"
  18. #include "LiveDebugVariables.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/LiveInterval.h"
  22. #include "llvm/CodeGen/LiveIntervals.h"
  23. #include "llvm/CodeGen/LiveStacks.h"
  24. #include "llvm/CodeGen/MachineBasicBlock.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineFunctionPass.h"
  28. #include "llvm/CodeGen/MachineInstr.h"
  29. #include "llvm/CodeGen/MachineOperand.h"
  30. #include "llvm/CodeGen/MachineRegisterInfo.h"
  31. #include "llvm/CodeGen/SlotIndexes.h"
  32. #include "llvm/CodeGen/TargetFrameLowering.h"
  33. #include "llvm/CodeGen/TargetInstrInfo.h"
  34. #include "llvm/CodeGen/TargetOpcodes.h"
  35. #include "llvm/CodeGen/TargetRegisterInfo.h"
  36. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  37. #include "llvm/Config/llvm-config.h"
  38. #include "llvm/MC/LaneBitmask.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/Compiler.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include <cassert>
  44. #include <iterator>
  45. #include <utility>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "regalloc"
  48. STATISTIC(NumSpillSlots, "Number of spill slots allocated");
  49. STATISTIC(NumIdCopies, "Number of identity moves eliminated after rewriting");
  50. //===----------------------------------------------------------------------===//
  51. // VirtRegMap implementation
  52. //===----------------------------------------------------------------------===//
  53. char VirtRegMap::ID = 0;
  54. INITIALIZE_PASS(VirtRegMap, "virtregmap", "Virtual Register Map", false, false)
  55. bool VirtRegMap::runOnMachineFunction(MachineFunction &mf) {
  56. MRI = &mf.getRegInfo();
  57. TII = mf.getSubtarget().getInstrInfo();
  58. TRI = mf.getSubtarget().getRegisterInfo();
  59. MF = &mf;
  60. Virt2PhysMap.clear();
  61. Virt2StackSlotMap.clear();
  62. Virt2SplitMap.clear();
  63. Virt2ShapeMap.clear();
  64. grow();
  65. return false;
  66. }
  67. void VirtRegMap::grow() {
  68. unsigned NumRegs = MF->getRegInfo().getNumVirtRegs();
  69. Virt2PhysMap.resize(NumRegs);
  70. Virt2StackSlotMap.resize(NumRegs);
  71. Virt2SplitMap.resize(NumRegs);
  72. }
  73. void VirtRegMap::assignVirt2Phys(Register virtReg, MCPhysReg physReg) {
  74. assert(virtReg.isVirtual() && Register::isPhysicalRegister(physReg));
  75. assert(Virt2PhysMap[virtReg.id()] == NO_PHYS_REG &&
  76. "attempt to assign physical register to already mapped "
  77. "virtual register");
  78. assert(!getRegInfo().isReserved(physReg) &&
  79. "Attempt to map virtReg to a reserved physReg");
  80. Virt2PhysMap[virtReg.id()] = physReg;
  81. }
  82. unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
  83. unsigned Size = TRI->getSpillSize(*RC);
  84. Align Alignment = TRI->getSpillAlign(*RC);
  85. // Set preferred alignment if we are still able to realign the stack
  86. auto &ST = MF->getSubtarget();
  87. Align CurrentAlign = ST.getFrameLowering()->getStackAlign();
  88. if (Alignment > CurrentAlign && !ST.getRegisterInfo()->canRealignStack(*MF)) {
  89. Alignment = CurrentAlign;
  90. }
  91. int SS = MF->getFrameInfo().CreateSpillStackObject(Size, Alignment);
  92. ++NumSpillSlots;
  93. return SS;
  94. }
  95. bool VirtRegMap::hasPreferredPhys(Register VirtReg) const {
  96. Register Hint = MRI->getSimpleHint(VirtReg);
  97. if (!Hint.isValid())
  98. return false;
  99. if (Hint.isVirtual())
  100. Hint = getPhys(Hint);
  101. return Register(getPhys(VirtReg)) == Hint;
  102. }
  103. bool VirtRegMap::hasKnownPreference(Register VirtReg) const {
  104. std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(VirtReg);
  105. if (Register::isPhysicalRegister(Hint.second))
  106. return true;
  107. if (Register::isVirtualRegister(Hint.second))
  108. return hasPhys(Hint.second);
  109. return false;
  110. }
  111. int VirtRegMap::assignVirt2StackSlot(Register virtReg) {
  112. assert(virtReg.isVirtual());
  113. assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
  114. "attempt to assign stack slot to already spilled register");
  115. const TargetRegisterClass* RC = MF->getRegInfo().getRegClass(virtReg);
  116. return Virt2StackSlotMap[virtReg.id()] = createSpillSlot(RC);
  117. }
  118. void VirtRegMap::assignVirt2StackSlot(Register virtReg, int SS) {
  119. assert(virtReg.isVirtual());
  120. assert(Virt2StackSlotMap[virtReg.id()] == NO_STACK_SLOT &&
  121. "attempt to assign stack slot to already spilled register");
  122. assert((SS >= 0 ||
  123. (SS >= MF->getFrameInfo().getObjectIndexBegin())) &&
  124. "illegal fixed frame index");
  125. Virt2StackSlotMap[virtReg.id()] = SS;
  126. }
  127. void VirtRegMap::print(raw_ostream &OS, const Module*) const {
  128. OS << "********** REGISTER MAP **********\n";
  129. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  130. unsigned Reg = Register::index2VirtReg(i);
  131. if (Virt2PhysMap[Reg] != (unsigned)VirtRegMap::NO_PHYS_REG) {
  132. OS << '[' << printReg(Reg, TRI) << " -> "
  133. << printReg(Virt2PhysMap[Reg], TRI) << "] "
  134. << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  135. }
  136. }
  137. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  138. unsigned Reg = Register::index2VirtReg(i);
  139. if (Virt2StackSlotMap[Reg] != VirtRegMap::NO_STACK_SLOT) {
  140. OS << '[' << printReg(Reg, TRI) << " -> fi#" << Virt2StackSlotMap[Reg]
  141. << "] " << TRI->getRegClassName(MRI->getRegClass(Reg)) << "\n";
  142. }
  143. }
  144. OS << '\n';
  145. }
  146. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  147. LLVM_DUMP_METHOD void VirtRegMap::dump() const {
  148. print(dbgs());
  149. }
  150. #endif
  151. //===----------------------------------------------------------------------===//
  152. // VirtRegRewriter
  153. //===----------------------------------------------------------------------===//
  154. //
  155. // The VirtRegRewriter is the last of the register allocator passes.
  156. // It rewrites virtual registers to physical registers as specified in the
  157. // VirtRegMap analysis. It also updates live-in information on basic blocks
  158. // according to LiveIntervals.
  159. //
  160. namespace {
  161. class VirtRegRewriter : public MachineFunctionPass {
  162. MachineFunction *MF;
  163. const TargetRegisterInfo *TRI;
  164. const TargetInstrInfo *TII;
  165. MachineRegisterInfo *MRI;
  166. SlotIndexes *Indexes;
  167. LiveIntervals *LIS;
  168. VirtRegMap *VRM;
  169. LiveDebugVariables *DebugVars;
  170. DenseSet<Register> RewriteRegs;
  171. bool ClearVirtRegs;
  172. void rewrite();
  173. void addMBBLiveIns();
  174. bool readsUndefSubreg(const MachineOperand &MO) const;
  175. void addLiveInsForSubRanges(const LiveInterval &LI, MCRegister PhysReg) const;
  176. void handleIdentityCopy(MachineInstr &MI);
  177. void expandCopyBundle(MachineInstr &MI) const;
  178. bool subRegLiveThrough(const MachineInstr &MI, MCRegister SuperPhysReg) const;
  179. public:
  180. static char ID;
  181. VirtRegRewriter(bool ClearVirtRegs_ = true) :
  182. MachineFunctionPass(ID),
  183. ClearVirtRegs(ClearVirtRegs_) {}
  184. void getAnalysisUsage(AnalysisUsage &AU) const override;
  185. bool runOnMachineFunction(MachineFunction&) override;
  186. MachineFunctionProperties getSetProperties() const override {
  187. if (ClearVirtRegs) {
  188. return MachineFunctionProperties().set(
  189. MachineFunctionProperties::Property::NoVRegs);
  190. }
  191. return MachineFunctionProperties();
  192. }
  193. };
  194. } // end anonymous namespace
  195. char VirtRegRewriter::ID = 0;
  196. char &llvm::VirtRegRewriterID = VirtRegRewriter::ID;
  197. INITIALIZE_PASS_BEGIN(VirtRegRewriter, "virtregrewriter",
  198. "Virtual Register Rewriter", false, false)
  199. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  200. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  201. INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
  202. INITIALIZE_PASS_DEPENDENCY(LiveStacks)
  203. INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
  204. INITIALIZE_PASS_END(VirtRegRewriter, "virtregrewriter",
  205. "Virtual Register Rewriter", false, false)
  206. void VirtRegRewriter::getAnalysisUsage(AnalysisUsage &AU) const {
  207. AU.setPreservesCFG();
  208. AU.addRequired<LiveIntervals>();
  209. AU.addPreserved<LiveIntervals>();
  210. AU.addRequired<SlotIndexes>();
  211. AU.addPreserved<SlotIndexes>();
  212. AU.addRequired<LiveDebugVariables>();
  213. AU.addRequired<LiveStacks>();
  214. AU.addPreserved<LiveStacks>();
  215. AU.addRequired<VirtRegMap>();
  216. if (!ClearVirtRegs)
  217. AU.addPreserved<LiveDebugVariables>();
  218. MachineFunctionPass::getAnalysisUsage(AU);
  219. }
  220. bool VirtRegRewriter::runOnMachineFunction(MachineFunction &fn) {
  221. MF = &fn;
  222. TRI = MF->getSubtarget().getRegisterInfo();
  223. TII = MF->getSubtarget().getInstrInfo();
  224. MRI = &MF->getRegInfo();
  225. Indexes = &getAnalysis<SlotIndexes>();
  226. LIS = &getAnalysis<LiveIntervals>();
  227. VRM = &getAnalysis<VirtRegMap>();
  228. DebugVars = getAnalysisIfAvailable<LiveDebugVariables>();
  229. LLVM_DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
  230. << "********** Function: " << MF->getName() << '\n');
  231. LLVM_DEBUG(VRM->dump());
  232. // Add kill flags while we still have virtual registers.
  233. LIS->addKillFlags(VRM);
  234. // Live-in lists on basic blocks are required for physregs.
  235. addMBBLiveIns();
  236. // Rewrite virtual registers.
  237. rewrite();
  238. if (DebugVars && ClearVirtRegs) {
  239. // Write out new DBG_VALUE instructions.
  240. // We only do this if ClearVirtRegs is specified since this should be the
  241. // final run of the pass and we don't want to emit them multiple times.
  242. DebugVars->emitDebugValues(VRM);
  243. // All machine operands and other references to virtual registers have been
  244. // replaced. Remove the virtual registers and release all the transient data.
  245. VRM->clearAllVirt();
  246. MRI->clearVirtRegs();
  247. }
  248. return true;
  249. }
  250. void VirtRegRewriter::addLiveInsForSubRanges(const LiveInterval &LI,
  251. MCRegister PhysReg) const {
  252. assert(!LI.empty());
  253. assert(LI.hasSubRanges());
  254. using SubRangeIteratorPair =
  255. std::pair<const LiveInterval::SubRange *, LiveInterval::const_iterator>;
  256. SmallVector<SubRangeIteratorPair, 4> SubRanges;
  257. SlotIndex First;
  258. SlotIndex Last;
  259. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  260. SubRanges.push_back(std::make_pair(&SR, SR.begin()));
  261. if (!First.isValid() || SR.segments.front().start < First)
  262. First = SR.segments.front().start;
  263. if (!Last.isValid() || SR.segments.back().end > Last)
  264. Last = SR.segments.back().end;
  265. }
  266. // Check all mbb start positions between First and Last while
  267. // simulatenously advancing an iterator for each subrange.
  268. for (SlotIndexes::MBBIndexIterator MBBI = Indexes->findMBBIndex(First);
  269. MBBI != Indexes->MBBIndexEnd() && MBBI->first <= Last; ++MBBI) {
  270. SlotIndex MBBBegin = MBBI->first;
  271. // Advance all subrange iterators so that their end position is just
  272. // behind MBBBegin (or the iterator is at the end).
  273. LaneBitmask LaneMask;
  274. for (auto &RangeIterPair : SubRanges) {
  275. const LiveInterval::SubRange *SR = RangeIterPair.first;
  276. LiveInterval::const_iterator &SRI = RangeIterPair.second;
  277. while (SRI != SR->end() && SRI->end <= MBBBegin)
  278. ++SRI;
  279. if (SRI == SR->end())
  280. continue;
  281. if (SRI->start <= MBBBegin)
  282. LaneMask |= SR->LaneMask;
  283. }
  284. if (LaneMask.none())
  285. continue;
  286. MachineBasicBlock *MBB = MBBI->second;
  287. MBB->addLiveIn(PhysReg, LaneMask);
  288. }
  289. }
  290. // Compute MBB live-in lists from virtual register live ranges and their
  291. // assignments.
  292. void VirtRegRewriter::addMBBLiveIns() {
  293. for (unsigned Idx = 0, IdxE = MRI->getNumVirtRegs(); Idx != IdxE; ++Idx) {
  294. Register VirtReg = Register::index2VirtReg(Idx);
  295. if (MRI->reg_nodbg_empty(VirtReg))
  296. continue;
  297. LiveInterval &LI = LIS->getInterval(VirtReg);
  298. if (LI.empty() || LIS->intervalIsInOneMBB(LI))
  299. continue;
  300. // This is a virtual register that is live across basic blocks. Its
  301. // assigned PhysReg must be marked as live-in to those blocks.
  302. Register PhysReg = VRM->getPhys(VirtReg);
  303. if (PhysReg == VirtRegMap::NO_PHYS_REG) {
  304. // There may be no physical register assigned if only some register
  305. // classes were already allocated.
  306. assert(!ClearVirtRegs && "Unmapped virtual register");
  307. continue;
  308. }
  309. if (LI.hasSubRanges()) {
  310. addLiveInsForSubRanges(LI, PhysReg);
  311. } else {
  312. // Go over MBB begin positions and see if we have segments covering them.
  313. // The following works because segments and the MBBIndex list are both
  314. // sorted by slot indexes.
  315. SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin();
  316. for (const auto &Seg : LI) {
  317. I = Indexes->advanceMBBIndex(I, Seg.start);
  318. for (; I != Indexes->MBBIndexEnd() && I->first < Seg.end; ++I) {
  319. MachineBasicBlock *MBB = I->second;
  320. MBB->addLiveIn(PhysReg);
  321. }
  322. }
  323. }
  324. }
  325. // Sort and unique MBB LiveIns as we've not checked if SubReg/PhysReg were in
  326. // each MBB's LiveIns set before calling addLiveIn on them.
  327. for (MachineBasicBlock &MBB : *MF)
  328. MBB.sortUniqueLiveIns();
  329. }
  330. /// Returns true if the given machine operand \p MO only reads undefined lanes.
  331. /// The function only works for use operands with a subregister set.
  332. bool VirtRegRewriter::readsUndefSubreg(const MachineOperand &MO) const {
  333. // Shortcut if the operand is already marked undef.
  334. if (MO.isUndef())
  335. return true;
  336. Register Reg = MO.getReg();
  337. const LiveInterval &LI = LIS->getInterval(Reg);
  338. const MachineInstr &MI = *MO.getParent();
  339. SlotIndex BaseIndex = LIS->getInstructionIndex(MI);
  340. // This code is only meant to handle reading undefined subregisters which
  341. // we couldn't properly detect before.
  342. assert(LI.liveAt(BaseIndex) &&
  343. "Reads of completely dead register should be marked undef already");
  344. unsigned SubRegIdx = MO.getSubReg();
  345. assert(SubRegIdx != 0 && LI.hasSubRanges());
  346. LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(SubRegIdx);
  347. // See if any of the relevant subregister liveranges is defined at this point.
  348. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  349. if ((SR.LaneMask & UseMask).any() && SR.liveAt(BaseIndex))
  350. return false;
  351. }
  352. return true;
  353. }
  354. void VirtRegRewriter::handleIdentityCopy(MachineInstr &MI) {
  355. if (!MI.isIdentityCopy())
  356. return;
  357. LLVM_DEBUG(dbgs() << "Identity copy: " << MI);
  358. ++NumIdCopies;
  359. Register DstReg = MI.getOperand(0).getReg();
  360. // We may have deferred allocation of the virtual register, and the rewrite
  361. // regs code doesn't handle the liveness update.
  362. if (DstReg.isVirtual())
  363. return;
  364. RewriteRegs.insert(DstReg);
  365. // Copies like:
  366. // %r0 = COPY undef %r0
  367. // %al = COPY %al, implicit-def %eax
  368. // give us additional liveness information: The target (super-)register
  369. // must not be valid before this point. Replace the COPY with a KILL
  370. // instruction to maintain this information.
  371. if (MI.getOperand(1).isUndef() || MI.getNumOperands() > 2) {
  372. MI.setDesc(TII->get(TargetOpcode::KILL));
  373. LLVM_DEBUG(dbgs() << " replace by: " << MI);
  374. return;
  375. }
  376. if (Indexes)
  377. Indexes->removeSingleMachineInstrFromMaps(MI);
  378. MI.eraseFromBundle();
  379. LLVM_DEBUG(dbgs() << " deleted.\n");
  380. }
  381. /// The liverange splitting logic sometimes produces bundles of copies when
  382. /// subregisters are involved. Expand these into a sequence of copy instructions
  383. /// after processing the last in the bundle. Does not update LiveIntervals
  384. /// which we shouldn't need for this instruction anymore.
  385. void VirtRegRewriter::expandCopyBundle(MachineInstr &MI) const {
  386. if (!MI.isCopy() && !MI.isKill())
  387. return;
  388. if (MI.isBundledWithPred() && !MI.isBundledWithSucc()) {
  389. SmallVector<MachineInstr *, 2> MIs({&MI});
  390. // Only do this when the complete bundle is made out of COPYs and KILLs.
  391. MachineBasicBlock &MBB = *MI.getParent();
  392. for (MachineBasicBlock::reverse_instr_iterator I =
  393. std::next(MI.getReverseIterator()), E = MBB.instr_rend();
  394. I != E && I->isBundledWithSucc(); ++I) {
  395. if (!I->isCopy() && !I->isKill())
  396. return;
  397. MIs.push_back(&*I);
  398. }
  399. MachineInstr *FirstMI = MIs.back();
  400. auto anyRegsAlias = [](const MachineInstr *Dst,
  401. ArrayRef<MachineInstr *> Srcs,
  402. const TargetRegisterInfo *TRI) {
  403. for (const MachineInstr *Src : Srcs)
  404. if (Src != Dst)
  405. if (TRI->regsOverlap(Dst->getOperand(0).getReg(),
  406. Src->getOperand(1).getReg()))
  407. return true;
  408. return false;
  409. };
  410. // If any of the destination registers in the bundle of copies alias any of
  411. // the source registers, try to schedule the instructions to avoid any
  412. // clobbering.
  413. for (int E = MIs.size(), PrevE = E; E > 1; PrevE = E) {
  414. for (int I = E; I--; )
  415. if (!anyRegsAlias(MIs[I], makeArrayRef(MIs).take_front(E), TRI)) {
  416. if (I + 1 != E)
  417. std::swap(MIs[I], MIs[E - 1]);
  418. --E;
  419. }
  420. if (PrevE == E) {
  421. MF->getFunction().getContext().emitError(
  422. "register rewriting failed: cycle in copy bundle");
  423. break;
  424. }
  425. }
  426. MachineInstr *BundleStart = FirstMI;
  427. for (MachineInstr *BundledMI : llvm::reverse(MIs)) {
  428. // If instruction is in the middle of the bundle, move it before the
  429. // bundle starts, otherwise, just unbundle it. When we get to the last
  430. // instruction, the bundle will have been completely undone.
  431. if (BundledMI != BundleStart) {
  432. BundledMI->removeFromBundle();
  433. MBB.insert(BundleStart, BundledMI);
  434. } else if (BundledMI->isBundledWithSucc()) {
  435. BundledMI->unbundleFromSucc();
  436. BundleStart = &*std::next(BundledMI->getIterator());
  437. }
  438. if (Indexes && BundledMI != FirstMI)
  439. Indexes->insertMachineInstrInMaps(*BundledMI);
  440. }
  441. }
  442. }
  443. /// Check whether (part of) \p SuperPhysReg is live through \p MI.
  444. /// \pre \p MI defines a subregister of a virtual register that
  445. /// has been assigned to \p SuperPhysReg.
  446. bool VirtRegRewriter::subRegLiveThrough(const MachineInstr &MI,
  447. MCRegister SuperPhysReg) const {
  448. SlotIndex MIIndex = LIS->getInstructionIndex(MI);
  449. SlotIndex BeforeMIUses = MIIndex.getBaseIndex();
  450. SlotIndex AfterMIDefs = MIIndex.getBoundaryIndex();
  451. for (MCRegUnitIterator Unit(SuperPhysReg, TRI); Unit.isValid(); ++Unit) {
  452. const LiveRange &UnitRange = LIS->getRegUnit(*Unit);
  453. // If the regunit is live both before and after MI,
  454. // we assume it is live through.
  455. // Generally speaking, this is not true, because something like
  456. // "RU = op RU" would match that description.
  457. // However, we know that we are trying to assess whether
  458. // a def of a virtual reg, vreg, is live at the same time of RU.
  459. // If we are in the "RU = op RU" situation, that means that vreg
  460. // is defined at the same time as RU (i.e., "vreg, RU = op RU").
  461. // Thus, vreg and RU interferes and vreg cannot be assigned to
  462. // SuperPhysReg. Therefore, this situation cannot happen.
  463. if (UnitRange.liveAt(AfterMIDefs) && UnitRange.liveAt(BeforeMIUses))
  464. return true;
  465. }
  466. return false;
  467. }
  468. void VirtRegRewriter::rewrite() {
  469. bool NoSubRegLiveness = !MRI->subRegLivenessEnabled();
  470. SmallVector<Register, 8> SuperDeads;
  471. SmallVector<Register, 8> SuperDefs;
  472. SmallVector<Register, 8> SuperKills;
  473. for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
  474. MBBI != MBBE; ++MBBI) {
  475. LLVM_DEBUG(MBBI->print(dbgs(), Indexes));
  476. for (MachineInstr &MI : llvm::make_early_inc_range(MBBI->instrs())) {
  477. for (MachineOperand &MO : MI.operands()) {
  478. // Make sure MRI knows about registers clobbered by regmasks.
  479. if (MO.isRegMask())
  480. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  481. if (!MO.isReg() || !MO.getReg().isVirtual())
  482. continue;
  483. Register VirtReg = MO.getReg();
  484. MCRegister PhysReg = VRM->getPhys(VirtReg);
  485. if (PhysReg == VirtRegMap::NO_PHYS_REG)
  486. continue;
  487. assert(Register(PhysReg).isPhysical());
  488. RewriteRegs.insert(PhysReg);
  489. assert(!MRI->isReserved(PhysReg) && "Reserved register assignment");
  490. // Preserve semantics of sub-register operands.
  491. unsigned SubReg = MO.getSubReg();
  492. if (SubReg != 0) {
  493. if (NoSubRegLiveness || !MRI->shouldTrackSubRegLiveness(VirtReg)) {
  494. // A virtual register kill refers to the whole register, so we may
  495. // have to add implicit killed operands for the super-register. A
  496. // partial redef always kills and redefines the super-register.
  497. if ((MO.readsReg() && (MO.isDef() || MO.isKill())) ||
  498. (MO.isDef() && subRegLiveThrough(MI, PhysReg)))
  499. SuperKills.push_back(PhysReg);
  500. if (MO.isDef()) {
  501. // Also add implicit defs for the super-register.
  502. if (MO.isDead())
  503. SuperDeads.push_back(PhysReg);
  504. else
  505. SuperDefs.push_back(PhysReg);
  506. }
  507. } else {
  508. if (MO.isUse()) {
  509. if (readsUndefSubreg(MO))
  510. // We need to add an <undef> flag if the subregister is
  511. // completely undefined (and we are not adding super-register
  512. // defs).
  513. MO.setIsUndef(true);
  514. } else if (!MO.isDead()) {
  515. assert(MO.isDef());
  516. }
  517. }
  518. // The def undef and def internal flags only make sense for
  519. // sub-register defs, and we are substituting a full physreg. An
  520. // implicit killed operand from the SuperKills list will represent the
  521. // partial read of the super-register.
  522. if (MO.isDef()) {
  523. MO.setIsUndef(false);
  524. MO.setIsInternalRead(false);
  525. }
  526. // PhysReg operands cannot have subregister indexes.
  527. PhysReg = TRI->getSubReg(PhysReg, SubReg);
  528. assert(PhysReg.isValid() && "Invalid SubReg for physical register");
  529. MO.setSubReg(0);
  530. }
  531. // Rewrite. Note we could have used MachineOperand::substPhysReg(), but
  532. // we need the inlining here.
  533. MO.setReg(PhysReg);
  534. MO.setIsRenamable(true);
  535. }
  536. // Add any missing super-register kills after rewriting the whole
  537. // instruction.
  538. while (!SuperKills.empty())
  539. MI.addRegisterKilled(SuperKills.pop_back_val(), TRI, true);
  540. while (!SuperDeads.empty())
  541. MI.addRegisterDead(SuperDeads.pop_back_val(), TRI, true);
  542. while (!SuperDefs.empty())
  543. MI.addRegisterDefined(SuperDefs.pop_back_val(), TRI);
  544. LLVM_DEBUG(dbgs() << "> " << MI);
  545. expandCopyBundle(MI);
  546. // We can remove identity copies right now.
  547. handleIdentityCopy(MI);
  548. }
  549. }
  550. if (LIS) {
  551. // Don't bother maintaining accurate LiveIntervals for registers which were
  552. // already allocated.
  553. for (Register PhysReg : RewriteRegs) {
  554. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid();
  555. ++Units) {
  556. LIS->removeRegUnit(*Units);
  557. }
  558. }
  559. }
  560. RewriteRegs.clear();
  561. }
  562. FunctionPass *llvm::createVirtRegRewriter(bool ClearVirtRegs) {
  563. return new VirtRegRewriter(ClearVirtRegs);
  564. }