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