49 #define DEBUG_TYPE "reg-scavenging" 51 STATISTIC(NumScavengedRegs,
"Number of frame index regs scavenged");
64 assert((NumRegUnits == 0 || NumRegUnits ==
TRI->getNumRegUnits()) &&
69 NumRegUnits =
TRI->getNumRegUnits();
70 KillRegUnits.
resize(NumRegUnits);
71 DefRegUnits.
resize(NumRegUnits);
72 TmpRegUnits.
resize(NumRegUnits);
76 for (ScavengedInfo &
SI : Scavenged) {
95 MBBI = std::prev(MBB.
end());
110 void RegScavenger::determineKillsAndDefs() {
111 assert(Tracking &&
"Must be tracking to determine kills and defs");
118 KillRegUnits.
reset();
121 if (MO.isRegMask()) {
123 for (
unsigned RU = 0, RUEnd =
TRI->getNumRegUnits(); RU != RUEnd; ++RU) {
125 if (MO.clobbersPhysReg(*RURI)) {
133 KillRegUnits |= TmpRegUnits;
158 assert(Tracking &&
"Cannot unprocess because we're not tracking");
162 determineKillsAndDefs();
165 setUnused(DefRegUnits);
166 setUsed(KillRegUnits);
169 if (MBBI == MBB->
begin()) {
182 assert(MBBI != MBB->
end() &&
"Already past the end of the basic block!");
183 MBBI = std::next(MBBI);
185 assert(MBBI != MBB->
end() &&
"Already at the end of the basic block!");
191 if (
I->Restore != &MI)
195 I->Restore =
nullptr;
198 if (MI.isDebugInstr())
201 determineKillsAndDefs();
223 bool SubUsed =
false;
229 bool SuperUsed =
false;
236 if (!SubUsed && !SuperUsed) {
248 assert((KillRegs.test(Reg) || isUnused(Reg) ||
249 isLiveInButUnusedBefore(Reg, MI, MBB,
TRI,
MRI)) &&
250 "Re-defining a live register!");
257 setUnused(KillRegUnits);
258 setUsed(DefRegUnits);
262 assert(Tracking &&
"Must be tracking to determine kills and defs");
268 for (ScavengedInfo &
I : Scavenged) {
269 if (
I.Restore == &MI) {
275 if (MBBI == MBB->
begin()) {
284 return includeReserved;
312 assert(Survivor > 0 &&
"No candidates for scavenging");
315 assert(StartMI != ME &&
"MI already at terminator");
319 bool inVirtLiveRange =
false;
320 for (++MI; InstrLimit > 0 && MI != ME; ++
MI, --
InstrLimit) {
321 if (MI->isDebugInstr()) {
325 bool isVirtKillInsn =
false;
326 bool isVirtDefInsn =
false;
331 if (!MO.isReg() || MO.isUndef() || !MO.getReg())
335 isVirtDefInsn =
true;
336 else if (MO.isKill())
337 isVirtKillInsn =
true;
341 Candidates.
reset(*AI);
345 if (!inVirtLiveRange) RestorePointMI =
MI;
348 if (isVirtKillInsn) inVirtLiveRange =
false;
349 if (isVirtDefInsn) inVirtLiveRange =
true;
352 if (Candidates.
test(Survivor))
356 if (Candidates.
none())
362 if (MI == ME) RestorePointMI = ME;
363 assert(RestorePointMI != StartMI &&
364 "No available scavenger restore location!");
367 UseMI = RestorePointMI;
378 static std::pair<MCPhysReg, MachineBasicBlock::iterator>
383 bool FoundTo =
false;
387 unsigned InstrLimit = 25;
402 return std::make_pair(Reg, MBB.
end());
415 if (Survivor == 0 || !Used.
available(Survivor)) {
423 if (AvilableReg == 0)
425 Survivor = AvilableReg;
427 if (--InstrCountDown == 0)
432 bool FoundVReg =
false;
448 return std::make_pair(Survivor, Pos);
460 RegScavenger::ScavengedInfo &
468 unsigned NeedSize =
TRI->getSpillSize(RC);
469 unsigned NeedAlign =
TRI->getSpillAlignment(RC);
473 for (
unsigned I = 0;
I < Scavenged.
size(); ++
I) {
474 if (Scavenged[
I].Reg != 0)
477 int FI = Scavenged[
I].FrameIndex;
478 if (FI < FIB || FI >= FIE)
482 if (NeedSize > S || NeedAlign > A)
490 unsigned D = (S-NeedSize) + (A-NeedAlign);
497 if (SI == Scavenged.
size()) {
504 Scavenged[
SI].Reg =
Reg;
508 if (!
TRI->saveScavengerRegister(*MBB, Before, UseMI, &RC, Reg)) {
510 int FI = Scavenged[
SI].FrameIndex;
511 if (FI < FIB || FI >= FIE) {
512 std::string Msg = std::string(
"Error while trying to spill ") +
513 TRI->getName(Reg) +
" from class " +
TRI->getRegClassName(&RC) +
514 ": Cannot scavenge register without an emergency spill slot!";
522 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum,
this);
527 II = std::prev(UseMI);
530 TRI->eliminateFrameIndex(II, SPAdj, FIOperandNum,
this);
532 return Scavenged[
SI];
537 int SPAdj,
bool AllowSpill) {
545 if (MO.isReg() && MO.getReg() != 0 && !(MO.isUse() && MO.isUndef()) &&
548 Candidates.
reset(*AI);
554 Available &= Candidates;
556 Candidates = Available;
560 Register SReg = findSurvivorReg(I, Candidates, 25, UseMI);
571 ScavengedInfo &Scavenged = spill(SReg, *RC, SPAdj, I, UseMI);
572 Scavenged.Restore = &*std::prev(UseMI);
582 bool RestoreAfter,
int SPAdj,
590 std::pair<MCPhysReg, MachineBasicBlock::iterator>
P =
595 assert(Reg != 0 &&
"No register left to scavenge!");
597 if (SpillBefore == MBB.
end()) {
607 RestoreAfter ? std::next(MBBI) : MBBI;
609 if (ReloadBefore != MBB.
end())
611 ScavengedInfo &Scavenged = spill(Reg, RC, SPAdj, SpillBefore, ReloadBefore);
612 Scavenged.Restore = &*std::prev(SpillBefore);
615 <<
" until " << *SpillBefore);
634 if (CommonMBB ==
nullptr)
636 assert(MBB == CommonMBB &&
"All defs+uses must be in the same basic block");
640 assert((!RealDef || RealDef == &MI) &&
641 "Can have at most one definition which is not a redefinition");
646 assert(RealDef !=
nullptr &&
"Must have at least 1 Def");
658 return !MO.getParent()->readsRegister(VReg, &TRI);
661 "Must have one definition that does not redefine vreg");
669 ReserveAfter, SPAdj);
685 bool NextInstructionReadsVReg =
false;
692 if (NextInstructionReadsVReg) {
709 N->addRegisterKilled(SReg, &TRI,
false);
715 NextInstructionReadsVReg =
false;
728 assert(!MO.isInternalRead() &&
"Cannot assign inside bundles");
729 assert((!MO.isUndef() || MO.isDef()) &&
"Cannot handle undef uses");
731 NextInstructionReadsVReg =
true;
735 I->addRegisterDead(SReg, &TRI,
false);
743 assert(!MO.isInternalRead() &&
"Cannot assign inside bundles");
744 assert((!MO.isUndef() || MO.isDef()) &&
"Cannot handle undef uses");
745 assert(!MO.readsReg() &&
"Vreg use in first instruction not allowed");
770 LLVM_DEBUG(
dbgs() <<
"Warning: Required two scavenging passes for block " 817 "Scavenge virtual registers inside basic blocks",
false,
false)
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isReserved(Register PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
static unsigned virtReg2Index(unsigned Reg)
Convert a virtual register number to a 0-based index.
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Store the specified register of the given register class to the specified stack frame index...
ArrayRef< MCPhysReg > getRawAllocationOrder(const MachineFunction &MF) const
Returns the preferred order for allocating registers from this register class in MF.
const MachineFunctionProperties & getProperties() const
Get the function properties.
void push_back(const T &Elt)
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(unsigned Reg) const
bool test(unsigned Idx) const
static void addRegUnits(const SIRegisterInfo &TRI, BitVector &BV, unsigned Reg)
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
iterator_range< mop_iterator > operands()
void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
Load the specified register of the given register class from the specified stack frame index...
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
MCSuperRegIterator enumerates all super-registers of Reg.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
unsigned getNumOperands() const
Retuns the total number of operands.
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
void backward()
Update internal register state and move MBB iterator backwards.
def_iterator def_begin(unsigned RegNo) const
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
void setRegUsed(Register Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Tell the scavenger a register is used.
void forward()
Move the internal MBB iterator and update register states.
void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
MCRegUnitRootIterator enumerates the root registers of a register unit.
BitVector getRegsAvailable(const TargetRegisterClass *RC)
Return all available registers in the register class in Mask.
int getObjectIndexBegin() const
Return the minimum frame object index.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
int getObjectIndexEnd() const
Return one past the maximum frame object index.
virtual const TargetInstrInfo * getInstrInfo() const
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
void addRegMasked(MCPhysReg Reg, LaneBitmask Mask)
Adds register units covered by physical register Reg that are part of the lanemask Mask...
void removeReg(MCPhysReg Reg)
Removes all register units covered by physical register Reg.
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
static Register scavengeVReg(MachineRegisterInfo &MRI, RegScavenger &RS, Register VReg, bool ReserveAfter)
Allocate a register for the virtual register VReg.
initializer< Ty > init(const Ty &Val)
MachineInstrBundleIterator< MachineInstr > iterator
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
This file declares the machine register scavenger class.
const TargetRegisterInfo * getTargetRegisterInfo() const
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineInstrBuilder & UseMI
bool isRegUsed(Register Reg, bool includeReserved=true) const
Return if a specific register is currently used.
bool any() const
any - Returns true if any bit is set.
void unprocess()
Invert the behavior of forward() on the current instruction (undo the changes to the available regist...
MCRegAliasIterator enumerates all registers aliasing Reg.
void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isDebugInstr() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static bool scavengeFrameVirtualRegsInBlock(MachineRegisterInfo &MRI, RegScavenger &RS, MachineBasicBlock &MBB)
Allocate (scavenge) vregs inside a single basic block.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
MachineOperand class - Representation of each machine instruction operand.
MachineInstrBuilder MachineInstrBuilder & DefMI
Information about stack frame layout on the target.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
Register scavengeRegisterBackwards(const TargetRegisterClass &RC, MachineBasicBlock::iterator To, bool RestoreAfter, int SPAdj, bool AllowSpill=true)
Make a register of the specific register class available from the current position backwards to the p...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
bool none() const
none - Returns true if none of the bits are set.
TargetSubtargetInfo - Generic base class for all target subtargets.
static unsigned getFrameIndexOperandNum(MachineInstr &MI)
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void enterBasicBlock(MachineBasicBlock &MBB)
Start tracking liveness from the begin of basic block MBB.
Register scavengeRegister(const TargetRegisterClass *RC, MachineBasicBlock::iterator I, int SPAdj, bool AllowSpill=true)
Make a register of the specific register class available and do the appropriate bookkeeping.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
Register FindUnusedReg(const TargetRegisterClass *RC) const
Find an unused register of the specified register class.
virtual const TargetFrameLowering * getFrameLowering() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
A set of register units used to track register liveness.
static cl::opt< unsigned > InstrLimit("dfa-instr-limit", cl::Hidden, cl::init(0), cl::desc("If present, stops packetizing after N instructions"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static def_iterator def_end()
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
bool isValid() const
Check if the iterator is at the end of the list.
static std::pair< MCPhysReg, MachineBasicBlock::iterator > findSurvivorBackwards(const MachineRegisterInfo &MRI, MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const LiveRegUnits &LiveOut, ArrayRef< MCPhysReg > AllocationOrder, bool RestoreAfter)
Given the bitvector Available of free register units at position From.
const MachineOperand & getOperand(unsigned i) const
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
Wrapper class representing virtual and physical registers.