- BitVector RegStatesCopy(NumPhysRegs, false);
- CreateRegClassMask(RegClass, RegStatesCopy);
- RegStatesCopy &= RegStates;
-
- // If looking for a non-callee-saved register, mask off all the callee-saved
- // registers.
- if (ExCalleeSaved)
- RegStatesCopy &= ~CalleeSavedRegs;
-
- // Returns the first unused (bit is set) register, or 0 is none is found.
- int Reg = RegStatesCopy.find_first();
- return (Reg == -1) ? 0 : Reg;
+ BitVector Candidates(NumPhysRegs, false);
+ CreateRegClassMask(RC, Candidates);
+ // Do not include reserved registers.
+ Candidates ^= ReservedRegs & Candidates;
+
+ // Exclude all the registers being used by the instruction.
+ for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
+ MachineOperand &MO = I->getOperand(i);
+ if (MO.isReg() && MO.getReg() != 0 &&
+ !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
+ Candidates.reset(MO.getReg());
+ }
+
+ // Find the register whose use is furthest away.
+ MachineBasicBlock::iterator UseMI;
+ unsigned SReg = findSurvivorReg(I, Candidates, 25, UseMI);
+
+ // If we found an unused register there is no reason to spill it. We have
+ // probably found a callee-saved register that has been saved in the
+ // prologue, but happens to be unused at this point.
+ if (!isAliasUsed(SReg))
+ return SReg;
+
+ assert(ScavengedReg == 0 &&
+ "Scavenger slot is live, unable to scavenge another register!");
+
+ // Avoid infinite regress
+ ScavengedReg = SReg;
+
+ // If the target knows how to save/restore the register, let it do so;
+ // otherwise, use the emergency stack spill slot.
+ if (!TRI->saveScavengerRegister(*MBB, I, UseMI, RC, SReg)) {
+ // Spill the scavenged register before I.
+ assert(ScavengingFrameIndex >= 0 &&
+ "Cannot scavenge register without an emergency spill slot!");
+ TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
+ MachineBasicBlock::iterator II = prior(I);
+ TRI->eliminateFrameIndex(II, SPAdj, NULL, this);
+
+ // Restore the scavenged register before its use (or first terminator).
+ TII->loadRegFromStackSlot(*MBB, UseMI, SReg, ScavengingFrameIndex, RC);
+ II = prior(UseMI);
+ TRI->eliminateFrameIndex(II, SPAdj, NULL, this);
+ }
+
+ ScavengeRestore = prior(UseMI);
+
+ // Doing this here leads to infinite regress.
+ // ScavengedReg = SReg;
+ ScavengedRC = RC;
+
+ return SReg;