1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
15 //===----------------------------------------------------------------------===//
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/TargetMachine.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
31 #define DEBUG_TYPE "reg-scavenging"
33 /// setUsed - Set the register and its sub-registers as being used.
34 void RegScavenger::setUsed(unsigned Reg) {
35 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
36 SubRegs.isValid(); ++SubRegs)
37 RegsAvailable.reset(*SubRegs);
40 bool RegScavenger::isAliasUsed(unsigned Reg) const {
41 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
42 if (isUsed(*AI, *AI == Reg))
47 void RegScavenger::initRegState() {
48 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
49 IE = Scavenged.end(); I != IE; ++I) {
54 // All registers started out unused.
60 // Live-in registers are in use.
61 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
62 E = MBB->livein_end(); I != E; ++I)
65 // Pristine CSRs are also unavailable.
66 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
67 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
71 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
72 MachineFunction &MF = *mbb->getParent();
73 const TargetMachine &TM = MF.getTarget();
74 TII = TM.getInstrInfo();
75 TRI = TM.getRegisterInfo();
76 MRI = &MF.getRegInfo();
78 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
81 // It is not possible to use the register scavenger after late optimization
82 // passes that don't preserve accurate liveness information.
83 assert(MRI->tracksLiveness() &&
84 "Cannot use register scavenger with inaccurate liveness");
88 NumPhysRegs = TRI->getNumRegs();
89 RegsAvailable.resize(NumPhysRegs);
90 KillRegs.resize(NumPhysRegs);
91 DefRegs.resize(NumPhysRegs);
93 // Create callee-saved registers bitvector.
94 CalleeSavedRegs.resize(NumPhysRegs);
95 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
96 if (CSRegs != nullptr)
97 for (unsigned i = 0; CSRegs[i]; ++i)
98 CalleeSavedRegs.set(CSRegs[i]);
107 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
108 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
109 SubRegs.isValid(); ++SubRegs)
113 void RegScavenger::determineKillsAndDefs() {
114 assert(Tracking && "Must be tracking to determine kills and defs");
116 MachineInstr *MI = MBBI;
117 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
119 // Find out which registers are early clobbered, killed, defined, and marked
120 // def-dead in this instruction.
121 // FIXME: The scavenger is not predication aware. If the instruction is
122 // predicated, conservatively assume "kill" markers do not actually kill the
123 // register. Similarly ignores "dead" markers.
124 bool isPred = TII->isPredicated(MI);
127 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
128 const MachineOperand &MO = MI->getOperand(i);
130 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
133 unsigned Reg = MO.getReg();
134 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
138 // Ignore undef uses.
141 if (!isPred && MO.isKill())
142 addRegWithSubRegs(KillRegs, Reg);
145 if (!isPred && MO.isDead())
146 addRegWithSubRegs(KillRegs, Reg);
148 addRegWithSubRegs(DefRegs, Reg);
153 void RegScavenger::unprocess() {
154 assert(Tracking && "Cannot unprocess because we're not tracking");
156 MachineInstr *MI = MBBI;
157 if (!MI->isDebugValue()) {
158 determineKillsAndDefs();
160 // Commit the changes.
165 if (MBBI == MBB->begin()) {
166 MBBI = MachineBasicBlock::iterator(nullptr);
172 void RegScavenger::forward() {
178 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
179 MBBI = std::next(MBBI);
181 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
183 MachineInstr *MI = MBBI;
185 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
186 IE = Scavenged.end(); I != IE; ++I) {
187 if (I->Restore != MI)
191 I->Restore = nullptr;
194 if (MI->isDebugValue())
197 determineKillsAndDefs();
199 // Verify uses and defs.
201 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
202 const MachineOperand &MO = MI->getOperand(i);
205 unsigned Reg = MO.getReg();
206 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
212 // Check if it's partial live: e.g.
213 // D0 = insert_subreg D0<undef>, S0
215 // The problem is the insert_subreg could be eliminated. The use of
216 // D0 is using a partially undef value. This is not *incorrect* since
217 // S1 is can be freely clobbered.
218 // Ideally we would like a way to model this, but leaving the
219 // insert_subreg around causes both correctness and performance issues.
220 bool SubUsed = false;
221 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
222 if (isUsed(*SubRegs)) {
227 MBB->getParent()->verify(nullptr, "In Register Scavenger");
228 llvm_unreachable("Using an undefined register!");
235 // FIXME: Enable this once we've figured out how to correctly transfer
236 // implicit kills during codegen passes like the coalescer.
237 assert((KillRegs.test(Reg) || isUnused(Reg) ||
238 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
239 "Re-defining a live register!");
245 // Commit the changes.
250 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
251 used = RegsAvailable;
254 used |= MRI->getReservedRegs();
256 used.reset(MRI->getReservedRegs());
259 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
260 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
262 if (!isAliasUsed(*I)) {
263 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
270 /// getRegsAvailable - Return all available registers in the register class
272 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
273 BitVector Mask(TRI->getNumRegs());
274 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
276 if (!isAliasUsed(*I))
281 /// findSurvivorReg - Return the candidate register that is unused for the
282 /// longest after StargMII. UseMI is set to the instruction where the search
285 /// No more than InstrLimit instructions are inspected.
287 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
288 BitVector &Candidates,
290 MachineBasicBlock::iterator &UseMI) {
291 int Survivor = Candidates.find_first();
292 assert(Survivor > 0 && "No candidates for scavenging");
294 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
295 assert(StartMI != ME && "MI already at terminator");
296 MachineBasicBlock::iterator RestorePointMI = StartMI;
297 MachineBasicBlock::iterator MI = StartMI;
299 bool inVirtLiveRange = false;
300 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
301 if (MI->isDebugValue()) {
302 ++InstrLimit; // Don't count debug instructions
305 bool isVirtKillInsn = false;
306 bool isVirtDefInsn = false;
307 // Remove any candidates touched by instruction.
308 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
309 const MachineOperand &MO = MI->getOperand(i);
311 Candidates.clearBitsNotInMask(MO.getRegMask());
312 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
314 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
316 isVirtDefInsn = true;
317 else if (MO.isKill())
318 isVirtKillInsn = true;
321 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
322 Candidates.reset(*AI);
324 // If we're not in a virtual reg's live range, this is a valid
326 if (!inVirtLiveRange) RestorePointMI = MI;
328 // Update whether we're in the live range of a virtual register
329 if (isVirtKillInsn) inVirtLiveRange = false;
330 if (isVirtDefInsn) inVirtLiveRange = true;
332 // Was our survivor untouched by this instruction?
333 if (Candidates.test(Survivor))
336 // All candidates gone?
337 if (Candidates.none())
340 Survivor = Candidates.find_first();
342 // If we ran off the end, that's where we want to restore.
343 if (MI == ME) RestorePointMI = ME;
344 assert (RestorePointMI != StartMI &&
345 "No available scavenger restore location!");
347 // We ran out of candidates, so stop the search.
348 UseMI = RestorePointMI;
352 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
354 while (!MI->getOperand(i).isFI()) {
356 assert(i < MI->getNumOperands() &&
357 "Instr doesn't have FrameIndex operand!");
362 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
363 MachineBasicBlock::iterator I,
365 // Consider all allocatable registers in the register class initially
366 BitVector Candidates =
367 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
369 // Exclude all the registers being used by the instruction.
370 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
371 MachineOperand &MO = I->getOperand(i);
372 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
373 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
374 Candidates.reset(MO.getReg());
377 // Try to find a register that's unused if there is one, as then we won't
378 // have to spill. Search explicitly rather than masking out based on
379 // RegsAvailable, as RegsAvailable does not take aliases into account.
380 // That's what getRegsAvailable() is for.
381 BitVector Available = getRegsAvailable(RC);
382 Available &= Candidates;
384 Candidates = Available;
386 // Find the register whose use is furthest away.
387 MachineBasicBlock::iterator UseMI;
388 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
390 // If we found an unused register there is no reason to spill it.
391 if (!isAliasUsed(SReg)) {
392 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
396 // Find an available scavenging slot.
398 for (SI = 0; SI < Scavenged.size(); ++SI)
399 if (Scavenged[SI].Reg == 0)
402 if (SI == Scavenged.size()) {
403 // We need to scavenge a register but have no spill slot, the target
404 // must know how to do it (if not, we'll assert below).
405 Scavenged.push_back(ScavengedInfo());
408 // Avoid infinite regress
409 Scavenged[SI].Reg = SReg;
411 // If the target knows how to save/restore the register, let it do so;
412 // otherwise, use the emergency stack spill slot.
413 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
414 // Spill the scavenged register before I.
415 assert(Scavenged[SI].FrameIndex >= 0 &&
416 "Cannot scavenge register without an emergency spill slot!");
417 TII->storeRegToStackSlot(*MBB, I, SReg, true, Scavenged[SI].FrameIndex,
419 MachineBasicBlock::iterator II = std::prev(I);
421 unsigned FIOperandNum = getFrameIndexOperandNum(II);
422 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
424 // Restore the scavenged register before its use (or first terminator).
425 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, Scavenged[SI].FrameIndex,
427 II = std::prev(UseMI);
429 FIOperandNum = getFrameIndexOperandNum(II);
430 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum, this);
433 Scavenged[SI].Restore = std::prev(UseMI);
435 // Doing this here leads to infinite regress.
436 // Scavenged[SI].Reg = SReg;
438 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<