30#define DEBUG_TYPE "loongarch-frame-lowering"
59 unsigned Addi = IsLA64 ? LoongArch::ADDI_D : LoongArch::ADDI_W;
61 if (DestReg == SrcReg && Val == 0)
81 if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
82 int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
95 unsigned Opc = IsLA64 ? LoongArch::ADD_D : LoongArch::ADD_W;
98 Opc = IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W;
111void LoongArchFrameLowering::determineFrameLayout(
MachineFunction &MF)
const {
129 FuncSize +=
TII->getInstSizeInBytes(
MI);
138 if (
MI.getOpcode() == LoongArch::PseudoST_CFR)
152 unsigned ScavSlotsNum = 0;
165 unsigned EstimateStackSize = MFI.estimateStackSize(MF);
169 ScavSlotsNum = std::max(ScavSlotsNum, 1u);
176 for (
unsigned i = 0; i < ScavSlotsNum; ++i) {
178 MFI.CreateSpillStackObject(RI->getSpillSize(RC), RI->getSpillAlign(RC));
179 RS->addScavengingFrameIndex(FI);
183 <<
") as the emergency spill slot.\n");
191 uint64_t RealStackSize,
bool EmitCFI,
197 const bool IsLA64 = STI.
is64Bit();
202 if (!NeedProbe ||
Offset <= ProbeSize) {
205 CFIBuilder.buildDefCFAOffset(RealStackSize);
207 if (NeedProbe && DynAllocation) {
210 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
221 if (
Offset < ProbeSize * 5) {
222 const uint64_t CFAAdjust = RealStackSize -
Offset;
224 uint64_t CurrentOffset = 0;
225 while (CurrentOffset + ProbeSize <=
Offset) {
229 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
235 CurrentOffset += ProbeSize;
237 CFIBuilder.buildDefCFAOffset(CurrentOffset + CFAAdjust);
240 const uint64_t Residual =
Offset - CurrentOffset;
244 CFIBuilder.buildDefCFAOffset(RealStackSize);
249 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
261 const uint64_t Residual =
Offset - RoundedSize;
262 const uint64_t CFAAdjust = RealStackSize -
Offset;
264 const Register TargetReg = LoongArch::R13;
270 CFIBuilder.buildDefCFA(TargetReg, RoundedSize + CFAAdjust);
279 CFIBuilder.buildDefCFARegister(
SPReg);
287 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
296 CFIBuilder.buildDefCFAOffset(RealStackSize);
306 bool IsLA64 = STI.is64Bit();
319 determineFrameLayout(MF);
331 if (FirstSPAdjustAmount)
332 StackSize = FirstSPAdjustAmount;
338 const bool DynAllocation =
341 allocateStack(
MBB,
MBBI, MF, StackSize, StackSize,
342 true, NeedProbe, ProbeSize, DynAllocation,
351 std::advance(
MBBI, CSI.size());
355 for (
const auto &Entry : CSI) {
358 nullptr, RI->getDwarfRegNum(Entry.getReg(),
true),
Offset));
367 StackSize - LoongArchFI->getVarArgsSaveSize(),
373 LoongArchFI->getVarArgsSaveSize()));
380 if (FirstSPAdjustAmount) {
381 uint64_t SecondSPAdjustAmount = RealStackSize - FirstSPAdjustAmount;
382 assert(SecondSPAdjustAmount > 0 &&
383 "SecondSPAdjustAmount should be greater than zero");
384 allocateStack(
MBB,
MBBI, MF, SecondSPAdjustAmount, RealStackSize,
385 !
hasFP(MF), NeedProbe, ProbeSize, DynAllocation,
391 if (RI->hasStackRealignment(MF)) {
393 assert(
Align > 0 &&
"The stack realignment size is invalid!");
395 TII->get(IsLA64 ? LoongArch::BSTRINS_D : LoongArch::BSTRINS_W),
432 auto LastFrameDestroy =
MBBI;
434 LastFrameDestroy = std::prev(
MBBI, CSI.size());
441 assert(
hasFP(MF) &&
"frame pointer should not have been eliminated");
442 adjustReg(
MBB, LastFrameDestroy,
DL,
SPReg, LoongArch::R22,
443 -StackSize + LoongArchFI->getVarArgsSaveSize(),
448 if (FirstSPAdjustAmount) {
449 uint64_t SecondSPAdjustAmount = StackSize - FirstSPAdjustAmount;
450 assert(SecondSPAdjustAmount > 0 &&
451 "SecondSPAdjustAmount should be greater than zero");
453 adjustReg(
MBB, LastFrameDestroy,
DL,
SPReg,
SPReg, SecondSPAdjustAmount,
455 StackSize = FirstSPAdjustAmount;
465 assert(TargetReg != LoongArch::R3 &&
466 "New top of stack cannot already be in $sp");
473 const bool IsLA64 = STI.
is64Bit();
481 MF.
insert(MBBInsertPoint, LoopTestMBB);
483 MF.
insert(MBBInsertPoint, ExitMBB);
485 const Register ScratchReg = LoongArch::R14;
489 TII->movImm(
MBB,
MBBI,
DL, ScratchReg, ProbeSize, Flags);
494 TII->get(IsLA64 ? LoongArch::SUB_D : LoongArch::SUB_W),
SPReg)
501 TII->get(IsLA64 ? LoongArch::ST_D : LoongArch::ST_W))
508 BuildMI(*LoopTestMBB, LoopTestMBB->
end(),
DL,
TII->get(LoongArch::BNE))
519 MBB.addSuccessor(LoopTestMBB);
531 if (
MI.getOpcode() == LoongArch::PROBED_STACKALLOC) {
539 Register TargetReg =
MI->getOperand(0).getReg();
541 MBBI->eraseFromParent();
578 SavedRegs.
set(LoongArch::R1);
579 SavedRegs.
set(LoongArch::R22);
608 int64_t Amount =
MI->getOperand(0).getImm();
614 if (
MI->getOpcode() == LoongArch::ADJCALLSTACKDOWN)
624 const bool DynAllocation =
626 allocateStack(
MBB,
MI, MF, -Amount, -Amount,
628 true, ProbeSize, DynAllocation,
637 return MBB.erase(
MI);
650 for (
auto &CS : CSI) {
655 !(Reg == LoongArch::R1 && MF->
getFrameInfo().isReturnAddressTaken());
657 TII.storeRegToStackSlot(
MBB,
MI, Reg, IsKill, CS.getFrameIdx(), RC,
683 MinCSFI = CSI[0].getFrameIdx();
684 MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
687 if (FI >= MinCSFI && FI <= MaxCSFI) {
688 FrameReg = LoongArch::R3;
689 if (FirstSPAdjustAmount)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
const HexagonInstrInfo * TII
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static uint64_t estimateFunctionSizeInBytes(const LoongArchInstrInfo *TII, const MachineFunction &MF)
static void emitStackProbeInline(MachineBasicBlock::iterator MBBI, DebugLoc DL, Register TargetReg)
static bool needScavSlotForCFR(MachineFunction &MF)
Register const TargetRegisterInfo * TRI
Promote Memory to Register
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
This file declares the machine register scavenger class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
Check if the array is empty.
BitVector & set()
Set all bits in the bitvector.
Helper class for creating CFI instructions and inserting them into MIR.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasOptNone() const
Do not optimize this function (-O0).
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
uint64_t getFirstSPAdjustAmount(const MachineFunction &MF) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const override
Replace a StackProbe stub (if any) with the actual probe code inline.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
bool hasFPImpl(const MachineFunction &MF) const override
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
bool hasBP(const MachineFunction &MF) const
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
int getBranchRelaxationSpillFrameIndex()
void setBranchRelaxationSpillFrameIndex(int Index)
const LoongArchTargetLowering * getTargetLowering() const override
const LoongArchInstrInfo * getInstrInfo() const override
const LoongArchFrameLowering * getFrameLowering() const override
bool hasInlineStackProbe(const MachineFunction &MF) const override
True if stack clash protection is enabled for this function.
unsigned getStackProbeSize(const MachineFunction &MF, Align StackAlign) const
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Wrapper class representing physical registers. Should be passed by value.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
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.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Wrapper class representing virtual and physical registers.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
int64_t getFixed() const
Returns the fixed component of the stack.
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
LLVM_ABI bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
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.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
@ Kill
The last use of a register.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
unsigned Log2(Align A)
Returns the log2 of the alignment.
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.