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/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetSubtargetInfo.h"
31 #define DEBUG_TYPE "reg-scavenging"
33 /// setUsed - Set the register units of this register as used.
34 void RegScavenger::setRegUsed(unsigned Reg) {
35 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
36 RegUnitsAvailable.reset(*RUI);
39 void RegScavenger::initRegState() {
40 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
41 IE = Scavenged.end(); I != IE; ++I) {
46 // All register units start out unused.
47 RegUnitsAvailable.set();
52 // Live-in registers are in use.
53 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
54 E = MBB->livein_end(); I != E; ++I)
57 // Pristine CSRs are also unavailable.
58 const MachineFunction &MF = *MBB->getParent();
59 BitVector PR = MF.getFrameInfo()->getPristineRegs(MF);
60 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
64 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
65 MachineFunction &MF = *mbb->getParent();
66 TII = MF.getSubtarget().getInstrInfo();
67 TRI = MF.getSubtarget().getRegisterInfo();
68 MRI = &MF.getRegInfo();
70 assert((NumRegUnits == 0 || NumRegUnits == TRI->getNumRegUnits()) &&
73 // It is not possible to use the register scavenger after late optimization
74 // passes that don't preserve accurate liveness information.
75 assert(MRI->tracksLiveness() &&
76 "Cannot use register scavenger with inaccurate liveness");
80 NumRegUnits = TRI->getNumRegUnits();
81 RegUnitsAvailable.resize(NumRegUnits);
82 KillRegUnits.resize(NumRegUnits);
83 DefRegUnits.resize(NumRegUnits);
84 TmpRegUnits.resize(NumRegUnits);
93 void RegScavenger::addRegUnits(BitVector &BV, unsigned Reg) {
94 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
98 void RegScavenger::determineKillsAndDefs() {
99 assert(Tracking && "Must be tracking to determine kills and defs");
101 MachineInstr *MI = MBBI;
102 assert(!MI->isDebugValue() && "Debug values have no kills or defs");
104 // Find out which registers are early clobbered, killed, defined, and marked
105 // def-dead in this instruction.
106 KillRegUnits.reset();
108 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
109 const MachineOperand &MO = MI->getOperand(i);
110 if (MO.isRegMask()) {
113 for (unsigned RU = 0, RUEnd = TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
114 for (MCRegUnitRootIterator RURI(RU, TRI); RURI.isValid(); ++RURI) {
115 if (MO.clobbersPhysReg(*RURI)) {
123 KillRegUnits |= TmpRegUnits;
127 unsigned Reg = MO.getReg();
128 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
132 // Ignore undef uses.
136 addRegUnits(KillRegUnits, Reg);
140 addRegUnits(KillRegUnits, Reg);
142 addRegUnits(DefRegUnits, Reg);
147 void RegScavenger::unprocess() {
148 assert(Tracking && "Cannot unprocess because we're not tracking");
150 MachineInstr *MI = MBBI;
151 if (!MI->isDebugValue()) {
152 determineKillsAndDefs();
154 // Commit the changes.
155 setUsed(KillRegUnits);
156 setUnused(DefRegUnits);
159 if (MBBI == MBB->begin()) {
160 MBBI = MachineBasicBlock::iterator(nullptr);
166 void RegScavenger::forward() {
172 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
173 MBBI = std::next(MBBI);
175 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
177 MachineInstr *MI = MBBI;
179 for (SmallVectorImpl<ScavengedInfo>::iterator I = Scavenged.begin(),
180 IE = Scavenged.end(); I != IE; ++I) {
181 if (I->Restore != MI)
185 I->Restore = nullptr;
188 if (MI->isDebugValue())
191 determineKillsAndDefs();
193 // Verify uses and defs.
195 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
196 const MachineOperand &MO = MI->getOperand(i);
199 unsigned Reg = MO.getReg();
200 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || isReserved(Reg))
205 if (!isRegUsed(Reg)) {
206 // Check if it's partial live: e.g.
207 // D0 = insert_subreg D0<undef>, S0
209 // The problem is the insert_subreg could be eliminated. The use of
210 // D0 is using a partially undef value. This is not *incorrect* since
211 // S1 is can be freely clobbered.
212 // Ideally we would like a way to model this, but leaving the
213 // insert_subreg around causes both correctness and performance issues.
214 bool SubUsed = false;
215 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
216 if (isRegUsed(*SubRegs)) {
220 bool SuperUsed = false;
221 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
222 if (isRegUsed(*SR)) {
227 if (!SubUsed && !SuperUsed) {
228 MBB->getParent()->verify(nullptr, "In Register Scavenger");
229 llvm_unreachable("Using an undefined register!");
237 // FIXME: Enable this once we've figured out how to correctly transfer
238 // implicit kills during codegen passes like the coalescer.
239 assert((KillRegs.test(Reg) || isUnused(Reg) ||
240 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
241 "Re-defining a live register!");
247 // Commit the changes.
248 setUnused(KillRegUnits);
249 setUsed(DefRegUnits);
252 bool RegScavenger::isRegUsed(unsigned Reg, bool includeReserved) const {
253 if (includeReserved && isReserved(Reg))
255 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI)
256 if (!RegUnitsAvailable.test(*RUI))
261 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
262 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
264 if (!isRegUsed(*I)) {
265 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
272 /// getRegsAvailable - Return all available registers in the register class
274 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
275 BitVector Mask(TRI->getNumRegs());
276 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
283 /// findSurvivorReg - Return the candidate register that is unused for the
284 /// longest after StartMII. UseMI is set to the instruction where the search
287 /// No more than InstrLimit instructions are inspected.
289 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
290 BitVector &Candidates,
292 MachineBasicBlock::iterator &UseMI) {
293 int Survivor = Candidates.find_first();
294 assert(Survivor > 0 && "No candidates for scavenging");
296 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
297 assert(StartMI != ME && "MI already at terminator");
298 MachineBasicBlock::iterator RestorePointMI = StartMI;
299 MachineBasicBlock::iterator MI = StartMI;
301 bool inVirtLiveRange = false;
302 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
303 if (MI->isDebugValue()) {
304 ++InstrLimit; // Don't count debug instructions
307 bool isVirtKillInsn = false;
308 bool isVirtDefInsn = false;
309 // Remove any candidates touched by instruction.
310 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
311 const MachineOperand &MO = MI->getOperand(i);
313 Candidates.clearBitsNotInMask(MO.getRegMask());
314 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
316 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
318 isVirtDefInsn = true;
319 else if (MO.isKill())
320 isVirtKillInsn = true;
323 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
324 Candidates.reset(*AI);
326 // If we're not in a virtual reg's live range, this is a valid
328 if (!inVirtLiveRange) RestorePointMI = MI;
330 // Update whether we're in the live range of a virtual register
331 if (isVirtKillInsn) inVirtLiveRange = false;
332 if (isVirtDefInsn) inVirtLiveRange = true;
334 // Was our survivor untouched by this instruction?
335 if (Candidates.test(Survivor))
338 // All candidates gone?
339 if (Candidates.none())
342 Survivor = Candidates.find_first();
344 // If we ran off the end, that's where we want to restore.
345 if (MI == ME) RestorePointMI = ME;
346 assert (RestorePointMI != StartMI &&
347 "No available scavenger restore location!");
349 // We ran out of candidates, so stop the search.
350 UseMI = RestorePointMI;
354 static unsigned getFrameIndexOperandNum(MachineInstr *MI) {
356 while (!MI->getOperand(i).isFI()) {
358 assert(i < MI->getNumOperands() &&
359 "Instr doesn't have FrameIndex operand!");
364 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
365 MachineBasicBlock::iterator I,
367 // Consider all allocatable registers in the register class initially
368 BitVector Candidates =
369 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
371 // Exclude all the registers being used by the instruction.
372 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
373 MachineOperand &MO = I->getOperand(i);
374 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
375 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
376 Candidates.reset(MO.getReg());
379 // Try to find a register that's unused if there is one, as then we won't
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 (!isRegUsed(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) <<