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