1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===// 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 machine register scavenger. It can provide 11 // information, such as unused registers, at any point in a machine basic block. 12 // It also provides a mechanism to make registers available by evicting them to 13 // spill slots. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/CodeGen/RegisterScavenging.h" 18 #include "llvm/CodeGen/MachineBasicBlock.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineFunction.h" 21 #include "llvm/CodeGen/MachineInstr.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Target/TargetInstrInfo.h" 27 #include "llvm/Target/TargetRegisterInfo.h" 28 #include "llvm/Target/TargetSubtargetInfo.h" 29 using namespace llvm; 30 31 #define DEBUG_TYPE "reg-scavenging" 32 33 /// setUsed - Set the register units of this register as used. 34 void RegScavenger::setRegUsed(unsigned Reg, LaneBitmask LaneMask) { 35 for (MCRegUnitMaskIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) { 36 LaneBitmask UnitMask = (*RUI).second; 37 if (UnitMask == 0 || (LaneMask & UnitMask) != 0) 38 RegUnitsAvailable.reset((*RUI).first); 39 } 40 } 41 42 void RegScavenger::initRegState() { 43 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(), 44 IE = Scavenged.end(); I != IE; ++I) { 45 I->Reg = 0; 46 I->Restore = nullptr; 47 } 48 49 // All register units start out unused. 50 RegUnitsAvailable.set(); 51 52 // Live-in registers are in use. 53 for (const auto &LI : MBB->liveins()) 54 setRegUsed(LI.PhysReg, LI.LaneMask); 55 56 // Pristine CSRs are also unavailable. 57 const MachineFunction &MF = *MBB->getParent(); 58 BitVector PR = MF.getFrameInfo()->getPristineRegs(MF); 59 for (int I = PR.find_first(); I>0; I = PR.find_next(I)) 60 setRegUsed(I); 61 } 62 63 void RegScavenger::enterBasicBlock(MachineBasicBlock &MBB) { 64 MachineFunction &MF = *MBB.getParent(); 65 TII = MF.getSubtarget().getInstrInfo(); 66 TRI = MF.getSubtarget().getRegisterInfo(); 67 MRI = &MF.getRegInfo(); 68 69 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) && 70 "Target changed?"); 71 72 // It is not possible to use the register scavenger after late optimization 73 // passes that don't preserve accurate liveness information. 74 assert(MRI->tracksLiveness() && 75 "Cannot use register scavenger with inaccurate liveness"); 76 77 // Self-initialize. 78 if (!this->MBB) { 79 NumRegUnits = TRI->getNumRegUnits(); 80 RegUnitsAvailable.resize(NumRegUnits); 81 KillRegUnits.resize(NumRegUnits); 82 DefRegUnits.resize(NumRegUnits); 83 TmpRegUnits.resize(NumRegUnits); 84 } 85 this->MBB = &MBB; 86 87 initRegState(); 88 89 Tracking = false; 90 } 91 92 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) { 93 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) 94 BV.set(*RUI); 95 } 96 97 void RegScavenger::determineKillsAndDefs() { 98 assert(Tracking && "Must be tracking to determine kills and defs"); 99 100 MachineInstr *MI = MBBI; 101 assert(!MI->isDebugValue() && "Debug values have no kills or defs"); 102 103 // Find out which registers are early clobbered, killed, defined, and marked 104 // def-dead in this instruction. 105 KillRegUnits.reset(); 106 DefRegUnits.reset(); 107 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 108 const MachineOperand &MO = MI->getOperand(i); 109 if (MO.isRegMask()) { 110 111 TmpRegUnits.clear(); 112 for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) { 113 for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) { 114 if (MO.clobbersPhysReg(*RURI)) { 115 TmpRegUnits.set(RU); 116 break; 117 } 118 } 119 } 120 121 // Apply the mask. 122 KillRegUnits |= TmpRegUnits; 123 } 124 if (!MO.isReg()) 125 continue; 126 unsigned Reg = MO.getReg(); 127 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg)) 128 continue; 129 130 if (MO.isUse()) { 131 // Ignore undef uses. 132 if (MO.isUndef()) 133 continue; 134 if (MO.isKill()) 135 addRegUnits(KillRegUnits, Reg); 136 } else { 137 assert(MO.isDef()); 138 if (MO.isDead()) 139 addRegUnits(KillRegUnits, Reg); 140 else 141 addRegUnits(DefRegUnits, Reg); 142 } 143 } 144 } 145 146 void RegScavenger::unprocess() { 147 assert(Tracking && "Cannot unprocess because we're not tracking"); 148 149 MachineInstr *MI = MBBI; 150 if (!MI->isDebugValue()) { 151 determineKillsAndDefs(); 152 153 // Commit the changes. 154 setUsed(KillRegUnits); 155 setUnused(DefRegUnits); 156 } 157 158 if (MBBI == MBB->begin()) { 159 MBBI = MachineBasicBlock::iterator(nullptr); 160 Tracking = false; 161 } else 162 --MBBI; 163 } 164 165 void RegScavenger::forward() { 166 // Move ptr forward. 167 if (!Tracking) { 168 MBBI = MBB->begin(); 169 Tracking = true; 170 } else { 171 assert(MBBI != MBB->end() && "Already past the end of the basic block!"); 172 MBBI = std::next(MBBI); 173 } 174 assert(MBBI != MBB->end() && "Already at the end of the basic block!"); 175 176 MachineInstr *MI = MBBI; 177 178 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(), 179 IE = Scavenged.end(); I != IE; ++I) { 180 if (I->Restore != MI) 181 continue; 182 183 I->Reg = 0; 184 I->Restore = nullptr; 185 } 186 187 if (MI->isDebugValue()) 188 return; 189 190 determineKillsAndDefs(); 191 192 // Verify uses and defs. 193 #ifndef NDEBUG 194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 195 const MachineOperand &MO = MI->getOperand(i); 196 if (!MO.isReg()) 197 continue; 198 unsigned Reg = MO.getReg(); 199 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg)) 200 continue; 201 if (MO.isUse()) { 202 if (MO.isUndef()) 203 continue; 204 if (!isRegUsed(Reg)) { 205 // Check if it's partial live: e.g. 206 // D0 = insert_subreg D0<undef>, S0 207 // ... D0 208 // The problem is the insert_subreg could be eliminated. The use of 209 // D0 is using a partially undef value. This is not *incorrect* since 210 // S1 is can be freely clobbered. 211 // Ideally we would like a way to model this, but leaving the 212 // insert_subreg around causes both correctness and performance issues. 213 bool SubUsed = false; 214 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) 215 if (isRegUsed(*SubRegs)) { 216 SubUsed = true; 217 break; 218 } 219 bool SuperUsed = false; 220 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) { 221 if (isRegUsed(*SR)) { 222 SuperUsed = true; 223 break; 224 } 225 } 226 if (!SubUsed && !SuperUsed) { 227 MBB->getParent()->verify(nullptr, "In Register Scavenger"); 228 llvm_unreachable("Using an undefined register!"); 229 } 230 (void)SubUsed; 231 (void)SuperUsed; 232 } 233 } else { 234 assert(MO.isDef()); 235 #if 0 236 // FIXME: Enable this once we've figured out how to correctly transfer 237 // implicit kills during codegen passes like the coalescer. 238 assert((KillRegs.test(Reg) || isUnused(Reg) || 239 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && 240 "Re-defining a live register!"); 241 #endif 242 } 243 } 244 #endif // NDEBUG 245 246 // Commit the changes. 247 setUnused(KillRegUnits); 248 setUsed(DefRegUnits); 249 } 250 251 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const { 252 if (includeReserved && isReserved(Reg)) 253 return true; 254 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) 255 if (!RegUnitsAvailable.test(*RUI)) 256 return true; 257 return false; 258 } 259 260 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { 261 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 262 I != E; ++I) 263 if (!isRegUsed(*I)) { 264 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) << 265 "\n"); 266 return *I; 267 } 268 return 0; 269 } 270 271 /// getRegsAvailable - Return all available registers in the register class 272 /// in Mask. 273 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { 274 BitVector Mask(TRI->getNumRegs()); 275 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 276 I != E; ++I) 277 if (!isRegUsed(*I)) 278 Mask.set(*I); 279 return Mask; 280 } 281 282 /// findSurvivorReg - Return the candidate register that is unused for the 283 /// longest after StartMII. UseMI is set to the instruction where the search 284 /// stopped. 285 /// 286 /// No more than InstrLimit instructions are inspected. 287 /// 288 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, 289 BitVector &Candidates, 290 unsigned InstrLimit, 291 MachineBasicBlock::iterator &UseMI) { 292 int Survivor = Candidates.find_first(); 293 assert(Survivor > 0 && "No candidates for scavenging"); 294 295 MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); 296 assert(StartMI != ME && "MI already at terminator"); 297 MachineBasicBlock::iterator RestorePointMI = StartMI; 298 MachineBasicBlock::iterator MI = StartMI; 299 300 bool inVirtLiveRange = false; 301 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { 302 if (MI->isDebugValue()) { 303 ++InstrLimit; // Don't count debug instructions 304 continue; 305 } 306 bool isVirtKillInsn = false; 307 bool isVirtDefInsn = false; 308 // Remove any candidates touched by instruction. 309 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 310 const MachineOperand &MO = MI->getOperand(i); 311 if (MO.isRegMask()) 312 Candidates.clearBitsNotInMask(MO.getRegMask()); 313 if (!MO.isReg() || MO.isUndef() || !MO.getReg()) 314 continue; 315 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) { 316 if (MO.isDef()) 317 isVirtDefInsn = true; 318 else if (MO.isKill()) 319 isVirtKillInsn = true; 320 continue; 321 } 322 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) 323 Candidates.reset(*AI); 324 } 325 // If we're not in a virtual reg's live range, this is a valid 326 // restore point. 327 if (!inVirtLiveRange) RestorePointMI = MI; 328 329 // Update whether we're in the live range of a virtual register 330 if (isVirtKillInsn) inVirtLiveRange = false; 331 if (isVirtDefInsn) inVirtLiveRange = true; 332 333 // Was our survivor untouched by this instruction? 334 if (Candidates.test(Survivor)) 335 continue; 336 337 // All candidates gone? 338 if (Candidates.none()) 339 break; 340 341 Survivor = Candidates.find_first(); 342 } 343 // If we ran off the end, that's where we want to restore. 344 if (MI == ME) RestorePointMI = ME; 345 assert (RestorePointMI != StartMI && 346 "No available scavenger restore location!"); 347 348 // We ran out of candidates, so stop the search. 349 UseMI = RestorePointMI; 350 return Survivor; 351 } 352 353 static unsigned getFrameIndexOperandNum(MachineInstr *MI) { 354 unsigned i = 0; 355 while (!MI->getOperand(i).isFI()) { 356 ++i; 357 assert(i < MI->getNumOperands() && 358 "Instr doesn't have FrameIndex operand!"); 359 } 360 return i; 361 } 362 363 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC, 364 MachineBasicBlock::iterator I, 365 int SPAdj) { 366 // Consider all allocatable registers in the register class initially 367 BitVector Candidates = 368 TRI->getAllocatableSet(*I->getParent()->getParent(), RC); 369 370 // Exclude all the registers being used by the instruction. 371 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 372 MachineOperand &MO = I->getOperand(i); 373 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) && 374 !TargetRegisterInfo::isVirtualRegister(MO.getReg())) 375 Candidates.reset(MO.getReg()); 376 } 377 378 // Try to find a register that's unused if there is one, as then we won't 379 // have to spill. 380 BitVector Available = getRegsAvailable(RC); 381 Available &= Candidates; 382 if (Available.any()) 383 Candidates = Available; 384 385 // Find the register whose use is furthest away. 386 MachineBasicBlock::iterator UseMI; 387 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI); 388 389 // If we found an unused register there is no reason to spill it. 390 if (!isRegUsed(SReg)) { 391 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n"); 392 return SReg; 393 } 394 395 // Find an available scavenging slot. 396 unsigned SI; 397 for (SI = 0; SI < Scavenged.size(); ++SI) 398 if (Scavenged[SI].Reg == 0) 399 break; 400 401 if (SI == Scavenged.size()) { 402 // We need to scavenge a register but have no spill slot, the target 403 // must know how to do it (if not, we'll assert below). 404 Scavenged.push_back(ScavengedInfo()); 405 } 406 407 // Avoid infinite regress 408 Scavenged[SI].Reg = SReg; 409 410 // If the target knows how to save/restore the register, let it do so; 411 // otherwise, use the emergency stack spill slot. 412 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) { 413 // Spill the scavenged register before I. 414 assert(Scavenged[SI].FrameIndex >= 0 && 415 "Cannot scavenge register without an emergency spill slot!"); 416 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex, 417 RC, TRI); 418 MachineBasicBlock::iterator II = std::prev(I); 419 420 unsigned FIOperandNum = getFrameIndexOperandNum(II); 421 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this); 422 423 // Restore the scavenged register before its use (or first terminator). 424 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex, 425 RC, TRI); 426 II = std::prev(UseMI); 427 428 FIOperandNum = getFrameIndexOperandNum(II); 429 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this); 430 } 431 432 Scavenged[SI].Restore = std::prev(UseMI); 433 434 // Doing this here leads to infinite regress. 435 // Scavenged[SI].Reg = SReg; 436 437 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) << 438 "\n"); 439 440 return SReg; 441 } 442