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"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
36 /// setUsed - Set the register and its sub-registers as being used.
37 void RegScavenger::setUsed(unsigned Reg) {
38 RegsAvailable.reset(Reg);
40 for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
41 unsigned SubReg = *SubRegs; ++SubRegs)
42 RegsAvailable.reset(SubReg);
45 bool RegScavenger::isAliasUsed(unsigned Reg) const {
48 for (const uint16_t *R = TRI->getAliasSet(Reg); *R; ++R)
54 void RegScavenger::initRegState() {
57 ScavengeRestore = NULL;
59 // All registers started out unused.
65 // Live-in registers are in use.
66 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
67 E = MBB->livein_end(); I != E; ++I)
70 // Pristine CSRs are also unavailable.
71 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
72 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
76 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
77 MachineFunction &MF = *mbb->getParent();
78 const TargetMachine &TM = MF.getTarget();
79 TII = TM.getInstrInfo();
80 TRI = TM.getRegisterInfo();
81 MRI = &MF.getRegInfo();
83 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
88 NumPhysRegs = TRI->getNumRegs();
89 RegsAvailable.resize(NumPhysRegs);
90 KillRegs.resize(NumPhysRegs);
91 DefRegs.resize(NumPhysRegs);
93 // Create reserved registers bitvector.
94 ReservedRegs = TRI->getReservedRegs(MF);
96 // Create callee-saved registers bitvector.
97 CalleeSavedRegs.resize(NumPhysRegs);
98 const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
100 for (unsigned i = 0; CSRegs[i]; ++i)
101 CalleeSavedRegs.set(CSRegs[i]);
110 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
112 for (const uint16_t *R = TRI->getSubRegisters(Reg); *R; R++)
116 void RegScavenger::forward() {
122 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
123 MBBI = llvm::next(MBBI);
125 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
127 MachineInstr *MI = MBBI;
129 if (MI == ScavengeRestore) {
132 ScavengeRestore = NULL;
135 if (MI->isDebugValue())
138 // Find out which registers are early clobbered, killed, defined, and marked
139 // def-dead in this instruction.
140 // FIXME: The scavenger is not predication aware. If the instruction is
141 // predicated, conservatively assume "kill" markers do not actually kill the
142 // register. Similarly ignores "dead" markers.
143 bool isPred = TII->isPredicated(MI);
146 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
147 const MachineOperand &MO = MI->getOperand(i);
149 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
152 unsigned Reg = MO.getReg();
153 if (!Reg || isReserved(Reg))
157 // Ignore undef uses.
160 if (!isPred && MO.isKill())
161 addRegWithSubRegs(KillRegs, Reg);
164 if (!isPred && MO.isDead())
165 addRegWithSubRegs(KillRegs, Reg);
167 addRegWithSubRegs(DefRegs, Reg);
171 // Verify uses and defs.
173 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
174 const MachineOperand &MO = MI->getOperand(i);
177 unsigned Reg = MO.getReg();
178 if (!Reg || isReserved(Reg))
184 // Check if it's partial live: e.g.
185 // D0 = insert_subreg D0<undef>, S0
187 // The problem is the insert_subreg could be eliminated. The use of
188 // D0 is using a partially undef value. This is not *incorrect* since
189 // S1 is can be freely clobbered.
190 // Ideally we would like a way to model this, but leaving the
191 // insert_subreg around causes both correctness and performance issues.
192 bool SubUsed = false;
193 for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
194 unsigned SubReg = *SubRegs; ++SubRegs)
195 if (isUsed(SubReg)) {
200 MBB->getParent()->verify(NULL, "In Register Scavenger");
201 llvm_unreachable("Using an undefined register!");
208 // FIXME: Enable this once we've figured out how to correctly transfer
209 // implicit kills during codegen passes like the coalescer.
210 assert((KillRegs.test(Reg) || isUnused(Reg) ||
211 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
212 "Re-defining a live register!");
218 // Commit the changes.
223 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
224 used = RegsAvailable;
227 used |= ReservedRegs;
229 used.reset(ReservedRegs);
232 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
233 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
235 if (!isAliasUsed(*I)) {
236 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
243 /// getRegsAvailable - Return all available registers in the register class
245 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
246 BitVector Mask(TRI->getNumRegs());
247 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
249 if (!isAliasUsed(*I))
254 /// findSurvivorReg - Return the candidate register that is unused for the
255 /// longest after StargMII. UseMI is set to the instruction where the search
258 /// No more than InstrLimit instructions are inspected.
260 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
261 BitVector &Candidates,
263 MachineBasicBlock::iterator &UseMI) {
264 int Survivor = Candidates.find_first();
265 assert(Survivor > 0 && "No candidates for scavenging");
267 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
268 assert(StartMI != ME && "MI already at terminator");
269 MachineBasicBlock::iterator RestorePointMI = StartMI;
270 MachineBasicBlock::iterator MI = StartMI;
272 bool inVirtLiveRange = false;
273 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
274 if (MI->isDebugValue()) {
275 ++InstrLimit; // Don't count debug instructions
278 bool isVirtKillInsn = false;
279 bool isVirtDefInsn = false;
280 // Remove any candidates touched by instruction.
281 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282 const MachineOperand &MO = MI->getOperand(i);
284 Candidates.clearBitsNotInMask(MO.getRegMask());
285 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
287 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
289 isVirtDefInsn = true;
290 else if (MO.isKill())
291 isVirtKillInsn = true;
294 Candidates.reset(MO.getReg());
295 for (const uint16_t *R = TRI->getAliasSet(MO.getReg()); *R; R++)
296 Candidates.reset(*R);
298 // If we're not in a virtual reg's live range, this is a valid
300 if (!inVirtLiveRange) RestorePointMI = MI;
302 // Update whether we're in the live range of a virtual register
303 if (isVirtKillInsn) inVirtLiveRange = false;
304 if (isVirtDefInsn) inVirtLiveRange = true;
306 // Was our survivor untouched by this instruction?
307 if (Candidates.test(Survivor))
310 // All candidates gone?
311 if (Candidates.none())
314 Survivor = Candidates.find_first();
316 // If we ran off the end, that's where we want to restore.
317 if (MI == ME) RestorePointMI = ME;
318 assert (RestorePointMI != StartMI &&
319 "No available scavenger restore location!");
321 // We ran out of candidates, so stop the search.
322 UseMI = RestorePointMI;
326 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
327 MachineBasicBlock::iterator I,
329 // Consider all allocatable registers in the register class initially
330 BitVector Candidates =
331 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
333 // Exclude all the registers being used by the instruction.
334 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
335 MachineOperand &MO = I->getOperand(i);
336 if (MO.isReg() && MO.getReg() != 0 &&
337 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
338 Candidates.reset(MO.getReg());
341 // Try to find a register that's unused if there is one, as then we won't
342 // have to spill. Search explicitly rather than masking out based on
343 // RegsAvailable, as RegsAvailable does not take aliases into account.
344 // That's what getRegsAvailable() is for.
345 BitVector Available = getRegsAvailable(RC);
346 Available &= Candidates;
348 Candidates = Available;
350 // Find the register whose use is furthest away.
351 MachineBasicBlock::iterator UseMI;
352 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
354 // If we found an unused register there is no reason to spill it.
355 if (!isAliasUsed(SReg)) {
356 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
360 assert(ScavengedReg == 0 &&
361 "Scavenger slot is live, unable to scavenge another register!");
363 // Avoid infinite regress
366 // If the target knows how to save/restore the register, let it do so;
367 // otherwise, use the emergency stack spill slot.
368 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
369 // Spill the scavenged register before I.
370 assert(ScavengingFrameIndex >= 0 &&
371 "Cannot scavenge register without an emergency spill slot!");
372 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
373 MachineBasicBlock::iterator II = prior(I);
374 TRI->eliminateFrameIndex(II, SPAdj, this);
376 // Restore the scavenged register before its use (or first terminator).
377 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
379 TRI->eliminateFrameIndex(II, SPAdj, this);
382 ScavengeRestore = prior(UseMI);
384 // Doing this here leads to infinite regress.
385 // ScavengedReg = SReg;
388 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<