31#define DEBUG_TYPE "si-lower-sgpr-spills"
38 "amdgpu-num-vgprs-for-wwm-alloc",
39 cl::desc(
"Max num VGPRs for whole-wave register allocation."),
42class SILowerSGPRSpills {
58 : LIS(LIS), Indexes(Indexes), MDT(MDT) {}
63 void updateLaneVGPRDomInstr(
91char SILowerSGPRSpillsLegacy::ID = 0;
94 "SI lower SGPR spill instructions",
false,
false)
106 if (
MBB.isLiveIn(*R)) {
131 Reg,
Reg == RI->getReturnAddressReg(MF) ? MVT::i64 : MVT::i32);
138 TII.storeRegToStackSlot(SaveBlock,
I,
Reg, !IsLiveIn, CS.getFrameIdx(),
173 I == RestoreBlock.
begin() ?
I : std::prev(
I);
204void SILowerSGPRSpills::calculateSaveRestoreBlocks(
MachineFunction &MF) {
214 "Multiple save points not yet supported!");
218 "Multiple restore points not yet supported!");
220 MachineBasicBlock *RestoreBlock = RestorePoint.first;
231 for (MachineBasicBlock &
MBB : MF) {
249bool SILowerSGPRSpills::spillCalleeSavedRegs(
250 MachineFunction &MF, SmallVectorImpl<int> &CalleeSavedFIs) {
254 const SIFrameLowering *TFI =
ST.getFrameLowering();
256 RegScavenger *
RS =
nullptr;
260 TFI->determineCalleeSavesSGPR(MF, SavedRegs, RS);
263 if (!
F.hasFnAttribute(Attribute::Naked)) {
268 std::vector<CalleeSavedInfo> CSI;
271 for (
unsigned I = 0; CSRegs[
I]; ++
I) {
272 MCRegister
Reg = CSRegs[
I];
275 const TargetRegisterClass *RC =
276 TRI->getMinimalPhysRegClass(
Reg, MVT::i32);
278 TRI->getSpillAlign(*RC),
true);
280 CSI.emplace_back(
Reg, JunkFI);
286 for (MachineBasicBlock *SaveBlock : SaveBlocks)
290 assert(SaveBlocks.size() == 1 &&
"shrink wrapping not fully implemented");
293 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
302void SILowerSGPRSpills::updateLaneVGPRDomInstr(
304 DenseMap<Register, MachineBasicBlock::iterator> &LaneVGPRDomInstr) {
311 SIMachineFunctionInfo *FuncInfo =
316 for (
auto &Spill : VGPRSpills) {
317 if (PrevLaneVGPR ==
Spill.VGPR)
320 PrevLaneVGPR =
Spill.VGPR;
322 if (
Spill.Lane == 0 &&
I == LaneVGPRDomInstr.
end()) {
324 LaneVGPRDomInstr[
Spill.VGPR] = InsertPt;
327 auto PrevInsertPt =
I->second;
328 MachineBasicBlock *DomMBB = PrevInsertPt->getParent();
334 if (MDT->
dominates(&*InsertPt, &*PrevInsertPt))
335 I->second = InsertPt;
344 I->second = InsertPt;
345 else if (DomMBB != PrevInsertPt->getParent())
351void SILowerSGPRSpills::determineRegsForWWMAllocation(MachineFunction &MF,
352 BitVector &RegMask) {
355 SIMachineFunctionInfo *MFI = MF.
getInfo<SIMachineFunctionInfo>();
357 BitVector ReservedRegs =
TRI->getReservedRegs(MF);
358 BitVector NonWwmAllocMask(
TRI->getNumRegs());
364 unsigned NumRegs = MaxNumVGPRsForWwmAllocation;
368 auto [MaxNumVGPRs, MaxNumAGPRs] =
ST.getMaxNumVectorRegs(MF.
getFunction());
372 for (
unsigned Reg = AMDGPU::VGPR0 + MaxNumVGPRs - 1;
373 (
I < NumRegs) && (
Reg >= AMDGPU::VGPR0); --
Reg) {
375 !
MRI.isPhysRegUsed(
Reg,
true)) {
376 TRI->markSuperRegs(RegMask,
Reg);
383 TRI->markSuperRegs(RegMask, AMDGPU::VGPR0);
385 "cannot find enough VGPRs for wwm-regalloc");
389bool SILowerSGPRSpillsLegacy::runOnMachineFunction(MachineFunction &MF) {
390 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
391 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() :
nullptr;
392 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
393 SlotIndexes *Indexes = SIWrapper ? &SIWrapper->getSI() :
nullptr;
394 MachineDominatorTree *MDT =
395 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
396 return SILowerSGPRSpills(LIS, Indexes, MDT).run(MF);
399bool SILowerSGPRSpills::run(MachineFunction &MF) {
401 TII =
ST.getInstrInfo();
408 calculateSaveRestoreBlocks(MF);
409 SmallVector<int> CalleeSavedFIs;
410 bool HasCSRs = spillCalleeSavedRegs(MF, CalleeSavedFIs);
414 SIMachineFunctionInfo *FuncInfo = MF.
getInfo<SIMachineFunctionInfo>();
418 RestoreBlocks.
clear();
422 bool MadeChange =
false;
423 bool SpilledToVirtVGPRLanes =
false;
427 const bool HasSGPRSpillToVGPR =
TRI->spillSGPRToVGPR() &&
429 if (HasSGPRSpillToVGPR) {
440 DenseMap<Register, MachineBasicBlock::iterator> LaneVGPRDomInstr;
442 for (MachineBasicBlock &
MBB : MF) {
444 if (!
TII->isSGPRSpill(
MI))
447 if (
MI.getOperand(0).isUndef()) {
450 MI.eraseFromParent();
454 int FI =
TII->getNamedOperand(
MI, AMDGPU::OpName::addr)->getIndex();
458 if (IsCalleeSaveSGPRSpill) {
471 bool Spilled =
TRI->eliminateSGPRToVGPRSpillFrameIndex(
472 MI, FI,
nullptr, Indexes, LIS,
true);
475 "failed to spill SGPR to physical VGPR lane when allocated");
478 MachineInstrSpan MIS(&
MI, &
MBB);
480 bool Spilled =
TRI->eliminateSGPRToVGPRSpillFrameIndex(
481 MI, FI,
nullptr, Indexes, LIS);
484 "failed to spill SGPR to virtual VGPR lane when allocated");
486 updateLaneVGPRDomInstr(FI, &
MBB, MIS.
begin(), LaneVGPRDomInstr);
487 SpilledToVirtVGPRLanes =
true;
494 auto InsertPt = LaneVGPRDomInstr[
Reg];
496 MachineBasicBlock &
Block = *InsertPt->getParent();
515 BitVector WwmRegMask(
TRI->getNumRegs());
517 determineRegsForWWMAllocation(MF, WwmRegMask);
519 BitVector NonWwmRegMask(WwmRegMask);
520 NonWwmRegMask.flip().clearBitsNotInMask(
TRI->getAllVGPRRegMask());
527 for (MachineBasicBlock &
MBB : MF) {
532 for (MachineInstr &
MI :
MBB) {
533 if (
MI.isDebugValue()) {
534 uint32_t StackOperandIdx =
MI.isDebugValueList() ? 2 : 0;
535 if (
MI.getOperand(StackOperandIdx).isFI() &&
537 MI.getOperand(StackOperandIdx).getIndex()) &&
538 SpillFIs[
MI.getOperand(StackOperandIdx).getIndex()]) {
539 MI.getOperand(StackOperandIdx)
540 .ChangeToRegister(
Register(),
false );
556 if (SpilledToVirtVGPRLanes) {
557 const TargetRegisterClass *RC =
TRI->getWaveMaskRegClass();
562 if (UnusedLowSGPR &&
TRI->getHWRegIndex(UnusedLowSGPR) <
572 RestoreBlocks.
clear();
584 SILowerSGPRSpills(LIS, Indexes, MDT).
run(MF);
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
This file declares the machine register scavenger class.
static bool isLiveIntoMBB(MCRegister Reg, MachineBasicBlock &MBB, const TargetRegisterInfo *TRI)
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, MutableArrayRef< CalleeSavedInfo > CSI, SlotIndexes *Indexes, LiveIntervals *LIS)
Insert restore code for the callee-saved registers used in the function.
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI, SlotIndexes *Indexes, LiveIntervals *LIS)
Insert spill code for the callee-saved registers used in the function.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool test(unsigned Idx) const
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
iterator find(const_arg_type_t< KeyT > Val)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
const HexagonRegisterInfo & getRegisterInfo() const
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
MCRegAliasIterator enumerates all registers aliasing Reg.
Wrapper class representing physical registers. Should be passed by value.
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &)
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setCalleeSavedInfoValid(bool v)
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackObjects() const
Return true if there are any stack objects in this function.
uint8_t getStackID(int ObjectIdx) const
const SaveRestorePoints & getRestorePoints() const
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
const SaveRestorePoints & getSavePoints() const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
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.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineInstrSpan provides an interface to get an iteration range containing the instruction it was in...
MachineBasicBlock::iterator begin()
Representation of each machine instruction.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void setSGPRForEXECCopy(Register Reg)
void setFlag(Register Reg, uint8_t Flag)
ArrayRef< SIRegisterInfo::SpilledReg > getSGPRSpillToVirtualVGPRLanes(int FrameIndex) const
Register getSGPRForEXECCopy() const
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
void updateNonWWMRegMask(BitVector &RegMask)
bool hasSpilledSGPRs() const
ArrayRef< Register > getSGPRSpillVGPRs() const
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
LLVM_ABI void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
LLVM_ABI void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Information about stack frame layout on the target.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto reverse(ContainerTy &&C)
char & SILowerSGPRSpillsLegacyID
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.