1 //===- RegisterScavenging.cpp - Machine register scavenging ---------------===// 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 /// \file 10 /// This file implements the machine register scavenger. It can provide 11 /// information, such as unused registers, at any point in a machine basic 12 /// block. It also provides a mechanism to make registers available by evicting 13 /// them to spill slots. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/CodeGen/RegisterScavenging.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/CodeGen/LiveRegUnits.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachineInstr.h" 28 #include "llvm/CodeGen/MachineOperand.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/TargetFrameLowering.h" 31 #include "llvm/CodeGen/TargetInstrInfo.h" 32 #include "llvm/CodeGen/TargetRegisterInfo.h" 33 #include "llvm/CodeGen/TargetSubtargetInfo.h" 34 #include "llvm/InitializePasses.h" 35 #include "llvm/MC/MCRegisterInfo.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cassert> 41 #include <iterator> 42 #include <limits> 43 #include <utility> 44 45 using namespace llvm; 46 47 #define DEBUG_TYPE "reg-scavenging" 48 49 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged"); 50 51 void RegScavenger::setRegUsed(Register Reg, LaneBitmask LaneMask) { 52 LiveUnits.addRegMasked(Reg, LaneMask); 53 } 54 55 void RegScavenger::init(MachineBasicBlock &MBB) { 56 MachineFunction &MF = *MBB.getParent(); 57 TII = MF.getSubtarget().getInstrInfo(); 58 TRI = MF.getSubtarget().getRegisterInfo(); 59 MRI = &MF.getRegInfo(); 60 LiveUnits.init(*TRI); 61 62 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) && 63 "Target changed?"); 64 65 // Self-initialize. 66 if (!this->MBB) { 67 NumRegUnits = TRI->getNumRegUnits(); 68 KillRegUnits.resize(NumRegUnits); 69 DefRegUnits.resize(NumRegUnits); 70 TmpRegUnits.resize(NumRegUnits); 71 } 72 this->MBB = &MBB; 73 74 for (ScavengedInfo &SI : Scavenged) { 75 SI.Reg = 0; 76 SI.Restore = nullptr; 77 } 78 79 Tracking = false; 80 } 81 82 void RegScavenger::enterBasicBlock(MachineBasicBlock &MBB) { 83 init(MBB); 84 LiveUnits.addLiveIns(MBB); 85 } 86 87 void RegScavenger::enterBasicBlockEnd(MachineBasicBlock &MBB) { 88 init(MBB); 89 LiveUnits.addLiveOuts(MBB); 90 91 // Move internal iterator at the last instruction of the block. 92 if (!MBB.empty()) { 93 MBBI = std::prev(MBB.end()); 94 Tracking = true; 95 } 96 } 97 98 void RegScavenger::addRegUnits(BitVector &BV, MCRegister Reg) { 99 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) 100 BV.set(*RUI); 101 } 102 103 void RegScavenger::removeRegUnits(BitVector &BV, MCRegister Reg) { 104 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) 105 BV.reset(*RUI); 106 } 107 108 void RegScavenger::determineKillsAndDefs() { 109 assert(Tracking && "Must be tracking to determine kills and defs"); 110 111 MachineInstr &MI = *MBBI; 112 assert(!MI.isDebugInstr() && "Debug values have no kills or defs"); 113 114 // Find out which registers are early clobbered, killed, defined, and marked 115 // def-dead in this instruction. 116 KillRegUnits.reset(); 117 DefRegUnits.reset(); 118 for (const MachineOperand &MO : MI.operands()) { 119 if (MO.isRegMask()) { 120 TmpRegUnits.reset(); 121 for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) { 122 for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) { 123 if (MO.clobbersPhysReg(*RURI)) { 124 TmpRegUnits.set(RU); 125 break; 126 } 127 } 128 } 129 130 // Apply the mask. 131 KillRegUnits |= TmpRegUnits; 132 } 133 if (!MO.isReg()) 134 continue; 135 if (!MO.getReg().isPhysical() || isReserved(MO.getReg())) 136 continue; 137 MCRegister Reg = MO.getReg().asMCReg(); 138 139 if (MO.isUse()) { 140 // Ignore undef uses. 141 if (MO.isUndef()) 142 continue; 143 if (MO.isKill()) 144 addRegUnits(KillRegUnits, Reg); 145 } else { 146 assert(MO.isDef()); 147 if (MO.isDead()) 148 addRegUnits(KillRegUnits, Reg); 149 else 150 addRegUnits(DefRegUnits, Reg); 151 } 152 } 153 } 154 155 void RegScavenger::forward() { 156 // Move ptr forward. 157 if (!Tracking) { 158 MBBI = MBB->begin(); 159 Tracking = true; 160 } else { 161 assert(MBBI != MBB->end() && "Already past the end of the basic block!"); 162 MBBI = std::next(MBBI); 163 } 164 assert(MBBI != MBB->end() && "Already at the end of the basic block!"); 165 166 MachineInstr &MI = *MBBI; 167 168 for (ScavengedInfo &I : Scavenged) { 169 if (I.Restore != &MI) 170 continue; 171 172 I.Reg = 0; 173 I.Restore = nullptr; 174 } 175 176 if (MI.isDebugOrPseudoInstr()) 177 return; 178 179 determineKillsAndDefs(); 180 181 // Verify uses and defs. 182 #ifndef NDEBUG 183 for (const MachineOperand &MO : MI.operands()) { 184 if (!MO.isReg()) 185 continue; 186 Register Reg = MO.getReg(); 187 if (!Reg.isPhysical() || isReserved(Reg)) 188 continue; 189 if (MO.isUse()) { 190 if (MO.isUndef()) 191 continue; 192 if (!isRegUsed(Reg)) { 193 // Check if it's partial live: e.g. 194 // D0 = insert_subreg undef D0, S0 195 // ... D0 196 // The problem is the insert_subreg could be eliminated. The use of 197 // D0 is using a partially undef value. This is not *incorrect* since 198 // S1 is can be freely clobbered. 199 // Ideally we would like a way to model this, but leaving the 200 // insert_subreg around causes both correctness and performance issues. 201 if (none_of(TRI->subregs(Reg), 202 [&](MCPhysReg SR) { return isRegUsed(SR); }) && 203 none_of(TRI->superregs(Reg), 204 [&](MCPhysReg SR) { return isRegUsed(SR); })) { 205 MBB->getParent()->verify(nullptr, "In Register Scavenger"); 206 llvm_unreachable("Using an undefined register!"); 207 } 208 } 209 } else { 210 assert(MO.isDef()); 211 #if 0 212 // FIXME: Enable this once we've figured out how to correctly transfer 213 // implicit kills during codegen passes like the coalescer. 214 assert((KillRegs.test(Reg) || isUnused(Reg) || 215 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) && 216 "Re-defining a live register!"); 217 #endif 218 } 219 } 220 #endif // NDEBUG 221 222 // Commit the changes. 223 setUnused(KillRegUnits); 224 setUsed(DefRegUnits); 225 } 226 227 void RegScavenger::backward() { 228 assert(Tracking && "Must be tracking to determine kills and defs"); 229 230 const MachineInstr &MI = *MBBI; 231 LiveUnits.stepBackward(MI); 232 233 // Expire scavenge spill frameindex uses. 234 for (ScavengedInfo &I : Scavenged) { 235 if (I.Restore == &MI) { 236 I.Reg = 0; 237 I.Restore = nullptr; 238 } 239 } 240 241 if (MBBI == MBB->begin()) { 242 MBBI = MachineBasicBlock::iterator(nullptr); 243 Tracking = false; 244 } else 245 --MBBI; 246 } 247 248 bool RegScavenger::isRegUsed(Register Reg, bool includeReserved) const { 249 if (isReserved(Reg)) 250 return includeReserved; 251 return !LiveUnits.available(Reg); 252 } 253 254 Register RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const { 255 for (Register Reg : *RC) { 256 if (!isRegUsed(Reg)) { 257 LLVM_DEBUG(dbgs() << "Scavenger found unused reg: " << printReg(Reg, TRI) 258 << "\n"); 259 return Reg; 260 } 261 } 262 return 0; 263 } 264 265 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) { 266 BitVector Mask(TRI->getNumRegs()); 267 for (Register Reg : *RC) 268 if (!isRegUsed(Reg)) 269 Mask.set(Reg); 270 return Mask; 271 } 272 273 Register RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI, 274 BitVector &Candidates, 275 unsigned InstrLimit, 276 MachineBasicBlock::iterator &UseMI) { 277 int Survivor = Candidates.find_first(); 278 assert(Survivor > 0 && "No candidates for scavenging"); 279 280 MachineBasicBlock::iterator ME = MBB->getFirstTerminator(); 281 assert(StartMI != ME && "MI already at terminator"); 282 MachineBasicBlock::iterator RestorePointMI = StartMI; 283 MachineBasicBlock::iterator MI = StartMI; 284 285 bool inVirtLiveRange = false; 286 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) { 287 if (MI->isDebugOrPseudoInstr()) { 288 ++InstrLimit; // Don't count debug instructions 289 continue; 290 } 291 bool isVirtKillInsn = false; 292 bool isVirtDefInsn = false; 293 // Remove any candidates touched by instruction. 294 for (const MachineOperand &MO : MI->operands()) { 295 if (MO.isRegMask()) 296 Candidates.clearBitsNotInMask(MO.getRegMask()); 297 if (!MO.isReg() || MO.isUndef() || !MO.getReg()) 298 continue; 299 if (MO.getReg().isVirtual()) { 300 if (MO.isDef()) 301 isVirtDefInsn = true; 302 else if (MO.isKill()) 303 isVirtKillInsn = true; 304 continue; 305 } 306 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) 307 Candidates.reset(*AI); 308 } 309 // If we're not in a virtual reg's live range, this is a valid 310 // restore point. 311 if (!inVirtLiveRange) RestorePointMI = MI; 312 313 // Update whether we're in the live range of a virtual register 314 if (isVirtKillInsn) inVirtLiveRange = false; 315 if (isVirtDefInsn) inVirtLiveRange = true; 316 317 // Was our survivor untouched by this instruction? 318 if (Candidates.test(Survivor)) 319 continue; 320 321 // All candidates gone? 322 if (Candidates.none()) 323 break; 324 325 Survivor = Candidates.find_first(); 326 } 327 // If we ran off the end, that's where we want to restore. 328 if (MI == ME) RestorePointMI = ME; 329 assert(RestorePointMI != StartMI && 330 "No available scavenger restore location!"); 331 332 // We ran out of candidates, so stop the search. 333 UseMI = RestorePointMI; 334 return Survivor; 335 } 336 337 /// Given the bitvector \p Available of free register units at position 338 /// \p From. Search backwards to find a register that is part of \p 339 /// Candidates and not used/clobbered until the point \p To. If there is 340 /// multiple candidates continue searching and pick the one that is not used/ 341 /// clobbered for the longest time. 342 /// Returns the register and the earliest position we know it to be free or 343 /// the position MBB.end() if no register is available. 344 static std::pair<MCPhysReg, MachineBasicBlock::iterator> 345 findSurvivorBackwards(const MachineRegisterInfo &MRI, 346 MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, 347 const LiveRegUnits &LiveOut, ArrayRef<MCPhysReg> AllocationOrder, 348 bool RestoreAfter) { 349 bool FoundTo = false; 350 MCPhysReg Survivor = 0; 351 MachineBasicBlock::iterator Pos; 352 MachineBasicBlock &MBB = *From->getParent(); 353 unsigned InstrLimit = 25; 354 unsigned InstrCountDown = InstrLimit; 355 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 356 LiveRegUnits Used(TRI); 357 358 assert(From->getParent() == To->getParent() && 359 "Target instruction is in other than current basic block, use " 360 "enterBasicBlockEnd first"); 361 362 for (MachineBasicBlock::iterator I = From;; --I) { 363 const MachineInstr &MI = *I; 364 365 Used.accumulate(MI); 366 367 if (I == To) { 368 // See if one of the registers in RC wasn't used so far. 369 for (MCPhysReg Reg : AllocationOrder) { 370 if (!MRI.isReserved(Reg) && Used.available(Reg) && 371 LiveOut.available(Reg)) 372 return std::make_pair(Reg, MBB.end()); 373 } 374 // Otherwise we will continue up to InstrLimit instructions to find 375 // the register which is not defined/used for the longest time. 376 FoundTo = true; 377 Pos = To; 378 // Note: It was fine so far to start our search at From, however now that 379 // we have to spill, and can only place the restore after From then 380 // add the regs used/defed by std::next(From) to the set. 381 if (RestoreAfter) 382 Used.accumulate(*std::next(From)); 383 } 384 if (FoundTo) { 385 // Don't search to FrameSetup instructions if we were searching from 386 // Non-FrameSetup instructions. Otherwise, the spill position may point 387 // before FrameSetup instructions. 388 if (!From->getFlag(MachineInstr::FrameSetup) && 389 MI.getFlag(MachineInstr::FrameSetup)) 390 break; 391 392 if (Survivor == 0 || !Used.available(Survivor)) { 393 MCPhysReg AvilableReg = 0; 394 for (MCPhysReg Reg : AllocationOrder) { 395 if (!MRI.isReserved(Reg) && Used.available(Reg)) { 396 AvilableReg = Reg; 397 break; 398 } 399 } 400 if (AvilableReg == 0) 401 break; 402 Survivor = AvilableReg; 403 } 404 if (--InstrCountDown == 0) 405 break; 406 407 // Keep searching when we find a vreg since the spilled register will 408 // be usefull for this other vreg as well later. 409 bool FoundVReg = false; 410 for (const MachineOperand &MO : MI.operands()) { 411 if (MO.isReg() && MO.getReg().isVirtual()) { 412 FoundVReg = true; 413 break; 414 } 415 } 416 if (FoundVReg) { 417 InstrCountDown = InstrLimit; 418 Pos = I; 419 } 420 if (I == MBB.begin()) 421 break; 422 } 423 assert(I != MBB.begin() && "Did not find target instruction while " 424 "iterating backwards"); 425 } 426 427 return std::make_pair(Survivor, Pos); 428 } 429 430 static unsigned getFrameIndexOperandNum(MachineInstr &MI) { 431 unsigned i = 0; 432 while (!MI.getOperand(i).isFI()) { 433 ++i; 434 assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!"); 435 } 436 return i; 437 } 438 439 RegScavenger::ScavengedInfo & 440 RegScavenger::spill(Register Reg, const TargetRegisterClass &RC, int SPAdj, 441 MachineBasicBlock::iterator Before, 442 MachineBasicBlock::iterator &UseMI) { 443 // Find an available scavenging slot with size and alignment matching 444 // the requirements of the class RC. 445 const MachineFunction &MF = *Before->getMF(); 446 const MachineFrameInfo &MFI = MF.getFrameInfo(); 447 unsigned NeedSize = TRI->getSpillSize(RC); 448 Align NeedAlign = TRI->getSpillAlign(RC); 449 450 unsigned SI = Scavenged.size(), Diff = std::numeric_limits<unsigned>::max(); 451 int FIB = MFI.getObjectIndexBegin(), FIE = MFI.getObjectIndexEnd(); 452 for (unsigned I = 0; I < Scavenged.size(); ++I) { 453 if (Scavenged[I].Reg != 0) 454 continue; 455 // Verify that this slot is valid for this register. 456 int FI = Scavenged[I].FrameIndex; 457 if (FI < FIB || FI >= FIE) 458 continue; 459 unsigned S = MFI.getObjectSize(FI); 460 Align A = MFI.getObjectAlign(FI); 461 if (NeedSize > S || NeedAlign > A) 462 continue; 463 // Avoid wasting slots with large size and/or large alignment. Pick one 464 // that is the best fit for this register class (in street metric). 465 // Picking a larger slot than necessary could happen if a slot for a 466 // larger register is reserved before a slot for a smaller one. When 467 // trying to spill a smaller register, the large slot would be found 468 // first, thus making it impossible to spill the larger register later. 469 unsigned D = (S - NeedSize) + (A.value() - NeedAlign.value()); 470 if (D < Diff) { 471 SI = I; 472 Diff = D; 473 } 474 } 475 476 if (SI == Scavenged.size()) { 477 // We need to scavenge a register but have no spill slot, the target 478 // must know how to do it (if not, we'll assert below). 479 Scavenged.push_back(ScavengedInfo(FIE)); 480 } 481 482 // Avoid infinite regress 483 Scavenged[SI].Reg = Reg; 484 485 // If the target knows how to save/restore the register, let it do so; 486 // otherwise, use the emergency stack spill slot. 487 if (!TRI->saveScavengerRegister(*MBB, Before, UseMI, &RC, Reg)) { 488 // Spill the scavenged register before \p Before. 489 int FI = Scavenged[SI].FrameIndex; 490 if (FI < FIB || FI >= FIE) { 491 report_fatal_error(Twine("Error while trying to spill ") + 492 TRI->getName(Reg) + " from class " + 493 TRI->getRegClassName(&RC) + 494 ": Cannot scavenge register without an emergency " 495 "spill slot!"); 496 } 497 TII->storeRegToStackSlot(*MBB, Before, Reg, true, FI, &RC, TRI, Register()); 498 MachineBasicBlock::iterator II = std::prev(Before); 499 500 unsigned FIOperandNum = getFrameIndexOperandNum(*II); 501 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this); 502 503 // Restore the scavenged register before its use (or first terminator). 504 TII->loadRegFromStackSlot(*MBB, UseMI, Reg, FI, &RC, TRI, Register()); 505 II = std::prev(UseMI); 506 507 FIOperandNum = getFrameIndexOperandNum(*II); 508 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this); 509 } 510 return Scavenged[SI]; 511 } 512 513 Register RegScavenger::scavengeRegister(const TargetRegisterClass *RC, 514 MachineBasicBlock::iterator I, 515 int SPAdj, bool AllowSpill) { 516 MachineInstr &MI = *I; 517 const MachineFunction &MF = *MI.getMF(); 518 // Consider all allocatable registers in the register class initially 519 BitVector Candidates = TRI->getAllocatableSet(MF, RC); 520 521 // Exclude all the registers being used by the instruction. 522 for (const MachineOperand &MO : MI.operands()) { 523 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) && 524 !MO.getReg().isVirtual()) 525 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) 526 Candidates.reset(*AI); 527 } 528 529 // If we have already scavenged some registers, remove them from the 530 // candidates. If we end up recursively calling eliminateFrameIndex, we don't 531 // want to be clobbering previously scavenged registers or their associated 532 // stack slots. 533 for (ScavengedInfo &SI : Scavenged) { 534 if (SI.Reg) { 535 if (isRegUsed(SI.Reg)) { 536 LLVM_DEBUG( 537 dbgs() << "Removing " << printReg(SI.Reg, TRI) << 538 " from scavenging candidates since it was already scavenged\n"); 539 for (MCRegAliasIterator AI(SI.Reg, TRI, true); AI.isValid(); ++AI) 540 Candidates.reset(*AI); 541 } 542 } 543 } 544 545 // Try to find a register that's unused if there is one, as then we won't 546 // have to spill. 547 BitVector Available = getRegsAvailable(RC); 548 Available &= Candidates; 549 if (Available.any()) 550 Candidates = Available; 551 552 // Find the register whose use is furthest away. 553 MachineBasicBlock::iterator UseMI; 554 Register SReg = findSurvivorReg(I, Candidates, 25, UseMI); 555 556 // If we found an unused register there is no reason to spill it. 557 if (!isRegUsed(SReg)) { 558 LLVM_DEBUG(dbgs() << "Scavenged register: " << printReg(SReg, TRI) << "\n"); 559 return SReg; 560 } 561 562 if (!AllowSpill) 563 return 0; 564 565 #ifndef NDEBUG 566 for (ScavengedInfo &SI : Scavenged) { 567 assert(SI.Reg != SReg && "scavenged a previously scavenged register"); 568 } 569 #endif 570 571 ScavengedInfo &Scavenged = spill(SReg, *RC, SPAdj, I, UseMI); 572 Scavenged.Restore = &*std::prev(UseMI); 573 574 LLVM_DEBUG(dbgs() << "Scavenged register (with spill): " 575 << printReg(SReg, TRI) << "\n"); 576 577 return SReg; 578 } 579 580 Register RegScavenger::scavengeRegisterBackwards(const TargetRegisterClass &RC, 581 MachineBasicBlock::iterator To, 582 bool RestoreAfter, int SPAdj, 583 bool AllowSpill) { 584 const MachineBasicBlock &MBB = *To->getParent(); 585 const MachineFunction &MF = *MBB.getParent(); 586 587 // Find the register whose use is furthest away. 588 MachineBasicBlock::iterator UseMI; 589 ArrayRef<MCPhysReg> AllocationOrder = RC.getRawAllocationOrder(MF); 590 std::pair<MCPhysReg, MachineBasicBlock::iterator> P = 591 findSurvivorBackwards(*MRI, MBBI, To, LiveUnits, AllocationOrder, 592 RestoreAfter); 593 MCPhysReg Reg = P.first; 594 MachineBasicBlock::iterator SpillBefore = P.second; 595 // Found an available register? 596 if (Reg != 0 && SpillBefore == MBB.end()) { 597 LLVM_DEBUG(dbgs() << "Scavenged free register: " << printReg(Reg, TRI) 598 << '\n'); 599 return Reg; 600 } 601 602 if (!AllowSpill) 603 return 0; 604 605 assert(Reg != 0 && "No register left to scavenge!"); 606 607 MachineBasicBlock::iterator ReloadAfter = 608 RestoreAfter ? std::next(MBBI) : MBBI; 609 MachineBasicBlock::iterator ReloadBefore = std::next(ReloadAfter); 610 if (ReloadBefore != MBB.end()) 611 LLVM_DEBUG(dbgs() << "Reload before: " << *ReloadBefore << '\n'); 612 ScavengedInfo &Scavenged = spill(Reg, RC, SPAdj, SpillBefore, ReloadBefore); 613 Scavenged.Restore = &*std::prev(SpillBefore); 614 LiveUnits.removeReg(Reg); 615 LLVM_DEBUG(dbgs() << "Scavenged register with spill: " << printReg(Reg, TRI) 616 << " until " << *SpillBefore); 617 return Reg; 618 } 619 620 /// Allocate a register for the virtual register \p VReg. The last use of 621 /// \p VReg is around the current position of the register scavenger \p RS. 622 /// \p ReserveAfter controls whether the scavenged register needs to be reserved 623 /// after the current instruction, otherwise it will only be reserved before the 624 /// current instruction. 625 static Register scavengeVReg(MachineRegisterInfo &MRI, RegScavenger &RS, 626 Register VReg, bool ReserveAfter) { 627 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 628 #ifndef NDEBUG 629 // Verify that all definitions and uses are in the same basic block. 630 const MachineBasicBlock *CommonMBB = nullptr; 631 // Real definition for the reg, re-definitions are not considered. 632 const MachineInstr *RealDef = nullptr; 633 for (MachineOperand &MO : MRI.reg_nodbg_operands(VReg)) { 634 MachineBasicBlock *MBB = MO.getParent()->getParent(); 635 if (CommonMBB == nullptr) 636 CommonMBB = MBB; 637 assert(MBB == CommonMBB && "All defs+uses must be in the same basic block"); 638 if (MO.isDef()) { 639 const MachineInstr &MI = *MO.getParent(); 640 if (!MI.readsRegister(VReg, &TRI)) { 641 assert((!RealDef || RealDef == &MI) && 642 "Can have at most one definition which is not a redefinition"); 643 RealDef = &MI; 644 } 645 } 646 } 647 assert(RealDef != nullptr && "Must have at least 1 Def"); 648 #endif 649 650 // We should only have one definition of the register. However to accommodate 651 // the requirements of two address code we also allow definitions in 652 // subsequent instructions provided they also read the register. That way 653 // we get a single contiguous lifetime. 654 // 655 // Definitions in MRI.def_begin() are unordered, search for the first. 656 MachineRegisterInfo::def_iterator FirstDef = llvm::find_if( 657 MRI.def_operands(VReg), [VReg, &TRI](const MachineOperand &MO) { 658 return !MO.getParent()->readsRegister(VReg, &TRI); 659 }); 660 assert(FirstDef != MRI.def_end() && 661 "Must have one definition that does not redefine vreg"); 662 MachineInstr &DefMI = *FirstDef->getParent(); 663 664 // The register scavenger will report a free register inserting an emergency 665 // spill/reload if necessary. 666 int SPAdj = 0; 667 const TargetRegisterClass &RC = *MRI.getRegClass(VReg); 668 Register SReg = RS.scavengeRegisterBackwards(RC, DefMI.getIterator(), 669 ReserveAfter, SPAdj); 670 MRI.replaceRegWith(VReg, SReg); 671 ++NumScavengedRegs; 672 return SReg; 673 } 674 675 /// Allocate (scavenge) vregs inside a single basic block. 676 /// Returns true if the target spill callback created new vregs and a 2nd pass 677 /// is necessary. 678 static bool scavengeFrameVirtualRegsInBlock(MachineRegisterInfo &MRI, 679 RegScavenger &RS, 680 MachineBasicBlock &MBB) { 681 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 682 RS.enterBasicBlockEnd(MBB); 683 684 unsigned InitialNumVirtRegs = MRI.getNumVirtRegs(); 685 bool NextInstructionReadsVReg = false; 686 for (MachineBasicBlock::iterator I = MBB.end(); I != MBB.begin(); ) { 687 --I; 688 // Move RegScavenger to the position between *I and *std::next(I). 689 RS.backward(I); 690 691 // Look for unassigned vregs in the uses of *std::next(I). 692 if (NextInstructionReadsVReg) { 693 MachineBasicBlock::iterator N = std::next(I); 694 const MachineInstr &NMI = *N; 695 for (const MachineOperand &MO : NMI.operands()) { 696 if (!MO.isReg()) 697 continue; 698 Register Reg = MO.getReg(); 699 // We only care about virtual registers and ignore virtual registers 700 // created by the target callbacks in the process (those will be handled 701 // in a scavenging round). 702 if (!Reg.isVirtual() || 703 Register::virtReg2Index(Reg) >= InitialNumVirtRegs) 704 continue; 705 if (!MO.readsReg()) 706 continue; 707 708 Register SReg = scavengeVReg(MRI, RS, Reg, true); 709 N->addRegisterKilled(SReg, &TRI, false); 710 RS.setRegUsed(SReg); 711 } 712 } 713 714 // Look for unassigned vregs in the defs of *I. 715 NextInstructionReadsVReg = false; 716 const MachineInstr &MI = *I; 717 for (const MachineOperand &MO : MI.operands()) { 718 if (!MO.isReg()) 719 continue; 720 Register Reg = MO.getReg(); 721 // Only vregs, no newly created vregs (see above). 722 if (!Reg.isVirtual() || 723 Register::virtReg2Index(Reg) >= InitialNumVirtRegs) 724 continue; 725 // We have to look at all operands anyway so we can precalculate here 726 // whether there is a reading operand. This allows use to skip the use 727 // step in the next iteration if there was none. 728 assert(!MO.isInternalRead() && "Cannot assign inside bundles"); 729 assert((!MO.isUndef() || MO.isDef()) && "Cannot handle undef uses"); 730 if (MO.readsReg()) { 731 NextInstructionReadsVReg = true; 732 } 733 if (MO.isDef()) { 734 Register SReg = scavengeVReg(MRI, RS, Reg, false); 735 I->addRegisterDead(SReg, &TRI, false); 736 } 737 } 738 } 739 #ifndef NDEBUG 740 for (const MachineOperand &MO : MBB.front().operands()) { 741 if (!MO.isReg() || !MO.getReg().isVirtual()) 742 continue; 743 assert(!MO.isInternalRead() && "Cannot assign inside bundles"); 744 assert((!MO.isUndef() || MO.isDef()) && "Cannot handle undef uses"); 745 assert(!MO.readsReg() && "Vreg use in first instruction not allowed"); 746 } 747 #endif 748 749 return MRI.getNumVirtRegs() != InitialNumVirtRegs; 750 } 751 752 void llvm::scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS) { 753 // FIXME: Iterating over the instruction stream is unnecessary. We can simply 754 // iterate over the vreg use list, which at this point only contains machine 755 // operands for which eliminateFrameIndex need a new scratch reg. 756 MachineRegisterInfo &MRI = MF.getRegInfo(); 757 // Shortcut. 758 if (MRI.getNumVirtRegs() == 0) { 759 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs); 760 return; 761 } 762 763 // Run through the instructions and find any virtual registers. 764 for (MachineBasicBlock &MBB : MF) { 765 if (MBB.empty()) 766 continue; 767 768 bool Again = scavengeFrameVirtualRegsInBlock(MRI, RS, MBB); 769 if (Again) { 770 LLVM_DEBUG(dbgs() << "Warning: Required two scavenging passes for block " 771 << MBB.getName() << '\n'); 772 Again = scavengeFrameVirtualRegsInBlock(MRI, RS, MBB); 773 // The target required a 2nd run (because it created new vregs while 774 // spilling). Refuse to do another pass to keep compiletime in check. 775 if (Again) 776 report_fatal_error("Incomplete scavenging after 2nd pass"); 777 } 778 } 779 780 MRI.clearVirtRegs(); 781 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs); 782 } 783 784 namespace { 785 786 /// This class runs register scavenging independ of the PrologEpilogInserter. 787 /// This is used in for testing. 788 class ScavengerTest : public MachineFunctionPass { 789 public: 790 static char ID; 791 792 ScavengerTest() : MachineFunctionPass(ID) {} 793 794 bool runOnMachineFunction(MachineFunction &MF) override { 795 const TargetSubtargetInfo &STI = MF.getSubtarget(); 796 const TargetFrameLowering &TFL = *STI.getFrameLowering(); 797 798 RegScavenger RS; 799 // Let's hope that calling those outside of PrologEpilogueInserter works 800 // well enough to initialize the scavenger with some emergency spillslots 801 // for the target. 802 BitVector SavedRegs; 803 TFL.determineCalleeSaves(MF, SavedRegs, &RS); 804 TFL.processFunctionBeforeFrameFinalized(MF, &RS); 805 806 // Let's scavenge the current function 807 scavengeFrameVirtualRegs(MF, RS); 808 return true; 809 } 810 }; 811 812 } // end anonymous namespace 813 814 char ScavengerTest::ID; 815 816 INITIALIZE_PASS(ScavengerTest, "scavenger-test", 817 "Scavenge virtual registers inside basic blocks", false, false) 818