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 unsigned *SubRegs = TRI->getSubRegisters(Reg);
41 unsigned SubReg = *SubRegs; ++SubRegs)
42 RegsAvailable.reset(SubReg);
45 bool RegScavenger::isAliasUsed(unsigned Reg) const {
48 for (const unsigned *R = TRI->getAliasSet(Reg); *R; ++R)
54 void RegScavenger::initRegState() {
57 ScavengeRestore = NULL;
59 // All registers started out unused.
62 // Reserved registers are always used.
63 RegsAvailable ^= ReservedRegs;
68 // Live-in registers are in use.
69 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
70 E = MBB->livein_end(); I != E; ++I)
73 // Pristine CSRs are also unavailable.
74 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
75 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
79 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
80 MachineFunction &MF = *mbb->getParent();
81 const TargetMachine &TM = MF.getTarget();
82 TII = TM.getInstrInfo();
83 TRI = TM.getRegisterInfo();
84 MRI = &MF.getRegInfo();
86 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
91 NumPhysRegs = TRI->getNumRegs();
92 RegsAvailable.resize(NumPhysRegs);
94 // Create reserved registers bitvector.
95 ReservedRegs = TRI->getReservedRegs(MF);
97 // Create callee-saved registers bitvector.
98 CalleeSavedRegs.resize(NumPhysRegs);
99 const unsigned *CSRegs = TRI->getCalleeSavedRegs();
101 for (unsigned i = 0; CSRegs[i]; ++i)
102 CalleeSavedRegs.set(CSRegs[i]);
111 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
113 for (const unsigned *R = TRI->getSubRegisters(Reg); *R; R++)
117 void RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) {
119 for (const unsigned *R = TRI->getAliasSet(Reg); *R; R++)
123 void RegScavenger::forward() {
129 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
130 MBBI = llvm::next(MBBI);
133 MachineInstr *MI = MBBI;
135 if (MI == ScavengeRestore) {
138 ScavengeRestore = NULL;
141 if (MI->isDebugValue())
144 // Find out which registers are early clobbered, killed, defined, and marked
145 // def-dead in this instruction.
146 // FIXME: The scavenger is not predication aware. If the instruction is
147 // predicated, conservatively assume "kill" markers do not actually kill the
148 // register. Similarly ignores "dead" markers.
149 bool isPred = TII->isPredicated(MI);
150 BitVector EarlyClobberRegs(NumPhysRegs);
151 BitVector KillRegs(NumPhysRegs);
152 BitVector DefRegs(NumPhysRegs);
153 BitVector DeadRegs(NumPhysRegs);
154 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
155 const MachineOperand &MO = MI->getOperand(i);
156 if (!MO.isReg() || MO.isUndef())
158 unsigned Reg = MO.getReg();
159 if (!Reg || isReserved(Reg))
163 // Two-address operands implicitly kill.
164 if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i)))
165 addRegWithSubRegs(KillRegs, Reg);
168 if (!isPred && MO.isDead())
169 addRegWithSubRegs(DeadRegs, Reg);
171 addRegWithSubRegs(DefRegs, Reg);
172 if (MO.isEarlyClobber())
173 addRegWithAliases(EarlyClobberRegs, Reg);
177 // Verify uses and defs.
178 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
179 const MachineOperand &MO = MI->getOperand(i);
180 if (!MO.isReg() || MO.isUndef())
182 unsigned Reg = MO.getReg();
183 if (!Reg || isReserved(Reg))
187 // Check if it's partial live: e.g.
188 // D0 = insert_subreg D0<undef>, S0
190 // The problem is the insert_subreg could be eliminated. The use of
191 // D0 is using a partially undef value. This is not *incorrect* since
192 // S1 is can be freely clobbered.
193 // Ideally we would like a way to model this, but leaving the
194 // insert_subreg around causes both correctness and performance issues.
195 bool SubUsed = false;
196 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
197 unsigned SubReg = *SubRegs; ++SubRegs)
198 if (isUsed(SubReg)) {
202 assert(SubUsed && "Using an undefined register!");
204 assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i)) &&
205 "Using an early clobbered register!");
209 // FIXME: Enable this once we've figured out how to correctly transfer
210 // implicit kills during codegen passes like the coalescer.
211 assert((KillRegs.test(Reg) || isUnused(Reg) ||
212 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
213 "Re-defining a live register!");
218 // Commit the changes.
224 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
226 used = ~RegsAvailable;
228 used = ~RegsAvailable & ~ReservedRegs;
231 /// CreateRegClassMask - Set the bits that represent the registers in the
232 /// TargetRegisterClass.
233 static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
234 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
239 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
240 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
242 if (!isAliasUsed(*I)) {
243 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
250 /// getRegsAvailable - Return all available registers in the register class
252 void RegScavenger::getRegsAvailable(const TargetRegisterClass *RC,
254 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
256 if (!isAliasUsed(*I))
260 /// findSurvivorReg - Return the candidate register that is unused for the
261 /// longest after StargMII. UseMI is set to the instruction where the search
264 /// No more than InstrLimit instructions are inspected.
266 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
267 BitVector &Candidates,
269 MachineBasicBlock::iterator &UseMI) {
270 int Survivor = Candidates.find_first();
271 assert(Survivor > 0 && "No candidates for scavenging");
273 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
274 assert(StartMI != ME && "MI already at terminator");
275 MachineBasicBlock::iterator RestorePointMI = StartMI;
276 MachineBasicBlock::iterator MI = StartMI;
278 bool inVirtLiveRange = false;
279 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
280 if (MI->isDebugValue()) {
281 ++InstrLimit; // Don't count debug instructions
284 bool isVirtKillInsn = false;
285 bool isVirtDefInsn = false;
286 // Remove any candidates touched by instruction.
287 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
288 const MachineOperand &MO = MI->getOperand(i);
289 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
291 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
293 isVirtDefInsn = true;
294 else if (MO.isKill())
295 isVirtKillInsn = true;
298 Candidates.reset(MO.getReg());
299 for (const unsigned *R = TRI->getAliasSet(MO.getReg()); *R; R++)
300 Candidates.reset(*R);
302 // If we're not in a virtual reg's live range, this is a valid
304 if (!inVirtLiveRange) RestorePointMI = MI;
306 // Update whether we're in the live range of a virtual register
307 if (isVirtKillInsn) inVirtLiveRange = false;
308 if (isVirtDefInsn) inVirtLiveRange = true;
310 // Was our survivor untouched by this instruction?
311 if (Candidates.test(Survivor))
314 // All candidates gone?
315 if (Candidates.none())
318 Survivor = Candidates.find_first();
320 // If we ran off the end, that's where we want to restore.
321 if (MI == ME) RestorePointMI = ME;
322 assert (RestorePointMI != StartMI &&
323 "No available scavenger restore location!");
325 // We ran out of candidates, so stop the search.
326 UseMI = RestorePointMI;
330 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
331 MachineBasicBlock::iterator I,
333 // Mask off the registers which are not in the TargetRegisterClass.
334 BitVector Candidates(NumPhysRegs, false);
335 CreateRegClassMask(RC, Candidates);
336 // Do not include reserved registers.
337 Candidates ^= ReservedRegs & Candidates;
339 // Exclude all the registers being used by the instruction.
340 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
341 MachineOperand &MO = I->getOperand(i);
342 if (MO.isReg() && MO.getReg() != 0 &&
343 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
344 Candidates.reset(MO.getReg());
347 // Try to find a register that's unused if there is one, as then we won't
349 if ((Candidates & RegsAvailable).any())
350 Candidates &= RegsAvailable;
352 // Find the register whose use is furthest away.
353 MachineBasicBlock::iterator UseMI;
354 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
356 // If we found an unused register there is no reason to spill it.
357 if (!isAliasUsed(SReg)) {
358 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
362 assert(ScavengedReg == 0 &&
363 "Scavenger slot is live, unable to scavenge another register!");
365 // Avoid infinite regress
368 // If the target knows how to save/restore the register, let it do so;
369 // otherwise, use the emergency stack spill slot.
370 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
371 // Spill the scavenged register before I.
372 assert(ScavengingFrameIndex >= 0 &&
373 "Cannot scavenge register without an emergency spill slot!");
374 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
375 MachineBasicBlock::iterator II = prior(I);
376 TRI->eliminateFrameIndex(II, SPAdj, this);
378 // Restore the scavenged register before its use (or first terminator).
379 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
381 TRI->eliminateFrameIndex(II, SPAdj, this);
384 ScavengeRestore = prior(UseMI);
386 // Doing this here leads to infinite regress.
387 // ScavengedReg = SReg;
390 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<