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 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
32 /// setUsed - Set the register and its sub-registers as being used.
33 void RegScavenger::setUsed(unsigned Reg) {
34 RegsAvailable.reset(Reg);
36 for (MCSubRegIterator SubRegs(Reg, TRI); 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() {
50 ScavengeRestore = NULL;
52 // All registers started out unused.
58 // Live-in registers are in use.
59 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
60 E = MBB->livein_end(); I != E; ++I)
63 // Pristine CSRs are also unavailable.
64 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
65 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
69 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
70 MachineFunction &MF = *mbb->getParent();
71 const TargetMachine &TM = MF.getTarget();
72 TII = TM.getInstrInfo();
73 TRI = TM.getRegisterInfo();
74 MRI = &MF.getRegInfo();
76 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
79 // It is not possible to use the register scavenger after late optimization
80 // passes that don't preserve accurate liveness information.
81 assert(MRI->tracksLiveness() &&
82 "Cannot use register scavenger with inaccurate liveness");
86 NumPhysRegs = TRI->getNumRegs();
87 RegsAvailable.resize(NumPhysRegs);
88 KillRegs.resize(NumPhysRegs);
89 DefRegs.resize(NumPhysRegs);
91 // Create callee-saved registers bitvector.
92 CalleeSavedRegs.resize(NumPhysRegs);
93 const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
95 for (unsigned i = 0; CSRegs[i]; ++i)
96 CalleeSavedRegs.set(CSRegs[i]);
105 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
107 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
111 void RegScavenger::forward() {
117 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
118 MBBI = llvm::next(MBBI);
120 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
122 MachineInstr *MI = MBBI;
124 if (MI == ScavengeRestore) {
127 ScavengeRestore = NULL;
130 if (MI->isDebugValue())
133 // Find out which registers are early clobbered, killed, defined, and marked
134 // def-dead in this instruction.
135 // FIXME: The scavenger is not predication aware. If the instruction is
136 // predicated, conservatively assume "kill" markers do not actually kill the
137 // register. Similarly ignores "dead" markers.
138 bool isPred = TII->isPredicated(MI);
141 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
142 const MachineOperand &MO = MI->getOperand(i);
144 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
147 unsigned Reg = MO.getReg();
148 if (!Reg || isReserved(Reg))
152 // Ignore undef uses.
155 if (!isPred && MO.isKill())
156 addRegWithSubRegs(KillRegs, Reg);
159 if (!isPred && MO.isDead())
160 addRegWithSubRegs(KillRegs, Reg);
162 addRegWithSubRegs(DefRegs, Reg);
166 // Verify uses and defs.
168 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
169 const MachineOperand &MO = MI->getOperand(i);
172 unsigned Reg = MO.getReg();
173 if (!Reg || isReserved(Reg))
179 // Check if it's partial live: e.g.
180 // D0 = insert_subreg D0<undef>, S0
182 // The problem is the insert_subreg could be eliminated. The use of
183 // D0 is using a partially undef value. This is not *incorrect* since
184 // S1 is can be freely clobbered.
185 // Ideally we would like a way to model this, but leaving the
186 // insert_subreg around causes both correctness and performance issues.
187 bool SubUsed = false;
188 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
189 if (isUsed(*SubRegs)) {
194 MBB->getParent()->verify(NULL, "In Register Scavenger");
195 llvm_unreachable("Using an undefined register!");
202 // FIXME: Enable this once we've figured out how to correctly transfer
203 // implicit kills during codegen passes like the coalescer.
204 assert((KillRegs.test(Reg) || isUnused(Reg) ||
205 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
206 "Re-defining a live register!");
212 // Commit the changes.
217 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
218 used = RegsAvailable;
221 used |= MRI->getReservedRegs();
223 used.reset(MRI->getReservedRegs());
226 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
227 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
229 if (!isAliasUsed(*I)) {
230 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
237 /// getRegsAvailable - Return all available registers in the register class
239 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
240 BitVector Mask(TRI->getNumRegs());
241 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
243 if (!isAliasUsed(*I))
248 /// findSurvivorReg - Return the candidate register that is unused for the
249 /// longest after StargMII. UseMI is set to the instruction where the search
252 /// No more than InstrLimit instructions are inspected.
254 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
255 BitVector &Candidates,
257 MachineBasicBlock::iterator &UseMI) {
258 int Survivor = Candidates.find_first();
259 assert(Survivor > 0 && "No candidates for scavenging");
261 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
262 assert(StartMI != ME && "MI already at terminator");
263 MachineBasicBlock::iterator RestorePointMI = StartMI;
264 MachineBasicBlock::iterator MI = StartMI;
266 bool inVirtLiveRange = false;
267 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
268 if (MI->isDebugValue()) {
269 ++InstrLimit; // Don't count debug instructions
272 bool isVirtKillInsn = false;
273 bool isVirtDefInsn = false;
274 // Remove any candidates touched by instruction.
275 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
276 const MachineOperand &MO = MI->getOperand(i);
278 Candidates.clearBitsNotInMask(MO.getRegMask());
279 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
281 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
283 isVirtDefInsn = true;
284 else if (MO.isKill())
285 isVirtKillInsn = true;
288 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
289 Candidates.reset(*AI);
291 // If we're not in a virtual reg's live range, this is a valid
293 if (!inVirtLiveRange) RestorePointMI = MI;
295 // Update whether we're in the live range of a virtual register
296 if (isVirtKillInsn) inVirtLiveRange = false;
297 if (isVirtDefInsn) inVirtLiveRange = true;
299 // Was our survivor untouched by this instruction?
300 if (Candidates.test(Survivor))
303 // All candidates gone?
304 if (Candidates.none())
307 Survivor = Candidates.find_first();
309 // If we ran off the end, that's where we want to restore.
310 if (MI == ME) RestorePointMI = ME;
311 assert (RestorePointMI != StartMI &&
312 "No available scavenger restore location!");
314 // We ran out of candidates, so stop the search.
315 UseMI = RestorePointMI;
319 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
320 MachineBasicBlock::iterator I,
322 // Consider all allocatable registers in the register class initially
323 BitVector Candidates =
324 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
326 // Exclude all the registers being used by the instruction.
327 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
328 MachineOperand &MO = I->getOperand(i);
329 if (MO.isReg() && MO.getReg() != 0 &&
330 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
331 Candidates.reset(MO.getReg());
334 // Try to find a register that's unused if there is one, as then we won't
335 // have to spill. Search explicitly rather than masking out based on
336 // RegsAvailable, as RegsAvailable does not take aliases into account.
337 // That's what getRegsAvailable() is for.
338 BitVector Available = getRegsAvailable(RC);
339 Available &= Candidates;
341 Candidates = Available;
343 // Find the register whose use is furthest away.
344 MachineBasicBlock::iterator UseMI;
345 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
347 // If we found an unused register there is no reason to spill it.
348 if (!isAliasUsed(SReg)) {
349 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
353 assert(ScavengedReg == 0 &&
354 "Scavenger slot is live, unable to scavenge another register!");
356 // Avoid infinite regress
359 // If the target knows how to save/restore the register, let it do so;
360 // otherwise, use the emergency stack spill slot.
361 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
362 // Spill the scavenged register before I.
363 assert(ScavengingFrameIndex >= 0 &&
364 "Cannot scavenge register without an emergency spill slot!");
365 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
366 MachineBasicBlock::iterator II = prior(I);
367 TRI->eliminateFrameIndex(II, SPAdj, this);
369 // Restore the scavenged register before its use (or first terminator).
370 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
372 TRI->eliminateFrameIndex(II, SPAdj, this);
375 ScavengeRestore = prior(UseMI);
377 // Doing this here leads to infinite regress.
378 // ScavengedReg = SReg;
381 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<