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