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 (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
41 RegsAvailable.reset(*SubRegs);
44 bool RegScavenger::isAliasUsed(unsigned Reg) const {
45 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
46 if (isUsed(*AI, *AI == Reg))
51 void RegScavenger::initRegState() {
54 ScavengeRestore = NULL;
56 // All registers started out unused.
62 // Live-in registers are in use.
63 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
64 E = MBB->livein_end(); I != E; ++I)
67 // Pristine CSRs are also unavailable.
68 BitVector PR = MBB->getParent()->getFrameInfo()->getPristineRegs(MBB);
69 for (int I = PR.find_first(); I>0; I = PR.find_next(I))
73 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
74 MachineFunction &MF = *mbb->getParent();
75 const TargetMachine &TM = MF.getTarget();
76 TII = TM.getInstrInfo();
77 TRI = TM.getRegisterInfo();
78 MRI = &MF.getRegInfo();
80 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
83 // It is not possible to use the register scavenger after late optimization
84 // passes that don't preserve accurate liveness information.
85 assert(MRI->tracksLiveness() &&
86 "Cannot use register scavenger with inaccurate liveness");
90 NumPhysRegs = TRI->getNumRegs();
91 RegsAvailable.resize(NumPhysRegs);
92 KillRegs.resize(NumPhysRegs);
93 DefRegs.resize(NumPhysRegs);
95 // Create callee-saved registers bitvector.
96 CalleeSavedRegs.resize(NumPhysRegs);
97 const uint16_t *CSRegs = TRI->getCalleeSavedRegs(&MF);
99 for (unsigned i = 0; CSRegs[i]; ++i)
100 CalleeSavedRegs.set(CSRegs[i]);
109 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
111 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
115 void RegScavenger::forward() {
121 assert(MBBI != MBB->end() && "Already past the end of the basic block!");
122 MBBI = llvm::next(MBBI);
124 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
126 MachineInstr *MI = MBBI;
128 if (MI == ScavengeRestore) {
131 ScavengeRestore = NULL;
134 if (MI->isDebugValue())
137 // Find out which registers are early clobbered, killed, defined, and marked
138 // def-dead in this instruction.
139 // FIXME: The scavenger is not predication aware. If the instruction is
140 // predicated, conservatively assume "kill" markers do not actually kill the
141 // register. Similarly ignores "dead" markers.
142 bool isPred = TII->isPredicated(MI);
145 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
146 const MachineOperand &MO = MI->getOperand(i);
148 (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
151 unsigned Reg = MO.getReg();
152 if (!Reg || isReserved(Reg))
156 // Ignore undef uses.
159 if (!isPred && MO.isKill())
160 addRegWithSubRegs(KillRegs, Reg);
163 if (!isPred && MO.isDead())
164 addRegWithSubRegs(KillRegs, Reg);
166 addRegWithSubRegs(DefRegs, Reg);
170 // Verify uses and defs.
172 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
173 const MachineOperand &MO = MI->getOperand(i);
176 unsigned Reg = MO.getReg();
177 if (!Reg || isReserved(Reg))
183 // Check if it's partial live: e.g.
184 // D0 = insert_subreg D0<undef>, S0
186 // The problem is the insert_subreg could be eliminated. The use of
187 // D0 is using a partially undef value. This is not *incorrect* since
188 // S1 is can be freely clobbered.
189 // Ideally we would like a way to model this, but leaving the
190 // insert_subreg around causes both correctness and performance issues.
191 bool SubUsed = false;
192 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
193 if (isUsed(*SubRegs)) {
198 MBB->getParent()->verify(NULL, "In Register Scavenger");
199 llvm_unreachable("Using an undefined register!");
206 // FIXME: Enable this once we've figured out how to correctly transfer
207 // implicit kills during codegen passes like the coalescer.
208 assert((KillRegs.test(Reg) || isUnused(Reg) ||
209 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
210 "Re-defining a live register!");
216 // Commit the changes.
221 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
222 used = RegsAvailable;
225 used |= MRI->getReservedRegs();
227 used.reset(MRI->getReservedRegs());
230 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
231 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
233 if (!isAliasUsed(*I)) {
234 DEBUG(dbgs() << "Scavenger found unused reg: " << TRI->getName(*I) <<
241 /// getRegsAvailable - Return all available registers in the register class
243 BitVector RegScavenger::getRegsAvailable(const TargetRegisterClass *RC) {
244 BitVector Mask(TRI->getNumRegs());
245 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
247 if (!isAliasUsed(*I))
252 /// findSurvivorReg - Return the candidate register that is unused for the
253 /// longest after StargMII. UseMI is set to the instruction where the search
256 /// No more than InstrLimit instructions are inspected.
258 unsigned RegScavenger::findSurvivorReg(MachineBasicBlock::iterator StartMI,
259 BitVector &Candidates,
261 MachineBasicBlock::iterator &UseMI) {
262 int Survivor = Candidates.find_first();
263 assert(Survivor > 0 && "No candidates for scavenging");
265 MachineBasicBlock::iterator ME = MBB->getFirstTerminator();
266 assert(StartMI != ME && "MI already at terminator");
267 MachineBasicBlock::iterator RestorePointMI = StartMI;
268 MachineBasicBlock::iterator MI = StartMI;
270 bool inVirtLiveRange = false;
271 for (++MI; InstrLimit > 0 && MI != ME; ++MI, --InstrLimit) {
272 if (MI->isDebugValue()) {
273 ++InstrLimit; // Don't count debug instructions
276 bool isVirtKillInsn = false;
277 bool isVirtDefInsn = false;
278 // Remove any candidates touched by instruction.
279 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
280 const MachineOperand &MO = MI->getOperand(i);
282 Candidates.clearBitsNotInMask(MO.getRegMask());
283 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
285 if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
287 isVirtDefInsn = true;
288 else if (MO.isKill())
289 isVirtKillInsn = true;
292 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
293 Candidates.reset(*AI);
295 // If we're not in a virtual reg's live range, this is a valid
297 if (!inVirtLiveRange) RestorePointMI = MI;
299 // Update whether we're in the live range of a virtual register
300 if (isVirtKillInsn) inVirtLiveRange = false;
301 if (isVirtDefInsn) inVirtLiveRange = true;
303 // Was our survivor untouched by this instruction?
304 if (Candidates.test(Survivor))
307 // All candidates gone?
308 if (Candidates.none())
311 Survivor = Candidates.find_first();
313 // If we ran off the end, that's where we want to restore.
314 if (MI == ME) RestorePointMI = ME;
315 assert (RestorePointMI != StartMI &&
316 "No available scavenger restore location!");
318 // We ran out of candidates, so stop the search.
319 UseMI = RestorePointMI;
323 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
324 MachineBasicBlock::iterator I,
326 // Consider all allocatable registers in the register class initially
327 BitVector Candidates =
328 TRI->getAllocatableSet(*I->getParent()->getParent(), RC);
330 // Exclude all the registers being used by the instruction.
331 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
332 MachineOperand &MO = I->getOperand(i);
333 if (MO.isReg() && MO.getReg() != 0 &&
334 !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
335 Candidates.reset(MO.getReg());
338 // Try to find a register that's unused if there is one, as then we won't
339 // have to spill. Search explicitly rather than masking out based on
340 // RegsAvailable, as RegsAvailable does not take aliases into account.
341 // That's what getRegsAvailable() is for.
342 BitVector Available = getRegsAvailable(RC);
343 Available &= Candidates;
345 Candidates = Available;
347 // Find the register whose use is furthest away.
348 MachineBasicBlock::iterator UseMI;
349 unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
351 // If we found an unused register there is no reason to spill it.
352 if (!isAliasUsed(SReg)) {
353 DEBUG(dbgs() << "Scavenged register: " << TRI->getName(SReg) << "\n");
357 assert(ScavengedReg == 0 &&
358 "Scavenger slot is live, unable to scavenge another register!");
360 // Avoid infinite regress
363 // If the target knows how to save/restore the register, let it do so;
364 // otherwise, use the emergency stack spill slot.
365 if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
366 // Spill the scavenged register before I.
367 assert(ScavengingFrameIndex >= 0 &&
368 "Cannot scavenge register without an emergency spill slot!");
369 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC,TRI);
370 MachineBasicBlock::iterator II = prior(I);
371 TRI->eliminateFrameIndex(II, SPAdj, this);
373 // Restore the scavenged register before its use (or first terminator).
374 TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC, TRI);
376 TRI->eliminateFrameIndex(II, SPAdj, this);
379 ScavengeRestore = prior(UseMI);
381 // Doing this here leads to infinite regress.
382 // ScavengedReg = SReg;
385 DEBUG(dbgs() << "Scavenged register (with spill): " << TRI->getName(SReg) <<