Path: blob/main/contrib/llvm-project/llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
35266 views
//===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains the AArch64 implementation of TargetFrameLowering class.9//10// On AArch64, stack frames are structured as follows:11//12// The stack grows downward.13//14// All of the individual frame areas on the frame below are optional, i.e. it's15// possible to create a function so that the particular area isn't present16// in the frame.17//18// At function entry, the "frame" looks as follows:19//20// | | Higher address21// |-----------------------------------|22// | |23// | arguments passed on the stack |24// | |25// |-----------------------------------| <- sp26// | | Lower address27//28//29// After the prologue has run, the frame has the following general structure.30// Note that this doesn't depict the case where a red-zone is used. Also,31// technically the last frame area (VLAs) doesn't get created until in the32// main function body, after the prologue is run. However, it's depicted here33// for completeness.34//35// | | Higher address36// |-----------------------------------|37// | |38// | arguments passed on the stack |39// | |40// |-----------------------------------|41// | |42// | (Win64 only) varargs from reg |43// | |44// |-----------------------------------|45// | |46// | callee-saved gpr registers | <--.47// | | | On Darwin platforms these48// |- - - - - - - - - - - - - - - - - -| | callee saves are swapped,49// | prev_lr | | (frame record first)50// | prev_fp | <--'51// | async context if needed |52// | (a.k.a. "frame record") |53// |-----------------------------------| <- fp(=x29)54// | <hazard padding> |55// |-----------------------------------|56// | |57// | callee-saved fp/simd/SVE regs |58// | |59// |-----------------------------------|60// | |61// | SVE stack objects |62// | |63// |-----------------------------------|64// |.empty.space.to.make.part.below....|65// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at66// |.the.standard.16-byte.alignment....| compile time; if present)67// |-----------------------------------|68// | local variables of fixed size |69// | including spill slots |70// | <FPR> |71// | <hazard padding> |72// | <GPR> |73// |-----------------------------------| <- bp(not defined by ABI,74// |.variable-sized.local.variables....| LLVM chooses X19)75// |.(VLAs)............................| (size of this area is unknown at76// |...................................| compile time)77// |-----------------------------------| <- sp78// | | Lower address79//80//81// To access the data in a frame, at-compile time, a constant offset must be82// computable from one of the pointers (fp, bp, sp) to access it. The size83// of the areas with a dotted background cannot be computed at compile-time84// if they are present, making it required to have all three of fp, bp and85// sp to be set up to be able to access all contents in the frame areas,86// assuming all of the frame areas are non-empty.87//88// For most functions, some of the frame areas are empty. For those functions,89// it may not be necessary to set up fp or bp:90// * A base pointer is definitely needed when there are both VLAs and local91// variables with more-than-default alignment requirements.92// * A frame pointer is definitely needed when there are local variables with93// more-than-default alignment requirements.94//95// For Darwin platforms the frame-record (fp, lr) is stored at the top of the96// callee-saved area, since the unwind encoding does not allow for encoding97// this dynamically and existing tools depend on this layout. For other98// platforms, the frame-record is stored at the bottom of the (gpr) callee-saved99// area to allow SVE stack objects (allocated directly below the callee-saves,100// if available) to be accessed directly from the framepointer.101// The SVE spill/fill instructions have VL-scaled addressing modes such102// as:103// ldr z8, [fp, #-7 mul vl]104// For SVE the size of the vector length (VL) is not known at compile-time, so105// '#-7 mul vl' is an offset that can only be evaluated at runtime. With this106// layout, we don't need to add an unscaled offset to the framepointer before107// accessing the SVE object in the frame.108//109// In some cases when a base pointer is not strictly needed, it is generated110// anyway when offsets from the frame pointer to access local variables become111// so large that the offset can't be encoded in the immediate fields of loads112// or stores.113//114// Outgoing function arguments must be at the bottom of the stack frame when115// calling another function. If we do not have variable-sized stack objects, we116// can allocate a "reserved call frame" area at the bottom of the local117// variable area, large enough for all outgoing calls. If we do have VLAs, then118// the stack pointer must be decremented and incremented around each call to119// make space for the arguments below the VLAs.120//121// FIXME: also explain the redzone concept.122//123// About stack hazards: Under some SME contexts, a coprocessor with its own124// separate cache can used for FP operations. This can create hazards if the CPU125// and the SME unit try to access the same area of memory, including if the126// access is to an area of the stack. To try to alleviate this we attempt to127// introduce extra padding into the stack frame between FP and GPR accesses,128// controlled by the StackHazardSize option. Without changing the layout of the129// stack frame in the diagram above, a stack object of size StackHazardSize is130// added between GPR and FPR CSRs. Another is added to the stack objects131// section, and stack objects are sorted so that FPR > Hazard padding slot >132// GPRs (where possible). Unfortunately some things are not handled well (VLA133// area, arguments on the stack, object with both GPR and FPR accesses), but if134// those are controlled by the user then the entire stack frame becomes GPR at135// the start/end with FPR in the middle, surrounded by Hazard padding.136//137// An example of the prologue:138//139// .globl __foo140// .align 2141// __foo:142// Ltmp0:143// .cfi_startproc144// .cfi_personality 155, ___gxx_personality_v0145// Leh_func_begin:146// .cfi_lsda 16, Lexception33147//148// stp xa,bx, [sp, -#offset]!149// ...150// stp x28, x27, [sp, #offset-32]151// stp fp, lr, [sp, #offset-16]152// add fp, sp, #offset - 16153// sub sp, sp, #1360154//155// The Stack:156// +-------------------------------------------+157// 10000 | ........ | ........ | ........ | ........ |158// 10004 | ........ | ........ | ........ | ........ |159// +-------------------------------------------+160// 10008 | ........ | ........ | ........ | ........ |161// 1000c | ........ | ........ | ........ | ........ |162// +===========================================+163// 10010 | X28 Register |164// 10014 | X28 Register |165// +-------------------------------------------+166// 10018 | X27 Register |167// 1001c | X27 Register |168// +===========================================+169// 10020 | Frame Pointer |170// 10024 | Frame Pointer |171// +-------------------------------------------+172// 10028 | Link Register |173// 1002c | Link Register |174// +===========================================+175// 10030 | ........ | ........ | ........ | ........ |176// 10034 | ........ | ........ | ........ | ........ |177// +-------------------------------------------+178// 10038 | ........ | ........ | ........ | ........ |179// 1003c | ........ | ........ | ........ | ........ |180// +-------------------------------------------+181//182// [sp] = 10030 :: >>initial value<<183// sp = 10020 :: stp fp, lr, [sp, #-16]!184// fp = sp == 10020 :: mov fp, sp185// [sp] == 10020 :: stp x28, x27, [sp, #-16]!186// sp == 10010 :: >>final value<<187//188// The frame pointer (w29) points to address 10020. If we use an offset of189// '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24190// for w27, and -32 for w28:191//192// Ltmp1:193// .cfi_def_cfa w29, 16194// Ltmp2:195// .cfi_offset w30, -8196// Ltmp3:197// .cfi_offset w29, -16198// Ltmp4:199// .cfi_offset w27, -24200// Ltmp5:201// .cfi_offset w28, -32202//203//===----------------------------------------------------------------------===//204205#include "AArch64FrameLowering.h"206#include "AArch64InstrInfo.h"207#include "AArch64MachineFunctionInfo.h"208#include "AArch64RegisterInfo.h"209#include "AArch64Subtarget.h"210#include "AArch64TargetMachine.h"211#include "MCTargetDesc/AArch64AddressingModes.h"212#include "MCTargetDesc/AArch64MCTargetDesc.h"213#include "llvm/ADT/ScopeExit.h"214#include "llvm/ADT/SmallVector.h"215#include "llvm/ADT/Statistic.h"216#include "llvm/Analysis/ValueTracking.h"217#include "llvm/CodeGen/LivePhysRegs.h"218#include "llvm/CodeGen/MachineBasicBlock.h"219#include "llvm/CodeGen/MachineFrameInfo.h"220#include "llvm/CodeGen/MachineFunction.h"221#include "llvm/CodeGen/MachineInstr.h"222#include "llvm/CodeGen/MachineInstrBuilder.h"223#include "llvm/CodeGen/MachineMemOperand.h"224#include "llvm/CodeGen/MachineModuleInfo.h"225#include "llvm/CodeGen/MachineOperand.h"226#include "llvm/CodeGen/MachineRegisterInfo.h"227#include "llvm/CodeGen/RegisterScavenging.h"228#include "llvm/CodeGen/TargetInstrInfo.h"229#include "llvm/CodeGen/TargetRegisterInfo.h"230#include "llvm/CodeGen/TargetSubtargetInfo.h"231#include "llvm/CodeGen/WinEHFuncInfo.h"232#include "llvm/IR/Attributes.h"233#include "llvm/IR/CallingConv.h"234#include "llvm/IR/DataLayout.h"235#include "llvm/IR/DebugLoc.h"236#include "llvm/IR/Function.h"237#include "llvm/MC/MCAsmInfo.h"238#include "llvm/MC/MCDwarf.h"239#include "llvm/Support/CommandLine.h"240#include "llvm/Support/Debug.h"241#include "llvm/Support/ErrorHandling.h"242#include "llvm/Support/FormatVariadic.h"243#include "llvm/Support/MathExtras.h"244#include "llvm/Support/raw_ostream.h"245#include "llvm/Target/TargetMachine.h"246#include "llvm/Target/TargetOptions.h"247#include <cassert>248#include <cstdint>249#include <iterator>250#include <optional>251#include <vector>252253using namespace llvm;254255#define DEBUG_TYPE "frame-info"256257static cl::opt<bool> EnableRedZone("aarch64-redzone",258cl::desc("enable use of redzone on AArch64"),259cl::init(false), cl::Hidden);260261static cl::opt<bool> StackTaggingMergeSetTag(262"stack-tagging-merge-settag",263cl::desc("merge settag instruction in function epilog"), cl::init(true),264cl::Hidden);265266static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects",267cl::desc("sort stack allocations"),268cl::init(true), cl::Hidden);269270cl::opt<bool> EnableHomogeneousPrologEpilog(271"homogeneous-prolog-epilog", cl::Hidden,272cl::desc("Emit homogeneous prologue and epilogue for the size "273"optimization (default = off)"));274275// Stack hazard padding size. 0 = disabled.276static cl::opt<unsigned> StackHazardSize("aarch64-stack-hazard-size",277cl::init(0), cl::Hidden);278// Stack hazard size for analysis remarks. StackHazardSize takes precedence.279static cl::opt<unsigned>280StackHazardRemarkSize("aarch64-stack-hazard-remark-size", cl::init(0),281cl::Hidden);282// Whether to insert padding into non-streaming functions (for testing).283static cl::opt<bool>284StackHazardInNonStreaming("aarch64-stack-hazard-in-non-streaming",285cl::init(false), cl::Hidden);286287STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");288289/// Returns how much of the incoming argument stack area (in bytes) we should290/// clean up in an epilogue. For the C calling convention this will be 0, for291/// guaranteed tail call conventions it can be positive (a normal return or a292/// tail call to a function that uses less stack space for arguments) or293/// negative (for a tail call to a function that needs more stack space than us294/// for arguments).295static int64_t getArgumentStackToRestore(MachineFunction &MF,296MachineBasicBlock &MBB) {297MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();298AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();299bool IsTailCallReturn = (MBB.end() != MBBI)300? AArch64InstrInfo::isTailCallReturnInst(*MBBI)301: false;302303int64_t ArgumentPopSize = 0;304if (IsTailCallReturn) {305MachineOperand &StackAdjust = MBBI->getOperand(1);306307// For a tail-call in a callee-pops-arguments environment, some or all of308// the stack may actually be in use for the call's arguments, this is309// calculated during LowerCall and consumed here...310ArgumentPopSize = StackAdjust.getImm();311} else {312// ... otherwise the amount to pop is *all* of the argument space,313// conveniently stored in the MachineFunctionInfo by314// LowerFormalArguments. This will, of course, be zero for the C calling315// convention.316ArgumentPopSize = AFI->getArgumentStackToRestore();317}318319return ArgumentPopSize;320}321322static bool produceCompactUnwindFrame(MachineFunction &MF);323static bool needsWinCFI(const MachineFunction &MF);324static StackOffset getSVEStackSize(const MachineFunction &MF);325static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB);326327/// Returns true if a homogeneous prolog or epilog code can be emitted328/// for the size optimization. If possible, a frame helper call is injected.329/// When Exit block is given, this check is for epilog.330bool AArch64FrameLowering::homogeneousPrologEpilog(331MachineFunction &MF, MachineBasicBlock *Exit) const {332if (!MF.getFunction().hasMinSize())333return false;334if (!EnableHomogeneousPrologEpilog)335return false;336if (EnableRedZone)337return false;338339// TODO: Window is supported yet.340if (needsWinCFI(MF))341return false;342// TODO: SVE is not supported yet.343if (getSVEStackSize(MF))344return false;345346// Bail on stack adjustment needed on return for simplicity.347const MachineFrameInfo &MFI = MF.getFrameInfo();348const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();349if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))350return false;351if (Exit && getArgumentStackToRestore(MF, *Exit))352return false;353354auto *AFI = MF.getInfo<AArch64FunctionInfo>();355if (AFI->hasSwiftAsyncContext() || AFI->hasStreamingModeChanges())356return false;357358// If there are an odd number of GPRs before LR and FP in the CSRs list,359// they will not be paired into one RegPairInfo, which is incompatible with360// the assumption made by the homogeneous prolog epilog pass.361const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();362unsigned NumGPRs = 0;363for (unsigned I = 0; CSRegs[I]; ++I) {364Register Reg = CSRegs[I];365if (Reg == AArch64::LR) {366assert(CSRegs[I + 1] == AArch64::FP);367if (NumGPRs % 2 != 0)368return false;369break;370}371if (AArch64::GPR64RegClass.contains(Reg))372++NumGPRs;373}374375return true;376}377378/// Returns true if CSRs should be paired.379bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {380return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF);381}382383/// This is the biggest offset to the stack pointer we can encode in aarch64384/// instructions (without using a separate calculation and a temp register).385/// Note that the exception here are vector stores/loads which cannot encode any386/// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).387static const unsigned DefaultSafeSPDisplacement = 255;388389/// Look at each instruction that references stack frames and return the stack390/// size limit beyond which some of these instructions will require a scratch391/// register during their expansion later.392static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {393// FIXME: For now, just conservatively guestimate based on unscaled indexing394// range. We'll end up allocating an unnecessary spill slot a lot, but395// realistically that's not a big deal at this stage of the game.396for (MachineBasicBlock &MBB : MF) {397for (MachineInstr &MI : MBB) {398if (MI.isDebugInstr() || MI.isPseudo() ||399MI.getOpcode() == AArch64::ADDXri ||400MI.getOpcode() == AArch64::ADDSXri)401continue;402403for (const MachineOperand &MO : MI.operands()) {404if (!MO.isFI())405continue;406407StackOffset Offset;408if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==409AArch64FrameOffsetCannotUpdate)410return 0;411}412}413}414return DefaultSafeSPDisplacement;415}416417TargetStackID::Value418AArch64FrameLowering::getStackIDForScalableVectors() const {419return TargetStackID::ScalableVector;420}421422/// Returns the size of the fixed object area (allocated next to sp on entry)423/// On Win64 this may include a var args area and an UnwindHelp object for EH.424static unsigned getFixedObjectSize(const MachineFunction &MF,425const AArch64FunctionInfo *AFI, bool IsWin64,426bool IsFunclet) {427if (!IsWin64 || IsFunclet) {428return AFI->getTailCallReservedStack();429} else {430if (AFI->getTailCallReservedStack() != 0 &&431!MF.getFunction().getAttributes().hasAttrSomewhere(432Attribute::SwiftAsync))433report_fatal_error("cannot generate ABI-changing tail call for Win64");434// Var args are stored here in the primary function.435const unsigned VarArgsArea = AFI->getVarArgsGPRSize();436// To support EH funclets we allocate an UnwindHelp object437const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0);438return AFI->getTailCallReservedStack() +439alignTo(VarArgsArea + UnwindHelpObject, 16);440}441}442443/// Returns the size of the entire SVE stackframe (calleesaves + spills).444static StackOffset getSVEStackSize(const MachineFunction &MF) {445const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();446return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE());447}448449bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {450if (!EnableRedZone)451return false;452453// Don't use the red zone if the function explicitly asks us not to.454// This is typically used for kernel code.455const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();456const unsigned RedZoneSize =457Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());458if (!RedZoneSize)459return false;460461const MachineFrameInfo &MFI = MF.getFrameInfo();462const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();463uint64_t NumBytes = AFI->getLocalStackSize();464465// If neither NEON or SVE are available, a COPY from one Q-reg to466// another requires a spill -> reload sequence. We can do that467// using a pre-decrementing store/post-decrementing load, but468// if we do so, we can't use the Red Zone.469bool LowerQRegCopyThroughMem = Subtarget.hasFPARMv8() &&470!Subtarget.isNeonAvailable() &&471!Subtarget.hasSVE();472473return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||474getSVEStackSize(MF) || LowerQRegCopyThroughMem);475}476477/// hasFP - Return true if the specified function should have a dedicated frame478/// pointer register.479bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {480const MachineFrameInfo &MFI = MF.getFrameInfo();481const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();482483// Win64 EH requires a frame pointer if funclets are present, as the locals484// are accessed off the frame pointer in both the parent function and the485// funclets.486if (MF.hasEHFunclets())487return true;488// Retain behavior of always omitting the FP for leaf functions when possible.489if (MF.getTarget().Options.DisableFramePointerElim(MF))490return true;491if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||492MFI.hasStackMap() || MFI.hasPatchPoint() ||493RegInfo->hasStackRealignment(MF))494return true;495// With large callframes around we may need to use FP to access the scavenging496// emergency spillslot.497//498// Unfortunately some calls to hasFP() like machine verifier ->499// getReservedReg() -> hasFP in the middle of global isel are too early500// to know the max call frame size. Hopefully conservatively returning "true"501// in those cases is fine.502// DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.503if (!MFI.isMaxCallFrameSizeComputed() ||504MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)505return true;506507return false;508}509510/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is511/// not required, we reserve argument space for call sites in the function512/// immediately on entry to the current function. This eliminates the need for513/// add/sub sp brackets around call sites. Returns true if the call frame is514/// included as part of the stack frame.515bool AArch64FrameLowering::hasReservedCallFrame(516const MachineFunction &MF) const {517// The stack probing code for the dynamically allocated outgoing arguments518// area assumes that the stack is probed at the top - either by the prologue519// code, which issues a probe if `hasVarSizedObjects` return true, or by the520// most recent variable-sized object allocation. Changing the condition here521// may need to be followed up by changes to the probe issuing logic.522return !MF.getFrameInfo().hasVarSizedObjects();523}524525MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(526MachineFunction &MF, MachineBasicBlock &MBB,527MachineBasicBlock::iterator I) const {528const AArch64InstrInfo *TII =529static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());530const AArch64TargetLowering *TLI =531MF.getSubtarget<AArch64Subtarget>().getTargetLowering();532[[maybe_unused]] MachineFrameInfo &MFI = MF.getFrameInfo();533DebugLoc DL = I->getDebugLoc();534unsigned Opc = I->getOpcode();535bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();536uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;537538if (!hasReservedCallFrame(MF)) {539int64_t Amount = I->getOperand(0).getImm();540Amount = alignTo(Amount, getStackAlign());541if (!IsDestroy)542Amount = -Amount;543544// N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it545// doesn't have to pop anything), then the first operand will be zero too so546// this adjustment is a no-op.547if (CalleePopAmount == 0) {548// FIXME: in-function stack adjustment for calls is limited to 24-bits549// because there's no guaranteed temporary register available.550//551// ADD/SUB (immediate) has only LSL #0 and LSL #12 available.552// 1) For offset <= 12-bit, we use LSL #0553// 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses554// LSL #0, and the other uses LSL #12.555//556// Most call frames will be allocated at the start of a function so557// this is OK, but it is a limitation that needs dealing with.558assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");559560if (TLI->hasInlineStackProbe(MF) &&561-Amount >= AArch64::StackProbeMaxUnprobedStack) {562// When stack probing is enabled, the decrement of SP may need to be563// probed. We only need to do this if the call site needs 1024 bytes of564// space or more, because a region smaller than that is allowed to be565// unprobed at an ABI boundary. We rely on the fact that SP has been566// probed exactly at this point, either by the prologue or most recent567// dynamic allocation.568assert(MFI.hasVarSizedObjects() &&569"non-reserved call frame without var sized objects?");570Register ScratchReg =571MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass);572inlineStackProbeFixed(I, ScratchReg, -Amount, StackOffset::get(0, 0));573} else {574emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,575StackOffset::getFixed(Amount), TII);576}577}578} else if (CalleePopAmount != 0) {579// If the calling convention demands that the callee pops arguments from the580// stack, we want to add it back if we have a reserved call frame.581assert(CalleePopAmount < 0xffffff && "call frame too large");582emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,583StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);584}585return MBB.erase(I);586}587588void AArch64FrameLowering::emitCalleeSavedGPRLocations(589MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {590MachineFunction &MF = *MBB.getParent();591MachineFrameInfo &MFI = MF.getFrameInfo();592AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();593SMEAttrs Attrs(MF.getFunction());594bool LocallyStreaming =595Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface();596597const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();598if (CSI.empty())599return;600601const TargetSubtargetInfo &STI = MF.getSubtarget();602const TargetRegisterInfo &TRI = *STI.getRegisterInfo();603const TargetInstrInfo &TII = *STI.getInstrInfo();604DebugLoc DL = MBB.findDebugLoc(MBBI);605606for (const auto &Info : CSI) {607unsigned FrameIdx = Info.getFrameIdx();608if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector)609continue;610611assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");612int64_t DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true);613int64_t Offset = MFI.getObjectOffset(FrameIdx) - getOffsetOfLocalArea();614615// The location of VG will be emitted before each streaming-mode change in616// the function. Only locally-streaming functions require emitting the617// non-streaming VG location here.618if ((LocallyStreaming && FrameIdx == AFI->getStreamingVGIdx()) ||619(!LocallyStreaming &&620DwarfReg == TRI.getDwarfRegNum(AArch64::VG, true)))621continue;622623unsigned CFIIndex = MF.addFrameInst(624MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));625BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))626.addCFIIndex(CFIIndex)627.setMIFlags(MachineInstr::FrameSetup);628}629}630631void AArch64FrameLowering::emitCalleeSavedSVELocations(632MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {633MachineFunction &MF = *MBB.getParent();634MachineFrameInfo &MFI = MF.getFrameInfo();635636// Add callee saved registers to move list.637const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();638if (CSI.empty())639return;640641const TargetSubtargetInfo &STI = MF.getSubtarget();642const TargetRegisterInfo &TRI = *STI.getRegisterInfo();643const TargetInstrInfo &TII = *STI.getInstrInfo();644DebugLoc DL = MBB.findDebugLoc(MBBI);645AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();646647for (const auto &Info : CSI) {648if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))649continue;650651// Not all unwinders may know about SVE registers, so assume the lowest652// common demoninator.653assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");654unsigned Reg = Info.getReg();655if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))656continue;657658StackOffset Offset =659StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) -660StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI));661662unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset));663BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))664.addCFIIndex(CFIIndex)665.setMIFlags(MachineInstr::FrameSetup);666}667}668669static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF,670MachineBasicBlock &MBB,671MachineBasicBlock::iterator InsertPt,672unsigned DwarfReg) {673unsigned CFIIndex =674MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg));675BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex);676}677678void AArch64FrameLowering::resetCFIToInitialState(679MachineBasicBlock &MBB) const {680681MachineFunction &MF = *MBB.getParent();682const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();683const TargetInstrInfo &TII = *Subtarget.getInstrInfo();684const auto &TRI =685static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo());686const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();687688const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION);689DebugLoc DL;690691// Reset the CFA to `SP + 0`.692MachineBasicBlock::iterator InsertPt = MBB.begin();693unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(694nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0));695BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);696697// Flip the RA sign state.698if (MFI.shouldSignReturnAddress(MF)) {699CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));700BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);701}702703// Shadow call stack uses X18, reset it.704if (MFI.needsShadowCallStackPrologueEpilogue(MF))705insertCFISameValue(CFIDesc, MF, MBB, InsertPt,706TRI.getDwarfRegNum(AArch64::X18, true));707708// Emit .cfi_same_value for callee-saved registers.709const std::vector<CalleeSavedInfo> &CSI =710MF.getFrameInfo().getCalleeSavedInfo();711for (const auto &Info : CSI) {712unsigned Reg = Info.getReg();713if (!TRI.regNeedsCFI(Reg, Reg))714continue;715insertCFISameValue(CFIDesc, MF, MBB, InsertPt,716TRI.getDwarfRegNum(Reg, true));717}718}719720static void emitCalleeSavedRestores(MachineBasicBlock &MBB,721MachineBasicBlock::iterator MBBI,722bool SVE) {723MachineFunction &MF = *MBB.getParent();724MachineFrameInfo &MFI = MF.getFrameInfo();725726const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();727if (CSI.empty())728return;729730const TargetSubtargetInfo &STI = MF.getSubtarget();731const TargetRegisterInfo &TRI = *STI.getRegisterInfo();732const TargetInstrInfo &TII = *STI.getInstrInfo();733DebugLoc DL = MBB.findDebugLoc(MBBI);734735for (const auto &Info : CSI) {736if (SVE !=737(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))738continue;739740unsigned Reg = Info.getReg();741if (SVE &&742!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))743continue;744745if (!Info.isRestored())746continue;747748unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(749nullptr, TRI.getDwarfRegNum(Info.getReg(), true)));750BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))751.addCFIIndex(CFIIndex)752.setMIFlags(MachineInstr::FrameDestroy);753}754}755756void AArch64FrameLowering::emitCalleeSavedGPRRestores(757MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {758emitCalleeSavedRestores(MBB, MBBI, false);759}760761void AArch64FrameLowering::emitCalleeSavedSVERestores(762MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {763emitCalleeSavedRestores(MBB, MBBI, true);764}765766// Return the maximum possible number of bytes for `Size` due to the767// architectural limit on the size of a SVE register.768static int64_t upperBound(StackOffset Size) {769static const int64_t MAX_BYTES_PER_SCALABLE_BYTE = 16;770return Size.getScalable() * MAX_BYTES_PER_SCALABLE_BYTE + Size.getFixed();771}772773void AArch64FrameLowering::allocateStackSpace(774MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,775int64_t RealignmentPadding, StackOffset AllocSize, bool NeedsWinCFI,776bool *HasWinCFI, bool EmitCFI, StackOffset InitialOffset,777bool FollowupAllocs) const {778779if (!AllocSize)780return;781782DebugLoc DL;783MachineFunction &MF = *MBB.getParent();784const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();785const TargetInstrInfo &TII = *Subtarget.getInstrInfo();786AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();787const MachineFrameInfo &MFI = MF.getFrameInfo();788789const int64_t MaxAlign = MFI.getMaxAlign().value();790const uint64_t AndMask = ~(MaxAlign - 1);791792if (!Subtarget.getTargetLowering()->hasInlineStackProbe(MF)) {793Register TargetReg = RealignmentPadding794? findScratchNonCalleeSaveRegister(&MBB)795: AArch64::SP;796// SUB Xd/SP, SP, AllocSize797emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII,798MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,799EmitCFI, InitialOffset);800801if (RealignmentPadding) {802// AND SP, X9, 0b11111...0000803BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP)804.addReg(TargetReg, RegState::Kill)805.addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))806.setMIFlags(MachineInstr::FrameSetup);807AFI.setStackRealigned(true);808809// No need for SEH instructions here; if we're realigning the stack,810// we've set a frame pointer and already finished the SEH prologue.811assert(!NeedsWinCFI);812}813return;814}815816//817// Stack probing allocation.818//819820// Fixed length allocation. If we don't need to re-align the stack and don't821// have SVE objects, we can use a more efficient sequence for stack probing.822if (AllocSize.getScalable() == 0 && RealignmentPadding == 0) {823Register ScratchReg = findScratchNonCalleeSaveRegister(&MBB);824assert(ScratchReg != AArch64::NoRegister);825BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC))826.addDef(ScratchReg)827.addImm(AllocSize.getFixed())828.addImm(InitialOffset.getFixed())829.addImm(InitialOffset.getScalable());830// The fixed allocation may leave unprobed bytes at the top of the831// stack. If we have subsequent alocation (e.g. if we have variable-sized832// objects), we need to issue an extra probe, so these allocations start in833// a known state.834if (FollowupAllocs) {835// STR XZR, [SP]836BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui))837.addReg(AArch64::XZR)838.addReg(AArch64::SP)839.addImm(0)840.setMIFlags(MachineInstr::FrameSetup);841}842843return;844}845846// Variable length allocation.847848// If the (unknown) allocation size cannot exceed the probe size, decrement849// the stack pointer right away.850int64_t ProbeSize = AFI.getStackProbeSize();851if (upperBound(AllocSize) + RealignmentPadding <= ProbeSize) {852Register ScratchReg = RealignmentPadding853? findScratchNonCalleeSaveRegister(&MBB)854: AArch64::SP;855assert(ScratchReg != AArch64::NoRegister);856// SUB Xd, SP, AllocSize857emitFrameOffset(MBB, MBBI, DL, ScratchReg, AArch64::SP, -AllocSize, &TII,858MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,859EmitCFI, InitialOffset);860if (RealignmentPadding) {861// AND SP, Xn, 0b11111...0000862BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), AArch64::SP)863.addReg(ScratchReg, RegState::Kill)864.addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))865.setMIFlags(MachineInstr::FrameSetup);866AFI.setStackRealigned(true);867}868if (FollowupAllocs || upperBound(AllocSize) + RealignmentPadding >869AArch64::StackProbeMaxUnprobedStack) {870// STR XZR, [SP]871BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXui))872.addReg(AArch64::XZR)873.addReg(AArch64::SP)874.addImm(0)875.setMIFlags(MachineInstr::FrameSetup);876}877return;878}879880// Emit a variable-length allocation probing loop.881// TODO: As an optimisation, the loop can be "unrolled" into a few parts,882// each of them guaranteed to adjust the stack by less than the probe size.883Register TargetReg = findScratchNonCalleeSaveRegister(&MBB);884assert(TargetReg != AArch64::NoRegister);885// SUB Xd, SP, AllocSize886emitFrameOffset(MBB, MBBI, DL, TargetReg, AArch64::SP, -AllocSize, &TII,887MachineInstr::FrameSetup, false, NeedsWinCFI, HasWinCFI,888EmitCFI, InitialOffset);889if (RealignmentPadding) {890// AND Xn, Xn, 0b11111...0000891BuildMI(MBB, MBBI, DL, TII.get(AArch64::ANDXri), TargetReg)892.addReg(TargetReg, RegState::Kill)893.addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64))894.setMIFlags(MachineInstr::FrameSetup);895}896897BuildMI(MBB, MBBI, DL, TII.get(AArch64::PROBED_STACKALLOC_VAR))898.addReg(TargetReg);899if (EmitCFI) {900// Set the CFA register back to SP.901unsigned Reg =902Subtarget.getRegisterInfo()->getDwarfRegNum(AArch64::SP, true);903unsigned CFIIndex =904MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));905BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))906.addCFIIndex(CFIIndex)907.setMIFlags(MachineInstr::FrameSetup);908}909if (RealignmentPadding)910AFI.setStackRealigned(true);911}912913static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) {914switch (Reg.id()) {915default:916// The called routine is expected to preserve r19-r28917// r29 and r30 are used as frame pointer and link register resp.918return 0;919920// GPRs921#define CASE(n) \922case AArch64::W##n: \923case AArch64::X##n: \924return AArch64::X##n925CASE(0);926CASE(1);927CASE(2);928CASE(3);929CASE(4);930CASE(5);931CASE(6);932CASE(7);933CASE(8);934CASE(9);935CASE(10);936CASE(11);937CASE(12);938CASE(13);939CASE(14);940CASE(15);941CASE(16);942CASE(17);943CASE(18);944#undef CASE945946// FPRs947#define CASE(n) \948case AArch64::B##n: \949case AArch64::H##n: \950case AArch64::S##n: \951case AArch64::D##n: \952case AArch64::Q##n: \953return HasSVE ? AArch64::Z##n : AArch64::Q##n954CASE(0);955CASE(1);956CASE(2);957CASE(3);958CASE(4);959CASE(5);960CASE(6);961CASE(7);962CASE(8);963CASE(9);964CASE(10);965CASE(11);966CASE(12);967CASE(13);968CASE(14);969CASE(15);970CASE(16);971CASE(17);972CASE(18);973CASE(19);974CASE(20);975CASE(21);976CASE(22);977CASE(23);978CASE(24);979CASE(25);980CASE(26);981CASE(27);982CASE(28);983CASE(29);984CASE(30);985CASE(31);986#undef CASE987}988}989990void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,991MachineBasicBlock &MBB) const {992// Insertion point.993MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();994995// Fake a debug loc.996DebugLoc DL;997if (MBBI != MBB.end())998DL = MBBI->getDebugLoc();9991000const MachineFunction &MF = *MBB.getParent();1001const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();1002const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();10031004BitVector GPRsToZero(TRI.getNumRegs());1005BitVector FPRsToZero(TRI.getNumRegs());1006bool HasSVE = STI.hasSVE();1007for (MCRegister Reg : RegsToZero.set_bits()) {1008if (TRI.isGeneralPurposeRegister(MF, Reg)) {1009// For GPRs, we only care to clear out the 64-bit register.1010if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))1011GPRsToZero.set(XReg);1012} else if (AArch64InstrInfo::isFpOrNEON(Reg)) {1013// For FPRs,1014if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))1015FPRsToZero.set(XReg);1016}1017}10181019const AArch64InstrInfo &TII = *STI.getInstrInfo();10201021// Zero out GPRs.1022for (MCRegister Reg : GPRsToZero.set_bits())1023TII.buildClearRegister(Reg, MBB, MBBI, DL);10241025// Zero out FP/vector registers.1026for (MCRegister Reg : FPRsToZero.set_bits())1027TII.buildClearRegister(Reg, MBB, MBBI, DL);10281029if (HasSVE) {1030for (MCRegister PReg :1031{AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,1032AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,1033AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,1034AArch64::P15}) {1035if (RegsToZero[PReg])1036BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);1037}1038}1039}10401041static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs,1042const MachineBasicBlock &MBB) {1043const MachineFunction *MF = MBB.getParent();1044LiveRegs.addLiveIns(MBB);1045// Mark callee saved registers as used so we will not choose them.1046const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();1047for (unsigned i = 0; CSRegs[i]; ++i)1048LiveRegs.addReg(CSRegs[i]);1049}10501051// Find a scratch register that we can use at the start of the prologue to1052// re-align the stack pointer. We avoid using callee-save registers since they1053// may appear to be free when this is called from canUseAsPrologue (during1054// shrink wrapping), but then no longer be free when this is called from1055// emitPrologue.1056//1057// FIXME: This is a bit conservative, since in the above case we could use one1058// of the callee-save registers as a scratch temp to re-align the stack pointer,1059// but we would then have to make sure that we were in fact saving at least one1060// callee-save register in the prologue, which is additional complexity that1061// doesn't seem worth the benefit.1062static Register findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {1063MachineFunction *MF = MBB->getParent();10641065// If MBB is an entry block, use X9 as the scratch register1066// preserve_none functions may be using X9 to pass arguments,1067// so prefer to pick an available register below.1068if (&MF->front() == MBB &&1069MF->getFunction().getCallingConv() != CallingConv::PreserveNone)1070return AArch64::X9;10711072const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();1073const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();1074LivePhysRegs LiveRegs(TRI);1075getLiveRegsForEntryMBB(LiveRegs, *MBB);10761077// Prefer X9 since it was historically used for the prologue scratch reg.1078const MachineRegisterInfo &MRI = MF->getRegInfo();1079if (LiveRegs.available(MRI, AArch64::X9))1080return AArch64::X9;10811082for (unsigned Reg : AArch64::GPR64RegClass) {1083if (LiveRegs.available(MRI, Reg))1084return Reg;1085}1086return AArch64::NoRegister;1087}10881089bool AArch64FrameLowering::canUseAsPrologue(1090const MachineBasicBlock &MBB) const {1091const MachineFunction *MF = MBB.getParent();1092MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);1093const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();1094const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();1095const AArch64TargetLowering *TLI = Subtarget.getTargetLowering();1096const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>();10971098if (AFI->hasSwiftAsyncContext()) {1099const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();1100const MachineRegisterInfo &MRI = MF->getRegInfo();1101LivePhysRegs LiveRegs(TRI);1102getLiveRegsForEntryMBB(LiveRegs, MBB);1103// The StoreSwiftAsyncContext clobbers X16 and X17. Make sure they are1104// available.1105if (!LiveRegs.available(MRI, AArch64::X16) ||1106!LiveRegs.available(MRI, AArch64::X17))1107return false;1108}11091110// Certain stack probing sequences might clobber flags, then we can't use1111// the block as a prologue if the flags register is a live-in.1112if (MF->getInfo<AArch64FunctionInfo>()->hasStackProbing() &&1113MBB.isLiveIn(AArch64::NZCV))1114return false;11151116// Don't need a scratch register if we're not going to re-align the stack or1117// emit stack probes.1118if (!RegInfo->hasStackRealignment(*MF) && !TLI->hasInlineStackProbe(*MF))1119return true;1120// Otherwise, we can use any block as long as it has a scratch register1121// available.1122return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;1123}11241125static bool windowsRequiresStackProbe(MachineFunction &MF,1126uint64_t StackSizeInBytes) {1127const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();1128const AArch64FunctionInfo &MFI = *MF.getInfo<AArch64FunctionInfo>();1129// TODO: When implementing stack protectors, take that into account1130// for the probe threshold.1131return Subtarget.isTargetWindows() && MFI.hasStackProbing() &&1132StackSizeInBytes >= uint64_t(MFI.getStackProbeSize());1133}11341135static bool needsWinCFI(const MachineFunction &MF) {1136const Function &F = MF.getFunction();1137return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&1138F.needsUnwindTableEntry();1139}11401141bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(1142MachineFunction &MF, uint64_t StackBumpBytes) const {1143AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();1144const MachineFrameInfo &MFI = MF.getFrameInfo();1145const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();1146const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();1147if (homogeneousPrologEpilog(MF))1148return false;11491150if (AFI->getLocalStackSize() == 0)1151return false;11521153// For WinCFI, if optimizing for size, prefer to not combine the stack bump1154// (to force a stp with predecrement) to match the packed unwind format,1155// provided that there actually are any callee saved registers to merge the1156// decrement with.1157// This is potentially marginally slower, but allows using the packed1158// unwind format for functions that both have a local area and callee saved1159// registers. Using the packed unwind format notably reduces the size of1160// the unwind info.1161if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 &&1162MF.getFunction().hasOptSize())1163return false;11641165// 512 is the maximum immediate for stp/ldp that will be used for1166// callee-save save/restores1167if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))1168return false;11691170if (MFI.hasVarSizedObjects())1171return false;11721173if (RegInfo->hasStackRealignment(MF))1174return false;11751176// This isn't strictly necessary, but it simplifies things a bit since the1177// current RedZone handling code assumes the SP is adjusted by the1178// callee-save save/restore code.1179if (canUseRedZone(MF))1180return false;11811182// When there is an SVE area on the stack, always allocate the1183// callee-saves and spills/locals separately.1184if (getSVEStackSize(MF))1185return false;11861187return true;1188}11891190bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(1191MachineBasicBlock &MBB, unsigned StackBumpBytes) const {1192if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes))1193return false;11941195if (MBB.empty())1196return true;11971198// Disable combined SP bump if the last instruction is an MTE tag store. It1199// is almost always better to merge SP adjustment into those instructions.1200MachineBasicBlock::iterator LastI = MBB.getFirstTerminator();1201MachineBasicBlock::iterator Begin = MBB.begin();1202while (LastI != Begin) {1203--LastI;1204if (LastI->isTransient())1205continue;1206if (!LastI->getFlag(MachineInstr::FrameDestroy))1207break;1208}1209switch (LastI->getOpcode()) {1210case AArch64::STGloop:1211case AArch64::STZGloop:1212case AArch64::STGi:1213case AArch64::STZGi:1214case AArch64::ST2Gi:1215case AArch64::STZ2Gi:1216return false;1217default:1218return true;1219}1220llvm_unreachable("unreachable");1221}12221223// Given a load or a store instruction, generate an appropriate unwinding SEH1224// code on Windows.1225static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,1226const TargetInstrInfo &TII,1227MachineInstr::MIFlag Flag) {1228unsigned Opc = MBBI->getOpcode();1229MachineBasicBlock *MBB = MBBI->getParent();1230MachineFunction &MF = *MBB->getParent();1231DebugLoc DL = MBBI->getDebugLoc();1232unsigned ImmIdx = MBBI->getNumOperands() - 1;1233int Imm = MBBI->getOperand(ImmIdx).getImm();1234MachineInstrBuilder MIB;1235const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();1236const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();12371238switch (Opc) {1239default:1240llvm_unreachable("No SEH Opcode for this instruction");1241case AArch64::LDPDpost:1242Imm = -Imm;1243[[fallthrough]];1244case AArch64::STPDpre: {1245unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1246unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());1247MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))1248.addImm(Reg0)1249.addImm(Reg1)1250.addImm(Imm * 8)1251.setMIFlag(Flag);1252break;1253}1254case AArch64::LDPXpost:1255Imm = -Imm;1256[[fallthrough]];1257case AArch64::STPXpre: {1258Register Reg0 = MBBI->getOperand(1).getReg();1259Register Reg1 = MBBI->getOperand(2).getReg();1260if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)1261MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))1262.addImm(Imm * 8)1263.setMIFlag(Flag);1264else1265MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))1266.addImm(RegInfo->getSEHRegNum(Reg0))1267.addImm(RegInfo->getSEHRegNum(Reg1))1268.addImm(Imm * 8)1269.setMIFlag(Flag);1270break;1271}1272case AArch64::LDRDpost:1273Imm = -Imm;1274[[fallthrough]];1275case AArch64::STRDpre: {1276unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1277MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))1278.addImm(Reg)1279.addImm(Imm)1280.setMIFlag(Flag);1281break;1282}1283case AArch64::LDRXpost:1284Imm = -Imm;1285[[fallthrough]];1286case AArch64::STRXpre: {1287unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1288MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))1289.addImm(Reg)1290.addImm(Imm)1291.setMIFlag(Flag);1292break;1293}1294case AArch64::STPDi:1295case AArch64::LDPDi: {1296unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());1297unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1298MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))1299.addImm(Reg0)1300.addImm(Reg1)1301.addImm(Imm * 8)1302.setMIFlag(Flag);1303break;1304}1305case AArch64::STPXi:1306case AArch64::LDPXi: {1307Register Reg0 = MBBI->getOperand(0).getReg();1308Register Reg1 = MBBI->getOperand(1).getReg();1309if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)1310MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))1311.addImm(Imm * 8)1312.setMIFlag(Flag);1313else1314MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))1315.addImm(RegInfo->getSEHRegNum(Reg0))1316.addImm(RegInfo->getSEHRegNum(Reg1))1317.addImm(Imm * 8)1318.setMIFlag(Flag);1319break;1320}1321case AArch64::STRXui:1322case AArch64::LDRXui: {1323int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());1324MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))1325.addImm(Reg)1326.addImm(Imm * 8)1327.setMIFlag(Flag);1328break;1329}1330case AArch64::STRDui:1331case AArch64::LDRDui: {1332unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());1333MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))1334.addImm(Reg)1335.addImm(Imm * 8)1336.setMIFlag(Flag);1337break;1338}1339case AArch64::STPQi:1340case AArch64::LDPQi: {1341unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());1342unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1343MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQP))1344.addImm(Reg0)1345.addImm(Reg1)1346.addImm(Imm * 16)1347.setMIFlag(Flag);1348break;1349}1350case AArch64::LDPQpost:1351Imm = -Imm;1352[[fallthrough]];1353case AArch64::STPQpre: {1354unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());1355unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());1356MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQPX))1357.addImm(Reg0)1358.addImm(Reg1)1359.addImm(Imm * 16)1360.setMIFlag(Flag);1361break;1362}1363}1364auto I = MBB->insertAfter(MBBI, MIB);1365return I;1366}13671368// Fix up the SEH opcode associated with the save/restore instruction.1369static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,1370unsigned LocalStackSize) {1371MachineOperand *ImmOpnd = nullptr;1372unsigned ImmIdx = MBBI->getNumOperands() - 1;1373switch (MBBI->getOpcode()) {1374default:1375llvm_unreachable("Fix the offset in the SEH instruction");1376case AArch64::SEH_SaveFPLR:1377case AArch64::SEH_SaveRegP:1378case AArch64::SEH_SaveReg:1379case AArch64::SEH_SaveFRegP:1380case AArch64::SEH_SaveFReg:1381case AArch64::SEH_SaveAnyRegQP:1382case AArch64::SEH_SaveAnyRegQPX:1383ImmOpnd = &MBBI->getOperand(ImmIdx);1384break;1385}1386if (ImmOpnd)1387ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);1388}13891390bool requiresGetVGCall(MachineFunction &MF) {1391AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();1392return AFI->hasStreamingModeChanges() &&1393!MF.getSubtarget<AArch64Subtarget>().hasSVE();1394}13951396static bool requiresSaveVG(MachineFunction &MF) {1397AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();1398// For Darwin platforms we don't save VG for non-SVE functions, even if SME1399// is enabled with streaming mode changes.1400if (!AFI->hasStreamingModeChanges())1401return false;1402auto &ST = MF.getSubtarget<AArch64Subtarget>();1403if (ST.isTargetDarwin())1404return ST.hasSVE();1405return true;1406}14071408bool isVGInstruction(MachineBasicBlock::iterator MBBI) {1409unsigned Opc = MBBI->getOpcode();1410if (Opc == AArch64::CNTD_XPiI || Opc == AArch64::RDSVLI_XI ||1411Opc == AArch64::UBFMXri)1412return true;14131414if (requiresGetVGCall(*MBBI->getMF())) {1415if (Opc == AArch64::ORRXrr)1416return true;14171418if (Opc == AArch64::BL) {1419auto Op1 = MBBI->getOperand(0);1420return Op1.isSymbol() &&1421(StringRef(Op1.getSymbolName()) == "__arm_get_current_vg");1422}1423}14241425return false;1426}14271428// Convert callee-save register save/restore instruction to do stack pointer1429// decrement/increment to allocate/deallocate the callee-save stack area by1430// converting store/load to use pre/post increment version.1431static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(1432MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,1433const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,1434bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI,1435MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup,1436int CFAOffset = 0) {1437unsigned NewOpc;14381439// If the function contains streaming mode changes, we expect instructions1440// to calculate the value of VG before spilling. For locally-streaming1441// functions, we need to do this for both the streaming and non-streaming1442// vector length. Move past these instructions if necessary.1443MachineFunction &MF = *MBB.getParent();1444if (requiresSaveVG(MF))1445while (isVGInstruction(MBBI))1446++MBBI;14471448switch (MBBI->getOpcode()) {1449default:1450llvm_unreachable("Unexpected callee-save save/restore opcode!");1451case AArch64::STPXi:1452NewOpc = AArch64::STPXpre;1453break;1454case AArch64::STPDi:1455NewOpc = AArch64::STPDpre;1456break;1457case AArch64::STPQi:1458NewOpc = AArch64::STPQpre;1459break;1460case AArch64::STRXui:1461NewOpc = AArch64::STRXpre;1462break;1463case AArch64::STRDui:1464NewOpc = AArch64::STRDpre;1465break;1466case AArch64::STRQui:1467NewOpc = AArch64::STRQpre;1468break;1469case AArch64::LDPXi:1470NewOpc = AArch64::LDPXpost;1471break;1472case AArch64::LDPDi:1473NewOpc = AArch64::LDPDpost;1474break;1475case AArch64::LDPQi:1476NewOpc = AArch64::LDPQpost;1477break;1478case AArch64::LDRXui:1479NewOpc = AArch64::LDRXpost;1480break;1481case AArch64::LDRDui:1482NewOpc = AArch64::LDRDpost;1483break;1484case AArch64::LDRQui:1485NewOpc = AArch64::LDRQpost;1486break;1487}1488// Get rid of the SEH code associated with the old instruction.1489if (NeedsWinCFI) {1490auto SEH = std::next(MBBI);1491if (AArch64InstrInfo::isSEHInstruction(*SEH))1492SEH->eraseFromParent();1493}14941495TypeSize Scale = TypeSize::getFixed(1), Width = TypeSize::getFixed(0);1496int64_t MinOffset, MaxOffset;1497bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo(1498NewOpc, Scale, Width, MinOffset, MaxOffset);1499(void)Success;1500assert(Success && "unknown load/store opcode");15011502// If the first store isn't right where we want SP then we can't fold the1503// update in so create a normal arithmetic instruction instead.1504if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 ||1505CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) {1506// If we are destroying the frame, make sure we add the increment after the1507// last frame operation.1508if (FrameFlag == MachineInstr::FrameDestroy)1509++MBBI;1510emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,1511StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag,1512false, false, nullptr, EmitCFI,1513StackOffset::getFixed(CFAOffset));15141515return std::prev(MBBI);1516}15171518MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));1519MIB.addReg(AArch64::SP, RegState::Define);15201521// Copy all operands other than the immediate offset.1522unsigned OpndIdx = 0;1523for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;1524++OpndIdx)1525MIB.add(MBBI->getOperand(OpndIdx));15261527assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&1528"Unexpected immediate offset in first/last callee-save save/restore "1529"instruction!");1530assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&1531"Unexpected base register in callee-save save/restore instruction!");1532assert(CSStackSizeInc % Scale == 0);1533MIB.addImm(CSStackSizeInc / (int)Scale);15341535MIB.setMIFlags(MBBI->getFlags());1536MIB.setMemRefs(MBBI->memoperands());15371538// Generate a new SEH code that corresponds to the new instruction.1539if (NeedsWinCFI) {1540*HasWinCFI = true;1541InsertSEH(*MIB, *TII, FrameFlag);1542}15431544if (EmitCFI) {1545unsigned CFIIndex = MF.addFrameInst(1546MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc));1547BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))1548.addCFIIndex(CFIIndex)1549.setMIFlags(FrameFlag);1550}15511552return std::prev(MBB.erase(MBBI));1553}15541555// Fixup callee-save register save/restore instructions to take into account1556// combined SP bump by adding the local stack size to the stack offsets.1557static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,1558uint64_t LocalStackSize,1559bool NeedsWinCFI,1560bool *HasWinCFI) {1561if (AArch64InstrInfo::isSEHInstruction(MI))1562return;15631564unsigned Opc = MI.getOpcode();1565unsigned Scale;1566switch (Opc) {1567case AArch64::STPXi:1568case AArch64::STRXui:1569case AArch64::STPDi:1570case AArch64::STRDui:1571case AArch64::LDPXi:1572case AArch64::LDRXui:1573case AArch64::LDPDi:1574case AArch64::LDRDui:1575Scale = 8;1576break;1577case AArch64::STPQi:1578case AArch64::STRQui:1579case AArch64::LDPQi:1580case AArch64::LDRQui:1581Scale = 16;1582break;1583default:1584llvm_unreachable("Unexpected callee-save save/restore opcode!");1585}15861587unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;1588assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&1589"Unexpected base register in callee-save save/restore instruction!");1590// Last operand is immediate offset that needs fixing.1591MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);1592// All generated opcodes have scaled offsets.1593assert(LocalStackSize % Scale == 0);1594OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);15951596if (NeedsWinCFI) {1597*HasWinCFI = true;1598auto MBBI = std::next(MachineBasicBlock::iterator(MI));1599assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");1600assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&1601"Expecting a SEH instruction");1602fixupSEHOpcode(MBBI, LocalStackSize);1603}1604}16051606static bool isTargetWindows(const MachineFunction &MF) {1607return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();1608}16091610// Convenience function to determine whether I is an SVE callee save.1611static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {1612switch (I->getOpcode()) {1613default:1614return false;1615case AArch64::PTRUE_C_B:1616case AArch64::LD1B_2Z_IMM:1617case AArch64::ST1B_2Z_IMM:1618case AArch64::STR_ZXI:1619case AArch64::STR_PXI:1620case AArch64::LDR_ZXI:1621case AArch64::LDR_PXI:1622return I->getFlag(MachineInstr::FrameSetup) ||1623I->getFlag(MachineInstr::FrameDestroy);1624}1625}16261627static void emitShadowCallStackPrologue(const TargetInstrInfo &TII,1628MachineFunction &MF,1629MachineBasicBlock &MBB,1630MachineBasicBlock::iterator MBBI,1631const DebugLoc &DL, bool NeedsWinCFI,1632bool NeedsUnwindInfo) {1633// Shadow call stack prolog: str x30, [x18], #81634BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost))1635.addReg(AArch64::X18, RegState::Define)1636.addReg(AArch64::LR)1637.addReg(AArch64::X18)1638.addImm(8)1639.setMIFlag(MachineInstr::FrameSetup);16401641// This instruction also makes x18 live-in to the entry block.1642MBB.addLiveIn(AArch64::X18);16431644if (NeedsWinCFI)1645BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop))1646.setMIFlag(MachineInstr::FrameSetup);16471648if (NeedsUnwindInfo) {1649// Emit a CFI instruction that causes 8 to be subtracted from the value of1650// x18 when unwinding past this frame.1651static const char CFIInst[] = {1652dwarf::DW_CFA_val_expression,165318, // register16542, // length1655static_cast<char>(unsigned(dwarf::DW_OP_breg18)),1656static_cast<char>(-8) & 0x7f, // addend (sleb128)1657};1658unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(1659nullptr, StringRef(CFIInst, sizeof(CFIInst))));1660BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION))1661.addCFIIndex(CFIIndex)1662.setMIFlag(MachineInstr::FrameSetup);1663}1664}16651666static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII,1667MachineFunction &MF,1668MachineBasicBlock &MBB,1669MachineBasicBlock::iterator MBBI,1670const DebugLoc &DL) {1671// Shadow call stack epilog: ldr x30, [x18, #-8]!1672BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre))1673.addReg(AArch64::X18, RegState::Define)1674.addReg(AArch64::LR, RegState::Define)1675.addReg(AArch64::X18)1676.addImm(-8)1677.setMIFlag(MachineInstr::FrameDestroy);16781679if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF)) {1680unsigned CFIIndex =1681MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));1682BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))1683.addCFIIndex(CFIIndex)1684.setMIFlags(MachineInstr::FrameDestroy);1685}1686}16871688// Define the current CFA rule to use the provided FP.1689static void emitDefineCFAWithFP(MachineFunction &MF, MachineBasicBlock &MBB,1690MachineBasicBlock::iterator MBBI,1691const DebugLoc &DL, unsigned FixedObject) {1692const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();1693const AArch64RegisterInfo *TRI = STI.getRegisterInfo();1694const TargetInstrInfo *TII = STI.getInstrInfo();1695AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();16961697const int OffsetToFirstCalleeSaveFromFP =1698AFI->getCalleeSaveBaseToFrameRecordOffset() -1699AFI->getCalleeSavedStackSize();1700Register FramePtr = TRI->getFrameRegister(MF);1701unsigned Reg = TRI->getDwarfRegNum(FramePtr, true);1702unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(1703nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));1704BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))1705.addCFIIndex(CFIIndex)1706.setMIFlags(MachineInstr::FrameSetup);1707}17081709#ifndef NDEBUG1710/// Collect live registers from the end of \p MI's parent up to (including) \p1711/// MI in \p LiveRegs.1712static void getLivePhysRegsUpTo(MachineInstr &MI, const TargetRegisterInfo &TRI,1713LivePhysRegs &LiveRegs) {17141715MachineBasicBlock &MBB = *MI.getParent();1716LiveRegs.addLiveOuts(MBB);1717for (const MachineInstr &MI :1718reverse(make_range(MI.getIterator(), MBB.instr_end())))1719LiveRegs.stepBackward(MI);1720}1721#endif17221723void AArch64FrameLowering::emitPrologue(MachineFunction &MF,1724MachineBasicBlock &MBB) const {1725MachineBasicBlock::iterator MBBI = MBB.begin();1726const MachineFrameInfo &MFI = MF.getFrameInfo();1727const Function &F = MF.getFunction();1728const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();1729const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();1730const TargetInstrInfo *TII = Subtarget.getInstrInfo();17311732AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();1733bool EmitCFI = AFI->needsDwarfUnwindInfo(MF);1734bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF);1735bool HasFP = hasFP(MF);1736bool NeedsWinCFI = needsWinCFI(MF);1737bool HasWinCFI = false;1738auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });17391740MachineBasicBlock::iterator End = MBB.end();1741#ifndef NDEBUG1742const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();1743// Collect live register from the end of MBB up to the start of the existing1744// frame setup instructions.1745MachineBasicBlock::iterator NonFrameStart = MBB.begin();1746while (NonFrameStart != End &&1747NonFrameStart->getFlag(MachineInstr::FrameSetup))1748++NonFrameStart;17491750LivePhysRegs LiveRegs(*TRI);1751if (NonFrameStart != MBB.end()) {1752getLivePhysRegsUpTo(*NonFrameStart, *TRI, LiveRegs);1753// Ignore registers used for stack management for now.1754LiveRegs.removeReg(AArch64::SP);1755LiveRegs.removeReg(AArch64::X19);1756LiveRegs.removeReg(AArch64::FP);1757LiveRegs.removeReg(AArch64::LR);17581759// X0 will be clobbered by a call to __arm_get_current_vg in the prologue.1760// This is necessary to spill VG if required where SVE is unavailable, but1761// X0 is preserved around this call.1762if (requiresGetVGCall(MF))1763LiveRegs.removeReg(AArch64::X0);1764}17651766auto VerifyClobberOnExit = make_scope_exit([&]() {1767if (NonFrameStart == MBB.end())1768return;1769// Check if any of the newly instructions clobber any of the live registers.1770for (MachineInstr &MI :1771make_range(MBB.instr_begin(), NonFrameStart->getIterator())) {1772for (auto &Op : MI.operands())1773if (Op.isReg() && Op.isDef())1774assert(!LiveRegs.contains(Op.getReg()) &&1775"live register clobbered by inserted prologue instructions");1776}1777});1778#endif17791780bool IsFunclet = MBB.isEHFuncletEntry();17811782// At this point, we're going to decide whether or not the function uses a1783// redzone. In most cases, the function doesn't have a redzone so let's1784// assume that's false and set it to true in the case that there's a redzone.1785AFI->setHasRedZone(false);17861787// Debug location must be unknown since the first debug location is used1788// to determine the end of the prologue.1789DebugLoc DL;17901791const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();1792if (MFnI.needsShadowCallStackPrologueEpilogue(MF))1793emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI,1794MFnI.needsDwarfUnwindInfo(MF));17951796if (MFnI.shouldSignReturnAddress(MF)) {1797BuildMI(MBB, MBBI, DL, TII->get(AArch64::PAUTH_PROLOGUE))1798.setMIFlag(MachineInstr::FrameSetup);1799if (NeedsWinCFI)1800HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR1801}18021803if (EmitCFI && MFnI.isMTETagged()) {1804BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITMTETAGGED))1805.setMIFlag(MachineInstr::FrameSetup);1806}18071808// We signal the presence of a Swift extended frame to external tools by1809// storing FP with 0b0001 in bits 63:60. In normal userland operation a simple1810// ORR is sufficient, it is assumed a Swift kernel would initialize the TBI1811// bits so that is still true.1812if (HasFP && AFI->hasSwiftAsyncContext()) {1813switch (MF.getTarget().Options.SwiftAsyncFramePointer) {1814case SwiftAsyncFramePointerMode::DeploymentBased:1815if (Subtarget.swiftAsyncContextIsDynamicallySet()) {1816// The special symbol below is absolute and has a *value* that can be1817// combined with the frame pointer to signal an extended frame.1818BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16)1819.addExternalSymbol("swift_async_extendedFramePointerFlags",1820AArch64II::MO_GOT);1821if (NeedsWinCFI) {1822BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))1823.setMIFlags(MachineInstr::FrameSetup);1824HasWinCFI = true;1825}1826BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP)1827.addUse(AArch64::FP)1828.addUse(AArch64::X16)1829.addImm(Subtarget.isTargetILP32() ? 32 : 0);1830if (NeedsWinCFI) {1831BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))1832.setMIFlags(MachineInstr::FrameSetup);1833HasWinCFI = true;1834}1835break;1836}1837[[fallthrough]];18381839case SwiftAsyncFramePointerMode::Always:1840// ORR x29, x29, #0x1000_0000_0000_00001841BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP)1842.addUse(AArch64::FP)1843.addImm(0x1100)1844.setMIFlag(MachineInstr::FrameSetup);1845if (NeedsWinCFI) {1846BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))1847.setMIFlags(MachineInstr::FrameSetup);1848HasWinCFI = true;1849}1850break;18511852case SwiftAsyncFramePointerMode::Never:1853break;1854}1855}18561857// All calls are tail calls in GHC calling conv, and functions have no1858// prologue/epilogue.1859if (MF.getFunction().getCallingConv() == CallingConv::GHC)1860return;18611862// Set tagged base pointer to the requested stack slot.1863// Ideally it should match SP value after prologue.1864std::optional<int> TBPI = AFI->getTaggedBasePointerIndex();1865if (TBPI)1866AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI));1867else1868AFI->setTaggedBasePointerOffset(MFI.getStackSize());18691870const StackOffset &SVEStackSize = getSVEStackSize(MF);18711872// getStackSize() includes all the locals in its size calculation. We don't1873// include these locals when computing the stack size of a funclet, as they1874// are allocated in the parent's stack frame and accessed via the frame1875// pointer from the funclet. We only save the callee saved registers in the1876// funclet, which are really the callee saved registers of the parent1877// function, including the funclet.1878int64_t NumBytes =1879IsFunclet ? getWinEHFuncletFrameSize(MF) : MFI.getStackSize();1880if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {1881assert(!HasFP && "unexpected function without stack frame but with FP");1882assert(!SVEStackSize &&1883"unexpected function without stack frame but with SVE objects");1884// All of the stack allocation is for locals.1885AFI->setLocalStackSize(NumBytes);1886if (!NumBytes)1887return;1888// REDZONE: If the stack size is less than 128 bytes, we don't need1889// to actually allocate.1890if (canUseRedZone(MF)) {1891AFI->setHasRedZone(true);1892++NumRedZoneFunctions;1893} else {1894emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,1895StackOffset::getFixed(-NumBytes), TII,1896MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);1897if (EmitCFI) {1898// Label used to tie together the PROLOG_LABEL and the MachineMoves.1899MCSymbol *FrameLabel = MF.getContext().createTempSymbol();1900// Encode the stack size of the leaf function.1901unsigned CFIIndex = MF.addFrameInst(1902MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));1903BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))1904.addCFIIndex(CFIIndex)1905.setMIFlags(MachineInstr::FrameSetup);1906}1907}19081909if (NeedsWinCFI) {1910HasWinCFI = true;1911BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))1912.setMIFlag(MachineInstr::FrameSetup);1913}19141915return;1916}19171918bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());1919unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);19201921auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;1922// All of the remaining stack allocations are for locals.1923AFI->setLocalStackSize(NumBytes - PrologueSaveSize);1924bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);1925bool HomPrologEpilog = homogeneousPrologEpilog(MF);1926if (CombineSPBump) {1927assert(!SVEStackSize && "Cannot combine SP bump with SVE");1928emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,1929StackOffset::getFixed(-NumBytes), TII,1930MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI,1931EmitAsyncCFI);1932NumBytes = 0;1933} else if (HomPrologEpilog) {1934// Stack has been already adjusted.1935NumBytes -= PrologueSaveSize;1936} else if (PrologueSaveSize != 0) {1937MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(1938MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI,1939EmitAsyncCFI);1940NumBytes -= PrologueSaveSize;1941}1942assert(NumBytes >= 0 && "Negative stack allocation size!?");19431944// Move past the saves of the callee-saved registers, fixing up the offsets1945// and pre-inc if we decided to combine the callee-save and local stack1946// pointer bump above.1947while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&1948!IsSVECalleeSave(MBBI)) {1949if (CombineSPBump &&1950// Only fix-up frame-setup load/store instructions.1951(!requiresSaveVG(MF) || !isVGInstruction(MBBI)))1952fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),1953NeedsWinCFI, &HasWinCFI);1954++MBBI;1955}19561957// For funclets the FP belongs to the containing function.1958if (!IsFunclet && HasFP) {1959// Only set up FP if we actually need to.1960int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();19611962if (CombineSPBump)1963FPOffset += AFI->getLocalStackSize();19641965if (AFI->hasSwiftAsyncContext()) {1966// Before we update the live FP we have to ensure there's a valid (or1967// null) asynchronous context in its slot just before FP in the frame1968// record, so store it now.1969const auto &Attrs = MF.getFunction().getAttributes();1970bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync);1971if (HaveInitialContext)1972MBB.addLiveIn(AArch64::X22);1973Register Reg = HaveInitialContext ? AArch64::X22 : AArch64::XZR;1974BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext))1975.addUse(Reg)1976.addUse(AArch64::SP)1977.addImm(FPOffset - 8)1978.setMIFlags(MachineInstr::FrameSetup);1979if (NeedsWinCFI) {1980// WinCFI and arm64e, where StoreSwiftAsyncContext is expanded1981// to multiple instructions, should be mutually-exclusive.1982assert(Subtarget.getTargetTriple().getArchName() != "arm64e");1983BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))1984.setMIFlags(MachineInstr::FrameSetup);1985HasWinCFI = true;1986}1987}19881989if (HomPrologEpilog) {1990auto Prolog = MBBI;1991--Prolog;1992assert(Prolog->getOpcode() == AArch64::HOM_Prolog);1993Prolog->addOperand(MachineOperand::CreateImm(FPOffset));1994} else {1995// Issue sub fp, sp, FPOffset or1996// mov fp,sp when FPOffset is zero.1997// Note: All stores of callee-saved registers are marked as "FrameSetup".1998// This code marks the instruction(s) that set the FP also.1999emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,2000StackOffset::getFixed(FPOffset), TII,2001MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);2002if (NeedsWinCFI && HasWinCFI) {2003BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))2004.setMIFlag(MachineInstr::FrameSetup);2005// After setting up the FP, the rest of the prolog doesn't need to be2006// included in the SEH unwind info.2007NeedsWinCFI = false;2008}2009}2010if (EmitAsyncCFI)2011emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject);2012}20132014// Now emit the moves for whatever callee saved regs we have (including FP,2015// LR if those are saved). Frame instructions for SVE register are emitted2016// later, after the instruction which actually save SVE regs.2017if (EmitAsyncCFI)2018emitCalleeSavedGPRLocations(MBB, MBBI);20192020// Alignment is required for the parent frame, not the funclet2021const bool NeedsRealignment =2022NumBytes && !IsFunclet && RegInfo->hasStackRealignment(MF);2023const int64_t RealignmentPadding =2024(NeedsRealignment && MFI.getMaxAlign() > Align(16))2025? MFI.getMaxAlign().value() - 162026: 0;20272028if (windowsRequiresStackProbe(MF, NumBytes + RealignmentPadding)) {2029uint64_t NumWords = (NumBytes + RealignmentPadding) >> 4;2030if (NeedsWinCFI) {2031HasWinCFI = true;2032// alloc_l can hold at most 256MB, so assume that NumBytes doesn't2033// exceed this amount. We need to move at most 2^24 - 1 into x15.2034// This is at most two instructions, MOVZ follwed by MOVK.2035// TODO: Fix to use multiple stack alloc unwind codes for stacks2036// exceeding 256MB in size.2037if (NumBytes >= (1 << 28))2038report_fatal_error("Stack size cannot exceed 256MB for stack "2039"unwinding purposes");20402041uint32_t LowNumWords = NumWords & 0xFFFF;2042BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)2043.addImm(LowNumWords)2044.addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))2045.setMIFlag(MachineInstr::FrameSetup);2046BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2047.setMIFlag(MachineInstr::FrameSetup);2048if ((NumWords & 0xFFFF0000) != 0) {2049BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)2050.addReg(AArch64::X15)2051.addImm((NumWords & 0xFFFF0000) >> 16) // High half2052.addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))2053.setMIFlag(MachineInstr::FrameSetup);2054BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2055.setMIFlag(MachineInstr::FrameSetup);2056}2057} else {2058BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)2059.addImm(NumWords)2060.setMIFlags(MachineInstr::FrameSetup);2061}20622063const char *ChkStk = Subtarget.getChkStkName();2064switch (MF.getTarget().getCodeModel()) {2065case CodeModel::Tiny:2066case CodeModel::Small:2067case CodeModel::Medium:2068case CodeModel::Kernel:2069BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))2070.addExternalSymbol(ChkStk)2071.addReg(AArch64::X15, RegState::Implicit)2072.addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)2073.addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)2074.addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)2075.setMIFlags(MachineInstr::FrameSetup);2076if (NeedsWinCFI) {2077HasWinCFI = true;2078BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2079.setMIFlag(MachineInstr::FrameSetup);2080}2081break;2082case CodeModel::Large:2083BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))2084.addReg(AArch64::X16, RegState::Define)2085.addExternalSymbol(ChkStk)2086.addExternalSymbol(ChkStk)2087.setMIFlags(MachineInstr::FrameSetup);2088if (NeedsWinCFI) {2089HasWinCFI = true;2090BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2091.setMIFlag(MachineInstr::FrameSetup);2092}20932094BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))2095.addReg(AArch64::X16, RegState::Kill)2096.addReg(AArch64::X15, RegState::Implicit | RegState::Define)2097.addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)2098.addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)2099.addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)2100.setMIFlags(MachineInstr::FrameSetup);2101if (NeedsWinCFI) {2102HasWinCFI = true;2103BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2104.setMIFlag(MachineInstr::FrameSetup);2105}2106break;2107}21082109BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)2110.addReg(AArch64::SP, RegState::Kill)2111.addReg(AArch64::X15, RegState::Kill)2112.addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))2113.setMIFlags(MachineInstr::FrameSetup);2114if (NeedsWinCFI) {2115HasWinCFI = true;2116BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))2117.addImm(NumBytes)2118.setMIFlag(MachineInstr::FrameSetup);2119}2120NumBytes = 0;21212122if (RealignmentPadding > 0) {2123if (RealignmentPadding >= 4096) {2124BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm))2125.addReg(AArch64::X16, RegState::Define)2126.addImm(RealignmentPadding)2127.setMIFlags(MachineInstr::FrameSetup);2128BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXrx64), AArch64::X15)2129.addReg(AArch64::SP)2130.addReg(AArch64::X16, RegState::Kill)2131.addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0))2132.setMIFlag(MachineInstr::FrameSetup);2133} else {2134BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXri), AArch64::X15)2135.addReg(AArch64::SP)2136.addImm(RealignmentPadding)2137.addImm(0)2138.setMIFlag(MachineInstr::FrameSetup);2139}21402141uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);2142BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)2143.addReg(AArch64::X15, RegState::Kill)2144.addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));2145AFI->setStackRealigned(true);21462147// No need for SEH instructions here; if we're realigning the stack,2148// we've set a frame pointer and already finished the SEH prologue.2149assert(!NeedsWinCFI);2150}2151}21522153StackOffset SVECalleeSavesSize = {}, SVELocalsSize = SVEStackSize;2154MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;21552156// Process the SVE callee-saves to determine what space needs to be2157// allocated.2158if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {2159LLVM_DEBUG(dbgs() << "SVECalleeSavedStackSize = " << CalleeSavedSize2160<< "\n");2161// Find callee save instructions in frame.2162CalleeSavesBegin = MBBI;2163assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");2164while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())2165++MBBI;2166CalleeSavesEnd = MBBI;21672168SVECalleeSavesSize = StackOffset::getScalable(CalleeSavedSize);2169SVELocalsSize = SVEStackSize - SVECalleeSavesSize;2170}21712172// Allocate space for the callee saves (if any).2173StackOffset CFAOffset =2174StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes);2175StackOffset LocalsSize = SVELocalsSize + StackOffset::getFixed(NumBytes);2176allocateStackSpace(MBB, CalleeSavesBegin, 0, SVECalleeSavesSize, false,2177nullptr, EmitAsyncCFI && !HasFP, CFAOffset,2178MFI.hasVarSizedObjects() || LocalsSize);2179CFAOffset += SVECalleeSavesSize;21802181if (EmitAsyncCFI)2182emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);21832184// Allocate space for the rest of the frame including SVE locals. Align the2185// stack as necessary.2186assert(!(canUseRedZone(MF) && NeedsRealignment) &&2187"Cannot use redzone with stack realignment");2188if (!canUseRedZone(MF)) {2189// FIXME: in the case of dynamic re-alignment, NumBytes doesn't have2190// the correct value here, as NumBytes also includes padding bytes,2191// which shouldn't be counted here.2192allocateStackSpace(MBB, CalleeSavesEnd, RealignmentPadding,2193SVELocalsSize + StackOffset::getFixed(NumBytes),2194NeedsWinCFI, &HasWinCFI, EmitAsyncCFI && !HasFP,2195CFAOffset, MFI.hasVarSizedObjects());2196}21972198// If we need a base pointer, set it up here. It's whatever the value of the2199// stack pointer is at this point. Any variable size objects will be allocated2200// after this, so we can still use the base pointer to reference locals.2201//2202// FIXME: Clarify FrameSetup flags here.2203// Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is2204// needed.2205// For funclets the BP belongs to the containing function.2206if (!IsFunclet && RegInfo->hasBasePointer(MF)) {2207TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,2208false);2209if (NeedsWinCFI) {2210HasWinCFI = true;2211BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2212.setMIFlag(MachineInstr::FrameSetup);2213}2214}22152216// The very last FrameSetup instruction indicates the end of prologue. Emit a2217// SEH opcode indicating the prologue end.2218if (NeedsWinCFI && HasWinCFI) {2219BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))2220.setMIFlag(MachineInstr::FrameSetup);2221}22222223// SEH funclets are passed the frame pointer in X1. If the parent2224// function uses the base register, then the base register is used2225// directly, and is not retrieved from X1.2226if (IsFunclet && F.hasPersonalityFn()) {2227EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());2228if (isAsynchronousEHPersonality(Per)) {2229BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)2230.addReg(AArch64::X1)2231.setMIFlag(MachineInstr::FrameSetup);2232MBB.addLiveIn(AArch64::X1);2233}2234}22352236if (EmitCFI && !EmitAsyncCFI) {2237if (HasFP) {2238emitDefineCFAWithFP(MF, MBB, MBBI, DL, FixedObject);2239} else {2240StackOffset TotalSize =2241SVEStackSize + StackOffset::getFixed((int64_t)MFI.getStackSize());2242unsigned CFIIndex = MF.addFrameInst(createDefCFA(2243*RegInfo, /*FrameReg=*/AArch64::SP, /*Reg=*/AArch64::SP, TotalSize,2244/*LastAdjustmentWasScalable=*/false));2245BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))2246.addCFIIndex(CFIIndex)2247.setMIFlags(MachineInstr::FrameSetup);2248}2249emitCalleeSavedGPRLocations(MBB, MBBI);2250emitCalleeSavedSVELocations(MBB, MBBI);2251}2252}22532254static bool isFuncletReturnInstr(const MachineInstr &MI) {2255switch (MI.getOpcode()) {2256default:2257return false;2258case AArch64::CATCHRET:2259case AArch64::CLEANUPRET:2260return true;2261}2262}22632264void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,2265MachineBasicBlock &MBB) const {2266MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();2267MachineFrameInfo &MFI = MF.getFrameInfo();2268AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();2269const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();2270const TargetInstrInfo *TII = Subtarget.getInstrInfo();2271DebugLoc DL;2272bool NeedsWinCFI = needsWinCFI(MF);2273bool EmitCFI = AFI->needsAsyncDwarfUnwindInfo(MF);2274bool HasWinCFI = false;2275bool IsFunclet = false;22762277if (MBB.end() != MBBI) {2278DL = MBBI->getDebugLoc();2279IsFunclet = isFuncletReturnInstr(*MBBI);2280}22812282MachineBasicBlock::iterator EpilogStartI = MBB.end();22832284auto FinishingTouches = make_scope_exit([&]() {2285if (AFI->shouldSignReturnAddress(MF)) {2286BuildMI(MBB, MBB.getFirstTerminator(), DL,2287TII->get(AArch64::PAUTH_EPILOGUE))2288.setMIFlag(MachineInstr::FrameDestroy);2289if (NeedsWinCFI)2290HasWinCFI = true; // AArch64PointerAuth pass will insert SEH_PACSignLR2291}2292if (AFI->needsShadowCallStackPrologueEpilogue(MF))2293emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL);2294if (EmitCFI)2295emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator());2296if (HasWinCFI) {2297BuildMI(MBB, MBB.getFirstTerminator(), DL,2298TII->get(AArch64::SEH_EpilogEnd))2299.setMIFlag(MachineInstr::FrameDestroy);2300if (!MF.hasWinCFI())2301MF.setHasWinCFI(true);2302}2303if (NeedsWinCFI) {2304assert(EpilogStartI != MBB.end());2305if (!HasWinCFI)2306MBB.erase(EpilogStartI);2307}2308});23092310int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)2311: MFI.getStackSize();23122313// All calls are tail calls in GHC calling conv, and functions have no2314// prologue/epilogue.2315if (MF.getFunction().getCallingConv() == CallingConv::GHC)2316return;23172318// How much of the stack used by incoming arguments this function is expected2319// to restore in this particular epilogue.2320int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB);2321bool IsWin64 = Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),2322MF.getFunction().isVarArg());2323unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);23242325int64_t AfterCSRPopSize = ArgumentStackToRestore;2326auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;2327// We cannot rely on the local stack size set in emitPrologue if the function2328// has funclets, as funclets have different local stack size requirements, and2329// the current value set in emitPrologue may be that of the containing2330// function.2331if (MF.hasEHFunclets())2332AFI->setLocalStackSize(NumBytes - PrologueSaveSize);2333if (homogeneousPrologEpilog(MF, &MBB)) {2334assert(!NeedsWinCFI);2335auto LastPopI = MBB.getFirstTerminator();2336if (LastPopI != MBB.begin()) {2337auto HomogeneousEpilog = std::prev(LastPopI);2338if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog)2339LastPopI = HomogeneousEpilog;2340}23412342// Adjust local stack2343emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,2344StackOffset::getFixed(AFI->getLocalStackSize()), TII,2345MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);23462347// SP has been already adjusted while restoring callee save regs.2348// We've bailed-out the case with adjusting SP for arguments.2349assert(AfterCSRPopSize == 0);2350return;2351}2352bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);2353// Assume we can't combine the last pop with the sp restore.23542355bool CombineAfterCSRBump = false;2356if (!CombineSPBump && PrologueSaveSize != 0) {2357MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());2358while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||2359AArch64InstrInfo::isSEHInstruction(*Pop))2360Pop = std::prev(Pop);2361// Converting the last ldp to a post-index ldp is valid only if the last2362// ldp's offset is 0.2363const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);2364// If the offset is 0 and the AfterCSR pop is not actually trying to2365// allocate more stack for arguments (in space that an untimely interrupt2366// may clobber), convert it to a post-index ldp.2367if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) {2368convertCalleeSaveRestoreToSPPrePostIncDec(2369MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI,2370MachineInstr::FrameDestroy, PrologueSaveSize);2371} else {2372// If not, make sure to emit an add after the last ldp.2373// We're doing this by transfering the size to be restored from the2374// adjustment *before* the CSR pops to the adjustment *after* the CSR2375// pops.2376AfterCSRPopSize += PrologueSaveSize;2377CombineAfterCSRBump = true;2378}2379}23802381// Move past the restores of the callee-saved registers.2382// If we plan on combining the sp bump of the local stack size and the callee2383// save stack size, we might need to adjust the CSR save and restore offsets.2384MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();2385MachineBasicBlock::iterator Begin = MBB.begin();2386while (LastPopI != Begin) {2387--LastPopI;2388if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||2389IsSVECalleeSave(LastPopI)) {2390++LastPopI;2391break;2392} else if (CombineSPBump)2393fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),2394NeedsWinCFI, &HasWinCFI);2395}23962397if (NeedsWinCFI) {2398// Note that there are cases where we insert SEH opcodes in the2399// epilogue when we had no SEH opcodes in the prologue. For2400// example, when there is no stack frame but there are stack2401// arguments. Insert the SEH_EpilogStart and remove it later if it2402// we didn't emit any SEH opcodes to avoid generating WinCFI for2403// functions that don't need it.2404BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))2405.setMIFlag(MachineInstr::FrameDestroy);2406EpilogStartI = LastPopI;2407--EpilogStartI;2408}24092410if (hasFP(MF) && AFI->hasSwiftAsyncContext()) {2411switch (MF.getTarget().Options.SwiftAsyncFramePointer) {2412case SwiftAsyncFramePointerMode::DeploymentBased:2413// Avoid the reload as it is GOT relative, and instead fall back to the2414// hardcoded value below. This allows a mismatch between the OS and2415// application without immediately terminating on the difference.2416[[fallthrough]];2417case SwiftAsyncFramePointerMode::Always:2418// We need to reset FP to its untagged state on return. Bit 60 is2419// currently used to show the presence of an extended frame.24202421// BIC x29, x29, #0x1000_0000_0000_00002422BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri),2423AArch64::FP)2424.addUse(AArch64::FP)2425.addImm(0x10fe)2426.setMIFlag(MachineInstr::FrameDestroy);2427if (NeedsWinCFI) {2428BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))2429.setMIFlags(MachineInstr::FrameDestroy);2430HasWinCFI = true;2431}2432break;24332434case SwiftAsyncFramePointerMode::Never:2435break;2436}2437}24382439const StackOffset &SVEStackSize = getSVEStackSize(MF);24402441// If there is a single SP update, insert it before the ret and we're done.2442if (CombineSPBump) {2443assert(!SVEStackSize && "Cannot combine SP bump with SVE");24442445// When we are about to restore the CSRs, the CFA register is SP again.2446if (EmitCFI && hasFP(MF)) {2447const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();2448unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);2449unsigned CFIIndex =2450MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes));2451BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))2452.addCFIIndex(CFIIndex)2453.setMIFlags(MachineInstr::FrameDestroy);2454}24552456emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,2457StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize),2458TII, MachineInstr::FrameDestroy, false, NeedsWinCFI,2459&HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes));2460return;2461}24622463NumBytes -= PrologueSaveSize;2464assert(NumBytes >= 0 && "Negative stack allocation size!?");24652466// Process the SVE callee-saves to determine what space needs to be2467// deallocated.2468StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;2469MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;2470if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {2471RestoreBegin = std::prev(RestoreEnd);2472while (RestoreBegin != MBB.begin() &&2473IsSVECalleeSave(std::prev(RestoreBegin)))2474--RestoreBegin;24752476assert(IsSVECalleeSave(RestoreBegin) &&2477IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");24782479StackOffset CalleeSavedSizeAsOffset =2480StackOffset::getScalable(CalleeSavedSize);2481DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;2482DeallocateAfter = CalleeSavedSizeAsOffset;2483}24842485// Deallocate the SVE area.2486if (SVEStackSize) {2487// If we have stack realignment or variable sized objects on the stack,2488// restore the stack pointer from the frame pointer prior to SVE CSR2489// restoration.2490if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) {2491if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {2492// Set SP to start of SVE callee-save area from which they can2493// be reloaded. The code below will deallocate the stack space2494// space by moving FP -> SP.2495emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,2496StackOffset::getScalable(-CalleeSavedSize), TII,2497MachineInstr::FrameDestroy);2498}2499} else {2500if (AFI->getSVECalleeSavedStackSize()) {2501// Deallocate the non-SVE locals first before we can deallocate (and2502// restore callee saves) from the SVE area.2503emitFrameOffset(2504MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,2505StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy,2506false, false, nullptr, EmitCFI && !hasFP(MF),2507SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize));2508NumBytes = 0;2509}25102511emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,2512DeallocateBefore, TII, MachineInstr::FrameDestroy, false,2513false, nullptr, EmitCFI && !hasFP(MF),2514SVEStackSize +2515StackOffset::getFixed(NumBytes + PrologueSaveSize));25162517emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,2518DeallocateAfter, TII, MachineInstr::FrameDestroy, false,2519false, nullptr, EmitCFI && !hasFP(MF),2520DeallocateAfter +2521StackOffset::getFixed(NumBytes + PrologueSaveSize));2522}2523if (EmitCFI)2524emitCalleeSavedSVERestores(MBB, RestoreEnd);2525}25262527if (!hasFP(MF)) {2528bool RedZone = canUseRedZone(MF);2529// If this was a redzone leaf function, we don't need to restore the2530// stack pointer (but we may need to pop stack args for fastcc).2531if (RedZone && AfterCSRPopSize == 0)2532return;25332534// Pop the local variables off the stack. If there are no callee-saved2535// registers, it means we are actually positioned at the terminator and can2536// combine stack increment for the locals and the stack increment for2537// callee-popped arguments into (possibly) a single instruction and be done.2538bool NoCalleeSaveRestore = PrologueSaveSize == 0;2539int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;2540if (NoCalleeSaveRestore)2541StackRestoreBytes += AfterCSRPopSize;25422543emitFrameOffset(2544MBB, LastPopI, DL, AArch64::SP, AArch64::SP,2545StackOffset::getFixed(StackRestoreBytes), TII,2546MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI,2547StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize));25482549// If we were able to combine the local stack pop with the argument pop,2550// then we're done.2551if (NoCalleeSaveRestore || AfterCSRPopSize == 0) {2552return;2553}25542555NumBytes = 0;2556}25572558// Restore the original stack pointer.2559// FIXME: Rather than doing the math here, we should instead just use2560// non-post-indexed loads for the restores if we aren't actually going to2561// be able to save any instructions.2562if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {2563emitFrameOffset(2564MBB, LastPopI, DL, AArch64::SP, AArch64::FP,2565StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()),2566TII, MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);2567} else if (NumBytes)2568emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,2569StackOffset::getFixed(NumBytes), TII,2570MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);25712572// When we are about to restore the CSRs, the CFA register is SP again.2573if (EmitCFI && hasFP(MF)) {2574const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();2575unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);2576unsigned CFIIndex = MF.addFrameInst(2577MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize));2578BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))2579.addCFIIndex(CFIIndex)2580.setMIFlags(MachineInstr::FrameDestroy);2581}25822583// This must be placed after the callee-save restore code because that code2584// assumes the SP is at the same location as it was after the callee-save save2585// code in the prologue.2586if (AfterCSRPopSize) {2587assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an "2588"interrupt may have clobbered");25892590emitFrameOffset(2591MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,2592StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy,2593false, NeedsWinCFI, &HasWinCFI, EmitCFI,2594StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0));2595}2596}25972598bool AArch64FrameLowering::enableCFIFixup(MachineFunction &MF) const {2599return TargetFrameLowering::enableCFIFixup(MF) &&2600MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF);2601}26022603/// getFrameIndexReference - Provide a base+offset reference to an FI slot for2604/// debug info. It's the same as what we use for resolving the code-gen2605/// references for now. FIXME: This can go wrong when references are2606/// SP-relative and simple call frames aren't used.2607StackOffset2608AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,2609Register &FrameReg) const {2610return resolveFrameIndexReference(2611MF, FI, FrameReg,2612/*PreferFP=*/2613MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress) ||2614MF.getFunction().hasFnAttribute(Attribute::SanitizeMemTag),2615/*ForSimm=*/false);2616}26172618StackOffset2619AArch64FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,2620int FI) const {2621// This function serves to provide a comparable offset from a single reference2622// point (the value of SP at function entry) that can be used for analysis,2623// e.g. the stack-frame-layout analysis pass. It is not guaranteed to be2624// correct for all objects in the presence of VLA-area objects or dynamic2625// stack re-alignment.26262627const auto &MFI = MF.getFrameInfo();26282629int64_t ObjectOffset = MFI.getObjectOffset(FI);2630StackOffset SVEStackSize = getSVEStackSize(MF);26312632// For VLA-area objects, just emit an offset at the end of the stack frame.2633// Whilst not quite correct, these objects do live at the end of the frame and2634// so it is more useful for analysis for the offset to reflect this.2635if (MFI.isVariableSizedObjectIndex(FI)) {2636return StackOffset::getFixed(-((int64_t)MFI.getStackSize())) - SVEStackSize;2637}26382639// This is correct in the absence of any SVE stack objects.2640if (!SVEStackSize)2641return StackOffset::getFixed(ObjectOffset - getOffsetOfLocalArea());26422643const auto *AFI = MF.getInfo<AArch64FunctionInfo>();2644if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {2645return StackOffset::get(-((int64_t)AFI->getCalleeSavedStackSize()),2646ObjectOffset);2647}26482649bool IsFixed = MFI.isFixedObjectIndex(FI);2650bool IsCSR =2651!IsFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));26522653StackOffset ScalableOffset = {};2654if (!IsFixed && !IsCSR)2655ScalableOffset = -SVEStackSize;26562657return StackOffset::getFixed(ObjectOffset) + ScalableOffset;2658}26592660StackOffset2661AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,2662int FI) const {2663return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI));2664}26652666static StackOffset getFPOffset(const MachineFunction &MF,2667int64_t ObjectOffset) {2668const auto *AFI = MF.getInfo<AArch64FunctionInfo>();2669const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();2670const Function &F = MF.getFunction();2671bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());2672unsigned FixedObject =2673getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);2674int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());2675int64_t FPAdjust =2676CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();2677return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);2678}26792680static StackOffset getStackOffset(const MachineFunction &MF,2681int64_t ObjectOffset) {2682const auto &MFI = MF.getFrameInfo();2683return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());2684}26852686// TODO: This function currently does not work for scalable vectors.2687int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,2688int FI) const {2689const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(2690MF.getSubtarget().getRegisterInfo());2691int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);2692return RegInfo->getLocalAddressRegister(MF) == AArch64::FP2693? getFPOffset(MF, ObjectOffset).getFixed()2694: getStackOffset(MF, ObjectOffset).getFixed();2695}26962697StackOffset AArch64FrameLowering::resolveFrameIndexReference(2698const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,2699bool ForSimm) const {2700const auto &MFI = MF.getFrameInfo();2701int64_t ObjectOffset = MFI.getObjectOffset(FI);2702bool isFixed = MFI.isFixedObjectIndex(FI);2703bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector;2704return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,2705PreferFP, ForSimm);2706}27072708StackOffset AArch64FrameLowering::resolveFrameOffsetReference(2709const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,2710Register &FrameReg, bool PreferFP, bool ForSimm) const {2711const auto &MFI = MF.getFrameInfo();2712const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(2713MF.getSubtarget().getRegisterInfo());2714const auto *AFI = MF.getInfo<AArch64FunctionInfo>();2715const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();27162717int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();2718int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();2719bool isCSR =2720!isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));27212722const StackOffset &SVEStackSize = getSVEStackSize(MF);27232724// Use frame pointer to reference fixed objects. Use it for locals if2725// there are VLAs or a dynamically realigned SP (and thus the SP isn't2726// reliable as a base). Make sure useFPForScavengingIndex() does the2727// right thing for the emergency spill slot.2728bool UseFP = false;2729if (AFI->hasStackFrame() && !isSVE) {2730// We shouldn't prefer using the FP to access fixed-sized stack objects when2731// there are scalable (SVE) objects in between the FP and the fixed-sized2732// objects.2733PreferFP &= !SVEStackSize;27342735// Note: Keeping the following as multiple 'if' statements rather than2736// merging to a single expression for readability.2737//2738// Argument access should always use the FP.2739if (isFixed) {2740UseFP = hasFP(MF);2741} else if (isCSR && RegInfo->hasStackRealignment(MF)) {2742// References to the CSR area must use FP if we're re-aligning the stack2743// since the dynamically-sized alignment padding is between the SP/BP and2744// the CSR area.2745assert(hasFP(MF) && "Re-aligned stack must have frame pointer");2746UseFP = true;2747} else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {2748// If the FPOffset is negative and we're producing a signed immediate, we2749// have to keep in mind that the available offset range for negative2750// offsets is smaller than for positive ones. If an offset is available2751// via the FP and the SP, use whichever is closest.2752bool FPOffsetFits = !ForSimm || FPOffset >= -256;2753PreferFP |= Offset > -FPOffset && !SVEStackSize;27542755if (MFI.hasVarSizedObjects()) {2756// If we have variable sized objects, we can use either FP or BP, as the2757// SP offset is unknown. We can use the base pointer if we have one and2758// FP is not preferred. If not, we're stuck with using FP.2759bool CanUseBP = RegInfo->hasBasePointer(MF);2760if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.2761UseFP = PreferFP;2762else if (!CanUseBP) // Can't use BP. Forced to use FP.2763UseFP = true;2764// else we can use BP and FP, but the offset from FP won't fit.2765// That will make us scavenge registers which we can probably avoid by2766// using BP. If it won't fit for BP either, we'll scavenge anyway.2767} else if (FPOffset >= 0) {2768// Use SP or FP, whichever gives us the best chance of the offset2769// being in range for direct access. If the FPOffset is positive,2770// that'll always be best, as the SP will be even further away.2771UseFP = true;2772} else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {2773// Funclets access the locals contained in the parent's stack frame2774// via the frame pointer, so we have to use the FP in the parent2775// function.2776(void) Subtarget;2777assert(Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),2778MF.getFunction().isVarArg()) &&2779"Funclets should only be present on Win64");2780UseFP = true;2781} else {2782// We have the choice between FP and (SP or BP).2783if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.2784UseFP = true;2785}2786}2787}27882789assert(2790((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&2791"In the presence of dynamic stack pointer realignment, "2792"non-argument/CSR objects cannot be accessed through the frame pointer");27932794if (isSVE) {2795StackOffset FPOffset =2796StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);2797StackOffset SPOffset =2798SVEStackSize +2799StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),2800ObjectOffset);2801// Always use the FP for SVE spills if available and beneficial.2802if (hasFP(MF) && (SPOffset.getFixed() ||2803FPOffset.getScalable() < SPOffset.getScalable() ||2804RegInfo->hasStackRealignment(MF))) {2805FrameReg = RegInfo->getFrameRegister(MF);2806return FPOffset;2807}28082809FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()2810: (unsigned)AArch64::SP;2811return SPOffset;2812}28132814StackOffset ScalableOffset = {};2815if (UseFP && !(isFixed || isCSR))2816ScalableOffset = -SVEStackSize;2817if (!UseFP && (isFixed || isCSR))2818ScalableOffset = SVEStackSize;28192820if (UseFP) {2821FrameReg = RegInfo->getFrameRegister(MF);2822return StackOffset::getFixed(FPOffset) + ScalableOffset;2823}28242825// Use the base pointer if we have one.2826if (RegInfo->hasBasePointer(MF))2827FrameReg = RegInfo->getBaseRegister();2828else {2829assert(!MFI.hasVarSizedObjects() &&2830"Can't use SP when we have var sized objects.");2831FrameReg = AArch64::SP;2832// If we're using the red zone for this function, the SP won't actually2833// be adjusted, so the offsets will be negative. They're also all2834// within range of the signed 9-bit immediate instructions.2835if (canUseRedZone(MF))2836Offset -= AFI->getLocalStackSize();2837}28382839return StackOffset::getFixed(Offset) + ScalableOffset;2840}28412842static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {2843// Do not set a kill flag on values that are also marked as live-in. This2844// happens with the @llvm-returnaddress intrinsic and with arguments passed in2845// callee saved registers.2846// Omitting the kill flags is conservatively correct even if the live-in2847// is not used after all.2848bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);2849return getKillRegState(!IsLiveIn);2850}28512852static bool produceCompactUnwindFrame(MachineFunction &MF) {2853const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();2854AttributeList Attrs = MF.getFunction().getAttributes();2855return Subtarget.isTargetMachO() &&2856!(Subtarget.getTargetLowering()->supportSwiftError() &&2857Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&2858MF.getFunction().getCallingConv() != CallingConv::SwiftTail &&2859!requiresSaveVG(MF);2860}28612862static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,2863bool NeedsWinCFI, bool IsFirst,2864const TargetRegisterInfo *TRI) {2865// If we are generating register pairs for a Windows function that requires2866// EH support, then pair consecutive registers only. There are no unwind2867// opcodes for saves/restores of non-consectuve register pairs.2868// The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,2869// save_lrpair.2870// https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling28712872if (Reg2 == AArch64::FP)2873return true;2874if (!NeedsWinCFI)2875return false;2876if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1)2877return false;2878// If pairing a GPR with LR, the pair can be described by the save_lrpair2879// opcode. If this is the first register pair, it would end up with a2880// predecrement, but there's no save_lrpair_x opcode, so we can only do this2881// if LR is paired with something else than the first register.2882// The save_lrpair opcode requires the first register to be an odd one.2883if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&2884(Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)2885return false;2886return true;2887}28882889/// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.2890/// WindowsCFI requires that only consecutive registers can be paired.2891/// LR and FP need to be allocated together when the frame needs to save2892/// the frame-record. This means any other register pairing with LR is invalid.2893static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,2894bool UsesWinAAPCS, bool NeedsWinCFI,2895bool NeedsFrameRecord, bool IsFirst,2896const TargetRegisterInfo *TRI) {2897if (UsesWinAAPCS)2898return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst,2899TRI);29002901// If we need to store the frame record, don't pair any register2902// with LR other than FP.2903if (NeedsFrameRecord)2904return Reg2 == AArch64::LR;29052906return false;2907}29082909namespace {29102911struct RegPairInfo {2912unsigned Reg1 = AArch64::NoRegister;2913unsigned Reg2 = AArch64::NoRegister;2914int FrameIdx;2915int Offset;2916enum RegType { GPR, FPR64, FPR128, PPR, ZPR, VG } Type;29172918RegPairInfo() = default;29192920bool isPaired() const { return Reg2 != AArch64::NoRegister; }29212922unsigned getScale() const {2923switch (Type) {2924case PPR:2925return 2;2926case GPR:2927case FPR64:2928case VG:2929return 8;2930case ZPR:2931case FPR128:2932return 16;2933}2934llvm_unreachable("Unsupported type");2935}29362937bool isScalable() const { return Type == PPR || Type == ZPR; }2938};29392940} // end anonymous namespace29412942static void computeCalleeSaveRegisterPairs(2943MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,2944const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,2945bool NeedsFrameRecord) {29462947if (CSI.empty())2948return;29492950bool IsWindows = isTargetWindows(MF);2951bool NeedsWinCFI = needsWinCFI(MF);2952AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();2953MachineFrameInfo &MFI = MF.getFrameInfo();2954CallingConv::ID CC = MF.getFunction().getCallingConv();2955unsigned Count = CSI.size();2956(void)CC;2957// MachO's compact unwind format relies on all registers being stored in2958// pairs.2959assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||2960CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS ||2961CC == CallingConv::Win64 || (Count & 1) == 0) &&2962"Odd number of callee-saved regs to spill!");2963int ByteOffset = AFI->getCalleeSavedStackSize();2964int StackFillDir = -1;2965int RegInc = 1;2966unsigned FirstReg = 0;2967if (NeedsWinCFI) {2968// For WinCFI, fill the stack from the bottom up.2969ByteOffset = 0;2970StackFillDir = 1;2971// As the CSI array is reversed to match PrologEpilogInserter, iterate2972// backwards, to pair up registers starting from lower numbered registers.2973RegInc = -1;2974FirstReg = Count - 1;2975}2976int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();2977bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();2978Register LastReg = 0;29792980// When iterating backwards, the loop condition relies on unsigned wraparound.2981for (unsigned i = FirstReg; i < Count; i += RegInc) {2982RegPairInfo RPI;2983RPI.Reg1 = CSI[i].getReg();29842985if (AArch64::GPR64RegClass.contains(RPI.Reg1))2986RPI.Type = RegPairInfo::GPR;2987else if (AArch64::FPR64RegClass.contains(RPI.Reg1))2988RPI.Type = RegPairInfo::FPR64;2989else if (AArch64::FPR128RegClass.contains(RPI.Reg1))2990RPI.Type = RegPairInfo::FPR128;2991else if (AArch64::ZPRRegClass.contains(RPI.Reg1))2992RPI.Type = RegPairInfo::ZPR;2993else if (AArch64::PPRRegClass.contains(RPI.Reg1))2994RPI.Type = RegPairInfo::PPR;2995else if (RPI.Reg1 == AArch64::VG)2996RPI.Type = RegPairInfo::VG;2997else2998llvm_unreachable("Unsupported register class.");29993000// Add the stack hazard size as we transition from GPR->FPR CSRs.3001if (AFI->hasStackHazardSlotIndex() &&3002(!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&3003AArch64InstrInfo::isFpOrNEON(RPI.Reg1))3004ByteOffset += StackFillDir * StackHazardSize;3005LastReg = RPI.Reg1;30063007// Add the next reg to the pair if it is in the same register class.3008if (unsigned(i + RegInc) < Count && !AFI->hasStackHazardSlotIndex()) {3009Register NextReg = CSI[i + RegInc].getReg();3010bool IsFirst = i == FirstReg;3011switch (RPI.Type) {3012case RegPairInfo::GPR:3013if (AArch64::GPR64RegClass.contains(NextReg) &&3014!invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,3015NeedsWinCFI, NeedsFrameRecord, IsFirst,3016TRI))3017RPI.Reg2 = NextReg;3018break;3019case RegPairInfo::FPR64:3020if (AArch64::FPR64RegClass.contains(NextReg) &&3021!invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,3022IsFirst, TRI))3023RPI.Reg2 = NextReg;3024break;3025case RegPairInfo::FPR128:3026if (AArch64::FPR128RegClass.contains(NextReg))3027RPI.Reg2 = NextReg;3028break;3029case RegPairInfo::PPR:3030break;3031case RegPairInfo::ZPR:3032if (AFI->getPredicateRegForFillSpill() != 0)3033if (((RPI.Reg1 - AArch64::Z0) & 1) == 0 && (NextReg == RPI.Reg1 + 1))3034RPI.Reg2 = NextReg;3035break;3036case RegPairInfo::VG:3037break;3038}3039}30403041// GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI3042// list to come in sorted by frame index so that we can issue the store3043// pair instructions directly. Assert if we see anything otherwise.3044//3045// The order of the registers in the list is controlled by3046// getCalleeSavedRegs(), so they will always be in-order, as well.3047assert((!RPI.isPaired() ||3048(CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&3049"Out of order callee saved regs!");30503051assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||3052RPI.Reg1 == AArch64::LR) &&3053"FrameRecord must be allocated together with LR");30543055// Windows AAPCS has FP and LR reversed.3056assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||3057RPI.Reg2 == AArch64::LR) &&3058"FrameRecord must be allocated together with LR");30593060// MachO's compact unwind format relies on all registers being stored in3061// adjacent register pairs.3062assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||3063CC == CallingConv::PreserveAll || CC == CallingConv::CXX_FAST_TLS ||3064CC == CallingConv::Win64 ||3065(RPI.isPaired() &&3066((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||3067RPI.Reg1 + 1 == RPI.Reg2))) &&3068"Callee-save registers not saved as adjacent register pair!");30693070RPI.FrameIdx = CSI[i].getFrameIdx();3071if (NeedsWinCFI &&3072RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair3073RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();3074int Scale = RPI.getScale();30753076int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;3077assert(OffsetPre % Scale == 0);30783079if (RPI.isScalable())3080ScalableByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);3081else3082ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);30833084// Swift's async context is directly before FP, so allocate an extra3085// 8 bytes for it.3086if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&3087((!IsWindows && RPI.Reg2 == AArch64::FP) ||3088(IsWindows && RPI.Reg2 == AArch64::LR)))3089ByteOffset += StackFillDir * 8;30903091// Round up size of non-pair to pair size if we need to pad the3092// callee-save area to ensure 16-byte alignment.3093if (NeedGapToAlignStack && !NeedsWinCFI && !RPI.isScalable() &&3094RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired() &&3095ByteOffset % 16 != 0) {3096ByteOffset += 8 * StackFillDir;3097assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));3098// A stack frame with a gap looks like this, bottom up:3099// d9, d8. x21, gap, x20, x19.3100// Set extra alignment on the x21 object to create the gap above it.3101MFI.setObjectAlignment(RPI.FrameIdx, Align(16));3102NeedGapToAlignStack = false;3103}31043105int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;3106assert(OffsetPost % Scale == 0);3107// If filling top down (default), we want the offset after incrementing it.3108// If filling bottom up (WinCFI) we need the original offset.3109int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;31103111// The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the3112// Swift context can directly precede FP.3113if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&3114((!IsWindows && RPI.Reg2 == AArch64::FP) ||3115(IsWindows && RPI.Reg2 == AArch64::LR)))3116Offset += 8;3117RPI.Offset = Offset / Scale;31183119assert((!RPI.isPaired() ||3120(!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||3121(RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&3122"Offset out of bounds for LDP/STP immediate");31233124// Save the offset to frame record so that the FP register can point to the3125// innermost frame record (spilled FP and LR registers).3126if (NeedsFrameRecord &&3127((!IsWindows && RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||3128(IsWindows && RPI.Reg1 == AArch64::FP && RPI.Reg2 == AArch64::LR)))3129AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);31303131RegPairs.push_back(RPI);3132if (RPI.isPaired())3133i += RegInc;3134}3135if (NeedsWinCFI) {3136// If we need an alignment gap in the stack, align the topmost stack3137// object. A stack frame with a gap looks like this, bottom up:3138// x19, d8. d9, gap.3139// Set extra alignment on the topmost stack object (the first element in3140// CSI, which goes top down), to create the gap above it.3141if (AFI->hasCalleeSaveStackFreeSpace())3142MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));3143// We iterated bottom up over the registers; flip RegPairs back to top3144// down order.3145std::reverse(RegPairs.begin(), RegPairs.end());3146}3147}31483149bool AArch64FrameLowering::spillCalleeSavedRegisters(3150MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,3151ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {3152MachineFunction &MF = *MBB.getParent();3153const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();3154AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();3155bool NeedsWinCFI = needsWinCFI(MF);3156DebugLoc DL;3157SmallVector<RegPairInfo, 8> RegPairs;31583159computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));31603161MachineRegisterInfo &MRI = MF.getRegInfo();3162// Refresh the reserved regs in case there are any potential changes since the3163// last freeze.3164MRI.freezeReservedRegs();31653166if (homogeneousPrologEpilog(MF)) {3167auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))3168.setMIFlag(MachineInstr::FrameSetup);31693170for (auto &RPI : RegPairs) {3171MIB.addReg(RPI.Reg1);3172MIB.addReg(RPI.Reg2);31733174// Update register live in.3175if (!MRI.isReserved(RPI.Reg1))3176MBB.addLiveIn(RPI.Reg1);3177if (RPI.isPaired() && !MRI.isReserved(RPI.Reg2))3178MBB.addLiveIn(RPI.Reg2);3179}3180return true;3181}3182bool PTrueCreated = false;3183for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {3184unsigned Reg1 = RPI.Reg1;3185unsigned Reg2 = RPI.Reg2;3186unsigned StrOpc;31873188// Issue sequence of spills for cs regs. The first spill may be converted3189// to a pre-decrement store later by emitPrologue if the callee-save stack3190// area allocation can't be combined with the local stack area allocation.3191// For example:3192// stp x22, x21, [sp, #0] // addImm(+0)3193// stp x20, x19, [sp, #16] // addImm(+2)3194// stp fp, lr, [sp, #32] // addImm(+4)3195// Rationale: This sequence saves uop updates compared to a sequence of3196// pre-increment spills like stp xi,xj,[sp,#-16]!3197// Note: Similar rationale and sequence for restores in epilog.3198unsigned Size;3199Align Alignment;3200switch (RPI.Type) {3201case RegPairInfo::GPR:3202StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;3203Size = 8;3204Alignment = Align(8);3205break;3206case RegPairInfo::FPR64:3207StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;3208Size = 8;3209Alignment = Align(8);3210break;3211case RegPairInfo::FPR128:3212StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;3213Size = 16;3214Alignment = Align(16);3215break;3216case RegPairInfo::ZPR:3217StrOpc = RPI.isPaired() ? AArch64::ST1B_2Z_IMM : AArch64::STR_ZXI;3218Size = 16;3219Alignment = Align(16);3220break;3221case RegPairInfo::PPR:3222StrOpc = AArch64::STR_PXI;3223Size = 2;3224Alignment = Align(2);3225break;3226case RegPairInfo::VG:3227StrOpc = AArch64::STRXui;3228Size = 8;3229Alignment = Align(8);3230break;3231}32323233unsigned X0Scratch = AArch64::NoRegister;3234if (Reg1 == AArch64::VG) {3235// Find an available register to store value of VG to.3236Reg1 = findScratchNonCalleeSaveRegister(&MBB);3237assert(Reg1 != AArch64::NoRegister);3238SMEAttrs Attrs(MF.getFunction());32393240if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface() &&3241AFI->getStreamingVGIdx() == std::numeric_limits<int>::max()) {3242// For locally-streaming functions, we need to store both the streaming3243// & non-streaming VG. Spill the streaming value first.3244BuildMI(MBB, MI, DL, TII.get(AArch64::RDSVLI_XI), Reg1)3245.addImm(1)3246.setMIFlag(MachineInstr::FrameSetup);3247BuildMI(MBB, MI, DL, TII.get(AArch64::UBFMXri), Reg1)3248.addReg(Reg1)3249.addImm(3)3250.addImm(63)3251.setMIFlag(MachineInstr::FrameSetup);32523253AFI->setStreamingVGIdx(RPI.FrameIdx);3254} else if (MF.getSubtarget<AArch64Subtarget>().hasSVE()) {3255BuildMI(MBB, MI, DL, TII.get(AArch64::CNTD_XPiI), Reg1)3256.addImm(31)3257.addImm(1)3258.setMIFlag(MachineInstr::FrameSetup);3259AFI->setVGIdx(RPI.FrameIdx);3260} else {3261const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();3262if (llvm::any_of(3263MBB.liveins(),3264[&STI](const MachineBasicBlock::RegisterMaskPair &LiveIn) {3265return STI.getRegisterInfo()->isSuperOrSubRegisterEq(3266AArch64::X0, LiveIn.PhysReg);3267}))3268X0Scratch = Reg1;32693270if (X0Scratch != AArch64::NoRegister)3271BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), Reg1)3272.addReg(AArch64::XZR)3273.addReg(AArch64::X0, RegState::Undef)3274.addReg(AArch64::X0, RegState::Implicit)3275.setMIFlag(MachineInstr::FrameSetup);32763277const uint32_t *RegMask = TRI->getCallPreservedMask(3278MF,3279CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1);3280BuildMI(MBB, MI, DL, TII.get(AArch64::BL))3281.addExternalSymbol("__arm_get_current_vg")3282.addRegMask(RegMask)3283.addReg(AArch64::X0, RegState::ImplicitDefine)3284.setMIFlag(MachineInstr::FrameSetup);3285Reg1 = AArch64::X0;3286AFI->setVGIdx(RPI.FrameIdx);3287}3288}32893290LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);3291if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);3292dbgs() << ") -> fi#(" << RPI.FrameIdx;3293if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;3294dbgs() << ")\n");32953296assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&3297"Windows unwdinding requires a consecutive (FP,LR) pair");3298// Windows unwind codes require consecutive registers if registers are3299// paired. Make the switch here, so that the code below will save (x,x+1)3300// and not (x+1,x).3301unsigned FrameIdxReg1 = RPI.FrameIdx;3302unsigned FrameIdxReg2 = RPI.FrameIdx + 1;3303if (NeedsWinCFI && RPI.isPaired()) {3304std::swap(Reg1, Reg2);3305std::swap(FrameIdxReg1, FrameIdxReg2);3306}33073308if (RPI.isPaired() && RPI.isScalable()) {3309[[maybe_unused]] const AArch64Subtarget &Subtarget =3310MF.getSubtarget<AArch64Subtarget>();3311AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();3312unsigned PnReg = AFI->getPredicateRegForFillSpill();3313assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) &&3314"Expects SVE2.1 or SME2 target and a predicate register");3315#ifdef EXPENSIVE_CHECKS3316auto IsPPR = [](const RegPairInfo &c) {3317return c.Reg1 == RegPairInfo::PPR;3318};3319auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR);3320auto IsZPR = [](const RegPairInfo &c) {3321return c.Type == RegPairInfo::ZPR;3322};3323auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR);3324assert(!(PPRBegin < ZPRBegin) &&3325"Expected callee save predicate to be handled first");3326#endif3327if (!PTrueCreated) {3328PTrueCreated = true;3329BuildMI(MBB, MI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)3330.setMIFlags(MachineInstr::FrameSetup);3331}3332MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));3333if (!MRI.isReserved(Reg1))3334MBB.addLiveIn(Reg1);3335if (!MRI.isReserved(Reg2))3336MBB.addLiveIn(Reg2);3337MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0));3338MIB.addMemOperand(MF.getMachineMemOperand(3339MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),3340MachineMemOperand::MOStore, Size, Alignment));3341MIB.addReg(PnReg);3342MIB.addReg(AArch64::SP)3343.addImm(RPI.Offset) // [sp, #offset*scale],3344// where factor*scale is implicit3345.setMIFlag(MachineInstr::FrameSetup);3346MIB.addMemOperand(MF.getMachineMemOperand(3347MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),3348MachineMemOperand::MOStore, Size, Alignment));3349if (NeedsWinCFI)3350InsertSEH(MIB, TII, MachineInstr::FrameSetup);3351} else { // The code when the pair of ZReg is not present3352MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));3353if (!MRI.isReserved(Reg1))3354MBB.addLiveIn(Reg1);3355if (RPI.isPaired()) {3356if (!MRI.isReserved(Reg2))3357MBB.addLiveIn(Reg2);3358MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));3359MIB.addMemOperand(MF.getMachineMemOperand(3360MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),3361MachineMemOperand::MOStore, Size, Alignment));3362}3363MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))3364.addReg(AArch64::SP)3365.addImm(RPI.Offset) // [sp, #offset*scale],3366// where factor*scale is implicit3367.setMIFlag(MachineInstr::FrameSetup);3368MIB.addMemOperand(MF.getMachineMemOperand(3369MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),3370MachineMemOperand::MOStore, Size, Alignment));3371if (NeedsWinCFI)3372InsertSEH(MIB, TII, MachineInstr::FrameSetup);3373}3374// Update the StackIDs of the SVE stack slots.3375MachineFrameInfo &MFI = MF.getFrameInfo();3376if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR) {3377MFI.setStackID(FrameIdxReg1, TargetStackID::ScalableVector);3378if (RPI.isPaired())3379MFI.setStackID(FrameIdxReg2, TargetStackID::ScalableVector);3380}33813382if (X0Scratch != AArch64::NoRegister)3383BuildMI(MBB, MI, DL, TII.get(AArch64::ORRXrr), AArch64::X0)3384.addReg(AArch64::XZR)3385.addReg(X0Scratch, RegState::Undef)3386.addReg(X0Scratch, RegState::Implicit)3387.setMIFlag(MachineInstr::FrameSetup);3388}3389return true;3390}33913392bool AArch64FrameLowering::restoreCalleeSavedRegisters(3393MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,3394MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {3395MachineFunction &MF = *MBB.getParent();3396const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();3397DebugLoc DL;3398SmallVector<RegPairInfo, 8> RegPairs;3399bool NeedsWinCFI = needsWinCFI(MF);34003401if (MBBI != MBB.end())3402DL = MBBI->getDebugLoc();34033404computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));3405if (homogeneousPrologEpilog(MF, &MBB)) {3406auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))3407.setMIFlag(MachineInstr::FrameDestroy);3408for (auto &RPI : RegPairs) {3409MIB.addReg(RPI.Reg1, RegState::Define);3410MIB.addReg(RPI.Reg2, RegState::Define);3411}3412return true;3413}34143415// For performance reasons restore SVE register in increasing order3416auto IsPPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::PPR; };3417auto PPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsPPR);3418auto PPREnd = std::find_if_not(PPRBegin, RegPairs.end(), IsPPR);3419std::reverse(PPRBegin, PPREnd);3420auto IsZPR = [](const RegPairInfo &c) { return c.Type == RegPairInfo::ZPR; };3421auto ZPRBegin = std::find_if(RegPairs.begin(), RegPairs.end(), IsZPR);3422auto ZPREnd = std::find_if_not(ZPRBegin, RegPairs.end(), IsZPR);3423std::reverse(ZPRBegin, ZPREnd);34243425bool PTrueCreated = false;3426for (const RegPairInfo &RPI : RegPairs) {3427unsigned Reg1 = RPI.Reg1;3428unsigned Reg2 = RPI.Reg2;34293430// Issue sequence of restores for cs regs. The last restore may be converted3431// to a post-increment load later by emitEpilogue if the callee-save stack3432// area allocation can't be combined with the local stack area allocation.3433// For example:3434// ldp fp, lr, [sp, #32] // addImm(+4)3435// ldp x20, x19, [sp, #16] // addImm(+2)3436// ldp x22, x21, [sp, #0] // addImm(+0)3437// Note: see comment in spillCalleeSavedRegisters()3438unsigned LdrOpc;3439unsigned Size;3440Align Alignment;3441switch (RPI.Type) {3442case RegPairInfo::GPR:3443LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;3444Size = 8;3445Alignment = Align(8);3446break;3447case RegPairInfo::FPR64:3448LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;3449Size = 8;3450Alignment = Align(8);3451break;3452case RegPairInfo::FPR128:3453LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;3454Size = 16;3455Alignment = Align(16);3456break;3457case RegPairInfo::ZPR:3458LdrOpc = RPI.isPaired() ? AArch64::LD1B_2Z_IMM : AArch64::LDR_ZXI;3459Size = 16;3460Alignment = Align(16);3461break;3462case RegPairInfo::PPR:3463LdrOpc = AArch64::LDR_PXI;3464Size = 2;3465Alignment = Align(2);3466break;3467case RegPairInfo::VG:3468continue;3469}3470LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);3471if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);3472dbgs() << ") -> fi#(" << RPI.FrameIdx;3473if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;3474dbgs() << ")\n");34753476// Windows unwind codes require consecutive registers if registers are3477// paired. Make the switch here, so that the code below will save (x,x+1)3478// and not (x+1,x).3479unsigned FrameIdxReg1 = RPI.FrameIdx;3480unsigned FrameIdxReg2 = RPI.FrameIdx + 1;3481if (NeedsWinCFI && RPI.isPaired()) {3482std::swap(Reg1, Reg2);3483std::swap(FrameIdxReg1, FrameIdxReg2);3484}34853486AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();3487if (RPI.isPaired() && RPI.isScalable()) {3488[[maybe_unused]] const AArch64Subtarget &Subtarget =3489MF.getSubtarget<AArch64Subtarget>();3490unsigned PnReg = AFI->getPredicateRegForFillSpill();3491assert(((Subtarget.hasSVE2p1() || Subtarget.hasSME2()) && PnReg != 0) &&3492"Expects SVE2.1 or SME2 target and a predicate register");3493#ifdef EXPENSIVE_CHECKS3494assert(!(PPRBegin < ZPRBegin) &&3495"Expected callee save predicate to be handled first");3496#endif3497if (!PTrueCreated) {3498PTrueCreated = true;3499BuildMI(MBB, MBBI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)3500.setMIFlags(MachineInstr::FrameDestroy);3501}3502MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));3503MIB.addReg(/*PairRegs*/ AArch64::Z0_Z1 + (RPI.Reg1 - AArch64::Z0),3504getDefRegState(true));3505MIB.addMemOperand(MF.getMachineMemOperand(3506MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),3507MachineMemOperand::MOLoad, Size, Alignment));3508MIB.addReg(PnReg);3509MIB.addReg(AArch64::SP)3510.addImm(RPI.Offset) // [sp, #offset*scale]3511// where factor*scale is implicit3512.setMIFlag(MachineInstr::FrameDestroy);3513MIB.addMemOperand(MF.getMachineMemOperand(3514MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),3515MachineMemOperand::MOLoad, Size, Alignment));3516if (NeedsWinCFI)3517InsertSEH(MIB, TII, MachineInstr::FrameDestroy);3518} else {3519MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));3520if (RPI.isPaired()) {3521MIB.addReg(Reg2, getDefRegState(true));3522MIB.addMemOperand(MF.getMachineMemOperand(3523MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),3524MachineMemOperand::MOLoad, Size, Alignment));3525}3526MIB.addReg(Reg1, getDefRegState(true));3527MIB.addReg(AArch64::SP)3528.addImm(RPI.Offset) // [sp, #offset*scale]3529// where factor*scale is implicit3530.setMIFlag(MachineInstr::FrameDestroy);3531MIB.addMemOperand(MF.getMachineMemOperand(3532MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),3533MachineMemOperand::MOLoad, Size, Alignment));3534if (NeedsWinCFI)3535InsertSEH(MIB, TII, MachineInstr::FrameDestroy);3536}3537}3538return true;3539}35403541// Return the FrameID for a MMO.3542static std::optional<int> getMMOFrameID(MachineMemOperand *MMO,3543const MachineFrameInfo &MFI) {3544auto *PSV =3545dyn_cast_or_null<FixedStackPseudoSourceValue>(MMO->getPseudoValue());3546if (PSV)3547return std::optional<int>(PSV->getFrameIndex());35483549if (MMO->getValue()) {3550if (auto *Al = dyn_cast<AllocaInst>(getUnderlyingObject(MMO->getValue()))) {3551for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd();3552FI++)3553if (MFI.getObjectAllocation(FI) == Al)3554return FI;3555}3556}35573558return std::nullopt;3559}35603561// Return the FrameID for a Load/Store instruction by looking at the first MMO.3562static std::optional<int> getLdStFrameID(const MachineInstr &MI,3563const MachineFrameInfo &MFI) {3564if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)3565return std::nullopt;35663567return getMMOFrameID(*MI.memoperands_begin(), MFI);3568}35693570// Check if a Hazard slot is needed for the current function, and if so create3571// one for it. The index is stored in AArch64FunctionInfo->StackHazardSlotIndex,3572// which can be used to determine if any hazard padding is needed.3573void AArch64FrameLowering::determineStackHazardSlot(3574MachineFunction &MF, BitVector &SavedRegs) const {3575if (StackHazardSize == 0 || StackHazardSize % 16 != 0 ||3576MF.getInfo<AArch64FunctionInfo>()->hasStackHazardSlotIndex())3577return;35783579// Stack hazards are only needed in streaming functions.3580SMEAttrs Attrs(MF.getFunction());3581if (!StackHazardInNonStreaming && Attrs.hasNonStreamingInterfaceAndBody())3582return;35833584MachineFrameInfo &MFI = MF.getFrameInfo();35853586// Add a hazard slot if there are any CSR FPR registers, or are any fp-only3587// stack objects.3588bool HasFPRCSRs = any_of(SavedRegs.set_bits(), [](unsigned Reg) {3589return AArch64::FPR64RegClass.contains(Reg) ||3590AArch64::FPR128RegClass.contains(Reg) ||3591AArch64::ZPRRegClass.contains(Reg) ||3592AArch64::PPRRegClass.contains(Reg);3593});3594bool HasFPRStackObjects = false;3595if (!HasFPRCSRs) {3596std::vector<unsigned> FrameObjects(MFI.getObjectIndexEnd());3597for (auto &MBB : MF) {3598for (auto &MI : MBB) {3599std::optional<int> FI = getLdStFrameID(MI, MFI);3600if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) {3601if (MFI.getStackID(*FI) == TargetStackID::ScalableVector ||3602AArch64InstrInfo::isFpOrNEON(MI))3603FrameObjects[*FI] |= 2;3604else3605FrameObjects[*FI] |= 1;3606}3607}3608}3609HasFPRStackObjects =3610any_of(FrameObjects, [](unsigned B) { return (B & 3) == 2; });3611}36123613if (HasFPRCSRs || HasFPRStackObjects) {3614int ID = MFI.CreateStackObject(StackHazardSize, Align(16), false);3615LLVM_DEBUG(dbgs() << "Created Hazard slot at " << ID << " size "3616<< StackHazardSize << "\n");3617MF.getInfo<AArch64FunctionInfo>()->setStackHazardSlotIndex(ID);3618}3619}36203621void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,3622BitVector &SavedRegs,3623RegScavenger *RS) const {3624// All calls are tail calls in GHC calling conv, and functions have no3625// prologue/epilogue.3626if (MF.getFunction().getCallingConv() == CallingConv::GHC)3627return;36283629TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);3630const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(3631MF.getSubtarget().getRegisterInfo());3632const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();3633AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();3634unsigned UnspilledCSGPR = AArch64::NoRegister;3635unsigned UnspilledCSGPRPaired = AArch64::NoRegister;36363637MachineFrameInfo &MFI = MF.getFrameInfo();3638const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();36393640unsigned BasePointerReg = RegInfo->hasBasePointer(MF)3641? RegInfo->getBaseRegister()3642: (unsigned)AArch64::NoRegister;36433644unsigned ExtraCSSpill = 0;3645bool HasUnpairedGPR64 = false;3646// Figure out which callee-saved registers to save/restore.3647for (unsigned i = 0; CSRegs[i]; ++i) {3648const unsigned Reg = CSRegs[i];36493650// Add the base pointer register to SavedRegs if it is callee-save.3651if (Reg == BasePointerReg)3652SavedRegs.set(Reg);36533654bool RegUsed = SavedRegs.test(Reg);3655unsigned PairedReg = AArch64::NoRegister;3656const bool RegIsGPR64 = AArch64::GPR64RegClass.contains(Reg);3657if (RegIsGPR64 || AArch64::FPR64RegClass.contains(Reg) ||3658AArch64::FPR128RegClass.contains(Reg)) {3659// Compensate for odd numbers of GP CSRs.3660// For now, all the known cases of odd number of CSRs are of GPRs.3661if (HasUnpairedGPR64)3662PairedReg = CSRegs[i % 2 == 0 ? i - 1 : i + 1];3663else3664PairedReg = CSRegs[i ^ 1];3665}36663667// If the function requires all the GP registers to save (SavedRegs),3668// and there are an odd number of GP CSRs at the same time (CSRegs),3669// PairedReg could be in a different register class from Reg, which would3670// lead to a FPR (usually D8) accidentally being marked saved.3671if (RegIsGPR64 && !AArch64::GPR64RegClass.contains(PairedReg)) {3672PairedReg = AArch64::NoRegister;3673HasUnpairedGPR64 = true;3674}3675assert(PairedReg == AArch64::NoRegister ||3676AArch64::GPR64RegClass.contains(Reg, PairedReg) ||3677AArch64::FPR64RegClass.contains(Reg, PairedReg) ||3678AArch64::FPR128RegClass.contains(Reg, PairedReg));36793680if (!RegUsed) {3681if (AArch64::GPR64RegClass.contains(Reg) &&3682!RegInfo->isReservedReg(MF, Reg)) {3683UnspilledCSGPR = Reg;3684UnspilledCSGPRPaired = PairedReg;3685}3686continue;3687}36883689// MachO's compact unwind format relies on all registers being stored in3690// pairs.3691// FIXME: the usual format is actually better if unwinding isn't needed.3692if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&3693!SavedRegs.test(PairedReg)) {3694SavedRegs.set(PairedReg);3695if (AArch64::GPR64RegClass.contains(PairedReg) &&3696!RegInfo->isReservedReg(MF, PairedReg))3697ExtraCSSpill = PairedReg;3698}3699}37003701if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&3702!Subtarget.isTargetWindows()) {3703// For Windows calling convention on a non-windows OS, where X18 is treated3704// as reserved, back up X18 when entering non-windows code (marked with the3705// Windows calling convention) and restore when returning regardless of3706// whether the individual function uses it - it might call other functions3707// that clobber it.3708SavedRegs.set(AArch64::X18);3709}37103711// Calculates the callee saved stack size.3712unsigned CSStackSize = 0;3713unsigned SVECSStackSize = 0;3714const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();3715const MachineRegisterInfo &MRI = MF.getRegInfo();3716for (unsigned Reg : SavedRegs.set_bits()) {3717auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;3718if (AArch64::PPRRegClass.contains(Reg) ||3719AArch64::ZPRRegClass.contains(Reg))3720SVECSStackSize += RegSize;3721else3722CSStackSize += RegSize;3723}37243725// Increase the callee-saved stack size if the function has streaming mode3726// changes, as we will need to spill the value of the VG register.3727// For locally streaming functions, we spill both the streaming and3728// non-streaming VG value.3729const Function &F = MF.getFunction();3730SMEAttrs Attrs(F);3731if (requiresSaveVG(MF)) {3732if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface())3733CSStackSize += 16;3734else3735CSStackSize += 8;3736}37373738// Determine if a Hazard slot should be used, and increase the CSStackSize by3739// StackHazardSize if so.3740determineStackHazardSlot(MF, SavedRegs);3741if (AFI->hasStackHazardSlotIndex())3742CSStackSize += StackHazardSize;37433744// Save number of saved regs, so we can easily update CSStackSize later.3745unsigned NumSavedRegs = SavedRegs.count();37463747// The frame record needs to be created by saving the appropriate registers3748uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);3749if (hasFP(MF) ||3750windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {3751SavedRegs.set(AArch64::FP);3752SavedRegs.set(AArch64::LR);3753}37543755LLVM_DEBUG({3756dbgs() << "*** determineCalleeSaves\nSaved CSRs:";3757for (unsigned Reg : SavedRegs.set_bits())3758dbgs() << ' ' << printReg(Reg, RegInfo);3759dbgs() << "\n";3760});37613762// If any callee-saved registers are used, the frame cannot be eliminated.3763int64_t SVEStackSize =3764alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);3765bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;37663767// The CSR spill slots have not been allocated yet, so estimateStackSize3768// won't include them.3769unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);37703771// We may address some of the stack above the canonical frame address, either3772// for our own arguments or during a call. Include that in calculating whether3773// we have complicated addressing concerns.3774int64_t CalleeStackUsed = 0;3775for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) {3776int64_t FixedOff = MFI.getObjectOffset(I);3777if (FixedOff > CalleeStackUsed)3778CalleeStackUsed = FixedOff;3779}37803781// Conservatively always assume BigStack when there are SVE spills.3782bool BigStack = SVEStackSize || (EstimatedStackSize + CSStackSize +3783CalleeStackUsed) > EstimatedStackSizeLimit;3784if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))3785AFI->setHasStackFrame(true);37863787// Estimate if we might need to scavenge a register at some point in order3788// to materialize a stack offset. If so, either spill one additional3789// callee-saved register or reserve a special spill slot to facilitate3790// register scavenging. If we already spilled an extra callee-saved register3791// above to keep the number of spills even, we don't need to do anything else3792// here.3793if (BigStack) {3794if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {3795LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)3796<< " to get a scratch register.\n");3797SavedRegs.set(UnspilledCSGPR);3798ExtraCSSpill = UnspilledCSGPR;37993800// MachO's compact unwind format relies on all registers being stored in3801// pairs, so if we need to spill one extra for BigStack, then we need to3802// store the pair.3803if (producePairRegisters(MF)) {3804if (UnspilledCSGPRPaired == AArch64::NoRegister) {3805// Failed to make a pair for compact unwind format, revert spilling.3806if (produceCompactUnwindFrame(MF)) {3807SavedRegs.reset(UnspilledCSGPR);3808ExtraCSSpill = AArch64::NoRegister;3809}3810} else3811SavedRegs.set(UnspilledCSGPRPaired);3812}3813}38143815// If we didn't find an extra callee-saved register to spill, create3816// an emergency spill slot.3817if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {3818const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();3819const TargetRegisterClass &RC = AArch64::GPR64RegClass;3820unsigned Size = TRI->getSpillSize(RC);3821Align Alignment = TRI->getSpillAlign(RC);3822int FI = MFI.CreateStackObject(Size, Alignment, false);3823RS->addScavengingFrameIndex(FI);3824LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI3825<< " as the emergency spill slot.\n");3826}3827}38283829// Adding the size of additional 64bit GPR saves.3830CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);38313832// A Swift asynchronous context extends the frame record with a pointer3833// directly before FP.3834if (hasFP(MF) && AFI->hasSwiftAsyncContext())3835CSStackSize += 8;38363837uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);3838LLVM_DEBUG(dbgs() << "Estimated stack frame size: "3839<< EstimatedStackSize + AlignedCSStackSize << " bytes.\n");38403841assert((!MFI.isCalleeSavedInfoValid() ||3842AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&3843"Should not invalidate callee saved info");38443845// Round up to register pair alignment to avoid additional SP adjustment3846// instructions.3847AFI->setCalleeSavedStackSize(AlignedCSStackSize);3848AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);3849AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));3850}38513852bool AArch64FrameLowering::assignCalleeSavedSpillSlots(3853MachineFunction &MF, const TargetRegisterInfo *RegInfo,3854std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,3855unsigned &MaxCSFrameIndex) const {3856bool NeedsWinCFI = needsWinCFI(MF);3857// To match the canonical windows frame layout, reverse the list of3858// callee saved registers to get them laid out by PrologEpilogInserter3859// in the right order. (PrologEpilogInserter allocates stack objects top3860// down. Windows canonical prologs store higher numbered registers at3861// the top, thus have the CSI array start from the highest registers.)3862if (NeedsWinCFI)3863std::reverse(CSI.begin(), CSI.end());38643865if (CSI.empty())3866return true; // Early exit if no callee saved registers are modified!38673868// Now that we know which registers need to be saved and restored, allocate3869// stack slots for them.3870MachineFrameInfo &MFI = MF.getFrameInfo();3871auto *AFI = MF.getInfo<AArch64FunctionInfo>();38723873bool UsesWinAAPCS = isTargetWindows(MF);3874if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) {3875int FrameIdx = MFI.CreateStackObject(8, Align(16), true);3876AFI->setSwiftAsyncContextFrameIdx(FrameIdx);3877if ((unsigned)FrameIdx < MinCSFrameIndex)3878MinCSFrameIndex = FrameIdx;3879if ((unsigned)FrameIdx > MaxCSFrameIndex)3880MaxCSFrameIndex = FrameIdx;3881}38823883// Insert VG into the list of CSRs, immediately before LR if saved.3884if (requiresSaveVG(MF)) {3885std::vector<CalleeSavedInfo> VGSaves;3886SMEAttrs Attrs(MF.getFunction());38873888auto VGInfo = CalleeSavedInfo(AArch64::VG);3889VGInfo.setRestored(false);3890VGSaves.push_back(VGInfo);38913892// Add VG again if the function is locally-streaming, as we will spill two3893// values.3894if (Attrs.hasStreamingBody() && !Attrs.hasStreamingInterface())3895VGSaves.push_back(VGInfo);38963897bool InsertBeforeLR = false;38983899for (unsigned I = 0; I < CSI.size(); I++)3900if (CSI[I].getReg() == AArch64::LR) {3901InsertBeforeLR = true;3902CSI.insert(CSI.begin() + I, VGSaves.begin(), VGSaves.end());3903break;3904}39053906if (!InsertBeforeLR)3907CSI.insert(CSI.end(), VGSaves.begin(), VGSaves.end());3908}39093910Register LastReg = 0;3911int HazardSlotIndex = std::numeric_limits<int>::max();3912for (auto &CS : CSI) {3913Register Reg = CS.getReg();3914const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);39153916// Create a hazard slot as we switch between GPR and FPR CSRs.3917if (AFI->hasStackHazardSlotIndex() &&3918(!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&3919AArch64InstrInfo::isFpOrNEON(Reg)) {3920assert(HazardSlotIndex == std::numeric_limits<int>::max() &&3921"Unexpected register order for hazard slot");3922HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);3923LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex3924<< "\n");3925AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);3926if ((unsigned)HazardSlotIndex < MinCSFrameIndex)3927MinCSFrameIndex = HazardSlotIndex;3928if ((unsigned)HazardSlotIndex > MaxCSFrameIndex)3929MaxCSFrameIndex = HazardSlotIndex;3930}39313932unsigned Size = RegInfo->getSpillSize(*RC);3933Align Alignment(RegInfo->getSpillAlign(*RC));3934int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);3935CS.setFrameIdx(FrameIdx);39363937if ((unsigned)FrameIdx < MinCSFrameIndex)3938MinCSFrameIndex = FrameIdx;3939if ((unsigned)FrameIdx > MaxCSFrameIndex)3940MaxCSFrameIndex = FrameIdx;39413942// Grab 8 bytes below FP for the extended asynchronous frame info.3943if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS &&3944Reg == AArch64::FP) {3945FrameIdx = MFI.CreateStackObject(8, Alignment, true);3946AFI->setSwiftAsyncContextFrameIdx(FrameIdx);3947if ((unsigned)FrameIdx < MinCSFrameIndex)3948MinCSFrameIndex = FrameIdx;3949if ((unsigned)FrameIdx > MaxCSFrameIndex)3950MaxCSFrameIndex = FrameIdx;3951}3952LastReg = Reg;3953}39543955// Add hazard slot in the case where no FPR CSRs are present.3956if (AFI->hasStackHazardSlotIndex() &&3957HazardSlotIndex == std::numeric_limits<int>::max()) {3958HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);3959LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex3960<< "\n");3961AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);3962if ((unsigned)HazardSlotIndex < MinCSFrameIndex)3963MinCSFrameIndex = HazardSlotIndex;3964if ((unsigned)HazardSlotIndex > MaxCSFrameIndex)3965MaxCSFrameIndex = HazardSlotIndex;3966}39673968return true;3969}39703971bool AArch64FrameLowering::enableStackSlotScavenging(3972const MachineFunction &MF) const {3973const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();3974// If the function has streaming-mode changes, don't scavenge a3975// spillslot in the callee-save area, as that might require an3976// 'addvl' in the streaming-mode-changing call-sequence when the3977// function doesn't use a FP.3978if (AFI->hasStreamingModeChanges() && !hasFP(MF))3979return false;3980// Don't allow register salvaging with hazard slots, in case it moves objects3981// into the wrong place.3982if (AFI->hasStackHazardSlotIndex())3983return false;3984return AFI->hasCalleeSaveStackFreeSpace();3985}39863987/// returns true if there are any SVE callee saves.3988static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,3989int &Min, int &Max) {3990Min = std::numeric_limits<int>::max();3991Max = std::numeric_limits<int>::min();39923993if (!MFI.isCalleeSavedInfoValid())3994return false;39953996const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();3997for (auto &CS : CSI) {3998if (AArch64::ZPRRegClass.contains(CS.getReg()) ||3999AArch64::PPRRegClass.contains(CS.getReg())) {4000assert((Max == std::numeric_limits<int>::min() ||4001Max + 1 == CS.getFrameIdx()) &&4002"SVE CalleeSaves are not consecutive");40034004Min = std::min(Min, CS.getFrameIdx());4005Max = std::max(Max, CS.getFrameIdx());4006}4007}4008return Min != std::numeric_limits<int>::max();4009}40104011// Process all the SVE stack objects and determine offsets for each4012// object. If AssignOffsets is true, the offsets get assigned.4013// Fills in the first and last callee-saved frame indices into4014// Min/MaxCSFrameIndex, respectively.4015// Returns the size of the stack.4016static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,4017int &MinCSFrameIndex,4018int &MaxCSFrameIndex,4019bool AssignOffsets) {4020#ifndef NDEBUG4021// First process all fixed stack objects.4022for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)4023assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&4024"SVE vectors should never be passed on the stack by value, only by "4025"reference.");4026#endif40274028auto Assign = [&MFI](int FI, int64_t Offset) {4029LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");4030MFI.setObjectOffset(FI, Offset);4031};40324033int64_t Offset = 0;40344035// Then process all callee saved slots.4036if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {4037// Assign offsets to the callee save slots.4038for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {4039Offset += MFI.getObjectSize(I);4040Offset = alignTo(Offset, MFI.getObjectAlign(I));4041if (AssignOffsets)4042Assign(I, -Offset);4043}4044}40454046// Ensure that the Callee-save area is aligned to 16bytes.4047Offset = alignTo(Offset, Align(16U));40484049// Create a buffer of SVE objects to allocate and sort it.4050SmallVector<int, 8> ObjectsToAllocate;4051// If we have a stack protector, and we've previously decided that we have SVE4052// objects on the stack and thus need it to go in the SVE stack area, then it4053// needs to go first.4054int StackProtectorFI = -1;4055if (MFI.hasStackProtectorIndex()) {4056StackProtectorFI = MFI.getStackProtectorIndex();4057if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)4058ObjectsToAllocate.push_back(StackProtectorFI);4059}4060for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {4061unsigned StackID = MFI.getStackID(I);4062if (StackID != TargetStackID::ScalableVector)4063continue;4064if (I == StackProtectorFI)4065continue;4066if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)4067continue;4068if (MFI.isDeadObjectIndex(I))4069continue;40704071ObjectsToAllocate.push_back(I);4072}40734074// Allocate all SVE locals and spills4075for (unsigned FI : ObjectsToAllocate) {4076Align Alignment = MFI.getObjectAlign(FI);4077// FIXME: Given that the length of SVE vectors is not necessarily a power of4078// two, we'd need to align every object dynamically at runtime if the4079// alignment is larger than 16. This is not yet supported.4080if (Alignment > Align(16))4081report_fatal_error(4082"Alignment of scalable vectors > 16 bytes is not yet supported");40834084Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);4085if (AssignOffsets)4086Assign(FI, -Offset);4087}40884089return Offset;4090}40914092int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(4093MachineFrameInfo &MFI) const {4094int MinCSFrameIndex, MaxCSFrameIndex;4095return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);4096}40974098int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(4099MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {4100return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,4101true);4102}41034104void AArch64FrameLowering::processFunctionBeforeFrameFinalized(4105MachineFunction &MF, RegScavenger *RS) const {4106MachineFrameInfo &MFI = MF.getFrameInfo();41074108assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&4109"Upwards growing stack unsupported");41104111int MinCSFrameIndex, MaxCSFrameIndex;4112int64_t SVEStackSize =4113assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);41144115AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();4116AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));4117AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);41184119// If this function isn't doing Win64-style C++ EH, we don't need to do4120// anything.4121if (!MF.hasEHFunclets())4122return;4123const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();4124WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();41254126MachineBasicBlock &MBB = MF.front();4127auto MBBI = MBB.begin();4128while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))4129++MBBI;41304131// Create an UnwindHelp object.4132// The UnwindHelp object is allocated at the start of the fixed object area4133int64_t FixedObject =4134getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);4135int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,4136/*SPOffset*/ -FixedObject,4137/*IsImmutable=*/false);4138EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;41394140// We need to store -2 into the UnwindHelp object at the start of the4141// function.4142DebugLoc DL;4143RS->enterBasicBlockEnd(MBB);4144RS->backward(MBBI);4145Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);4146assert(DstReg && "There must be a free register after frame setup");4147BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);4148BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))4149.addReg(DstReg, getKillRegState(true))4150.addFrameIndex(UnwindHelpFI)4151.addImm(0);4152}41534154namespace {4155struct TagStoreInstr {4156MachineInstr *MI;4157int64_t Offset, Size;4158explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)4159: MI(MI), Offset(Offset), Size(Size) {}4160};41614162class TagStoreEdit {4163MachineFunction *MF;4164MachineBasicBlock *MBB;4165MachineRegisterInfo *MRI;4166// Tag store instructions that are being replaced.4167SmallVector<TagStoreInstr, 8> TagStores;4168// Combined memref arguments of the above instructions.4169SmallVector<MachineMemOperand *, 8> CombinedMemRefs;41704171// Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +4172// FrameRegOffset + Size) with the address tag of SP.4173Register FrameReg;4174StackOffset FrameRegOffset;4175int64_t Size;4176// If not std::nullopt, move FrameReg to (FrameReg + FrameRegUpdate) at the4177// end.4178std::optional<int64_t> FrameRegUpdate;4179// MIFlags for any FrameReg updating instructions.4180unsigned FrameRegUpdateFlags;41814182// Use zeroing instruction variants.4183bool ZeroData;4184DebugLoc DL;41854186void emitUnrolled(MachineBasicBlock::iterator InsertI);4187void emitLoop(MachineBasicBlock::iterator InsertI);41884189public:4190TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)4191: MBB(MBB), ZeroData(ZeroData) {4192MF = MBB->getParent();4193MRI = &MF->getRegInfo();4194}4195// Add an instruction to be replaced. Instructions must be added in the4196// ascending order of Offset, and have to be adjacent.4197void addInstruction(TagStoreInstr I) {4198assert((TagStores.empty() ||4199TagStores.back().Offset + TagStores.back().Size == I.Offset) &&4200"Non-adjacent tag store instructions.");4201TagStores.push_back(I);4202}4203void clear() { TagStores.clear(); }4204// Emit equivalent code at the given location, and erase the current set of4205// instructions. May skip if the replacement is not profitable. May invalidate4206// the input iterator and replace it with a valid one.4207void emitCode(MachineBasicBlock::iterator &InsertI,4208const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);4209};42104211void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {4212const AArch64InstrInfo *TII =4213MF->getSubtarget<AArch64Subtarget>().getInstrInfo();42144215const int64_t kMinOffset = -256 * 16;4216const int64_t kMaxOffset = 255 * 16;42174218Register BaseReg = FrameReg;4219int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();4220if (BaseRegOffsetBytes < kMinOffset ||4221BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset ||4222// BaseReg can be FP, which is not necessarily aligned to 16-bytes. In4223// that case, BaseRegOffsetBytes will not be aligned to 16 bytes, which4224// is required for the offset of ST2G.4225BaseRegOffsetBytes % 16 != 0) {4226Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);4227emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,4228StackOffset::getFixed(BaseRegOffsetBytes), TII);4229BaseReg = ScratchReg;4230BaseRegOffsetBytes = 0;4231}42324233MachineInstr *LastI = nullptr;4234while (Size) {4235int64_t InstrSize = (Size > 16) ? 32 : 16;4236unsigned Opcode =4237InstrSize == 164238? (ZeroData ? AArch64::STZGi : AArch64::STGi)4239: (ZeroData ? AArch64::STZ2Gi : AArch64::ST2Gi);4240assert(BaseRegOffsetBytes % 16 == 0);4241MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))4242.addReg(AArch64::SP)4243.addReg(BaseReg)4244.addImm(BaseRegOffsetBytes / 16)4245.setMemRefs(CombinedMemRefs);4246// A store to [BaseReg, #0] should go last for an opportunity to fold the4247// final SP adjustment in the epilogue.4248if (BaseRegOffsetBytes == 0)4249LastI = I;4250BaseRegOffsetBytes += InstrSize;4251Size -= InstrSize;4252}42534254if (LastI)4255MBB->splice(InsertI, MBB, LastI);4256}42574258void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {4259const AArch64InstrInfo *TII =4260MF->getSubtarget<AArch64Subtarget>().getInstrInfo();42614262Register BaseReg = FrameRegUpdate4263? FrameReg4264: MRI->createVirtualRegister(&AArch64::GPR64RegClass);4265Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);42664267emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);42684269int64_t LoopSize = Size;4270// If the loop size is not a multiple of 32, split off one 16-byte store at4271// the end to fold BaseReg update into.4272if (FrameRegUpdate && *FrameRegUpdate)4273LoopSize -= LoopSize % 32;4274MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,4275TII->get(ZeroData ? AArch64::STZGloop_wback4276: AArch64::STGloop_wback))4277.addDef(SizeReg)4278.addDef(BaseReg)4279.addImm(LoopSize)4280.addReg(BaseReg)4281.setMemRefs(CombinedMemRefs);4282if (FrameRegUpdate)4283LoopI->setFlags(FrameRegUpdateFlags);42844285int64_t ExtraBaseRegUpdate =4286FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;4287if (LoopSize < Size) {4288assert(FrameRegUpdate);4289assert(Size - LoopSize == 16);4290// Tag 16 more bytes at BaseReg and update BaseReg.4291BuildMI(*MBB, InsertI, DL,4292TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))4293.addDef(BaseReg)4294.addReg(BaseReg)4295.addReg(BaseReg)4296.addImm(1 + ExtraBaseRegUpdate / 16)4297.setMemRefs(CombinedMemRefs)4298.setMIFlags(FrameRegUpdateFlags);4299} else if (ExtraBaseRegUpdate) {4300// Update BaseReg.4301BuildMI(4302*MBB, InsertI, DL,4303TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))4304.addDef(BaseReg)4305.addReg(BaseReg)4306.addImm(std::abs(ExtraBaseRegUpdate))4307.addImm(0)4308.setMIFlags(FrameRegUpdateFlags);4309}4310}43114312// Check if *II is a register update that can be merged into STGloop that ends4313// at (Reg + Size). RemainingOffset is the required adjustment to Reg after the4314// end of the loop.4315bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,4316int64_t Size, int64_t *TotalOffset) {4317MachineInstr &MI = *II;4318if ((MI.getOpcode() == AArch64::ADDXri ||4319MI.getOpcode() == AArch64::SUBXri) &&4320MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {4321unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());4322int64_t Offset = MI.getOperand(2).getImm() << Shift;4323if (MI.getOpcode() == AArch64::SUBXri)4324Offset = -Offset;4325int64_t AbsPostOffset = std::abs(Offset - Size);4326const int64_t kMaxOffset =43270xFFF; // Max encoding for unshifted ADDXri / SUBXri4328if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {4329*TotalOffset = Offset;4330return true;4331}4332}4333return false;4334}43354336void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,4337SmallVectorImpl<MachineMemOperand *> &MemRefs) {4338MemRefs.clear();4339for (auto &TS : TSE) {4340MachineInstr *MI = TS.MI;4341// An instruction without memory operands may access anything. Be4342// conservative and return an empty list.4343if (MI->memoperands_empty()) {4344MemRefs.clear();4345return;4346}4347MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());4348}4349}43504351void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,4352const AArch64FrameLowering *TFI,4353bool TryMergeSPUpdate) {4354if (TagStores.empty())4355return;4356TagStoreInstr &FirstTagStore = TagStores[0];4357TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];4358Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;4359DL = TagStores[0].MI->getDebugLoc();43604361Register Reg;4362FrameRegOffset = TFI->resolveFrameOffsetReference(4363*MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,4364/*PreferFP=*/false, /*ForSimm=*/true);4365FrameReg = Reg;4366FrameRegUpdate = std::nullopt;43674368mergeMemRefs(TagStores, CombinedMemRefs);43694370LLVM_DEBUG({4371dbgs() << "Replacing adjacent STG instructions:\n";4372for (const auto &Instr : TagStores) {4373dbgs() << " " << *Instr.MI;4374}4375});43764377// Size threshold where a loop becomes shorter than a linear sequence of4378// tagging instructions.4379const int kSetTagLoopThreshold = 176;4380if (Size < kSetTagLoopThreshold) {4381if (TagStores.size() < 2)4382return;4383emitUnrolled(InsertI);4384} else {4385MachineInstr *UpdateInstr = nullptr;4386int64_t TotalOffset = 0;4387if (TryMergeSPUpdate) {4388// See if we can merge base register update into the STGloop.4389// This is done in AArch64LoadStoreOptimizer for "normal" stores,4390// but STGloop is way too unusual for that, and also it only4391// realistically happens in function epilogue. Also, STGloop is expanded4392// before that pass.4393if (InsertI != MBB->end() &&4394canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,4395&TotalOffset)) {4396UpdateInstr = &*InsertI++;4397LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n "4398<< *UpdateInstr);4399}4400}44014402if (!UpdateInstr && TagStores.size() < 2)4403return;44044405if (UpdateInstr) {4406FrameRegUpdate = TotalOffset;4407FrameRegUpdateFlags = UpdateInstr->getFlags();4408}4409emitLoop(InsertI);4410if (UpdateInstr)4411UpdateInstr->eraseFromParent();4412}44134414for (auto &TS : TagStores)4415TS.MI->eraseFromParent();4416}44174418bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,4419int64_t &Size, bool &ZeroData) {4420MachineFunction &MF = *MI.getParent()->getParent();4421const MachineFrameInfo &MFI = MF.getFrameInfo();44224423unsigned Opcode = MI.getOpcode();4424ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGi ||4425Opcode == AArch64::STZ2Gi);44264427if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {4428if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())4429return false;4430if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())4431return false;4432Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());4433Size = MI.getOperand(2).getImm();4434return true;4435}44364437if (Opcode == AArch64::STGi || Opcode == AArch64::STZGi)4438Size = 16;4439else if (Opcode == AArch64::ST2Gi || Opcode == AArch64::STZ2Gi)4440Size = 32;4441else4442return false;44434444if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())4445return false;44464447Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +444816 * MI.getOperand(2).getImm();4449return true;4450}44514452// Detect a run of memory tagging instructions for adjacent stack frame slots,4453// and replace them with a shorter instruction sequence:4454// * replace STG + STG with ST2G4455// * replace STGloop + STGloop with STGloop4456// This code needs to run when stack slot offsets are already known, but before4457// FrameIndex operands in STG instructions are eliminated.4458MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,4459const AArch64FrameLowering *TFI,4460RegScavenger *RS) {4461bool FirstZeroData;4462int64_t Size, Offset;4463MachineInstr &MI = *II;4464MachineBasicBlock *MBB = MI.getParent();4465MachineBasicBlock::iterator NextI = ++II;4466if (&MI == &MBB->instr_back())4467return II;4468if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))4469return II;44704471SmallVector<TagStoreInstr, 4> Instrs;4472Instrs.emplace_back(&MI, Offset, Size);44734474constexpr int kScanLimit = 10;4475int Count = 0;4476for (MachineBasicBlock::iterator E = MBB->end();4477NextI != E && Count < kScanLimit; ++NextI) {4478MachineInstr &MI = *NextI;4479bool ZeroData;4480int64_t Size, Offset;4481// Collect instructions that update memory tags with a FrameIndex operand4482// and (when applicable) constant size, and whose output registers are dead4483// (the latter is almost always the case in practice). Since these4484// instructions effectively have no inputs or outputs, we are free to skip4485// any non-aliasing instructions in between without tracking used registers.4486if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {4487if (ZeroData != FirstZeroData)4488break;4489Instrs.emplace_back(&MI, Offset, Size);4490continue;4491}44924493// Only count non-transient, non-tagging instructions toward the scan4494// limit.4495if (!MI.isTransient())4496++Count;44974498// Just in case, stop before the epilogue code starts.4499if (MI.getFlag(MachineInstr::FrameSetup) ||4500MI.getFlag(MachineInstr::FrameDestroy))4501break;45024503// Reject anything that may alias the collected instructions.4504if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())4505break;4506}45074508// New code will be inserted after the last tagging instruction we've found.4509MachineBasicBlock::iterator InsertI = Instrs.back().MI;45104511// All the gathered stack tag instructions are merged and placed after4512// last tag store in the list. The check should be made if the nzcv4513// flag is live at the point where we are trying to insert. Otherwise4514// the nzcv flag might get clobbered if any stg loops are present.45154516// FIXME : This approach of bailing out from merge is conservative in4517// some ways like even if stg loops are not present after merge the4518// insert list, this liveness check is done (which is not needed).4519LivePhysRegs LiveRegs(*(MBB->getParent()->getSubtarget().getRegisterInfo()));4520LiveRegs.addLiveOuts(*MBB);4521for (auto I = MBB->rbegin();; ++I) {4522MachineInstr &MI = *I;4523if (MI == InsertI)4524break;4525LiveRegs.stepBackward(*I);4526}4527InsertI++;4528if (LiveRegs.contains(AArch64::NZCV))4529return InsertI;45304531llvm::stable_sort(Instrs,4532[](const TagStoreInstr &Left, const TagStoreInstr &Right) {4533return Left.Offset < Right.Offset;4534});45354536// Make sure that we don't have any overlapping stores.4537int64_t CurOffset = Instrs[0].Offset;4538for (auto &Instr : Instrs) {4539if (CurOffset > Instr.Offset)4540return NextI;4541CurOffset = Instr.Offset + Instr.Size;4542}45434544// Find contiguous runs of tagged memory and emit shorter instruction4545// sequencies for them when possible.4546TagStoreEdit TSE(MBB, FirstZeroData);4547std::optional<int64_t> EndOffset;4548for (auto &Instr : Instrs) {4549if (EndOffset && *EndOffset != Instr.Offset) {4550// Found a gap.4551TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);4552TSE.clear();4553}45544555TSE.addInstruction(Instr);4556EndOffset = Instr.Offset + Instr.Size;4557}45584559const MachineFunction *MF = MBB->getParent();4560// Multiple FP/SP updates in a loop cannot be described by CFI instructions.4561TSE.emitCode(4562InsertI, TFI, /*TryMergeSPUpdate = */4563!MF->getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(*MF));45644565return InsertI;4566}4567} // namespace45684569MachineBasicBlock::iterator emitVGSaveRestore(MachineBasicBlock::iterator II,4570const AArch64FrameLowering *TFI) {4571MachineInstr &MI = *II;4572MachineBasicBlock *MBB = MI.getParent();4573MachineFunction *MF = MBB->getParent();45744575if (MI.getOpcode() != AArch64::VGSavePseudo &&4576MI.getOpcode() != AArch64::VGRestorePseudo)4577return II;45784579SMEAttrs FuncAttrs(MF->getFunction());4580bool LocallyStreaming =4581FuncAttrs.hasStreamingBody() && !FuncAttrs.hasStreamingInterface();4582const AArch64FunctionInfo *AFI = MF->getInfo<AArch64FunctionInfo>();4583const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();4584const AArch64InstrInfo *TII =4585MF->getSubtarget<AArch64Subtarget>().getInstrInfo();45864587int64_t VGFrameIdx =4588LocallyStreaming ? AFI->getStreamingVGIdx() : AFI->getVGIdx();4589assert(VGFrameIdx != std::numeric_limits<int>::max() &&4590"Expected FrameIdx for VG");45914592unsigned CFIIndex;4593if (MI.getOpcode() == AArch64::VGSavePseudo) {4594const MachineFrameInfo &MFI = MF->getFrameInfo();4595int64_t Offset =4596MFI.getObjectOffset(VGFrameIdx) - TFI->getOffsetOfLocalArea();4597CFIIndex = MF->addFrameInst(MCCFIInstruction::createOffset(4598nullptr, TRI->getDwarfRegNum(AArch64::VG, true), Offset));4599} else4600CFIIndex = MF->addFrameInst(MCCFIInstruction::createRestore(4601nullptr, TRI->getDwarfRegNum(AArch64::VG, true)));46024603MachineInstr *UnwindInst = BuildMI(*MBB, II, II->getDebugLoc(),4604TII->get(TargetOpcode::CFI_INSTRUCTION))4605.addCFIIndex(CFIIndex);46064607MI.eraseFromParent();4608return UnwindInst->getIterator();4609}46104611void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(4612MachineFunction &MF, RegScavenger *RS = nullptr) const {4613for (auto &BB : MF)4614for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();) {4615if (requiresSaveVG(MF))4616II = emitVGSaveRestore(II, this);4617if (StackTaggingMergeSetTag)4618II = tryMergeAdjacentSTG(II, this, RS);4619}4620}46214622/// For Win64 AArch64 EH, the offset to the Unwind object is from the SP4623/// before the update. This is easily retrieved as it is exactly the offset4624/// that is set in processFunctionBeforeFrameFinalized.4625StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(4626const MachineFunction &MF, int FI, Register &FrameReg,4627bool IgnoreSPUpdates) const {4628const MachineFrameInfo &MFI = MF.getFrameInfo();4629if (IgnoreSPUpdates) {4630LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "4631<< MFI.getObjectOffset(FI) << "\n");4632FrameReg = AArch64::SP;4633return StackOffset::getFixed(MFI.getObjectOffset(FI));4634}46354636// Go to common code if we cannot provide sp + offset.4637if (MFI.hasVarSizedObjects() ||4638MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||4639MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))4640return getFrameIndexReference(MF, FI, FrameReg);46414642FrameReg = AArch64::SP;4643return getStackOffset(MF, MFI.getObjectOffset(FI));4644}46454646/// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve4647/// the parent's frame pointer4648unsigned AArch64FrameLowering::getWinEHParentFrameOffset(4649const MachineFunction &MF) const {4650return 0;4651}46524653/// Funclets only need to account for space for the callee saved registers,4654/// as the locals are accounted for in the parent's stack frame.4655unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(4656const MachineFunction &MF) const {4657// This is the size of the pushed CSRs.4658unsigned CSSize =4659MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();4660// This is the amount of stack a funclet needs to allocate.4661return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),4662getStackAlign());4663}46644665namespace {4666struct FrameObject {4667bool IsValid = false;4668// Index of the object in MFI.4669int ObjectIndex = 0;4670// Group ID this object belongs to.4671int GroupIndex = -1;4672// This object should be placed first (closest to SP).4673bool ObjectFirst = false;4674// This object's group (which always contains the object with4675// ObjectFirst==true) should be placed first.4676bool GroupFirst = false;46774678// Used to distinguish between FP and GPR accesses. The values are decided so4679// that they sort FPR < Hazard < GPR and they can be or'd together.4680unsigned Accesses = 0;4681enum { AccessFPR = 1, AccessHazard = 2, AccessGPR = 4 };4682};46834684class GroupBuilder {4685SmallVector<int, 8> CurrentMembers;4686int NextGroupIndex = 0;4687std::vector<FrameObject> &Objects;46884689public:4690GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}4691void AddMember(int Index) { CurrentMembers.push_back(Index); }4692void EndCurrentGroup() {4693if (CurrentMembers.size() > 1) {4694// Create a new group with the current member list. This might remove them4695// from their pre-existing groups. That's OK, dealing with overlapping4696// groups is too hard and unlikely to make a difference.4697LLVM_DEBUG(dbgs() << "group:");4698for (int Index : CurrentMembers) {4699Objects[Index].GroupIndex = NextGroupIndex;4700LLVM_DEBUG(dbgs() << " " << Index);4701}4702LLVM_DEBUG(dbgs() << "\n");4703NextGroupIndex++;4704}4705CurrentMembers.clear();4706}4707};47084709bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {4710// Objects at a lower index are closer to FP; objects at a higher index are4711// closer to SP.4712//4713// For consistency in our comparison, all invalid objects are placed4714// at the end. This also allows us to stop walking when we hit the4715// first invalid item after it's all sorted.4716//4717// If we want to include a stack hazard region, order FPR accesses < the4718// hazard object < GPRs accesses in order to create a separation between the4719// two. For the Accesses field 1 = FPR, 2 = Hazard Object, 4 = GPR.4720//4721// Otherwise the "first" object goes first (closest to SP), followed by the4722// members of the "first" group.4723//4724// The rest are sorted by the group index to keep the groups together.4725// Higher numbered groups are more likely to be around longer (i.e. untagged4726// in the function epilogue and not at some earlier point). Place them closer4727// to SP.4728//4729// If all else equal, sort by the object index to keep the objects in the4730// original order.4731return std::make_tuple(!A.IsValid, A.Accesses, A.ObjectFirst, A.GroupFirst,4732A.GroupIndex, A.ObjectIndex) <4733std::make_tuple(!B.IsValid, B.Accesses, B.ObjectFirst, B.GroupFirst,4734B.GroupIndex, B.ObjectIndex);4735}4736} // namespace47374738void AArch64FrameLowering::orderFrameObjects(4739const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {4740if (!OrderFrameObjects || ObjectsToAllocate.empty())4741return;47424743const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();4744const MachineFrameInfo &MFI = MF.getFrameInfo();4745std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());4746for (auto &Obj : ObjectsToAllocate) {4747FrameObjects[Obj].IsValid = true;4748FrameObjects[Obj].ObjectIndex = Obj;4749}47504751// Identify FPR vs GPR slots for hazards, and stack slots that are tagged at4752// the same time.4753GroupBuilder GB(FrameObjects);4754for (auto &MBB : MF) {4755for (auto &MI : MBB) {4756if (MI.isDebugInstr())4757continue;47584759if (AFI.hasStackHazardSlotIndex()) {4760std::optional<int> FI = getLdStFrameID(MI, MFI);4761if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) {4762if (MFI.getStackID(*FI) == TargetStackID::ScalableVector ||4763AArch64InstrInfo::isFpOrNEON(MI))4764FrameObjects[*FI].Accesses |= FrameObject::AccessFPR;4765else4766FrameObjects[*FI].Accesses |= FrameObject::AccessGPR;4767}4768}47694770int OpIndex;4771switch (MI.getOpcode()) {4772case AArch64::STGloop:4773case AArch64::STZGloop:4774OpIndex = 3;4775break;4776case AArch64::STGi:4777case AArch64::STZGi:4778case AArch64::ST2Gi:4779case AArch64::STZ2Gi:4780OpIndex = 1;4781break;4782default:4783OpIndex = -1;4784}47854786int TaggedFI = -1;4787if (OpIndex >= 0) {4788const MachineOperand &MO = MI.getOperand(OpIndex);4789if (MO.isFI()) {4790int FI = MO.getIndex();4791if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&4792FrameObjects[FI].IsValid)4793TaggedFI = FI;4794}4795}47964797// If this is a stack tagging instruction for a slot that is not part of a4798// group yet, either start a new group or add it to the current one.4799if (TaggedFI >= 0)4800GB.AddMember(TaggedFI);4801else4802GB.EndCurrentGroup();4803}4804// Groups should never span multiple basic blocks.4805GB.EndCurrentGroup();4806}48074808if (AFI.hasStackHazardSlotIndex()) {4809FrameObjects[AFI.getStackHazardSlotIndex()].Accesses =4810FrameObject::AccessHazard;4811// If a stack object is unknown or both GPR and FPR, sort it into GPR.4812for (auto &Obj : FrameObjects)4813if (!Obj.Accesses ||4814Obj.Accesses == (FrameObject::AccessGPR | FrameObject::AccessFPR))4815Obj.Accesses = FrameObject::AccessGPR;4816}48174818// If the function's tagged base pointer is pinned to a stack slot, we want to4819// put that slot first when possible. This will likely place it at SP + 0,4820// and save one instruction when generating the base pointer because IRG does4821// not allow an immediate offset.4822std::optional<int> TBPI = AFI.getTaggedBasePointerIndex();4823if (TBPI) {4824FrameObjects[*TBPI].ObjectFirst = true;4825FrameObjects[*TBPI].GroupFirst = true;4826int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;4827if (FirstGroupIndex >= 0)4828for (FrameObject &Object : FrameObjects)4829if (Object.GroupIndex == FirstGroupIndex)4830Object.GroupFirst = true;4831}48324833llvm::stable_sort(FrameObjects, FrameObjectCompare);48344835int i = 0;4836for (auto &Obj : FrameObjects) {4837// All invalid items are sorted at the end, so it's safe to stop.4838if (!Obj.IsValid)4839break;4840ObjectsToAllocate[i++] = Obj.ObjectIndex;4841}48424843LLVM_DEBUG({4844dbgs() << "Final frame order:\n";4845for (auto &Obj : FrameObjects) {4846if (!Obj.IsValid)4847break;4848dbgs() << " " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;4849if (Obj.ObjectFirst)4850dbgs() << ", first";4851if (Obj.GroupFirst)4852dbgs() << ", group-first";4853dbgs() << "\n";4854}4855});4856}48574858/// Emit a loop to decrement SP until it is equal to TargetReg, with probes at4859/// least every ProbeSize bytes. Returns an iterator of the first instruction4860/// after the loop. The difference between SP and TargetReg must be an exact4861/// multiple of ProbeSize.4862MachineBasicBlock::iterator4863AArch64FrameLowering::inlineStackProbeLoopExactMultiple(4864MachineBasicBlock::iterator MBBI, int64_t ProbeSize,4865Register TargetReg) const {4866MachineBasicBlock &MBB = *MBBI->getParent();4867MachineFunction &MF = *MBB.getParent();4868const AArch64InstrInfo *TII =4869MF.getSubtarget<AArch64Subtarget>().getInstrInfo();4870DebugLoc DL = MBB.findDebugLoc(MBBI);48714872MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());4873MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());4874MF.insert(MBBInsertPoint, LoopMBB);4875MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());4876MF.insert(MBBInsertPoint, ExitMBB);48774878// SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not encodable4879// in SUB).4880emitFrameOffset(*LoopMBB, LoopMBB->end(), DL, AArch64::SP, AArch64::SP,4881StackOffset::getFixed(-ProbeSize), TII,4882MachineInstr::FrameSetup);4883// STR XZR, [SP]4884BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::STRXui))4885.addReg(AArch64::XZR)4886.addReg(AArch64::SP)4887.addImm(0)4888.setMIFlags(MachineInstr::FrameSetup);4889// CMP SP, TargetReg4890BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::SUBSXrx64),4891AArch64::XZR)4892.addReg(AArch64::SP)4893.addReg(TargetReg)4894.addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 0))4895.setMIFlags(MachineInstr::FrameSetup);4896// B.CC Loop4897BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::Bcc))4898.addImm(AArch64CC::NE)4899.addMBB(LoopMBB)4900.setMIFlags(MachineInstr::FrameSetup);49014902LoopMBB->addSuccessor(ExitMBB);4903LoopMBB->addSuccessor(LoopMBB);4904// Synthesize the exit MBB.4905ExitMBB->splice(ExitMBB->end(), &MBB, MBBI, MBB.end());4906ExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);4907MBB.addSuccessor(LoopMBB);4908// Update liveins.4909fullyRecomputeLiveIns({ExitMBB, LoopMBB});49104911return ExitMBB->begin();4912}49134914void AArch64FrameLowering::inlineStackProbeFixed(4915MachineBasicBlock::iterator MBBI, Register ScratchReg, int64_t FrameSize,4916StackOffset CFAOffset) const {4917MachineBasicBlock *MBB = MBBI->getParent();4918MachineFunction &MF = *MBB->getParent();4919const AArch64InstrInfo *TII =4920MF.getSubtarget<AArch64Subtarget>().getInstrInfo();4921AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();4922bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF);4923bool HasFP = hasFP(MF);49244925DebugLoc DL;4926int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();4927int64_t NumBlocks = FrameSize / ProbeSize;4928int64_t ResidualSize = FrameSize % ProbeSize;49294930LLVM_DEBUG(dbgs() << "Stack probing: total " << FrameSize << " bytes, "4931<< NumBlocks << " blocks of " << ProbeSize4932<< " bytes, plus " << ResidualSize << " bytes\n");49334934// Decrement SP by NumBlock * ProbeSize bytes, with either unrolled or4935// ordinary loop.4936if (NumBlocks <= AArch64::StackProbeMaxLoopUnroll) {4937for (int i = 0; i < NumBlocks; ++i) {4938// SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not4939// encodable in a SUB).4940emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,4941StackOffset::getFixed(-ProbeSize), TII,4942MachineInstr::FrameSetup, false, false, nullptr,4943EmitAsyncCFI && !HasFP, CFAOffset);4944CFAOffset += StackOffset::getFixed(ProbeSize);4945// STR XZR, [SP]4946BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui))4947.addReg(AArch64::XZR)4948.addReg(AArch64::SP)4949.addImm(0)4950.setMIFlags(MachineInstr::FrameSetup);4951}4952} else if (NumBlocks != 0) {4953// SUB ScratchReg, SP, #FrameSize (or equivalent if FrameSize is not4954// encodable in ADD). ScrathReg may temporarily become the CFA register.4955emitFrameOffset(*MBB, MBBI, DL, ScratchReg, AArch64::SP,4956StackOffset::getFixed(-ProbeSize * NumBlocks), TII,4957MachineInstr::FrameSetup, false, false, nullptr,4958EmitAsyncCFI && !HasFP, CFAOffset);4959CFAOffset += StackOffset::getFixed(ProbeSize * NumBlocks);4960MBBI = inlineStackProbeLoopExactMultiple(MBBI, ProbeSize, ScratchReg);4961MBB = MBBI->getParent();4962if (EmitAsyncCFI && !HasFP) {4963// Set the CFA register back to SP.4964const AArch64RegisterInfo &RegInfo =4965*MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();4966unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);4967unsigned CFIIndex =4968MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));4969BuildMI(*MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))4970.addCFIIndex(CFIIndex)4971.setMIFlags(MachineInstr::FrameSetup);4972}4973}49744975if (ResidualSize != 0) {4976// SUB SP, SP, #ResidualSize (or equivalent if ResidualSize is not encodable4977// in SUB).4978emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,4979StackOffset::getFixed(-ResidualSize), TII,4980MachineInstr::FrameSetup, false, false, nullptr,4981EmitAsyncCFI && !HasFP, CFAOffset);4982if (ResidualSize > AArch64::StackProbeMaxUnprobedStack) {4983// STR XZR, [SP]4984BuildMI(*MBB, MBBI, DL, TII->get(AArch64::STRXui))4985.addReg(AArch64::XZR)4986.addReg(AArch64::SP)4987.addImm(0)4988.setMIFlags(MachineInstr::FrameSetup);4989}4990}4991}49924993void AArch64FrameLowering::inlineStackProbe(MachineFunction &MF,4994MachineBasicBlock &MBB) const {4995// Get the instructions that need to be replaced. We emit at most two of4996// these. Remember them in order to avoid complications coming from the need4997// to traverse the block while potentially creating more blocks.4998SmallVector<MachineInstr *, 4> ToReplace;4999for (MachineInstr &MI : MBB)5000if (MI.getOpcode() == AArch64::PROBED_STACKALLOC ||5001MI.getOpcode() == AArch64::PROBED_STACKALLOC_VAR)5002ToReplace.push_back(&MI);50035004for (MachineInstr *MI : ToReplace) {5005if (MI->getOpcode() == AArch64::PROBED_STACKALLOC) {5006Register ScratchReg = MI->getOperand(0).getReg();5007int64_t FrameSize = MI->getOperand(1).getImm();5008StackOffset CFAOffset = StackOffset::get(MI->getOperand(2).getImm(),5009MI->getOperand(3).getImm());5010inlineStackProbeFixed(MI->getIterator(), ScratchReg, FrameSize,5011CFAOffset);5012} else {5013assert(MI->getOpcode() == AArch64::PROBED_STACKALLOC_VAR &&5014"Stack probe pseudo-instruction expected");5015const AArch64InstrInfo *TII =5016MI->getMF()->getSubtarget<AArch64Subtarget>().getInstrInfo();5017Register TargetReg = MI->getOperand(0).getReg();5018(void)TII->probedStackAlloc(MI->getIterator(), TargetReg, true);5019}5020MI->eraseFromParent();5021}5022}50235024struct StackAccess {5025enum AccessType {5026NotAccessed = 0, // Stack object not accessed by load/store instructions.5027GPR = 1 << 0, // A general purpose register.5028PPR = 1 << 1, // A predicate register.5029FPR = 1 << 2, // A floating point/Neon/SVE register.5030};50315032int Idx;5033StackOffset Offset;5034int64_t Size;5035unsigned AccessTypes;50365037StackAccess() : Idx(0), Offset(), Size(0), AccessTypes(NotAccessed) {}50385039bool operator<(const StackAccess &Rhs) const {5040return std::make_tuple(start(), Idx) <5041std::make_tuple(Rhs.start(), Rhs.Idx);5042}50435044bool isCPU() const {5045// Predicate register load and store instructions execute on the CPU.5046return AccessTypes & (AccessType::GPR | AccessType::PPR);5047}5048bool isSME() const { return AccessTypes & AccessType::FPR; }5049bool isMixed() const { return isCPU() && isSME(); }50505051int64_t start() const { return Offset.getFixed() + Offset.getScalable(); }5052int64_t end() const { return start() + Size; }50535054std::string getTypeString() const {5055switch (AccessTypes) {5056case AccessType::FPR:5057return "FPR";5058case AccessType::PPR:5059return "PPR";5060case AccessType::GPR:5061return "GPR";5062case AccessType::NotAccessed:5063return "NA";5064default:5065return "Mixed";5066}5067}50685069void print(raw_ostream &OS) const {5070OS << getTypeString() << " stack object at [SP"5071<< (Offset.getFixed() < 0 ? "" : "+") << Offset.getFixed();5072if (Offset.getScalable())5073OS << (Offset.getScalable() < 0 ? "" : "+") << Offset.getScalable()5074<< " * vscale";5075OS << "]";5076}5077};50785079static inline raw_ostream &operator<<(raw_ostream &OS, const StackAccess &SA) {5080SA.print(OS);5081return OS;5082}50835084void AArch64FrameLowering::emitRemarks(5085const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const {50865087SMEAttrs Attrs(MF.getFunction());5088if (Attrs.hasNonStreamingInterfaceAndBody())5089return;50905091const uint64_t HazardSize =5092(StackHazardSize) ? StackHazardSize : StackHazardRemarkSize;50935094if (HazardSize == 0)5095return;50965097const MachineFrameInfo &MFI = MF.getFrameInfo();5098// Bail if function has no stack objects.5099if (!MFI.hasStackObjects())5100return;51015102std::vector<StackAccess> StackAccesses(MFI.getNumObjects());51035104size_t NumFPLdSt = 0;5105size_t NumNonFPLdSt = 0;51065107// Collect stack accesses via Load/Store instructions.5108for (const MachineBasicBlock &MBB : MF) {5109for (const MachineInstr &MI : MBB) {5110if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)5111continue;5112for (MachineMemOperand *MMO : MI.memoperands()) {5113std::optional<int> FI = getMMOFrameID(MMO, MFI);5114if (FI && !MFI.isDeadObjectIndex(*FI)) {5115int FrameIdx = *FI;51165117size_t ArrIdx = FrameIdx + MFI.getNumFixedObjects();5118if (StackAccesses[ArrIdx].AccessTypes == StackAccess::NotAccessed) {5119StackAccesses[ArrIdx].Idx = FrameIdx;5120StackAccesses[ArrIdx].Offset =5121getFrameIndexReferenceFromSP(MF, FrameIdx);5122StackAccesses[ArrIdx].Size = MFI.getObjectSize(FrameIdx);5123}51245125unsigned RegTy = StackAccess::AccessType::GPR;5126if (MFI.getStackID(FrameIdx) == TargetStackID::ScalableVector) {5127if (AArch64::PPRRegClass.contains(MI.getOperand(0).getReg()))5128RegTy = StackAccess::PPR;5129else5130RegTy = StackAccess::FPR;5131} else if (AArch64InstrInfo::isFpOrNEON(MI)) {5132RegTy = StackAccess::FPR;5133}51345135StackAccesses[ArrIdx].AccessTypes |= RegTy;51365137if (RegTy == StackAccess::FPR)5138++NumFPLdSt;5139else5140++NumNonFPLdSt;5141}5142}5143}5144}51455146if (NumFPLdSt == 0 || NumNonFPLdSt == 0)5147return;51485149llvm::sort(StackAccesses);5150StackAccesses.erase(llvm::remove_if(StackAccesses,5151[](const StackAccess &S) {5152return S.AccessTypes ==5153StackAccess::NotAccessed;5154}),5155StackAccesses.end());51565157SmallVector<const StackAccess *> MixedObjects;5158SmallVector<std::pair<const StackAccess *, const StackAccess *>> HazardPairs;51595160if (StackAccesses.front().isMixed())5161MixedObjects.push_back(&StackAccesses.front());51625163for (auto It = StackAccesses.begin(), End = std::prev(StackAccesses.end());5164It != End; ++It) {5165const auto &First = *It;5166const auto &Second = *(It + 1);51675168if (Second.isMixed())5169MixedObjects.push_back(&Second);51705171if ((First.isSME() && Second.isCPU()) ||5172(First.isCPU() && Second.isSME())) {5173uint64_t Distance = static_cast<uint64_t>(Second.start() - First.end());5174if (Distance < HazardSize)5175HazardPairs.emplace_back(&First, &Second);5176}5177}51785179auto EmitRemark = [&](llvm::StringRef Str) {5180ORE->emit([&]() {5181auto R = MachineOptimizationRemarkAnalysis(5182"sme", "StackHazard", MF.getFunction().getSubprogram(), &MF.front());5183return R << formatv("stack hazard in '{0}': ", MF.getName()).str() << Str;5184});5185};51865187for (const auto &P : HazardPairs)5188EmitRemark(formatv("{0} is too close to {1}", *P.first, *P.second).str());51895190for (const auto *Obj : MixedObjects)5191EmitRemark(5192formatv("{0} accessed by both GP and FP instructions", *Obj).str());5193}519451955196