VirtRegMap.cpp 21 KB

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