1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains the AArch64 implementation of TargetFrameLowering class.
11 // On AArch64, stack frames are structured as follows:
13 // The stack grows downward.
15 // All of the individual frame areas on the frame below are optional, i.e. it's
16 // possible to create a function so that the particular area isn't present
19 // At function entry, the "frame" looks as follows:
22 // |-----------------------------------|
24 // | arguments passed on the stack |
26 // |-----------------------------------| <- sp
30 // After the prologue has run, the frame has the following general structure.
31 // Note that this doesn't depict the case where a red-zone is used. Also,
32 // technically the last frame area (VLAs) doesn't get created until in the
33 // main function body, after the prologue is run. However, it's depicted here
37 // |-----------------------------------|
39 // | arguments passed on the stack |
41 // |-----------------------------------|
43 // | (Win64 only) varargs from reg |
45 // |-----------------------------------|
47 // | callee-saved gpr registers | <--.
48 // | | | On Darwin platforms these
49 // |- - - - - - - - - - - - - - - - - -| | callee saves are swapped,
50 // | prev_lr | | (frame record first)
52 // | async context if needed |
53 // | (a.k.a. "frame record") |
54 // |-----------------------------------| <- fp(=x29)
56 // | callee-saved fp/simd/SVE regs |
58 // |-----------------------------------|
60 // | SVE stack objects |
62 // |-----------------------------------|
63 // |.empty.space.to.make.part.below....|
64 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
65 // |.the.standard.16-byte.alignment....| compile time; if present)
66 // |-----------------------------------|
68 // | local variables of fixed size |
69 // | including spill slots |
70 // |-----------------------------------| <- bp(not defined by ABI,
71 // |.variable-sized.local.variables....| LLVM chooses X19)
72 // |.(VLAs)............................| (size of this area is unknown at
73 // |...................................| compile time)
74 // |-----------------------------------| <- sp
78 // To access the data in a frame, at-compile time, a constant offset must be
79 // computable from one of the pointers (fp, bp, sp) to access it. The size
80 // of the areas with a dotted background cannot be computed at compile-time
81 // if they are present, making it required to have all three of fp, bp and
82 // sp to be set up to be able to access all contents in the frame areas,
83 // assuming all of the frame areas are non-empty.
85 // For most functions, some of the frame areas are empty. For those functions,
86 // it may not be necessary to set up fp or bp:
87 // * A base pointer is definitely needed when there are both VLAs and local
88 // variables with more-than-default alignment requirements.
89 // * A frame pointer is definitely needed when there are local variables with
90 // more-than-default alignment requirements.
92 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
93 // callee-saved area, since the unwind encoding does not allow for encoding
94 // this dynamically and existing tools depend on this layout. For other
95 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
96 // area to allow SVE stack objects (allocated directly below the callee-saves,
97 // if available) to be accessed directly from the framepointer.
98 // The SVE spill/fill instructions have VL-scaled addressing modes such
100 // ldr z8, [fp, #-7 mul vl]
101 // For SVE the size of the vector length (VL) is not known at compile-time, so
102 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
103 // layout, we don't need to add an unscaled offset to the framepointer before
104 // accessing the SVE object in the frame.
106 // In some cases when a base pointer is not strictly needed, it is generated
107 // anyway when offsets from the frame pointer to access local variables become
108 // so large that the offset can't be encoded in the immediate fields of loads
111 // Outgoing function arguments must be at the bottom of the stack frame when
112 // calling another function. If we do not have variable-sized stack objects, we
113 // can allocate a "reserved call frame" area at the bottom of the local
114 // variable area, large enough for all outgoing calls. If we do have VLAs, then
115 // the stack pointer must be decremented and incremented around each call to
116 // make space for the arguments below the VLAs.
118 // FIXME: also explain the redzone concept.
120 // An example of the prologue:
127 // .cfi_personality 155, ___gxx_personality_v0
129 // .cfi_lsda 16, Lexception33
131 // stp xa,bx, [sp, -#offset]!
133 // stp x28, x27, [sp, #offset-32]
134 // stp fp, lr, [sp, #offset-16]
135 // add fp, sp, #offset - 16
139 // +-------------------------------------------+
140 // 10000 | ........ | ........ | ........ | ........ |
141 // 10004 | ........ | ........ | ........ | ........ |
142 // +-------------------------------------------+
143 // 10008 | ........ | ........ | ........ | ........ |
144 // 1000c | ........ | ........ | ........ | ........ |
145 // +===========================================+
146 // 10010 | X28 Register |
147 // 10014 | X28 Register |
148 // +-------------------------------------------+
149 // 10018 | X27 Register |
150 // 1001c | X27 Register |
151 // +===========================================+
152 // 10020 | Frame Pointer |
153 // 10024 | Frame Pointer |
154 // +-------------------------------------------+
155 // 10028 | Link Register |
156 // 1002c | Link Register |
157 // +===========================================+
158 // 10030 | ........ | ........ | ........ | ........ |
159 // 10034 | ........ | ........ | ........ | ........ |
160 // +-------------------------------------------+
161 // 10038 | ........ | ........ | ........ | ........ |
162 // 1003c | ........ | ........ | ........ | ........ |
163 // +-------------------------------------------+
165 // [sp] = 10030 :: >>initial value<<
166 // sp = 10020 :: stp fp, lr, [sp, #-16]!
167 // fp = sp == 10020 :: mov fp, sp
168 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
169 // sp == 10010 :: >>final value<<
171 // The frame pointer (w29) points to address 10020. If we use an offset of
172 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
173 // for w27, and -32 for w28:
176 // .cfi_def_cfa w29, 16
178 // .cfi_offset w30, -8
180 // .cfi_offset w29, -16
182 // .cfi_offset w27, -24
184 // .cfi_offset w28, -32
186 //===----------------------------------------------------------------------===//
188 #include "AArch64FrameLowering.h"
189 #include "AArch64InstrInfo.h"
190 #include "AArch64MachineFunctionInfo.h"
191 #include "AArch64RegisterInfo.h"
192 #include "AArch64Subtarget.h"
193 #include "AArch64TargetMachine.h"
194 #include "MCTargetDesc/AArch64AddressingModes.h"
195 #include "MCTargetDesc/AArch64MCTargetDesc.h"
196 #include "llvm/ADT/ScopeExit.h"
197 #include "llvm/ADT/SmallVector.h"
198 #include "llvm/ADT/Statistic.h"
199 #include "llvm/CodeGen/LivePhysRegs.h"
200 #include "llvm/CodeGen/MachineBasicBlock.h"
201 #include "llvm/CodeGen/MachineFrameInfo.h"
202 #include "llvm/CodeGen/MachineFunction.h"
203 #include "llvm/CodeGen/MachineInstr.h"
204 #include "llvm/CodeGen/MachineInstrBuilder.h"
205 #include "llvm/CodeGen/MachineMemOperand.h"
206 #include "llvm/CodeGen/MachineModuleInfo.h"
207 #include "llvm/CodeGen/MachineOperand.h"
208 #include "llvm/CodeGen/MachineRegisterInfo.h"
209 #include "llvm/CodeGen/RegisterScavenging.h"
210 #include "llvm/CodeGen/TargetInstrInfo.h"
211 #include "llvm/CodeGen/TargetRegisterInfo.h"
212 #include "llvm/CodeGen/TargetSubtargetInfo.h"
213 #include "llvm/CodeGen/WinEHFuncInfo.h"
214 #include "llvm/IR/Attributes.h"
215 #include "llvm/IR/CallingConv.h"
216 #include "llvm/IR/DataLayout.h"
217 #include "llvm/IR/DebugLoc.h"
218 #include "llvm/IR/Function.h"
219 #include "llvm/MC/MCAsmInfo.h"
220 #include "llvm/MC/MCDwarf.h"
221 #include "llvm/Support/CommandLine.h"
222 #include "llvm/Support/Debug.h"
223 #include "llvm/Support/ErrorHandling.h"
224 #include "llvm/Support/MathExtras.h"
225 #include "llvm/Support/raw_ostream.h"
226 #include "llvm/Target/TargetMachine.h"
227 #include "llvm/Target/TargetOptions.h"
234 using namespace llvm
;
236 #define DEBUG_TYPE "frame-info"
238 static cl::opt
<bool> EnableRedZone("aarch64-redzone",
239 cl::desc("enable use of redzone on AArch64"),
240 cl::init(false), cl::Hidden
);
243 ReverseCSRRestoreSeq("reverse-csr-restore-seq",
244 cl::desc("reverse the CSR restore sequence"),
245 cl::init(false), cl::Hidden
);
247 static cl::opt
<bool> StackTaggingMergeSetTag(
248 "stack-tagging-merge-settag",
249 cl::desc("merge settag instruction in function epilog"), cl::init(true),
252 static cl::opt
<bool> OrderFrameObjects("aarch64-order-frame-objects",
253 cl::desc("sort stack allocations"),
254 cl::init(true), cl::Hidden
);
256 cl::opt
<bool> EnableHomogeneousPrologEpilog(
257 "homogeneous-prolog-epilog", cl::Hidden
,
258 cl::desc("Emit homogeneous prologue and epilogue for the size "
259 "optimization (default = off)"));
261 STATISTIC(NumRedZoneFunctions
, "Number of functions using red zone");
263 /// Returns how much of the incoming argument stack area (in bytes) we should
264 /// clean up in an epilogue. For the C calling convention this will be 0, for
265 /// guaranteed tail call conventions it can be positive (a normal return or a
266 /// tail call to a function that uses less stack space for arguments) or
267 /// negative (for a tail call to a function that needs more stack space than us
269 static int64_t getArgumentStackToRestore(MachineFunction
&MF
,
270 MachineBasicBlock
&MBB
) {
271 MachineBasicBlock::iterator MBBI
= MBB
.getLastNonDebugInstr();
272 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
273 bool IsTailCallReturn
= (MBB
.end() != MBBI
)
274 ? AArch64InstrInfo::isTailCallReturnInst(*MBBI
)
277 int64_t ArgumentPopSize
= 0;
278 if (IsTailCallReturn
) {
279 MachineOperand
&StackAdjust
= MBBI
->getOperand(1);
281 // For a tail-call in a callee-pops-arguments environment, some or all of
282 // the stack may actually be in use for the call's arguments, this is
283 // calculated during LowerCall and consumed here...
284 ArgumentPopSize
= StackAdjust
.getImm();
286 // ... otherwise the amount to pop is *all* of the argument space,
287 // conveniently stored in the MachineFunctionInfo by
288 // LowerFormalArguments. This will, of course, be zero for the C calling
290 ArgumentPopSize
= AFI
->getArgumentStackToRestore();
293 return ArgumentPopSize
;
296 static bool produceCompactUnwindFrame(MachineFunction
&MF
);
297 static bool needsWinCFI(const MachineFunction
&MF
);
298 static StackOffset
getSVEStackSize(const MachineFunction
&MF
);
300 /// Returns true if a homogeneous prolog or epilog code can be emitted
301 /// for the size optimization. If possible, a frame helper call is injected.
302 /// When Exit block is given, this check is for epilog.
303 bool AArch64FrameLowering::homogeneousPrologEpilog(
304 MachineFunction
&MF
, MachineBasicBlock
*Exit
) const {
305 if (!MF
.getFunction().hasMinSize())
307 if (!EnableHomogeneousPrologEpilog
)
309 if (ReverseCSRRestoreSeq
)
314 // TODO: Window is supported yet.
317 // TODO: SVE is not supported yet.
318 if (getSVEStackSize(MF
))
321 // Bail on stack adjustment needed on return for simplicity.
322 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
323 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
324 if (MFI
.hasVarSizedObjects() || RegInfo
->hasStackRealignment(MF
))
326 if (Exit
&& getArgumentStackToRestore(MF
, *Exit
))
329 auto *AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
330 if (AFI
->hasSwiftAsyncContext())
333 // If there are an odd number of GPRs before LR and FP in the CSRs list,
334 // they will not be paired into one RegPairInfo, which is incompatible with
335 // the assumption made by the homogeneous prolog epilog pass.
336 const MCPhysReg
*CSRegs
= MF
.getRegInfo().getCalleeSavedRegs();
337 unsigned NumGPRs
= 0;
338 for (unsigned I
= 0; CSRegs
[I
]; ++I
) {
339 Register Reg
= CSRegs
[I
];
340 if (Reg
== AArch64::LR
) {
341 assert(CSRegs
[I
+ 1] == AArch64::FP
);
342 if (NumGPRs
% 2 != 0)
346 if (AArch64::GPR64RegClass
.contains(Reg
))
353 /// Returns true if CSRs should be paired.
354 bool AArch64FrameLowering::producePairRegisters(MachineFunction
&MF
) const {
355 return produceCompactUnwindFrame(MF
) || homogeneousPrologEpilog(MF
);
358 /// This is the biggest offset to the stack pointer we can encode in aarch64
359 /// instructions (without using a separate calculation and a temp register).
360 /// Note that the exception here are vector stores/loads which cannot encode any
361 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
362 static const unsigned DefaultSafeSPDisplacement
= 255;
364 /// Look at each instruction that references stack frames and return the stack
365 /// size limit beyond which some of these instructions will require a scratch
366 /// register during their expansion later.
367 static unsigned estimateRSStackSizeLimit(MachineFunction
&MF
) {
368 // FIXME: For now, just conservatively guestimate based on unscaled indexing
369 // range. We'll end up allocating an unnecessary spill slot a lot, but
370 // realistically that's not a big deal at this stage of the game.
371 for (MachineBasicBlock
&MBB
: MF
) {
372 for (MachineInstr
&MI
: MBB
) {
373 if (MI
.isDebugInstr() || MI
.isPseudo() ||
374 MI
.getOpcode() == AArch64::ADDXri
||
375 MI
.getOpcode() == AArch64::ADDSXri
)
378 for (const MachineOperand
&MO
: MI
.operands()) {
383 if (isAArch64FrameOffsetLegal(MI
, Offset
, nullptr, nullptr, nullptr) ==
384 AArch64FrameOffsetCannotUpdate
)
389 return DefaultSafeSPDisplacement
;
393 AArch64FrameLowering::getStackIDForScalableVectors() const {
394 return TargetStackID::ScalableVector
;
397 /// Returns the size of the fixed object area (allocated next to sp on entry)
398 /// On Win64 this may include a var args area and an UnwindHelp object for EH.
399 static unsigned getFixedObjectSize(const MachineFunction
&MF
,
400 const AArch64FunctionInfo
*AFI
, bool IsWin64
,
402 if (!IsWin64
|| IsFunclet
) {
403 return AFI
->getTailCallReservedStack();
405 if (AFI
->getTailCallReservedStack() != 0)
406 report_fatal_error("cannot generate ABI-changing tail call for Win64");
407 // Var args are stored here in the primary function.
408 const unsigned VarArgsArea
= AFI
->getVarArgsGPRSize();
409 // To support EH funclets we allocate an UnwindHelp object
410 const unsigned UnwindHelpObject
= (MF
.hasEHFunclets() ? 8 : 0);
411 return alignTo(VarArgsArea
+ UnwindHelpObject
, 16);
415 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
416 static StackOffset
getSVEStackSize(const MachineFunction
&MF
) {
417 const AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
418 return StackOffset::getScalable((int64_t)AFI
->getStackSizeSVE());
421 bool AArch64FrameLowering::canUseRedZone(const MachineFunction
&MF
) const {
425 // Don't use the red zone if the function explicitly asks us not to.
426 // This is typically used for kernel code.
427 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
428 const unsigned RedZoneSize
=
429 Subtarget
.getTargetLowering()->getRedZoneSize(MF
.getFunction());
433 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
434 const AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
435 uint64_t NumBytes
= AFI
->getLocalStackSize();
437 return !(MFI
.hasCalls() || hasFP(MF
) || NumBytes
> RedZoneSize
||
438 getSVEStackSize(MF
));
441 /// hasFP - Return true if the specified function should have a dedicated frame
442 /// pointer register.
443 bool AArch64FrameLowering::hasFP(const MachineFunction
&MF
) const {
444 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
445 const TargetRegisterInfo
*RegInfo
= MF
.getSubtarget().getRegisterInfo();
447 // Win64 EH requires a frame pointer if funclets are present, as the locals
448 // are accessed off the frame pointer in both the parent function and the
450 if (MF
.hasEHFunclets())
452 // Retain behavior of always omitting the FP for leaf functions when possible.
453 if (MF
.getTarget().Options
.DisableFramePointerElim(MF
))
455 if (MFI
.hasVarSizedObjects() || MFI
.isFrameAddressTaken() ||
456 MFI
.hasStackMap() || MFI
.hasPatchPoint() ||
457 RegInfo
->hasStackRealignment(MF
))
459 // With large callframes around we may need to use FP to access the scavenging
460 // emergency spillslot.
462 // Unfortunately some calls to hasFP() like machine verifier ->
463 // getReservedReg() -> hasFP in the middle of global isel are too early
464 // to know the max call frame size. Hopefully conservatively returning "true"
465 // in those cases is fine.
466 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
467 if (!MFI
.isMaxCallFrameSizeComputed() ||
468 MFI
.getMaxCallFrameSize() > DefaultSafeSPDisplacement
)
474 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
475 /// not required, we reserve argument space for call sites in the function
476 /// immediately on entry to the current function. This eliminates the need for
477 /// add/sub sp brackets around call sites. Returns true if the call frame is
478 /// included as part of the stack frame.
480 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction
&MF
) const {
481 return !MF
.getFrameInfo().hasVarSizedObjects();
484 MachineBasicBlock::iterator
AArch64FrameLowering::eliminateCallFramePseudoInstr(
485 MachineFunction
&MF
, MachineBasicBlock
&MBB
,
486 MachineBasicBlock::iterator I
) const {
487 const AArch64InstrInfo
*TII
=
488 static_cast<const AArch64InstrInfo
*>(MF
.getSubtarget().getInstrInfo());
489 DebugLoc DL
= I
->getDebugLoc();
490 unsigned Opc
= I
->getOpcode();
491 bool IsDestroy
= Opc
== TII
->getCallFrameDestroyOpcode();
492 uint64_t CalleePopAmount
= IsDestroy
? I
->getOperand(1).getImm() : 0;
494 if (!hasReservedCallFrame(MF
)) {
495 int64_t Amount
= I
->getOperand(0).getImm();
496 Amount
= alignTo(Amount
, getStackAlign());
500 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
501 // doesn't have to pop anything), then the first operand will be zero too so
502 // this adjustment is a no-op.
503 if (CalleePopAmount
== 0) {
504 // FIXME: in-function stack adjustment for calls is limited to 24-bits
505 // because there's no guaranteed temporary register available.
507 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
508 // 1) For offset <= 12-bit, we use LSL #0
509 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
510 // LSL #0, and the other uses LSL #12.
512 // Most call frames will be allocated at the start of a function so
513 // this is OK, but it is a limitation that needs dealing with.
514 assert(Amount
> -0xffffff && Amount
< 0xffffff && "call frame too large");
515 emitFrameOffset(MBB
, I
, DL
, AArch64::SP
, AArch64::SP
,
516 StackOffset::getFixed(Amount
), TII
);
518 } else if (CalleePopAmount
!= 0) {
519 // If the calling convention demands that the callee pops arguments from the
520 // stack, we want to add it back if we have a reserved call frame.
521 assert(CalleePopAmount
< 0xffffff && "call frame too large");
522 emitFrameOffset(MBB
, I
, DL
, AArch64::SP
, AArch64::SP
,
523 StackOffset::getFixed(-(int64_t)CalleePopAmount
), TII
);
528 void AArch64FrameLowering::emitCalleeSavedGPRLocations(
529 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
) const {
530 MachineFunction
&MF
= *MBB
.getParent();
531 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
533 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
537 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
538 const TargetRegisterInfo
&TRI
= *STI
.getRegisterInfo();
539 const TargetInstrInfo
&TII
= *STI
.getInstrInfo();
540 DebugLoc DL
= MBB
.findDebugLoc(MBBI
);
542 for (const auto &Info
: CSI
) {
543 if (MFI
.getStackID(Info
.getFrameIdx()) == TargetStackID::ScalableVector
)
546 assert(!Info
.isSpilledToReg() && "Spilling to registers not implemented");
547 unsigned DwarfReg
= TRI
.getDwarfRegNum(Info
.getReg(), true);
550 MFI
.getObjectOffset(Info
.getFrameIdx()) - getOffsetOfLocalArea();
551 unsigned CFIIndex
= MF
.addFrameInst(
552 MCCFIInstruction::createOffset(nullptr, DwarfReg
, Offset
));
553 BuildMI(MBB
, MBBI
, DL
, TII
.get(TargetOpcode::CFI_INSTRUCTION
))
554 .addCFIIndex(CFIIndex
)
555 .setMIFlags(MachineInstr::FrameSetup
);
559 void AArch64FrameLowering::emitCalleeSavedSVELocations(
560 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
) const {
561 MachineFunction
&MF
= *MBB
.getParent();
562 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
564 // Add callee saved registers to move list.
565 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
569 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
570 const TargetRegisterInfo
&TRI
= *STI
.getRegisterInfo();
571 const TargetInstrInfo
&TII
= *STI
.getInstrInfo();
572 DebugLoc DL
= MBB
.findDebugLoc(MBBI
);
573 AArch64FunctionInfo
&AFI
= *MF
.getInfo
<AArch64FunctionInfo
>();
575 for (const auto &Info
: CSI
) {
576 if (!(MFI
.getStackID(Info
.getFrameIdx()) == TargetStackID::ScalableVector
))
579 // Not all unwinders may know about SVE registers, so assume the lowest
580 // common demoninator.
581 assert(!Info
.isSpilledToReg() && "Spilling to registers not implemented");
582 unsigned Reg
= Info
.getReg();
583 if (!static_cast<const AArch64RegisterInfo
&>(TRI
).regNeedsCFI(Reg
, Reg
))
587 StackOffset::getScalable(MFI
.getObjectOffset(Info
.getFrameIdx())) -
588 StackOffset::getFixed(AFI
.getCalleeSavedStackSize(MFI
));
590 unsigned CFIIndex
= MF
.addFrameInst(createCFAOffset(TRI
, Reg
, Offset
));
591 BuildMI(MBB
, MBBI
, DL
, TII
.get(TargetOpcode::CFI_INSTRUCTION
))
592 .addCFIIndex(CFIIndex
)
593 .setMIFlags(MachineInstr::FrameSetup
);
597 static void insertCFISameValue(const MCInstrDesc
&Desc
, MachineFunction
&MF
,
598 MachineBasicBlock
&MBB
,
599 MachineBasicBlock::iterator InsertPt
,
602 MF
.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg
));
603 BuildMI(MBB
, InsertPt
, DebugLoc(), Desc
).addCFIIndex(CFIIndex
);
606 void AArch64FrameLowering::resetCFIToInitialState(
607 MachineBasicBlock
&MBB
) const {
609 MachineFunction
&MF
= *MBB
.getParent();
610 const auto &Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
611 const TargetInstrInfo
&TII
= *Subtarget
.getInstrInfo();
613 static_cast<const AArch64RegisterInfo
&>(*Subtarget
.getRegisterInfo());
614 const auto &MFI
= *MF
.getInfo
<AArch64FunctionInfo
>();
616 const MCInstrDesc
&CFIDesc
= TII
.get(TargetOpcode::CFI_INSTRUCTION
);
619 // Reset the CFA to `SP + 0`.
620 MachineBasicBlock::iterator InsertPt
= MBB
.begin();
621 unsigned CFIIndex
= MF
.addFrameInst(MCCFIInstruction::cfiDefCfa(
622 nullptr, TRI
.getDwarfRegNum(AArch64::SP
, true), 0));
623 BuildMI(MBB
, InsertPt
, DL
, CFIDesc
).addCFIIndex(CFIIndex
);
625 // Flip the RA sign state.
626 if (MFI
.shouldSignReturnAddress(MF
)) {
627 CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
628 BuildMI(MBB
, InsertPt
, DL
, CFIDesc
).addCFIIndex(CFIIndex
);
631 // Shadow call stack uses X18, reset it.
632 if (MFI
.needsShadowCallStackPrologueEpilogue(MF
))
633 insertCFISameValue(CFIDesc
, MF
, MBB
, InsertPt
,
634 TRI
.getDwarfRegNum(AArch64::X18
, true));
636 // Emit .cfi_same_value for callee-saved registers.
637 const std::vector
<CalleeSavedInfo
> &CSI
=
638 MF
.getFrameInfo().getCalleeSavedInfo();
639 for (const auto &Info
: CSI
) {
640 unsigned Reg
= Info
.getReg();
641 if (!TRI
.regNeedsCFI(Reg
, Reg
))
643 insertCFISameValue(CFIDesc
, MF
, MBB
, InsertPt
,
644 TRI
.getDwarfRegNum(Reg
, true));
648 static void emitCalleeSavedRestores(MachineBasicBlock
&MBB
,
649 MachineBasicBlock::iterator MBBI
,
651 MachineFunction
&MF
= *MBB
.getParent();
652 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
654 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
658 const TargetSubtargetInfo
&STI
= MF
.getSubtarget();
659 const TargetRegisterInfo
&TRI
= *STI
.getRegisterInfo();
660 const TargetInstrInfo
&TII
= *STI
.getInstrInfo();
661 DebugLoc DL
= MBB
.findDebugLoc(MBBI
);
663 for (const auto &Info
: CSI
) {
665 (MFI
.getStackID(Info
.getFrameIdx()) == TargetStackID::ScalableVector
))
668 unsigned Reg
= Info
.getReg();
670 !static_cast<const AArch64RegisterInfo
&>(TRI
).regNeedsCFI(Reg
, Reg
))
673 unsigned CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createRestore(
674 nullptr, TRI
.getDwarfRegNum(Info
.getReg(), true)));
675 BuildMI(MBB
, MBBI
, DL
, TII
.get(TargetOpcode::CFI_INSTRUCTION
))
676 .addCFIIndex(CFIIndex
)
677 .setMIFlags(MachineInstr::FrameDestroy
);
681 void AArch64FrameLowering::emitCalleeSavedGPRRestores(
682 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
) const {
683 emitCalleeSavedRestores(MBB
, MBBI
, false);
686 void AArch64FrameLowering::emitCalleeSavedSVERestores(
687 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
) const {
688 emitCalleeSavedRestores(MBB
, MBBI
, true);
691 static MCRegister
getRegisterOrZero(MCRegister Reg
, bool HasSVE
) {
694 // The called routine is expected to preserve r19-r28
695 // r29 and r30 are used as frame pointer and link register resp.
700 case AArch64::W##n: \
701 case AArch64::X##n: \
726 case AArch64::B##n: \
727 case AArch64::H##n: \
728 case AArch64::S##n: \
729 case AArch64::D##n: \
730 case AArch64::Q##n: \
731 return HasSVE ? AArch64::Z##n : AArch64::Q##n
768 void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero
,
769 MachineBasicBlock
&MBB
) const {
771 MachineBasicBlock::iterator MBBI
= MBB
.getFirstTerminator();
775 if (MBBI
!= MBB
.end())
776 DL
= MBBI
->getDebugLoc();
778 const MachineFunction
&MF
= *MBB
.getParent();
779 const AArch64Subtarget
&STI
= MF
.getSubtarget
<AArch64Subtarget
>();
780 const AArch64RegisterInfo
&TRI
= *STI
.getRegisterInfo();
782 BitVector
GPRsToZero(TRI
.getNumRegs());
783 BitVector
FPRsToZero(TRI
.getNumRegs());
784 bool HasSVE
= STI
.hasSVE();
785 for (MCRegister Reg
: RegsToZero
.set_bits()) {
786 if (TRI
.isGeneralPurposeRegister(MF
, Reg
)) {
787 // For GPRs, we only care to clear out the 64-bit register.
788 if (MCRegister XReg
= getRegisterOrZero(Reg
, HasSVE
))
789 GPRsToZero
.set(XReg
);
790 } else if (AArch64::FPR128RegClass
.contains(Reg
) ||
791 AArch64::FPR64RegClass
.contains(Reg
) ||
792 AArch64::FPR32RegClass
.contains(Reg
) ||
793 AArch64::FPR16RegClass
.contains(Reg
) ||
794 AArch64::FPR8RegClass
.contains(Reg
)) {
796 if (MCRegister XReg
= getRegisterOrZero(Reg
, HasSVE
))
797 FPRsToZero
.set(XReg
);
801 const AArch64InstrInfo
&TII
= *STI
.getInstrInfo();
804 for (MCRegister Reg
: GPRsToZero
.set_bits())
805 TII
.buildClearRegister(Reg
, MBB
, MBBI
, DL
);
807 // Zero out FP/vector registers.
808 for (MCRegister Reg
: FPRsToZero
.set_bits())
809 TII
.buildClearRegister(Reg
, MBB
, MBBI
, DL
);
812 for (MCRegister PReg
:
813 {AArch64::P0
, AArch64::P1
, AArch64::P2
, AArch64::P3
, AArch64::P4
,
814 AArch64::P5
, AArch64::P6
, AArch64::P7
, AArch64::P8
, AArch64::P9
,
815 AArch64::P10
, AArch64::P11
, AArch64::P12
, AArch64::P13
, AArch64::P14
,
817 if (RegsToZero
[PReg
])
818 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::PFALSE
), PReg
);
823 // Find a scratch register that we can use at the start of the prologue to
824 // re-align the stack pointer. We avoid using callee-save registers since they
825 // may appear to be free when this is called from canUseAsPrologue (during
826 // shrink wrapping), but then no longer be free when this is called from
829 // FIXME: This is a bit conservative, since in the above case we could use one
830 // of the callee-save registers as a scratch temp to re-align the stack pointer,
831 // but we would then have to make sure that we were in fact saving at least one
832 // callee-save register in the prologue, which is additional complexity that
833 // doesn't seem worth the benefit.
834 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock
*MBB
) {
835 MachineFunction
*MF
= MBB
->getParent();
837 // If MBB is an entry block, use X9 as the scratch register
838 if (&MF
->front() == MBB
)
841 const AArch64Subtarget
&Subtarget
= MF
->getSubtarget
<AArch64Subtarget
>();
842 const AArch64RegisterInfo
&TRI
= *Subtarget
.getRegisterInfo();
843 LivePhysRegs
LiveRegs(TRI
);
844 LiveRegs
.addLiveIns(*MBB
);
846 // Mark callee saved registers as used so we will not choose them.
847 const MCPhysReg
*CSRegs
= MF
->getRegInfo().getCalleeSavedRegs();
848 for (unsigned i
= 0; CSRegs
[i
]; ++i
)
849 LiveRegs
.addReg(CSRegs
[i
]);
851 // Prefer X9 since it was historically used for the prologue scratch reg.
852 const MachineRegisterInfo
&MRI
= MF
->getRegInfo();
853 if (LiveRegs
.available(MRI
, AArch64::X9
))
856 for (unsigned Reg
: AArch64::GPR64RegClass
) {
857 if (LiveRegs
.available(MRI
, Reg
))
860 return AArch64::NoRegister
;
863 bool AArch64FrameLowering::canUseAsPrologue(
864 const MachineBasicBlock
&MBB
) const {
865 const MachineFunction
*MF
= MBB
.getParent();
866 MachineBasicBlock
*TmpMBB
= const_cast<MachineBasicBlock
*>(&MBB
);
867 const AArch64Subtarget
&Subtarget
= MF
->getSubtarget
<AArch64Subtarget
>();
868 const AArch64RegisterInfo
*RegInfo
= Subtarget
.getRegisterInfo();
870 // Don't need a scratch register if we're not going to re-align the stack.
871 if (!RegInfo
->hasStackRealignment(*MF
))
873 // Otherwise, we can use any block as long as it has a scratch register
875 return findScratchNonCalleeSaveRegister(TmpMBB
) != AArch64::NoRegister
;
878 static bool windowsRequiresStackProbe(MachineFunction
&MF
,
879 uint64_t StackSizeInBytes
) {
880 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
881 if (!Subtarget
.isTargetWindows())
883 const Function
&F
= MF
.getFunction();
884 // TODO: When implementing stack protectors, take that into account
885 // for the probe threshold.
886 unsigned StackProbeSize
=
887 F
.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
888 return (StackSizeInBytes
>= StackProbeSize
) &&
889 !F
.hasFnAttribute("no-stack-arg-probe");
892 static bool needsWinCFI(const MachineFunction
&MF
) {
893 const Function
&F
= MF
.getFunction();
894 return MF
.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
895 F
.needsUnwindTableEntry();
898 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
899 MachineFunction
&MF
, uint64_t StackBumpBytes
) const {
900 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
901 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
902 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
903 const AArch64RegisterInfo
*RegInfo
= Subtarget
.getRegisterInfo();
904 if (homogeneousPrologEpilog(MF
))
907 if (AFI
->getLocalStackSize() == 0)
910 // For WinCFI, if optimizing for size, prefer to not combine the stack bump
911 // (to force a stp with predecrement) to match the packed unwind format,
912 // provided that there actually are any callee saved registers to merge the
914 // This is potentially marginally slower, but allows using the packed
915 // unwind format for functions that both have a local area and callee saved
916 // registers. Using the packed unwind format notably reduces the size of
918 if (needsWinCFI(MF
) && AFI
->getCalleeSavedStackSize() > 0 &&
919 MF
.getFunction().hasOptSize())
922 // 512 is the maximum immediate for stp/ldp that will be used for
923 // callee-save save/restores
924 if (StackBumpBytes
>= 512 || windowsRequiresStackProbe(MF
, StackBumpBytes
))
927 if (MFI
.hasVarSizedObjects())
930 if (RegInfo
->hasStackRealignment(MF
))
933 // This isn't strictly necessary, but it simplifies things a bit since the
934 // current RedZone handling code assumes the SP is adjusted by the
935 // callee-save save/restore code.
936 if (canUseRedZone(MF
))
939 // When there is an SVE area on the stack, always allocate the
940 // callee-saves and spills/locals separately.
941 if (getSVEStackSize(MF
))
947 bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(
948 MachineBasicBlock
&MBB
, unsigned StackBumpBytes
) const {
949 if (!shouldCombineCSRLocalStackBump(*MBB
.getParent(), StackBumpBytes
))
955 // Disable combined SP bump if the last instruction is an MTE tag store. It
956 // is almost always better to merge SP adjustment into those instructions.
957 MachineBasicBlock::iterator LastI
= MBB
.getFirstTerminator();
958 MachineBasicBlock::iterator Begin
= MBB
.begin();
959 while (LastI
!= Begin
) {
961 if (LastI
->isTransient())
963 if (!LastI
->getFlag(MachineInstr::FrameDestroy
))
966 switch (LastI
->getOpcode()) {
967 case AArch64::STGloop
:
968 case AArch64::STZGloop
:
972 case AArch64::STZ2Gi
:
977 llvm_unreachable("unreachable");
980 // Given a load or a store instruction, generate an appropriate unwinding SEH
982 static MachineBasicBlock::iterator
InsertSEH(MachineBasicBlock::iterator MBBI
,
983 const TargetInstrInfo
&TII
,
984 MachineInstr::MIFlag Flag
) {
985 unsigned Opc
= MBBI
->getOpcode();
986 MachineBasicBlock
*MBB
= MBBI
->getParent();
987 MachineFunction
&MF
= *MBB
->getParent();
988 DebugLoc DL
= MBBI
->getDebugLoc();
989 unsigned ImmIdx
= MBBI
->getNumOperands() - 1;
990 int Imm
= MBBI
->getOperand(ImmIdx
).getImm();
991 MachineInstrBuilder MIB
;
992 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
993 const AArch64RegisterInfo
*RegInfo
= Subtarget
.getRegisterInfo();
997 llvm_unreachable("No SEH Opcode for this instruction");
998 case AArch64::LDPDpost
:
1001 case AArch64::STPDpre
: {
1002 unsigned Reg0
= RegInfo
->getSEHRegNum(MBBI
->getOperand(1).getReg());
1003 unsigned Reg1
= RegInfo
->getSEHRegNum(MBBI
->getOperand(2).getReg());
1004 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFRegP_X
))
1011 case AArch64::LDPXpost
:
1014 case AArch64::STPXpre
: {
1015 Register Reg0
= MBBI
->getOperand(1).getReg();
1016 Register Reg1
= MBBI
->getOperand(2).getReg();
1017 if (Reg0
== AArch64::FP
&& Reg1
== AArch64::LR
)
1018 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFPLR_X
))
1022 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveRegP_X
))
1023 .addImm(RegInfo
->getSEHRegNum(Reg0
))
1024 .addImm(RegInfo
->getSEHRegNum(Reg1
))
1029 case AArch64::LDRDpost
:
1032 case AArch64::STRDpre
: {
1033 unsigned Reg
= RegInfo
->getSEHRegNum(MBBI
->getOperand(1).getReg());
1034 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFReg_X
))
1040 case AArch64::LDRXpost
:
1043 case AArch64::STRXpre
: {
1044 unsigned Reg
= RegInfo
->getSEHRegNum(MBBI
->getOperand(1).getReg());
1045 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveReg_X
))
1051 case AArch64::STPDi
:
1052 case AArch64::LDPDi
: {
1053 unsigned Reg0
= RegInfo
->getSEHRegNum(MBBI
->getOperand(0).getReg());
1054 unsigned Reg1
= RegInfo
->getSEHRegNum(MBBI
->getOperand(1).getReg());
1055 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFRegP
))
1062 case AArch64::STPXi
:
1063 case AArch64::LDPXi
: {
1064 Register Reg0
= MBBI
->getOperand(0).getReg();
1065 Register Reg1
= MBBI
->getOperand(1).getReg();
1066 if (Reg0
== AArch64::FP
&& Reg1
== AArch64::LR
)
1067 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFPLR
))
1071 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveRegP
))
1072 .addImm(RegInfo
->getSEHRegNum(Reg0
))
1073 .addImm(RegInfo
->getSEHRegNum(Reg1
))
1078 case AArch64::STRXui
:
1079 case AArch64::LDRXui
: {
1080 int Reg
= RegInfo
->getSEHRegNum(MBBI
->getOperand(0).getReg());
1081 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveReg
))
1087 case AArch64::STRDui
:
1088 case AArch64::LDRDui
: {
1089 unsigned Reg
= RegInfo
->getSEHRegNum(MBBI
->getOperand(0).getReg());
1090 MIB
= BuildMI(MF
, DL
, TII
.get(AArch64::SEH_SaveFReg
))
1097 auto I
= MBB
->insertAfter(MBBI
, MIB
);
1101 // Fix up the SEH opcode associated with the save/restore instruction.
1102 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI
,
1103 unsigned LocalStackSize
) {
1104 MachineOperand
*ImmOpnd
= nullptr;
1105 unsigned ImmIdx
= MBBI
->getNumOperands() - 1;
1106 switch (MBBI
->getOpcode()) {
1108 llvm_unreachable("Fix the offset in the SEH instruction");
1109 case AArch64::SEH_SaveFPLR
:
1110 case AArch64::SEH_SaveRegP
:
1111 case AArch64::SEH_SaveReg
:
1112 case AArch64::SEH_SaveFRegP
:
1113 case AArch64::SEH_SaveFReg
:
1114 ImmOpnd
= &MBBI
->getOperand(ImmIdx
);
1118 ImmOpnd
->setImm(ImmOpnd
->getImm() + LocalStackSize
);
1121 // Convert callee-save register save/restore instruction to do stack pointer
1122 // decrement/increment to allocate/deallocate the callee-save stack area by
1123 // converting store/load to use pre/post increment version.
1124 static MachineBasicBlock::iterator
convertCalleeSaveRestoreToSPPrePostIncDec(
1125 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
,
1126 const DebugLoc
&DL
, const TargetInstrInfo
*TII
, int CSStackSizeInc
,
1127 bool NeedsWinCFI
, bool *HasWinCFI
, bool EmitCFI
,
1128 MachineInstr::MIFlag FrameFlag
= MachineInstr::FrameSetup
,
1129 int CFAOffset
= 0) {
1131 switch (MBBI
->getOpcode()) {
1133 llvm_unreachable("Unexpected callee-save save/restore opcode!");
1134 case AArch64::STPXi
:
1135 NewOpc
= AArch64::STPXpre
;
1137 case AArch64::STPDi
:
1138 NewOpc
= AArch64::STPDpre
;
1140 case AArch64::STPQi
:
1141 NewOpc
= AArch64::STPQpre
;
1143 case AArch64::STRXui
:
1144 NewOpc
= AArch64::STRXpre
;
1146 case AArch64::STRDui
:
1147 NewOpc
= AArch64::STRDpre
;
1149 case AArch64::STRQui
:
1150 NewOpc
= AArch64::STRQpre
;
1152 case AArch64::LDPXi
:
1153 NewOpc
= AArch64::LDPXpost
;
1155 case AArch64::LDPDi
:
1156 NewOpc
= AArch64::LDPDpost
;
1158 case AArch64::LDPQi
:
1159 NewOpc
= AArch64::LDPQpost
;
1161 case AArch64::LDRXui
:
1162 NewOpc
= AArch64::LDRXpost
;
1164 case AArch64::LDRDui
:
1165 NewOpc
= AArch64::LDRDpost
;
1167 case AArch64::LDRQui
:
1168 NewOpc
= AArch64::LDRQpost
;
1171 // Get rid of the SEH code associated with the old instruction.
1173 auto SEH
= std::next(MBBI
);
1174 if (AArch64InstrInfo::isSEHInstruction(*SEH
))
1175 SEH
->eraseFromParent();
1178 TypeSize Scale
= TypeSize::Fixed(1);
1180 int64_t MinOffset
, MaxOffset
;
1181 bool Success
= static_cast<const AArch64InstrInfo
*>(TII
)->getMemOpInfo(
1182 NewOpc
, Scale
, Width
, MinOffset
, MaxOffset
);
1184 assert(Success
&& "unknown load/store opcode");
1186 // If the first store isn't right where we want SP then we can't fold the
1187 // update in so create a normal arithmetic instruction instead.
1188 MachineFunction
&MF
= *MBB
.getParent();
1189 if (MBBI
->getOperand(MBBI
->getNumOperands() - 1).getImm() != 0 ||
1190 CSStackSizeInc
< MinOffset
|| CSStackSizeInc
> MaxOffset
) {
1191 emitFrameOffset(MBB
, MBBI
, DL
, AArch64::SP
, AArch64::SP
,
1192 StackOffset::getFixed(CSStackSizeInc
), TII
, FrameFlag
,
1193 false, false, nullptr, EmitCFI
,
1194 StackOffset::getFixed(CFAOffset
));
1196 return std::prev(MBBI
);
1199 MachineInstrBuilder MIB
= BuildMI(MBB
, MBBI
, DL
, TII
->get(NewOpc
));
1200 MIB
.addReg(AArch64::SP
, RegState::Define
);
1202 // Copy all operands other than the immediate offset.
1203 unsigned OpndIdx
= 0;
1204 for (unsigned OpndEnd
= MBBI
->getNumOperands() - 1; OpndIdx
< OpndEnd
;
1206 MIB
.add(MBBI
->getOperand(OpndIdx
));
1208 assert(MBBI
->getOperand(OpndIdx
).getImm() == 0 &&
1209 "Unexpected immediate offset in first/last callee-save save/restore "
1211 assert(MBBI
->getOperand(OpndIdx
- 1).getReg() == AArch64::SP
&&
1212 "Unexpected base register in callee-save save/restore instruction!");
1213 assert(CSStackSizeInc
% Scale
== 0);
1214 MIB
.addImm(CSStackSizeInc
/ (int)Scale
);
1216 MIB
.setMIFlags(MBBI
->getFlags());
1217 MIB
.setMemRefs(MBBI
->memoperands());
1219 // Generate a new SEH code that corresponds to the new instruction.
1222 InsertSEH(*MIB
, *TII
, FrameFlag
);
1226 unsigned CFIIndex
= MF
.addFrameInst(
1227 MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset
- CSStackSizeInc
));
1228 BuildMI(MBB
, MBBI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
1229 .addCFIIndex(CFIIndex
)
1230 .setMIFlags(FrameFlag
);
1233 return std::prev(MBB
.erase(MBBI
));
1236 // Fixup callee-save register save/restore instructions to take into account
1237 // combined SP bump by adding the local stack size to the stack offsets.
1238 static void fixupCalleeSaveRestoreStackOffset(MachineInstr
&MI
,
1239 uint64_t LocalStackSize
,
1242 if (AArch64InstrInfo::isSEHInstruction(MI
))
1245 unsigned Opc
= MI
.getOpcode();
1248 case AArch64::STPXi
:
1249 case AArch64::STRXui
:
1250 case AArch64::STPDi
:
1251 case AArch64::STRDui
:
1252 case AArch64::LDPXi
:
1253 case AArch64::LDRXui
:
1254 case AArch64::LDPDi
:
1255 case AArch64::LDRDui
:
1258 case AArch64::STPQi
:
1259 case AArch64::STRQui
:
1260 case AArch64::LDPQi
:
1261 case AArch64::LDRQui
:
1265 llvm_unreachable("Unexpected callee-save save/restore opcode!");
1268 unsigned OffsetIdx
= MI
.getNumExplicitOperands() - 1;
1269 assert(MI
.getOperand(OffsetIdx
- 1).getReg() == AArch64::SP
&&
1270 "Unexpected base register in callee-save save/restore instruction!");
1271 // Last operand is immediate offset that needs fixing.
1272 MachineOperand
&OffsetOpnd
= MI
.getOperand(OffsetIdx
);
1273 // All generated opcodes have scaled offsets.
1274 assert(LocalStackSize
% Scale
== 0);
1275 OffsetOpnd
.setImm(OffsetOpnd
.getImm() + LocalStackSize
/ Scale
);
1279 auto MBBI
= std::next(MachineBasicBlock::iterator(MI
));
1280 assert(MBBI
!= MI
.getParent()->end() && "Expecting a valid instruction");
1281 assert(AArch64InstrInfo::isSEHInstruction(*MBBI
) &&
1282 "Expecting a SEH instruction");
1283 fixupSEHOpcode(MBBI
, LocalStackSize
);
1287 static bool isTargetWindows(const MachineFunction
&MF
) {
1288 return MF
.getSubtarget
<AArch64Subtarget
>().isTargetWindows();
1291 // Convenience function to determine whether I is an SVE callee save.
1292 static bool IsSVECalleeSave(MachineBasicBlock::iterator I
) {
1293 switch (I
->getOpcode()) {
1296 case AArch64::STR_ZXI
:
1297 case AArch64::STR_PXI
:
1298 case AArch64::LDR_ZXI
:
1299 case AArch64::LDR_PXI
:
1300 return I
->getFlag(MachineInstr::FrameSetup
) ||
1301 I
->getFlag(MachineInstr::FrameDestroy
);
1305 static void emitShadowCallStackPrologue(const TargetInstrInfo
&TII
,
1306 MachineFunction
&MF
,
1307 MachineBasicBlock
&MBB
,
1308 MachineBasicBlock::iterator MBBI
,
1309 const DebugLoc
&DL
, bool NeedsWinCFI
,
1310 bool NeedsUnwindInfo
) {
1311 // Shadow call stack prolog: str x30, [x18], #8
1312 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::STRXpost
))
1313 .addReg(AArch64::X18
, RegState::Define
)
1314 .addReg(AArch64::LR
)
1315 .addReg(AArch64::X18
)
1317 .setMIFlag(MachineInstr::FrameSetup
);
1319 // This instruction also makes x18 live-in to the entry block.
1320 MBB
.addLiveIn(AArch64::X18
);
1323 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::SEH_Nop
))
1324 .setMIFlag(MachineInstr::FrameSetup
);
1326 if (NeedsUnwindInfo
) {
1327 // Emit a CFI instruction that causes 8 to be subtracted from the value of
1328 // x18 when unwinding past this frame.
1329 static const char CFIInst
[] = {
1330 dwarf::DW_CFA_val_expression
,
1333 static_cast<char>(unsigned(dwarf::DW_OP_breg18
)),
1334 static_cast<char>(-8) & 0x7f, // addend (sleb128)
1336 unsigned CFIIndex
= MF
.addFrameInst(MCCFIInstruction::createEscape(
1337 nullptr, StringRef(CFIInst
, sizeof(CFIInst
))));
1338 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::CFI_INSTRUCTION
))
1339 .addCFIIndex(CFIIndex
)
1340 .setMIFlag(MachineInstr::FrameSetup
);
1344 static void emitShadowCallStackEpilogue(const TargetInstrInfo
&TII
,
1345 MachineFunction
&MF
,
1346 MachineBasicBlock
&MBB
,
1347 MachineBasicBlock::iterator MBBI
,
1348 const DebugLoc
&DL
) {
1349 // Shadow call stack epilog: ldr x30, [x18, #-8]!
1350 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::LDRXpre
))
1351 .addReg(AArch64::X18
, RegState::Define
)
1352 .addReg(AArch64::LR
, RegState::Define
)
1353 .addReg(AArch64::X18
)
1355 .setMIFlag(MachineInstr::FrameDestroy
);
1357 if (MF
.getInfo
<AArch64FunctionInfo
>()->needsAsyncDwarfUnwindInfo(MF
)) {
1359 MF
.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));
1360 BuildMI(MBB
, MBBI
, DL
, TII
.get(TargetOpcode::CFI_INSTRUCTION
))
1361 .addCFIIndex(CFIIndex
)
1362 .setMIFlags(MachineInstr::FrameDestroy
);
1366 // Define the current CFA rule to use the provided FP.
1367 static void emitDefineCFAWithFP(MachineFunction
&MF
, MachineBasicBlock
&MBB
,
1368 MachineBasicBlock::iterator MBBI
,
1369 const DebugLoc
&DL
, unsigned FixedObject
) {
1370 const AArch64Subtarget
&STI
= MF
.getSubtarget
<AArch64Subtarget
>();
1371 const AArch64RegisterInfo
*TRI
= STI
.getRegisterInfo();
1372 const TargetInstrInfo
*TII
= STI
.getInstrInfo();
1373 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
1375 const int OffsetToFirstCalleeSaveFromFP
=
1376 AFI
->getCalleeSaveBaseToFrameRecordOffset() -
1377 AFI
->getCalleeSavedStackSize();
1378 Register FramePtr
= TRI
->getFrameRegister(MF
);
1379 unsigned Reg
= TRI
->getDwarfRegNum(FramePtr
, true);
1380 unsigned CFIIndex
= MF
.addFrameInst(MCCFIInstruction::cfiDefCfa(
1381 nullptr, Reg
, FixedObject
- OffsetToFirstCalleeSaveFromFP
));
1382 BuildMI(MBB
, MBBI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
1383 .addCFIIndex(CFIIndex
)
1384 .setMIFlags(MachineInstr::FrameSetup
);
1387 void AArch64FrameLowering::emitPrologue(MachineFunction
&MF
,
1388 MachineBasicBlock
&MBB
) const {
1389 MachineBasicBlock::iterator MBBI
= MBB
.begin();
1390 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
1391 const Function
&F
= MF
.getFunction();
1392 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
1393 const AArch64RegisterInfo
*RegInfo
= Subtarget
.getRegisterInfo();
1394 const TargetInstrInfo
*TII
= Subtarget
.getInstrInfo();
1395 MachineModuleInfo
&MMI
= MF
.getMMI();
1396 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
1397 bool EmitCFI
= AFI
->needsDwarfUnwindInfo(MF
);
1398 bool EmitAsyncCFI
= AFI
->needsAsyncDwarfUnwindInfo(MF
);
1399 bool HasFP
= hasFP(MF
);
1400 bool NeedsWinCFI
= needsWinCFI(MF
);
1401 bool HasWinCFI
= false;
1402 auto Cleanup
= make_scope_exit([&]() { MF
.setHasWinCFI(HasWinCFI
); });
1404 bool IsFunclet
= MBB
.isEHFuncletEntry();
1406 // At this point, we're going to decide whether or not the function uses a
1407 // redzone. In most cases, the function doesn't have a redzone so let's
1408 // assume that's false and set it to true in the case that there's a redzone.
1409 AFI
->setHasRedZone(false);
1411 // Debug location must be unknown since the first debug location is used
1412 // to determine the end of the prologue.
1415 const auto &MFnI
= *MF
.getInfo
<AArch64FunctionInfo
>();
1416 if (MFnI
.needsShadowCallStackPrologueEpilogue(MF
))
1417 emitShadowCallStackPrologue(*TII
, MF
, MBB
, MBBI
, DL
, NeedsWinCFI
,
1418 MFnI
.needsDwarfUnwindInfo(MF
));
1420 if (MFnI
.shouldSignReturnAddress(MF
)) {
1421 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::PAUTH_PROLOGUE
))
1422 .setMIFlag(MachineInstr::FrameSetup
);
1424 HasWinCFI
= true; // AArch64PointerAuth pass will insert SEH_PACSignLR
1427 if (EmitCFI
&& MFnI
.isMTETagged()) {
1428 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::EMITMTETAGGED
))
1429 .setMIFlag(MachineInstr::FrameSetup
);
1432 // We signal the presence of a Swift extended frame to external tools by
1433 // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple
1434 // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI
1435 // bits so that is still true.
1436 if (HasFP
&& AFI
->hasSwiftAsyncContext()) {
1437 switch (MF
.getTarget().Options
.SwiftAsyncFramePointer
) {
1438 case SwiftAsyncFramePointerMode::DeploymentBased
:
1439 if (Subtarget
.swiftAsyncContextIsDynamicallySet()) {
1440 // The special symbol below is absolute and has a *value* that can be
1441 // combined with the frame pointer to signal an extended frame.
1442 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::LOADgot
), AArch64::X16
)
1443 .addExternalSymbol("swift_async_extendedFramePointerFlags",
1446 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1447 .setMIFlags(MachineInstr::FrameSetup
);
1450 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ORRXrs
), AArch64::FP
)
1451 .addUse(AArch64::FP
)
1452 .addUse(AArch64::X16
)
1453 .addImm(Subtarget
.isTargetILP32() ? 32 : 0);
1455 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1456 .setMIFlags(MachineInstr::FrameSetup
);
1463 case SwiftAsyncFramePointerMode::Always
:
1464 // ORR x29, x29, #0x1000_0000_0000_0000
1465 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ORRXri
), AArch64::FP
)
1466 .addUse(AArch64::FP
)
1468 .setMIFlag(MachineInstr::FrameSetup
);
1470 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1471 .setMIFlags(MachineInstr::FrameSetup
);
1476 case SwiftAsyncFramePointerMode::Never
:
1481 // All calls are tail calls in GHC calling conv, and functions have no
1482 // prologue/epilogue.
1483 if (MF
.getFunction().getCallingConv() == CallingConv::GHC
)
1486 // Set tagged base pointer to the requested stack slot.
1487 // Ideally it should match SP value after prologue.
1488 std::optional
<int> TBPI
= AFI
->getTaggedBasePointerIndex();
1490 AFI
->setTaggedBasePointerOffset(-MFI
.getObjectOffset(*TBPI
));
1492 AFI
->setTaggedBasePointerOffset(MFI
.getStackSize());
1494 const StackOffset
&SVEStackSize
= getSVEStackSize(MF
);
1496 // getStackSize() includes all the locals in its size calculation. We don't
1497 // include these locals when computing the stack size of a funclet, as they
1498 // are allocated in the parent's stack frame and accessed via the frame
1499 // pointer from the funclet. We only save the callee saved registers in the
1500 // funclet, which are really the callee saved registers of the parent
1501 // function, including the funclet.
1502 int64_t NumBytes
= IsFunclet
? getWinEHFuncletFrameSize(MF
)
1503 : MFI
.getStackSize();
1504 if (!AFI
->hasStackFrame() && !windowsRequiresStackProbe(MF
, NumBytes
)) {
1505 assert(!HasFP
&& "unexpected function without stack frame but with FP");
1506 assert(!SVEStackSize
&&
1507 "unexpected function without stack frame but with SVE objects");
1508 // All of the stack allocation is for locals.
1509 AFI
->setLocalStackSize(NumBytes
);
1512 // REDZONE: If the stack size is less than 128 bytes, we don't need
1513 // to actually allocate.
1514 if (canUseRedZone(MF
)) {
1515 AFI
->setHasRedZone(true);
1516 ++NumRedZoneFunctions
;
1518 emitFrameOffset(MBB
, MBBI
, DL
, AArch64::SP
, AArch64::SP
,
1519 StackOffset::getFixed(-NumBytes
), TII
,
1520 MachineInstr::FrameSetup
, false, NeedsWinCFI
, &HasWinCFI
);
1522 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
1523 MCSymbol
*FrameLabel
= MMI
.getContext().createTempSymbol();
1524 // Encode the stack size of the leaf function.
1525 unsigned CFIIndex
= MF
.addFrameInst(
1526 MCCFIInstruction::cfiDefCfaOffset(FrameLabel
, NumBytes
));
1527 BuildMI(MBB
, MBBI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
1528 .addCFIIndex(CFIIndex
)
1529 .setMIFlags(MachineInstr::FrameSetup
);
1535 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_PrologEnd
))
1536 .setMIFlag(MachineInstr::FrameSetup
);
1543 Subtarget
.isCallingConvWin64(MF
.getFunction().getCallingConv());
1544 unsigned FixedObject
= getFixedObjectSize(MF
, AFI
, IsWin64
, IsFunclet
);
1546 auto PrologueSaveSize
= AFI
->getCalleeSavedStackSize() + FixedObject
;
1547 // All of the remaining stack allocations are for locals.
1548 AFI
->setLocalStackSize(NumBytes
- PrologueSaveSize
);
1549 bool CombineSPBump
= shouldCombineCSRLocalStackBump(MF
, NumBytes
);
1550 bool HomPrologEpilog
= homogeneousPrologEpilog(MF
);
1551 if (CombineSPBump
) {
1552 assert(!SVEStackSize
&& "Cannot combine SP bump with SVE");
1553 emitFrameOffset(MBB
, MBBI
, DL
, AArch64::SP
, AArch64::SP
,
1554 StackOffset::getFixed(-NumBytes
), TII
,
1555 MachineInstr::FrameSetup
, false, NeedsWinCFI
, &HasWinCFI
,
1558 } else if (HomPrologEpilog
) {
1559 // Stack has been already adjusted.
1560 NumBytes
-= PrologueSaveSize
;
1561 } else if (PrologueSaveSize
!= 0) {
1562 MBBI
= convertCalleeSaveRestoreToSPPrePostIncDec(
1563 MBB
, MBBI
, DL
, TII
, -PrologueSaveSize
, NeedsWinCFI
, &HasWinCFI
,
1565 NumBytes
-= PrologueSaveSize
;
1567 assert(NumBytes
>= 0 && "Negative stack allocation size!?");
1569 // Move past the saves of the callee-saved registers, fixing up the offsets
1570 // and pre-inc if we decided to combine the callee-save and local stack
1571 // pointer bump above.
1572 MachineBasicBlock::iterator End
= MBB
.end();
1573 while (MBBI
!= End
&& MBBI
->getFlag(MachineInstr::FrameSetup
) &&
1574 !IsSVECalleeSave(MBBI
)) {
1576 fixupCalleeSaveRestoreStackOffset(*MBBI
, AFI
->getLocalStackSize(),
1577 NeedsWinCFI
, &HasWinCFI
);
1581 // For funclets the FP belongs to the containing function.
1582 if (!IsFunclet
&& HasFP
) {
1583 // Only set up FP if we actually need to.
1584 int64_t FPOffset
= AFI
->getCalleeSaveBaseToFrameRecordOffset();
1587 FPOffset
+= AFI
->getLocalStackSize();
1589 if (AFI
->hasSwiftAsyncContext()) {
1590 // Before we update the live FP we have to ensure there's a valid (or
1591 // null) asynchronous context in its slot just before FP in the frame
1592 // record, so store it now.
1593 const auto &Attrs
= MF
.getFunction().getAttributes();
1594 bool HaveInitialContext
= Attrs
.hasAttrSomewhere(Attribute::SwiftAsync
);
1595 if (HaveInitialContext
)
1596 MBB
.addLiveIn(AArch64::X22
);
1597 Register Reg
= HaveInitialContext
? AArch64::X22
: AArch64::XZR
;
1598 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::StoreSwiftAsyncContext
))
1600 .addUse(AArch64::SP
)
1601 .addImm(FPOffset
- 8)
1602 .setMIFlags(MachineInstr::FrameSetup
);
1604 // WinCFI and arm64e, where StoreSwiftAsyncContext is expanded
1605 // to multiple instructions, should be mutually-exclusive.
1606 assert(Subtarget
.getTargetTriple().getArchName() != "arm64e");
1607 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1608 .setMIFlags(MachineInstr::FrameSetup
);
1613 if (HomPrologEpilog
) {
1616 assert(Prolog
->getOpcode() == AArch64::HOM_Prolog
);
1617 Prolog
->addOperand(MachineOperand::CreateImm(FPOffset
));
1619 // Issue sub fp, sp, FPOffset or
1620 // mov fp,sp when FPOffset is zero.
1621 // Note: All stores of callee-saved registers are marked as "FrameSetup".
1622 // This code marks the instruction(s) that set the FP also.
1623 emitFrameOffset(MBB
, MBBI
, DL
, AArch64::FP
, AArch64::SP
,
1624 StackOffset::getFixed(FPOffset
), TII
,
1625 MachineInstr::FrameSetup
, false, NeedsWinCFI
, &HasWinCFI
);
1626 if (NeedsWinCFI
&& HasWinCFI
) {
1627 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_PrologEnd
))
1628 .setMIFlag(MachineInstr::FrameSetup
);
1629 // After setting up the FP, the rest of the prolog doesn't need to be
1630 // included in the SEH unwind info.
1631 NeedsWinCFI
= false;
1635 emitDefineCFAWithFP(MF
, MBB
, MBBI
, DL
, FixedObject
);
1638 // Now emit the moves for whatever callee saved regs we have (including FP,
1639 // LR if those are saved). Frame instructions for SVE register are emitted
1640 // later, after the instruction which actually save SVE regs.
1642 emitCalleeSavedGPRLocations(MBB
, MBBI
);
1644 // Alignment is required for the parent frame, not the funclet
1645 const bool NeedsRealignment
=
1646 NumBytes
&& !IsFunclet
&& RegInfo
->hasStackRealignment(MF
);
1647 int64_t RealignmentPadding
=
1648 (NeedsRealignment
&& MFI
.getMaxAlign() > Align(16))
1649 ? MFI
.getMaxAlign().value() - 16
1652 if (windowsRequiresStackProbe(MF
, NumBytes
+ RealignmentPadding
)) {
1653 uint64_t NumWords
= (NumBytes
+ RealignmentPadding
) >> 4;
1656 // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1657 // exceed this amount. We need to move at most 2^24 - 1 into x15.
1658 // This is at most two instructions, MOVZ follwed by MOVK.
1659 // TODO: Fix to use multiple stack alloc unwind codes for stacks
1660 // exceeding 256MB in size.
1661 if (NumBytes
>= (1 << 28))
1662 report_fatal_error("Stack size cannot exceed 256MB for stack "
1663 "unwinding purposes");
1665 uint32_t LowNumWords
= NumWords
& 0xFFFF;
1666 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::MOVZXi
), AArch64::X15
)
1667 .addImm(LowNumWords
)
1668 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL
, 0))
1669 .setMIFlag(MachineInstr::FrameSetup
);
1670 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1671 .setMIFlag(MachineInstr::FrameSetup
);
1672 if ((NumWords
& 0xFFFF0000) != 0) {
1673 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::MOVKXi
), AArch64::X15
)
1674 .addReg(AArch64::X15
)
1675 .addImm((NumWords
& 0xFFFF0000) >> 16) // High half
1676 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL
, 16))
1677 .setMIFlag(MachineInstr::FrameSetup
);
1678 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1679 .setMIFlag(MachineInstr::FrameSetup
);
1682 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::MOVi64imm
), AArch64::X15
)
1684 .setMIFlags(MachineInstr::FrameSetup
);
1687 const char* ChkStk
= Subtarget
.getChkStkName();
1688 switch (MF
.getTarget().getCodeModel()) {
1689 case CodeModel::Tiny
:
1690 case CodeModel::Small
:
1691 case CodeModel::Medium
:
1692 case CodeModel::Kernel
:
1693 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::BL
))
1694 .addExternalSymbol(ChkStk
)
1695 .addReg(AArch64::X15
, RegState::Implicit
)
1696 .addReg(AArch64::X16
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1697 .addReg(AArch64::X17
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1698 .addReg(AArch64::NZCV
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1699 .setMIFlags(MachineInstr::FrameSetup
);
1702 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1703 .setMIFlag(MachineInstr::FrameSetup
);
1706 case CodeModel::Large
:
1707 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::MOVaddrEXT
))
1708 .addReg(AArch64::X16
, RegState::Define
)
1709 .addExternalSymbol(ChkStk
)
1710 .addExternalSymbol(ChkStk
)
1711 .setMIFlags(MachineInstr::FrameSetup
);
1714 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1715 .setMIFlag(MachineInstr::FrameSetup
);
1718 BuildMI(MBB
, MBBI
, DL
, TII
->get(getBLRCallOpcode(MF
)))
1719 .addReg(AArch64::X16
, RegState::Kill
)
1720 .addReg(AArch64::X15
, RegState::Implicit
| RegState::Define
)
1721 .addReg(AArch64::X16
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1722 .addReg(AArch64::X17
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1723 .addReg(AArch64::NZCV
, RegState::Implicit
| RegState::Define
| RegState::Dead
)
1724 .setMIFlags(MachineInstr::FrameSetup
);
1727 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1728 .setMIFlag(MachineInstr::FrameSetup
);
1733 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SUBXrx64
), AArch64::SP
)
1734 .addReg(AArch64::SP
, RegState::Kill
)
1735 .addReg(AArch64::X15
, RegState::Kill
)
1736 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX
, 4))
1737 .setMIFlags(MachineInstr::FrameSetup
);
1740 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_StackAlloc
))
1742 .setMIFlag(MachineInstr::FrameSetup
);
1746 if (RealignmentPadding
> 0) {
1747 if (RealignmentPadding
>= 4096) {
1748 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::MOVi64imm
))
1749 .addReg(AArch64::X16
, RegState::Define
)
1750 .addImm(RealignmentPadding
)
1751 .setMIFlags(MachineInstr::FrameSetup
);
1752 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ADDXrx64
), AArch64::X15
)
1753 .addReg(AArch64::SP
)
1754 .addReg(AArch64::X16
, RegState::Kill
)
1755 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX
, 0))
1756 .setMIFlag(MachineInstr::FrameSetup
);
1758 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ADDXri
), AArch64::X15
)
1759 .addReg(AArch64::SP
)
1760 .addImm(RealignmentPadding
)
1762 .setMIFlag(MachineInstr::FrameSetup
);
1765 uint64_t AndMask
= ~(MFI
.getMaxAlign().value() - 1);
1766 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ANDXri
), AArch64::SP
)
1767 .addReg(AArch64::X15
, RegState::Kill
)
1768 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask
, 64));
1769 AFI
->setStackRealigned(true);
1771 // No need for SEH instructions here; if we're realigning the stack,
1772 // we've set a frame pointer and already finished the SEH prologue.
1773 assert(!NeedsWinCFI
);
1777 StackOffset AllocateBefore
= SVEStackSize
, AllocateAfter
= {};
1778 MachineBasicBlock::iterator CalleeSavesBegin
= MBBI
, CalleeSavesEnd
= MBBI
;
1780 // Process the SVE callee-saves to determine what space needs to be
1782 if (int64_t CalleeSavedSize
= AFI
->getSVECalleeSavedStackSize()) {
1783 // Find callee save instructions in frame.
1784 CalleeSavesBegin
= MBBI
;
1785 assert(IsSVECalleeSave(CalleeSavesBegin
) && "Unexpected instruction");
1786 while (IsSVECalleeSave(MBBI
) && MBBI
!= MBB
.getFirstTerminator())
1788 CalleeSavesEnd
= MBBI
;
1790 AllocateBefore
= StackOffset::getScalable(CalleeSavedSize
);
1791 AllocateAfter
= SVEStackSize
- AllocateBefore
;
1794 // Allocate space for the callee saves (if any).
1796 MBB
, CalleeSavesBegin
, DL
, AArch64::SP
, AArch64::SP
, -AllocateBefore
, TII
,
1797 MachineInstr::FrameSetup
, false, false, nullptr,
1798 EmitAsyncCFI
&& !HasFP
&& AllocateBefore
,
1799 StackOffset::getFixed((int64_t)MFI
.getStackSize() - NumBytes
));
1802 emitCalleeSavedSVELocations(MBB
, CalleeSavesEnd
);
1804 // Finally allocate remaining SVE stack space.
1805 emitFrameOffset(MBB
, CalleeSavesEnd
, DL
, AArch64::SP
, AArch64::SP
,
1806 -AllocateAfter
, TII
, MachineInstr::FrameSetup
, false, false,
1807 nullptr, EmitAsyncCFI
&& !HasFP
&& AllocateAfter
,
1808 AllocateBefore
+ StackOffset::getFixed(
1809 (int64_t)MFI
.getStackSize() - NumBytes
));
1811 // Allocate space for the rest of the frame.
1813 unsigned scratchSPReg
= AArch64::SP
;
1815 if (NeedsRealignment
) {
1816 scratchSPReg
= findScratchNonCalleeSaveRegister(&MBB
);
1817 assert(scratchSPReg
!= AArch64::NoRegister
);
1820 // If we're a leaf function, try using the red zone.
1821 if (!canUseRedZone(MF
)) {
1822 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1823 // the correct value here, as NumBytes also includes padding bytes,
1824 // which shouldn't be counted here.
1826 MBB
, MBBI
, DL
, scratchSPReg
, AArch64::SP
,
1827 StackOffset::getFixed(-NumBytes
), TII
, MachineInstr::FrameSetup
,
1828 false, NeedsWinCFI
, &HasWinCFI
, EmitAsyncCFI
&& !HasFP
,
1830 StackOffset::getFixed((int64_t)MFI
.getStackSize() - NumBytes
));
1832 if (NeedsRealignment
) {
1833 assert(MFI
.getMaxAlign() > Align(1));
1834 assert(scratchSPReg
!= AArch64::SP
);
1836 // SUB X9, SP, NumBytes
1837 // -- X9 is temporary register, so shouldn't contain any live data here,
1838 // -- free to use. This is already produced by emitFrameOffset above.
1839 // AND SP, X9, 0b11111...0000
1840 uint64_t AndMask
= ~(MFI
.getMaxAlign().value() - 1);
1842 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::ANDXri
), AArch64::SP
)
1843 .addReg(scratchSPReg
, RegState::Kill
)
1844 .addImm(AArch64_AM::encodeLogicalImmediate(AndMask
, 64));
1845 AFI
->setStackRealigned(true);
1847 // No need for SEH instructions here; if we're realigning the stack,
1848 // we've set a frame pointer and already finished the SEH prologue.
1849 assert(!NeedsWinCFI
);
1853 // If we need a base pointer, set it up here. It's whatever the value of the
1854 // stack pointer is at this point. Any variable size objects will be allocated
1855 // after this, so we can still use the base pointer to reference locals.
1857 // FIXME: Clarify FrameSetup flags here.
1858 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1860 // For funclets the BP belongs to the containing function.
1861 if (!IsFunclet
&& RegInfo
->hasBasePointer(MF
)) {
1862 TII
->copyPhysReg(MBB
, MBBI
, DL
, RegInfo
->getBaseRegister(), AArch64::SP
,
1866 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
1867 .setMIFlag(MachineInstr::FrameSetup
);
1871 // The very last FrameSetup instruction indicates the end of prologue. Emit a
1872 // SEH opcode indicating the prologue end.
1873 if (NeedsWinCFI
&& HasWinCFI
) {
1874 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_PrologEnd
))
1875 .setMIFlag(MachineInstr::FrameSetup
);
1878 // SEH funclets are passed the frame pointer in X1. If the parent
1879 // function uses the base register, then the base register is used
1880 // directly, and is not retrieved from X1.
1881 if (IsFunclet
&& F
.hasPersonalityFn()) {
1882 EHPersonality Per
= classifyEHPersonality(F
.getPersonalityFn());
1883 if (isAsynchronousEHPersonality(Per
)) {
1884 BuildMI(MBB
, MBBI
, DL
, TII
->get(TargetOpcode::COPY
), AArch64::FP
)
1885 .addReg(AArch64::X1
)
1886 .setMIFlag(MachineInstr::FrameSetup
);
1887 MBB
.addLiveIn(AArch64::X1
);
1891 if (EmitCFI
&& !EmitAsyncCFI
) {
1893 emitDefineCFAWithFP(MF
, MBB
, MBBI
, DL
, FixedObject
);
1895 StackOffset TotalSize
=
1896 SVEStackSize
+ StackOffset::getFixed((int64_t)MFI
.getStackSize());
1897 unsigned CFIIndex
= MF
.addFrameInst(createDefCFA(
1898 *RegInfo
, /*FrameReg=*/AArch64::SP
, /*Reg=*/AArch64::SP
, TotalSize
,
1899 /*LastAdjustmentWasScalable=*/false));
1900 BuildMI(MBB
, MBBI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
1901 .addCFIIndex(CFIIndex
)
1902 .setMIFlags(MachineInstr::FrameSetup
);
1904 emitCalleeSavedGPRLocations(MBB
, MBBI
);
1905 emitCalleeSavedSVELocations(MBB
, MBBI
);
1909 static bool isFuncletReturnInstr(const MachineInstr
&MI
) {
1910 switch (MI
.getOpcode()) {
1913 case AArch64::CATCHRET
:
1914 case AArch64::CLEANUPRET
:
1919 void AArch64FrameLowering::emitEpilogue(MachineFunction
&MF
,
1920 MachineBasicBlock
&MBB
) const {
1921 MachineBasicBlock::iterator MBBI
= MBB
.getLastNonDebugInstr();
1922 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
1923 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
1924 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
1925 const TargetInstrInfo
*TII
= Subtarget
.getInstrInfo();
1927 bool NeedsWinCFI
= needsWinCFI(MF
);
1928 bool EmitCFI
= AFI
->needsAsyncDwarfUnwindInfo(MF
);
1929 bool HasWinCFI
= false;
1930 bool IsFunclet
= false;
1932 if (MBB
.end() != MBBI
) {
1933 DL
= MBBI
->getDebugLoc();
1934 IsFunclet
= isFuncletReturnInstr(*MBBI
);
1937 MachineBasicBlock::iterator EpilogStartI
= MBB
.end();
1939 auto FinishingTouches
= make_scope_exit([&]() {
1940 if (AFI
->shouldSignReturnAddress(MF
)) {
1941 BuildMI(MBB
, MBB
.getFirstTerminator(), DL
,
1942 TII
->get(AArch64::PAUTH_EPILOGUE
))
1943 .setMIFlag(MachineInstr::FrameDestroy
);
1945 HasWinCFI
= true; // AArch64PointerAuth pass will insert SEH_PACSignLR
1947 if (AFI
->needsShadowCallStackPrologueEpilogue(MF
))
1948 emitShadowCallStackEpilogue(*TII
, MF
, MBB
, MBB
.getFirstTerminator(), DL
);
1950 emitCalleeSavedGPRRestores(MBB
, MBB
.getFirstTerminator());
1952 BuildMI(MBB
, MBB
.getFirstTerminator(), DL
,
1953 TII
->get(AArch64::SEH_EpilogEnd
))
1954 .setMIFlag(MachineInstr::FrameDestroy
);
1955 if (!MF
.hasWinCFI())
1956 MF
.setHasWinCFI(true);
1959 assert(EpilogStartI
!= MBB
.end());
1961 MBB
.erase(EpilogStartI
);
1965 int64_t NumBytes
= IsFunclet
? getWinEHFuncletFrameSize(MF
)
1966 : MFI
.getStackSize();
1968 // All calls are tail calls in GHC calling conv, and functions have no
1969 // prologue/epilogue.
1970 if (MF
.getFunction().getCallingConv() == CallingConv::GHC
)
1973 // How much of the stack used by incoming arguments this function is expected
1974 // to restore in this particular epilogue.
1975 int64_t ArgumentStackToRestore
= getArgumentStackToRestore(MF
, MBB
);
1977 Subtarget
.isCallingConvWin64(MF
.getFunction().getCallingConv());
1978 unsigned FixedObject
= getFixedObjectSize(MF
, AFI
, IsWin64
, IsFunclet
);
1980 int64_t AfterCSRPopSize
= ArgumentStackToRestore
;
1981 auto PrologueSaveSize
= AFI
->getCalleeSavedStackSize() + FixedObject
;
1982 // We cannot rely on the local stack size set in emitPrologue if the function
1983 // has funclets, as funclets have different local stack size requirements, and
1984 // the current value set in emitPrologue may be that of the containing
1986 if (MF
.hasEHFunclets())
1987 AFI
->setLocalStackSize(NumBytes
- PrologueSaveSize
);
1988 if (homogeneousPrologEpilog(MF
, &MBB
)) {
1989 assert(!NeedsWinCFI
);
1990 auto LastPopI
= MBB
.getFirstTerminator();
1991 if (LastPopI
!= MBB
.begin()) {
1992 auto HomogeneousEpilog
= std::prev(LastPopI
);
1993 if (HomogeneousEpilog
->getOpcode() == AArch64::HOM_Epilog
)
1994 LastPopI
= HomogeneousEpilog
;
1997 // Adjust local stack
1998 emitFrameOffset(MBB
, LastPopI
, DL
, AArch64::SP
, AArch64::SP
,
1999 StackOffset::getFixed(AFI
->getLocalStackSize()), TII
,
2000 MachineInstr::FrameDestroy
, false, NeedsWinCFI
, &HasWinCFI
);
2002 // SP has been already adjusted while restoring callee save regs.
2003 // We've bailed-out the case with adjusting SP for arguments.
2004 assert(AfterCSRPopSize
== 0);
2007 bool CombineSPBump
= shouldCombineCSRLocalStackBumpInEpilogue(MBB
, NumBytes
);
2008 // Assume we can't combine the last pop with the sp restore.
2010 bool CombineAfterCSRBump
= false;
2011 if (!CombineSPBump
&& PrologueSaveSize
!= 0) {
2012 MachineBasicBlock::iterator Pop
= std::prev(MBB
.getFirstTerminator());
2013 while (Pop
->getOpcode() == TargetOpcode::CFI_INSTRUCTION
||
2014 AArch64InstrInfo::isSEHInstruction(*Pop
))
2015 Pop
= std::prev(Pop
);
2016 // Converting the last ldp to a post-index ldp is valid only if the last
2017 // ldp's offset is 0.
2018 const MachineOperand
&OffsetOp
= Pop
->getOperand(Pop
->getNumOperands() - 1);
2019 // If the offset is 0 and the AfterCSR pop is not actually trying to
2020 // allocate more stack for arguments (in space that an untimely interrupt
2021 // may clobber), convert it to a post-index ldp.
2022 if (OffsetOp
.getImm() == 0 && AfterCSRPopSize
>= 0) {
2023 convertCalleeSaveRestoreToSPPrePostIncDec(
2024 MBB
, Pop
, DL
, TII
, PrologueSaveSize
, NeedsWinCFI
, &HasWinCFI
, EmitCFI
,
2025 MachineInstr::FrameDestroy
, PrologueSaveSize
);
2027 // If not, make sure to emit an add after the last ldp.
2028 // We're doing this by transfering the size to be restored from the
2029 // adjustment *before* the CSR pops to the adjustment *after* the CSR
2031 AfterCSRPopSize
+= PrologueSaveSize
;
2032 CombineAfterCSRBump
= true;
2036 // Move past the restores of the callee-saved registers.
2037 // If we plan on combining the sp bump of the local stack size and the callee
2038 // save stack size, we might need to adjust the CSR save and restore offsets.
2039 MachineBasicBlock::iterator LastPopI
= MBB
.getFirstTerminator();
2040 MachineBasicBlock::iterator Begin
= MBB
.begin();
2041 while (LastPopI
!= Begin
) {
2043 if (!LastPopI
->getFlag(MachineInstr::FrameDestroy
) ||
2044 IsSVECalleeSave(LastPopI
)) {
2047 } else if (CombineSPBump
)
2048 fixupCalleeSaveRestoreStackOffset(*LastPopI
, AFI
->getLocalStackSize(),
2049 NeedsWinCFI
, &HasWinCFI
);
2053 // Note that there are cases where we insert SEH opcodes in the
2054 // epilogue when we had no SEH opcodes in the prologue. For
2055 // example, when there is no stack frame but there are stack
2056 // arguments. Insert the SEH_EpilogStart and remove it later if it
2057 // we didn't emit any SEH opcodes to avoid generating WinCFI for
2058 // functions that don't need it.
2059 BuildMI(MBB
, LastPopI
, DL
, TII
->get(AArch64::SEH_EpilogStart
))
2060 .setMIFlag(MachineInstr::FrameDestroy
);
2061 EpilogStartI
= LastPopI
;
2065 if (hasFP(MF
) && AFI
->hasSwiftAsyncContext()) {
2066 switch (MF
.getTarget().Options
.SwiftAsyncFramePointer
) {
2067 case SwiftAsyncFramePointerMode::DeploymentBased
:
2068 // Avoid the reload as it is GOT relative, and instead fall back to the
2069 // hardcoded value below. This allows a mismatch between the OS and
2070 // application without immediately terminating on the difference.
2072 case SwiftAsyncFramePointerMode::Always
:
2073 // We need to reset FP to its untagged state on return. Bit 60 is
2074 // currently used to show the presence of an extended frame.
2076 // BIC x29, x29, #0x1000_0000_0000_0000
2077 BuildMI(MBB
, MBB
.getFirstTerminator(), DL
, TII
->get(AArch64::ANDXri
),
2079 .addUse(AArch64::FP
)
2081 .setMIFlag(MachineInstr::FrameDestroy
);
2083 BuildMI(MBB
, MBBI
, DL
, TII
->get(AArch64::SEH_Nop
))
2084 .setMIFlags(MachineInstr::FrameDestroy
);
2089 case SwiftAsyncFramePointerMode::Never
:
2094 const StackOffset
&SVEStackSize
= getSVEStackSize(MF
);
2096 // If there is a single SP update, insert it before the ret and we're done.
2097 if (CombineSPBump
) {
2098 assert(!SVEStackSize
&& "Cannot combine SP bump with SVE");
2100 // When we are about to restore the CSRs, the CFA register is SP again.
2101 if (EmitCFI
&& hasFP(MF
)) {
2102 const AArch64RegisterInfo
&RegInfo
= *Subtarget
.getRegisterInfo();
2103 unsigned Reg
= RegInfo
.getDwarfRegNum(AArch64::SP
, true);
2105 MF
.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg
, NumBytes
));
2106 BuildMI(MBB
, LastPopI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
2107 .addCFIIndex(CFIIndex
)
2108 .setMIFlags(MachineInstr::FrameDestroy
);
2111 emitFrameOffset(MBB
, MBB
.getFirstTerminator(), DL
, AArch64::SP
, AArch64::SP
,
2112 StackOffset::getFixed(NumBytes
+ (int64_t)AfterCSRPopSize
),
2113 TII
, MachineInstr::FrameDestroy
, false, NeedsWinCFI
,
2114 &HasWinCFI
, EmitCFI
, StackOffset::getFixed(NumBytes
));
2118 NumBytes
-= PrologueSaveSize
;
2119 assert(NumBytes
>= 0 && "Negative stack allocation size!?");
2121 // Process the SVE callee-saves to determine what space needs to be
2123 StackOffset DeallocateBefore
= {}, DeallocateAfter
= SVEStackSize
;
2124 MachineBasicBlock::iterator RestoreBegin
= LastPopI
, RestoreEnd
= LastPopI
;
2125 if (int64_t CalleeSavedSize
= AFI
->getSVECalleeSavedStackSize()) {
2126 RestoreBegin
= std::prev(RestoreEnd
);
2127 while (RestoreBegin
!= MBB
.begin() &&
2128 IsSVECalleeSave(std::prev(RestoreBegin
)))
2131 assert(IsSVECalleeSave(RestoreBegin
) &&
2132 IsSVECalleeSave(std::prev(RestoreEnd
)) && "Unexpected instruction");
2134 StackOffset CalleeSavedSizeAsOffset
=
2135 StackOffset::getScalable(CalleeSavedSize
);
2136 DeallocateBefore
= SVEStackSize
- CalleeSavedSizeAsOffset
;
2137 DeallocateAfter
= CalleeSavedSizeAsOffset
;
2140 // Deallocate the SVE area.
2142 // If we have stack realignment or variable sized objects on the stack,
2143 // restore the stack pointer from the frame pointer prior to SVE CSR
2145 if (AFI
->isStackRealigned() || MFI
.hasVarSizedObjects()) {
2146 if (int64_t CalleeSavedSize
= AFI
->getSVECalleeSavedStackSize()) {
2147 // Set SP to start of SVE callee-save area from which they can
2148 // be reloaded. The code below will deallocate the stack space
2149 // space by moving FP -> SP.
2150 emitFrameOffset(MBB
, RestoreBegin
, DL
, AArch64::SP
, AArch64::FP
,
2151 StackOffset::getScalable(-CalleeSavedSize
), TII
,
2152 MachineInstr::FrameDestroy
);
2155 if (AFI
->getSVECalleeSavedStackSize()) {
2156 // Deallocate the non-SVE locals first before we can deallocate (and
2157 // restore callee saves) from the SVE area.
2159 MBB
, RestoreBegin
, DL
, AArch64::SP
, AArch64::SP
,
2160 StackOffset::getFixed(NumBytes
), TII
, MachineInstr::FrameDestroy
,
2161 false, false, nullptr, EmitCFI
&& !hasFP(MF
),
2162 SVEStackSize
+ StackOffset::getFixed(NumBytes
+ PrologueSaveSize
));
2166 emitFrameOffset(MBB
, RestoreBegin
, DL
, AArch64::SP
, AArch64::SP
,
2167 DeallocateBefore
, TII
, MachineInstr::FrameDestroy
, false,
2168 false, nullptr, EmitCFI
&& !hasFP(MF
),
2170 StackOffset::getFixed(NumBytes
+ PrologueSaveSize
));
2172 emitFrameOffset(MBB
, RestoreEnd
, DL
, AArch64::SP
, AArch64::SP
,
2173 DeallocateAfter
, TII
, MachineInstr::FrameDestroy
, false,
2174 false, nullptr, EmitCFI
&& !hasFP(MF
),
2176 StackOffset::getFixed(NumBytes
+ PrologueSaveSize
));
2179 emitCalleeSavedSVERestores(MBB
, RestoreEnd
);
2183 bool RedZone
= canUseRedZone(MF
);
2184 // If this was a redzone leaf function, we don't need to restore the
2185 // stack pointer (but we may need to pop stack args for fastcc).
2186 if (RedZone
&& AfterCSRPopSize
== 0)
2189 // Pop the local variables off the stack. If there are no callee-saved
2190 // registers, it means we are actually positioned at the terminator and can
2191 // combine stack increment for the locals and the stack increment for
2192 // callee-popped arguments into (possibly) a single instruction and be done.
2193 bool NoCalleeSaveRestore
= PrologueSaveSize
== 0;
2194 int64_t StackRestoreBytes
= RedZone
? 0 : NumBytes
;
2195 if (NoCalleeSaveRestore
)
2196 StackRestoreBytes
+= AfterCSRPopSize
;
2199 MBB
, LastPopI
, DL
, AArch64::SP
, AArch64::SP
,
2200 StackOffset::getFixed(StackRestoreBytes
), TII
,
2201 MachineInstr::FrameDestroy
, false, NeedsWinCFI
, &HasWinCFI
, EmitCFI
,
2202 StackOffset::getFixed((RedZone
? 0 : NumBytes
) + PrologueSaveSize
));
2204 // If we were able to combine the local stack pop with the argument pop,
2206 if (NoCalleeSaveRestore
|| AfterCSRPopSize
== 0) {
2213 // Restore the original stack pointer.
2214 // FIXME: Rather than doing the math here, we should instead just use
2215 // non-post-indexed loads for the restores if we aren't actually going to
2216 // be able to save any instructions.
2217 if (!IsFunclet
&& (MFI
.hasVarSizedObjects() || AFI
->isStackRealigned())) {
2219 MBB
, LastPopI
, DL
, AArch64::SP
, AArch64::FP
,
2220 StackOffset::getFixed(-AFI
->getCalleeSaveBaseToFrameRecordOffset()),
2221 TII
, MachineInstr::FrameDestroy
, false, NeedsWinCFI
, &HasWinCFI
);
2222 } else if (NumBytes
)
2223 emitFrameOffset(MBB
, LastPopI
, DL
, AArch64::SP
, AArch64::SP
,
2224 StackOffset::getFixed(NumBytes
), TII
,
2225 MachineInstr::FrameDestroy
, false, NeedsWinCFI
, &HasWinCFI
);
2227 // When we are about to restore the CSRs, the CFA register is SP again.
2228 if (EmitCFI
&& hasFP(MF
)) {
2229 const AArch64RegisterInfo
&RegInfo
= *Subtarget
.getRegisterInfo();
2230 unsigned Reg
= RegInfo
.getDwarfRegNum(AArch64::SP
, true);
2231 unsigned CFIIndex
= MF
.addFrameInst(
2232 MCCFIInstruction::cfiDefCfa(nullptr, Reg
, PrologueSaveSize
));
2233 BuildMI(MBB
, LastPopI
, DL
, TII
->get(TargetOpcode::CFI_INSTRUCTION
))
2234 .addCFIIndex(CFIIndex
)
2235 .setMIFlags(MachineInstr::FrameDestroy
);
2238 // This must be placed after the callee-save restore code because that code
2239 // assumes the SP is at the same location as it was after the callee-save save
2240 // code in the prologue.
2241 if (AfterCSRPopSize
) {
2242 assert(AfterCSRPopSize
> 0 && "attempting to reallocate arg stack that an "
2243 "interrupt may have clobbered");
2246 MBB
, MBB
.getFirstTerminator(), DL
, AArch64::SP
, AArch64::SP
,
2247 StackOffset::getFixed(AfterCSRPopSize
), TII
, MachineInstr::FrameDestroy
,
2248 false, NeedsWinCFI
, &HasWinCFI
, EmitCFI
,
2249 StackOffset::getFixed(CombineAfterCSRBump
? PrologueSaveSize
: 0));
2253 bool AArch64FrameLowering::enableCFIFixup(MachineFunction
&MF
) const {
2254 return TargetFrameLowering::enableCFIFixup(MF
) &&
2255 MF
.getInfo
<AArch64FunctionInfo
>()->needsAsyncDwarfUnwindInfo(MF
);
2258 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
2259 /// debug info. It's the same as what we use for resolving the code-gen
2260 /// references for now. FIXME: This can go wrong when references are
2261 /// SP-relative and simple call frames aren't used.
2263 AArch64FrameLowering::getFrameIndexReference(const MachineFunction
&MF
, int FI
,
2264 Register
&FrameReg
) const {
2265 return resolveFrameIndexReference(
2268 MF
.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress
),
2273 AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction
&MF
,
2275 return StackOffset::getFixed(getSEHFrameIndexOffset(MF
, FI
));
2278 static StackOffset
getFPOffset(const MachineFunction
&MF
,
2279 int64_t ObjectOffset
) {
2280 const auto *AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
2281 const auto &Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
2283 Subtarget
.isCallingConvWin64(MF
.getFunction().getCallingConv());
2284 unsigned FixedObject
=
2285 getFixedObjectSize(MF
, AFI
, IsWin64
, /*IsFunclet=*/false);
2286 int64_t CalleeSaveSize
= AFI
->getCalleeSavedStackSize(MF
.getFrameInfo());
2288 CalleeSaveSize
- AFI
->getCalleeSaveBaseToFrameRecordOffset();
2289 return StackOffset::getFixed(ObjectOffset
+ FixedObject
+ FPAdjust
);
2292 static StackOffset
getStackOffset(const MachineFunction
&MF
,
2293 int64_t ObjectOffset
) {
2294 const auto &MFI
= MF
.getFrameInfo();
2295 return StackOffset::getFixed(ObjectOffset
+ (int64_t)MFI
.getStackSize());
2298 // TODO: This function currently does not work for scalable vectors.
2299 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction
&MF
,
2301 const auto *RegInfo
= static_cast<const AArch64RegisterInfo
*>(
2302 MF
.getSubtarget().getRegisterInfo());
2303 int ObjectOffset
= MF
.getFrameInfo().getObjectOffset(FI
);
2304 return RegInfo
->getLocalAddressRegister(MF
) == AArch64::FP
2305 ? getFPOffset(MF
, ObjectOffset
).getFixed()
2306 : getStackOffset(MF
, ObjectOffset
).getFixed();
2309 StackOffset
AArch64FrameLowering::resolveFrameIndexReference(
2310 const MachineFunction
&MF
, int FI
, Register
&FrameReg
, bool PreferFP
,
2311 bool ForSimm
) const {
2312 const auto &MFI
= MF
.getFrameInfo();
2313 int64_t ObjectOffset
= MFI
.getObjectOffset(FI
);
2314 bool isFixed
= MFI
.isFixedObjectIndex(FI
);
2315 bool isSVE
= MFI
.getStackID(FI
) == TargetStackID::ScalableVector
;
2316 return resolveFrameOffsetReference(MF
, ObjectOffset
, isFixed
, isSVE
, FrameReg
,
2320 StackOffset
AArch64FrameLowering::resolveFrameOffsetReference(
2321 const MachineFunction
&MF
, int64_t ObjectOffset
, bool isFixed
, bool isSVE
,
2322 Register
&FrameReg
, bool PreferFP
, bool ForSimm
) const {
2323 const auto &MFI
= MF
.getFrameInfo();
2324 const auto *RegInfo
= static_cast<const AArch64RegisterInfo
*>(
2325 MF
.getSubtarget().getRegisterInfo());
2326 const auto *AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
2327 const auto &Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
2329 int64_t FPOffset
= getFPOffset(MF
, ObjectOffset
).getFixed();
2330 int64_t Offset
= getStackOffset(MF
, ObjectOffset
).getFixed();
2332 !isFixed
&& ObjectOffset
>= -((int)AFI
->getCalleeSavedStackSize(MFI
));
2334 const StackOffset
&SVEStackSize
= getSVEStackSize(MF
);
2336 // Use frame pointer to reference fixed objects. Use it for locals if
2337 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
2338 // reliable as a base). Make sure useFPForScavengingIndex() does the
2339 // right thing for the emergency spill slot.
2341 if (AFI
->hasStackFrame() && !isSVE
) {
2342 // We shouldn't prefer using the FP to access fixed-sized stack objects when
2343 // there are scalable (SVE) objects in between the FP and the fixed-sized
2345 PreferFP
&= !SVEStackSize
;
2347 // Note: Keeping the following as multiple 'if' statements rather than
2348 // merging to a single expression for readability.
2350 // Argument access should always use the FP.
2353 } else if (isCSR
&& RegInfo
->hasStackRealignment(MF
)) {
2354 // References to the CSR area must use FP if we're re-aligning the stack
2355 // since the dynamically-sized alignment padding is between the SP/BP and
2357 assert(hasFP(MF
) && "Re-aligned stack must have frame pointer");
2359 } else if (hasFP(MF
) && !RegInfo
->hasStackRealignment(MF
)) {
2360 // If the FPOffset is negative and we're producing a signed immediate, we
2361 // have to keep in mind that the available offset range for negative
2362 // offsets is smaller than for positive ones. If an offset is available
2363 // via the FP and the SP, use whichever is closest.
2364 bool FPOffsetFits
= !ForSimm
|| FPOffset
>= -256;
2365 PreferFP
|= Offset
> -FPOffset
&& !SVEStackSize
;
2367 if (MFI
.hasVarSizedObjects()) {
2368 // If we have variable sized objects, we can use either FP or BP, as the
2369 // SP offset is unknown. We can use the base pointer if we have one and
2370 // FP is not preferred. If not, we're stuck with using FP.
2371 bool CanUseBP
= RegInfo
->hasBasePointer(MF
);
2372 if (FPOffsetFits
&& CanUseBP
) // Both are ok. Pick the best.
2374 else if (!CanUseBP
) // Can't use BP. Forced to use FP.
2376 // else we can use BP and FP, but the offset from FP won't fit.
2377 // That will make us scavenge registers which we can probably avoid by
2378 // using BP. If it won't fit for BP either, we'll scavenge anyway.
2379 } else if (FPOffset
>= 0) {
2380 // Use SP or FP, whichever gives us the best chance of the offset
2381 // being in range for direct access. If the FPOffset is positive,
2382 // that'll always be best, as the SP will be even further away.
2384 } else if (MF
.hasEHFunclets() && !RegInfo
->hasBasePointer(MF
)) {
2385 // Funclets access the locals contained in the parent's stack frame
2386 // via the frame pointer, so we have to use the FP in the parent
2390 Subtarget
.isCallingConvWin64(MF
.getFunction().getCallingConv()) &&
2391 "Funclets should only be present on Win64");
2394 // We have the choice between FP and (SP or BP).
2395 if (FPOffsetFits
&& PreferFP
) // If FP is the best fit, use it.
2402 ((isFixed
|| isCSR
) || !RegInfo
->hasStackRealignment(MF
) || !UseFP
) &&
2403 "In the presence of dynamic stack pointer realignment, "
2404 "non-argument/CSR objects cannot be accessed through the frame pointer");
2407 StackOffset FPOffset
=
2408 StackOffset::get(-AFI
->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset
);
2409 StackOffset SPOffset
=
2411 StackOffset::get(MFI
.getStackSize() - AFI
->getCalleeSavedStackSize(),
2413 // Always use the FP for SVE spills if available and beneficial.
2414 if (hasFP(MF
) && (SPOffset
.getFixed() ||
2415 FPOffset
.getScalable() < SPOffset
.getScalable() ||
2416 RegInfo
->hasStackRealignment(MF
))) {
2417 FrameReg
= RegInfo
->getFrameRegister(MF
);
2421 FrameReg
= RegInfo
->hasBasePointer(MF
) ? RegInfo
->getBaseRegister()
2422 : (unsigned)AArch64::SP
;
2426 StackOffset ScalableOffset
= {};
2427 if (UseFP
&& !(isFixed
|| isCSR
))
2428 ScalableOffset
= -SVEStackSize
;
2429 if (!UseFP
&& (isFixed
|| isCSR
))
2430 ScalableOffset
= SVEStackSize
;
2433 FrameReg
= RegInfo
->getFrameRegister(MF
);
2434 return StackOffset::getFixed(FPOffset
) + ScalableOffset
;
2437 // Use the base pointer if we have one.
2438 if (RegInfo
->hasBasePointer(MF
))
2439 FrameReg
= RegInfo
->getBaseRegister();
2441 assert(!MFI
.hasVarSizedObjects() &&
2442 "Can't use SP when we have var sized objects.");
2443 FrameReg
= AArch64::SP
;
2444 // If we're using the red zone for this function, the SP won't actually
2445 // be adjusted, so the offsets will be negative. They're also all
2446 // within range of the signed 9-bit immediate instructions.
2447 if (canUseRedZone(MF
))
2448 Offset
-= AFI
->getLocalStackSize();
2451 return StackOffset::getFixed(Offset
) + ScalableOffset
;
2454 static unsigned getPrologueDeath(MachineFunction
&MF
, unsigned Reg
) {
2455 // Do not set a kill flag on values that are also marked as live-in. This
2456 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2457 // callee saved registers.
2458 // Omitting the kill flags is conservatively correct even if the live-in
2459 // is not used after all.
2460 bool IsLiveIn
= MF
.getRegInfo().isLiveIn(Reg
);
2461 return getKillRegState(!IsLiveIn
);
2464 static bool produceCompactUnwindFrame(MachineFunction
&MF
) {
2465 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
2466 AttributeList Attrs
= MF
.getFunction().getAttributes();
2467 return Subtarget
.isTargetMachO() &&
2468 !(Subtarget
.getTargetLowering()->supportSwiftError() &&
2469 Attrs
.hasAttrSomewhere(Attribute::SwiftError
)) &&
2470 MF
.getFunction().getCallingConv() != CallingConv::SwiftTail
;
2473 static bool invalidateWindowsRegisterPairing(unsigned Reg1
, unsigned Reg2
,
2474 bool NeedsWinCFI
, bool IsFirst
,
2475 const TargetRegisterInfo
*TRI
) {
2476 // If we are generating register pairs for a Windows function that requires
2477 // EH support, then pair consecutive registers only. There are no unwind
2478 // opcodes for saves/restores of non-consectuve register pairs.
2479 // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
2481 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2483 if (Reg2
== AArch64::FP
)
2487 if (TRI
->getEncodingValue(Reg2
) == TRI
->getEncodingValue(Reg1
) + 1)
2489 // If pairing a GPR with LR, the pair can be described by the save_lrpair
2490 // opcode. If this is the first register pair, it would end up with a
2491 // predecrement, but there's no save_lrpair_x opcode, so we can only do this
2492 // if LR is paired with something else than the first register.
2493 // The save_lrpair opcode requires the first register to be an odd one.
2494 if (Reg1
>= AArch64::X19
&& Reg1
<= AArch64::X27
&&
2495 (Reg1
- AArch64::X19
) % 2 == 0 && Reg2
== AArch64::LR
&& !IsFirst
)
2500 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2501 /// WindowsCFI requires that only consecutive registers can be paired.
2502 /// LR and FP need to be allocated together when the frame needs to save
2503 /// the frame-record. This means any other register pairing with LR is invalid.
2504 static bool invalidateRegisterPairing(unsigned Reg1
, unsigned Reg2
,
2505 bool UsesWinAAPCS
, bool NeedsWinCFI
,
2506 bool NeedsFrameRecord
, bool IsFirst
,
2507 const TargetRegisterInfo
*TRI
) {
2509 return invalidateWindowsRegisterPairing(Reg1
, Reg2
, NeedsWinCFI
, IsFirst
,
2512 // If we need to store the frame record, don't pair any register
2513 // with LR other than FP.
2514 if (NeedsFrameRecord
)
2515 return Reg2
== AArch64::LR
;
2522 struct RegPairInfo
{
2523 unsigned Reg1
= AArch64::NoRegister
;
2524 unsigned Reg2
= AArch64::NoRegister
;
2527 enum RegType
{ GPR
, FPR64
, FPR128
, PPR
, ZPR
} Type
;
2529 RegPairInfo() = default;
2531 bool isPaired() const { return Reg2
!= AArch64::NoRegister
; }
2533 unsigned getScale() const {
2544 llvm_unreachable("Unsupported type");
2547 bool isScalable() const { return Type
== PPR
|| Type
== ZPR
; }
2550 } // end anonymous namespace
2552 static void computeCalleeSaveRegisterPairs(
2553 MachineFunction
&MF
, ArrayRef
<CalleeSavedInfo
> CSI
,
2554 const TargetRegisterInfo
*TRI
, SmallVectorImpl
<RegPairInfo
> &RegPairs
,
2555 bool NeedsFrameRecord
) {
2560 bool IsWindows
= isTargetWindows(MF
);
2561 bool NeedsWinCFI
= needsWinCFI(MF
);
2562 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
2563 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
2564 CallingConv::ID CC
= MF
.getFunction().getCallingConv();
2565 unsigned Count
= CSI
.size();
2567 // MachO's compact unwind format relies on all registers being stored in
2569 assert((!produceCompactUnwindFrame(MF
) || CC
== CallingConv::PreserveMost
||
2570 CC
== CallingConv::PreserveAll
|| CC
== CallingConv::CXX_FAST_TLS
||
2571 CC
== CallingConv::Win64
|| (Count
& 1) == 0) &&
2572 "Odd number of callee-saved regs to spill!");
2573 int ByteOffset
= AFI
->getCalleeSavedStackSize();
2574 int StackFillDir
= -1;
2576 unsigned FirstReg
= 0;
2578 // For WinCFI, fill the stack from the bottom up.
2581 // As the CSI array is reversed to match PrologEpilogInserter, iterate
2582 // backwards, to pair up registers starting from lower numbered registers.
2584 FirstReg
= Count
- 1;
2586 int ScalableByteOffset
= AFI
->getSVECalleeSavedStackSize();
2587 bool NeedGapToAlignStack
= AFI
->hasCalleeSaveStackFreeSpace();
2589 // When iterating backwards, the loop condition relies on unsigned wraparound.
2590 for (unsigned i
= FirstReg
; i
< Count
; i
+= RegInc
) {
2592 RPI
.Reg1
= CSI
[i
].getReg();
2594 if (AArch64::GPR64RegClass
.contains(RPI
.Reg1
))
2595 RPI
.Type
= RegPairInfo::GPR
;
2596 else if (AArch64::FPR64RegClass
.contains(RPI
.Reg1
))
2597 RPI
.Type
= RegPairInfo::FPR64
;
2598 else if (AArch64::FPR128RegClass
.contains(RPI
.Reg1
))
2599 RPI
.Type
= RegPairInfo::FPR128
;
2600 else if (AArch64::ZPRRegClass
.contains(RPI
.Reg1
))
2601 RPI
.Type
= RegPairInfo::ZPR
;
2602 else if (AArch64::PPRRegClass
.contains(RPI
.Reg1
))
2603 RPI
.Type
= RegPairInfo::PPR
;
2605 llvm_unreachable("Unsupported register class.");
2607 // Add the next reg to the pair if it is in the same register class.
2608 if (unsigned(i
+ RegInc
) < Count
) {
2609 Register NextReg
= CSI
[i
+ RegInc
].getReg();
2610 bool IsFirst
= i
== FirstReg
;
2612 case RegPairInfo::GPR
:
2613 if (AArch64::GPR64RegClass
.contains(NextReg
) &&
2614 !invalidateRegisterPairing(RPI
.Reg1
, NextReg
, IsWindows
,
2615 NeedsWinCFI
, NeedsFrameRecord
, IsFirst
,
2619 case RegPairInfo::FPR64
:
2620 if (AArch64::FPR64RegClass
.contains(NextReg
) &&
2621 !invalidateWindowsRegisterPairing(RPI
.Reg1
, NextReg
, NeedsWinCFI
,
2625 case RegPairInfo::FPR128
:
2626 if (AArch64::FPR128RegClass
.contains(NextReg
))
2629 case RegPairInfo::PPR
:
2630 case RegPairInfo::ZPR
:
2635 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2636 // list to come in sorted by frame index so that we can issue the store
2637 // pair instructions directly. Assert if we see anything otherwise.
2639 // The order of the registers in the list is controlled by
2640 // getCalleeSavedRegs(), so they will always be in-order, as well.
2641 assert((!RPI
.isPaired() ||
2642 (CSI
[i
].getFrameIdx() + RegInc
== CSI
[i
+ RegInc
].getFrameIdx())) &&
2643 "Out of order callee saved regs!");
2645 assert((!RPI
.isPaired() || !NeedsFrameRecord
|| RPI
.Reg2
!= AArch64::FP
||
2646 RPI
.Reg1
== AArch64::LR
) &&
2647 "FrameRecord must be allocated together with LR");
2649 // Windows AAPCS has FP and LR reversed.
2650 assert((!RPI
.isPaired() || !NeedsFrameRecord
|| RPI
.Reg1
!= AArch64::FP
||
2651 RPI
.Reg2
== AArch64::LR
) &&
2652 "FrameRecord must be allocated together with LR");
2654 // MachO's compact unwind format relies on all registers being stored in
2655 // adjacent register pairs.
2656 assert((!produceCompactUnwindFrame(MF
) || CC
== CallingConv::PreserveMost
||
2657 CC
== CallingConv::PreserveAll
|| CC
== CallingConv::CXX_FAST_TLS
||
2658 CC
== CallingConv::Win64
||
2660 ((RPI
.Reg1
== AArch64::LR
&& RPI
.Reg2
== AArch64::FP
) ||
2661 RPI
.Reg1
+ 1 == RPI
.Reg2
))) &&
2662 "Callee-save registers not saved as adjacent register pair!");
2664 RPI
.FrameIdx
= CSI
[i
].getFrameIdx();
2666 RPI
.isPaired()) // RPI.FrameIdx must be the lower index of the pair
2667 RPI
.FrameIdx
= CSI
[i
+ RegInc
].getFrameIdx();
2669 int Scale
= RPI
.getScale();
2671 int OffsetPre
= RPI
.isScalable() ? ScalableByteOffset
: ByteOffset
;
2672 assert(OffsetPre
% Scale
== 0);
2674 if (RPI
.isScalable())
2675 ScalableByteOffset
+= StackFillDir
* Scale
;
2677 ByteOffset
+= StackFillDir
* (RPI
.isPaired() ? 2 * Scale
: Scale
);
2679 // Swift's async context is directly before FP, so allocate an extra
2681 if (NeedsFrameRecord
&& AFI
->hasSwiftAsyncContext() &&
2682 ((!IsWindows
&& RPI
.Reg2
== AArch64::FP
) ||
2683 (IsWindows
&& RPI
.Reg2
== AArch64::LR
)))
2684 ByteOffset
+= StackFillDir
* 8;
2686 assert(!(RPI
.isScalable() && RPI
.isPaired()) &&
2687 "Paired spill/fill instructions don't exist for SVE vectors");
2689 // Round up size of non-pair to pair size if we need to pad the
2690 // callee-save area to ensure 16-byte alignment.
2691 if (NeedGapToAlignStack
&& !NeedsWinCFI
&&
2692 !RPI
.isScalable() && RPI
.Type
!= RegPairInfo::FPR128
&&
2693 !RPI
.isPaired() && ByteOffset
% 16 != 0) {
2694 ByteOffset
+= 8 * StackFillDir
;
2695 assert(MFI
.getObjectAlign(RPI
.FrameIdx
) <= Align(16));
2696 // A stack frame with a gap looks like this, bottom up:
2697 // d9, d8. x21, gap, x20, x19.
2698 // Set extra alignment on the x21 object to create the gap above it.
2699 MFI
.setObjectAlignment(RPI
.FrameIdx
, Align(16));
2700 NeedGapToAlignStack
= false;
2703 int OffsetPost
= RPI
.isScalable() ? ScalableByteOffset
: ByteOffset
;
2704 assert(OffsetPost
% Scale
== 0);
2705 // If filling top down (default), we want the offset after incrementing it.
2706 // If filling bottom up (WinCFI) we need the original offset.
2707 int Offset
= NeedsWinCFI
? OffsetPre
: OffsetPost
;
2709 // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
2710 // Swift context can directly precede FP.
2711 if (NeedsFrameRecord
&& AFI
->hasSwiftAsyncContext() &&
2712 ((!IsWindows
&& RPI
.Reg2
== AArch64::FP
) ||
2713 (IsWindows
&& RPI
.Reg2
== AArch64::LR
)))
2715 RPI
.Offset
= Offset
/ Scale
;
2717 assert(((!RPI
.isScalable() && RPI
.Offset
>= -64 && RPI
.Offset
<= 63) ||
2718 (RPI
.isScalable() && RPI
.Offset
>= -256 && RPI
.Offset
<= 255)) &&
2719 "Offset out of bounds for LDP/STP immediate");
2721 // Save the offset to frame record so that the FP register can point to the
2722 // innermost frame record (spilled FP and LR registers).
2723 if (NeedsFrameRecord
&& ((!IsWindows
&& RPI
.Reg1
== AArch64::LR
&&
2724 RPI
.Reg2
== AArch64::FP
) ||
2725 (IsWindows
&& RPI
.Reg1
== AArch64::FP
&&
2726 RPI
.Reg2
== AArch64::LR
)))
2727 AFI
->setCalleeSaveBaseToFrameRecordOffset(Offset
);
2729 RegPairs
.push_back(RPI
);
2734 // If we need an alignment gap in the stack, align the topmost stack
2735 // object. A stack frame with a gap looks like this, bottom up:
2736 // x19, d8. d9, gap.
2737 // Set extra alignment on the topmost stack object (the first element in
2738 // CSI, which goes top down), to create the gap above it.
2739 if (AFI
->hasCalleeSaveStackFreeSpace())
2740 MFI
.setObjectAlignment(CSI
[0].getFrameIdx(), Align(16));
2741 // We iterated bottom up over the registers; flip RegPairs back to top
2743 std::reverse(RegPairs
.begin(), RegPairs
.end());
2747 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2748 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MI
,
2749 ArrayRef
<CalleeSavedInfo
> CSI
, const TargetRegisterInfo
*TRI
) const {
2750 MachineFunction
&MF
= *MBB
.getParent();
2751 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
2752 bool NeedsWinCFI
= needsWinCFI(MF
);
2754 SmallVector
<RegPairInfo
, 8> RegPairs
;
2756 computeCalleeSaveRegisterPairs(MF
, CSI
, TRI
, RegPairs
, hasFP(MF
));
2758 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
2759 if (homogeneousPrologEpilog(MF
)) {
2760 auto MIB
= BuildMI(MBB
, MI
, DL
, TII
.get(AArch64::HOM_Prolog
))
2761 .setMIFlag(MachineInstr::FrameSetup
);
2763 for (auto &RPI
: RegPairs
) {
2764 MIB
.addReg(RPI
.Reg1
);
2765 MIB
.addReg(RPI
.Reg2
);
2767 // Update register live in.
2768 if (!MRI
.isReserved(RPI
.Reg1
))
2769 MBB
.addLiveIn(RPI
.Reg1
);
2770 if (RPI
.isPaired() && !MRI
.isReserved(RPI
.Reg2
))
2771 MBB
.addLiveIn(RPI
.Reg2
);
2775 for (const RegPairInfo
&RPI
: llvm::reverse(RegPairs
)) {
2776 unsigned Reg1
= RPI
.Reg1
;
2777 unsigned Reg2
= RPI
.Reg2
;
2780 // Issue sequence of spills for cs regs. The first spill may be converted
2781 // to a pre-decrement store later by emitPrologue if the callee-save stack
2782 // area allocation can't be combined with the local stack area allocation.
2784 // stp x22, x21, [sp, #0] // addImm(+0)
2785 // stp x20, x19, [sp, #16] // addImm(+2)
2786 // stp fp, lr, [sp, #32] // addImm(+4)
2787 // Rationale: This sequence saves uop updates compared to a sequence of
2788 // pre-increment spills like stp xi,xj,[sp,#-16]!
2789 // Note: Similar rationale and sequence for restores in epilog.
2793 case RegPairInfo::GPR
:
2794 StrOpc
= RPI
.isPaired() ? AArch64::STPXi
: AArch64::STRXui
;
2796 Alignment
= Align(8);
2798 case RegPairInfo::FPR64
:
2799 StrOpc
= RPI
.isPaired() ? AArch64::STPDi
: AArch64::STRDui
;
2801 Alignment
= Align(8);
2803 case RegPairInfo::FPR128
:
2804 StrOpc
= RPI
.isPaired() ? AArch64::STPQi
: AArch64::STRQui
;
2806 Alignment
= Align(16);
2808 case RegPairInfo::ZPR
:
2809 StrOpc
= AArch64::STR_ZXI
;
2811 Alignment
= Align(16);
2813 case RegPairInfo::PPR
:
2814 StrOpc
= AArch64::STR_PXI
;
2816 Alignment
= Align(2);
2819 LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1
, TRI
);
2820 if (RPI
.isPaired()) dbgs() << ", " << printReg(Reg2
, TRI
);
2821 dbgs() << ") -> fi#(" << RPI
.FrameIdx
;
2822 if (RPI
.isPaired()) dbgs() << ", " << RPI
.FrameIdx
+ 1;
2825 assert((!NeedsWinCFI
|| !(Reg1
== AArch64::LR
&& Reg2
== AArch64::FP
)) &&
2826 "Windows unwdinding requires a consecutive (FP,LR) pair");
2827 // Windows unwind codes require consecutive registers if registers are
2828 // paired. Make the switch here, so that the code below will save (x,x+1)
2830 unsigned FrameIdxReg1
= RPI
.FrameIdx
;
2831 unsigned FrameIdxReg2
= RPI
.FrameIdx
+ 1;
2832 if (NeedsWinCFI
&& RPI
.isPaired()) {
2833 std::swap(Reg1
, Reg2
);
2834 std::swap(FrameIdxReg1
, FrameIdxReg2
);
2836 MachineInstrBuilder MIB
= BuildMI(MBB
, MI
, DL
, TII
.get(StrOpc
));
2837 if (!MRI
.isReserved(Reg1
))
2838 MBB
.addLiveIn(Reg1
);
2839 if (RPI
.isPaired()) {
2840 if (!MRI
.isReserved(Reg2
))
2841 MBB
.addLiveIn(Reg2
);
2842 MIB
.addReg(Reg2
, getPrologueDeath(MF
, Reg2
));
2843 MIB
.addMemOperand(MF
.getMachineMemOperand(
2844 MachinePointerInfo::getFixedStack(MF
, FrameIdxReg2
),
2845 MachineMemOperand::MOStore
, Size
, Alignment
));
2847 MIB
.addReg(Reg1
, getPrologueDeath(MF
, Reg1
))
2848 .addReg(AArch64::SP
)
2849 .addImm(RPI
.Offset
) // [sp, #offset*scale],
2850 // where factor*scale is implicit
2851 .setMIFlag(MachineInstr::FrameSetup
);
2852 MIB
.addMemOperand(MF
.getMachineMemOperand(
2853 MachinePointerInfo::getFixedStack(MF
, FrameIdxReg1
),
2854 MachineMemOperand::MOStore
, Size
, Alignment
));
2856 InsertSEH(MIB
, TII
, MachineInstr::FrameSetup
);
2858 // Update the StackIDs of the SVE stack slots.
2859 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
2860 if (RPI
.Type
== RegPairInfo::ZPR
|| RPI
.Type
== RegPairInfo::PPR
)
2861 MFI
.setStackID(RPI
.FrameIdx
, TargetStackID::ScalableVector
);
2867 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2868 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator MBBI
,
2869 MutableArrayRef
<CalleeSavedInfo
> CSI
, const TargetRegisterInfo
*TRI
) const {
2870 MachineFunction
&MF
= *MBB
.getParent();
2871 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
2873 SmallVector
<RegPairInfo
, 8> RegPairs
;
2874 bool NeedsWinCFI
= needsWinCFI(MF
);
2876 if (MBBI
!= MBB
.end())
2877 DL
= MBBI
->getDebugLoc();
2879 computeCalleeSaveRegisterPairs(MF
, CSI
, TRI
, RegPairs
, hasFP(MF
));
2881 auto EmitMI
= [&](const RegPairInfo
&RPI
) -> MachineBasicBlock::iterator
{
2882 unsigned Reg1
= RPI
.Reg1
;
2883 unsigned Reg2
= RPI
.Reg2
;
2885 // Issue sequence of restores for cs regs. The last restore may be converted
2886 // to a post-increment load later by emitEpilogue if the callee-save stack
2887 // area allocation can't be combined with the local stack area allocation.
2889 // ldp fp, lr, [sp, #32] // addImm(+4)
2890 // ldp x20, x19, [sp, #16] // addImm(+2)
2891 // ldp x22, x21, [sp, #0] // addImm(+0)
2892 // Note: see comment in spillCalleeSavedRegisters()
2897 case RegPairInfo::GPR
:
2898 LdrOpc
= RPI
.isPaired() ? AArch64::LDPXi
: AArch64::LDRXui
;
2900 Alignment
= Align(8);
2902 case RegPairInfo::FPR64
:
2903 LdrOpc
= RPI
.isPaired() ? AArch64::LDPDi
: AArch64::LDRDui
;
2905 Alignment
= Align(8);
2907 case RegPairInfo::FPR128
:
2908 LdrOpc
= RPI
.isPaired() ? AArch64::LDPQi
: AArch64::LDRQui
;
2910 Alignment
= Align(16);
2912 case RegPairInfo::ZPR
:
2913 LdrOpc
= AArch64::LDR_ZXI
;
2915 Alignment
= Align(16);
2917 case RegPairInfo::PPR
:
2918 LdrOpc
= AArch64::LDR_PXI
;
2920 Alignment
= Align(2);
2923 LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1
, TRI
);
2924 if (RPI
.isPaired()) dbgs() << ", " << printReg(Reg2
, TRI
);
2925 dbgs() << ") -> fi#(" << RPI
.FrameIdx
;
2926 if (RPI
.isPaired()) dbgs() << ", " << RPI
.FrameIdx
+ 1;
2929 // Windows unwind codes require consecutive registers if registers are
2930 // paired. Make the switch here, so that the code below will save (x,x+1)
2932 unsigned FrameIdxReg1
= RPI
.FrameIdx
;
2933 unsigned FrameIdxReg2
= RPI
.FrameIdx
+ 1;
2934 if (NeedsWinCFI
&& RPI
.isPaired()) {
2935 std::swap(Reg1
, Reg2
);
2936 std::swap(FrameIdxReg1
, FrameIdxReg2
);
2938 MachineInstrBuilder MIB
= BuildMI(MBB
, MBBI
, DL
, TII
.get(LdrOpc
));
2939 if (RPI
.isPaired()) {
2940 MIB
.addReg(Reg2
, getDefRegState(true));
2941 MIB
.addMemOperand(MF
.getMachineMemOperand(
2942 MachinePointerInfo::getFixedStack(MF
, FrameIdxReg2
),
2943 MachineMemOperand::MOLoad
, Size
, Alignment
));
2945 MIB
.addReg(Reg1
, getDefRegState(true))
2946 .addReg(AArch64::SP
)
2947 .addImm(RPI
.Offset
) // [sp, #offset*scale]
2948 // where factor*scale is implicit
2949 .setMIFlag(MachineInstr::FrameDestroy
);
2950 MIB
.addMemOperand(MF
.getMachineMemOperand(
2951 MachinePointerInfo::getFixedStack(MF
, FrameIdxReg1
),
2952 MachineMemOperand::MOLoad
, Size
, Alignment
));
2954 InsertSEH(MIB
, TII
, MachineInstr::FrameDestroy
);
2956 return MIB
->getIterator();
2959 // SVE objects are always restored in reverse order.
2960 for (const RegPairInfo
&RPI
: reverse(RegPairs
))
2961 if (RPI
.isScalable())
2964 if (homogeneousPrologEpilog(MF
, &MBB
)) {
2965 auto MIB
= BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::HOM_Epilog
))
2966 .setMIFlag(MachineInstr::FrameDestroy
);
2967 for (auto &RPI
: RegPairs
) {
2968 MIB
.addReg(RPI
.Reg1
, RegState::Define
);
2969 MIB
.addReg(RPI
.Reg2
, RegState::Define
);
2974 if (ReverseCSRRestoreSeq
) {
2975 MachineBasicBlock::iterator First
= MBB
.end();
2976 for (const RegPairInfo
&RPI
: reverse(RegPairs
)) {
2977 if (RPI
.isScalable())
2979 MachineBasicBlock::iterator It
= EmitMI(RPI
);
2980 if (First
== MBB
.end())
2983 if (First
!= MBB
.end())
2984 MBB
.splice(MBBI
, &MBB
, First
);
2986 for (const RegPairInfo
&RPI
: RegPairs
) {
2987 if (RPI
.isScalable())
2996 void AArch64FrameLowering::determineCalleeSaves(MachineFunction
&MF
,
2997 BitVector
&SavedRegs
,
2998 RegScavenger
*RS
) const {
2999 // All calls are tail calls in GHC calling conv, and functions have no
3000 // prologue/epilogue.
3001 if (MF
.getFunction().getCallingConv() == CallingConv::GHC
)
3004 TargetFrameLowering::determineCalleeSaves(MF
, SavedRegs
, RS
);
3005 const AArch64RegisterInfo
*RegInfo
= static_cast<const AArch64RegisterInfo
*>(
3006 MF
.getSubtarget().getRegisterInfo());
3007 const AArch64Subtarget
&Subtarget
= MF
.getSubtarget
<AArch64Subtarget
>();
3008 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
3009 unsigned UnspilledCSGPR
= AArch64::NoRegister
;
3010 unsigned UnspilledCSGPRPaired
= AArch64::NoRegister
;
3012 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3013 const MCPhysReg
*CSRegs
= MF
.getRegInfo().getCalleeSavedRegs();
3015 unsigned BasePointerReg
= RegInfo
->hasBasePointer(MF
)
3016 ? RegInfo
->getBaseRegister()
3017 : (unsigned)AArch64::NoRegister
;
3019 unsigned ExtraCSSpill
= 0;
3020 bool HasUnpairedGPR64
= false;
3021 // Figure out which callee-saved registers to save/restore.
3022 for (unsigned i
= 0; CSRegs
[i
]; ++i
) {
3023 const unsigned Reg
= CSRegs
[i
];
3025 // Add the base pointer register to SavedRegs if it is callee-save.
3026 if (Reg
== BasePointerReg
)
3029 bool RegUsed
= SavedRegs
.test(Reg
);
3030 unsigned PairedReg
= AArch64::NoRegister
;
3031 const bool RegIsGPR64
= AArch64::GPR64RegClass
.contains(Reg
);
3032 if (RegIsGPR64
|| AArch64::FPR64RegClass
.contains(Reg
) ||
3033 AArch64::FPR128RegClass
.contains(Reg
)) {
3034 // Compensate for odd numbers of GP CSRs.
3035 // For now, all the known cases of odd number of CSRs are of GPRs.
3036 if (HasUnpairedGPR64
)
3037 PairedReg
= CSRegs
[i
% 2 == 0 ? i
- 1 : i
+ 1];
3039 PairedReg
= CSRegs
[i
^ 1];
3042 // If the function requires all the GP registers to save (SavedRegs),
3043 // and there are an odd number of GP CSRs at the same time (CSRegs),
3044 // PairedReg could be in a different register class from Reg, which would
3045 // lead to a FPR (usually D8) accidentally being marked saved.
3046 if (RegIsGPR64
&& !AArch64::GPR64RegClass
.contains(PairedReg
)) {
3047 PairedReg
= AArch64::NoRegister
;
3048 HasUnpairedGPR64
= true;
3050 assert(PairedReg
== AArch64::NoRegister
||
3051 AArch64::GPR64RegClass
.contains(Reg
, PairedReg
) ||
3052 AArch64::FPR64RegClass
.contains(Reg
, PairedReg
) ||
3053 AArch64::FPR128RegClass
.contains(Reg
, PairedReg
));
3056 if (AArch64::GPR64RegClass
.contains(Reg
) &&
3057 !RegInfo
->isReservedReg(MF
, Reg
)) {
3058 UnspilledCSGPR
= Reg
;
3059 UnspilledCSGPRPaired
= PairedReg
;
3064 // MachO's compact unwind format relies on all registers being stored in
3066 // FIXME: the usual format is actually better if unwinding isn't needed.
3067 if (producePairRegisters(MF
) && PairedReg
!= AArch64::NoRegister
&&
3068 !SavedRegs
.test(PairedReg
)) {
3069 SavedRegs
.set(PairedReg
);
3070 if (AArch64::GPR64RegClass
.contains(PairedReg
) &&
3071 !RegInfo
->isReservedReg(MF
, PairedReg
))
3072 ExtraCSSpill
= PairedReg
;
3076 if (MF
.getFunction().getCallingConv() == CallingConv::Win64
&&
3077 !Subtarget
.isTargetWindows()) {
3078 // For Windows calling convention on a non-windows OS, where X18 is treated
3079 // as reserved, back up X18 when entering non-windows code (marked with the
3080 // Windows calling convention) and restore when returning regardless of
3081 // whether the individual function uses it - it might call other functions
3083 SavedRegs
.set(AArch64::X18
);
3086 // Calculates the callee saved stack size.
3087 unsigned CSStackSize
= 0;
3088 unsigned SVECSStackSize
= 0;
3089 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
3090 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
3091 for (unsigned Reg
: SavedRegs
.set_bits()) {
3092 auto RegSize
= TRI
->getRegSizeInBits(Reg
, MRI
) / 8;
3093 if (AArch64::PPRRegClass
.contains(Reg
) ||
3094 AArch64::ZPRRegClass
.contains(Reg
))
3095 SVECSStackSize
+= RegSize
;
3097 CSStackSize
+= RegSize
;
3100 // Save number of saved regs, so we can easily update CSStackSize later.
3101 unsigned NumSavedRegs
= SavedRegs
.count();
3103 // The frame record needs to be created by saving the appropriate registers
3104 uint64_t EstimatedStackSize
= MFI
.estimateStackSize(MF
);
3106 windowsRequiresStackProbe(MF
, EstimatedStackSize
+ CSStackSize
+ 16)) {
3107 SavedRegs
.set(AArch64::FP
);
3108 SavedRegs
.set(AArch64::LR
);
3111 LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
3113 : SavedRegs
.set_bits()) dbgs()
3114 << ' ' << printReg(Reg
, RegInfo
);
3117 // If any callee-saved registers are used, the frame cannot be eliminated.
3118 int64_t SVEStackSize
=
3119 alignTo(SVECSStackSize
+ estimateSVEStackObjectOffsets(MFI
), 16);
3120 bool CanEliminateFrame
= (SavedRegs
.count() == 0) && !SVEStackSize
;
3122 // The CSR spill slots have not been allocated yet, so estimateStackSize
3123 // won't include them.
3124 unsigned EstimatedStackSizeLimit
= estimateRSStackSizeLimit(MF
);
3126 // We may address some of the stack above the canonical frame address, either
3127 // for our own arguments or during a call. Include that in calculating whether
3128 // we have complicated addressing concerns.
3129 int64_t CalleeStackUsed
= 0;
3130 for (int I
= MFI
.getObjectIndexBegin(); I
!= 0; ++I
) {
3131 int64_t FixedOff
= MFI
.getObjectOffset(I
);
3132 if (FixedOff
> CalleeStackUsed
) CalleeStackUsed
= FixedOff
;
3135 // Conservatively always assume BigStack when there are SVE spills.
3136 bool BigStack
= SVEStackSize
|| (EstimatedStackSize
+ CSStackSize
+
3137 CalleeStackUsed
) > EstimatedStackSizeLimit
;
3138 if (BigStack
|| !CanEliminateFrame
|| RegInfo
->cannotEliminateFrame(MF
))
3139 AFI
->setHasStackFrame(true);
3141 // Estimate if we might need to scavenge a register at some point in order
3142 // to materialize a stack offset. If so, either spill one additional
3143 // callee-saved register or reserve a special spill slot to facilitate
3144 // register scavenging. If we already spilled an extra callee-saved register
3145 // above to keep the number of spills even, we don't need to do anything else
3148 if (!ExtraCSSpill
&& UnspilledCSGPR
!= AArch64::NoRegister
) {
3149 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR
, RegInfo
)
3150 << " to get a scratch register.\n");
3151 SavedRegs
.set(UnspilledCSGPR
);
3152 ExtraCSSpill
= UnspilledCSGPR
;
3154 // MachO's compact unwind format relies on all registers being stored in
3155 // pairs, so if we need to spill one extra for BigStack, then we need to
3157 if (producePairRegisters(MF
)) {
3158 if (UnspilledCSGPRPaired
== AArch64::NoRegister
) {
3159 // Failed to make a pair for compact unwind format, revert spilling.
3160 if (produceCompactUnwindFrame(MF
)) {
3161 SavedRegs
.reset(UnspilledCSGPR
);
3162 ExtraCSSpill
= AArch64::NoRegister
;
3165 SavedRegs
.set(UnspilledCSGPRPaired
);
3169 // If we didn't find an extra callee-saved register to spill, create
3170 // an emergency spill slot.
3171 if (!ExtraCSSpill
|| MF
.getRegInfo().isPhysRegUsed(ExtraCSSpill
)) {
3172 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
3173 const TargetRegisterClass
&RC
= AArch64::GPR64RegClass
;
3174 unsigned Size
= TRI
->getSpillSize(RC
);
3175 Align Alignment
= TRI
->getSpillAlign(RC
);
3176 int FI
= MFI
.CreateStackObject(Size
, Alignment
, false);
3177 RS
->addScavengingFrameIndex(FI
);
3178 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
3179 << " as the emergency spill slot.\n");
3183 // Adding the size of additional 64bit GPR saves.
3184 CSStackSize
+= 8 * (SavedRegs
.count() - NumSavedRegs
);
3186 // A Swift asynchronous context extends the frame record with a pointer
3187 // directly before FP.
3188 if (hasFP(MF
) && AFI
->hasSwiftAsyncContext())
3191 uint64_t AlignedCSStackSize
= alignTo(CSStackSize
, 16);
3192 LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
3193 << EstimatedStackSize
+ AlignedCSStackSize
3196 assert((!MFI
.isCalleeSavedInfoValid() ||
3197 AFI
->getCalleeSavedStackSize() == AlignedCSStackSize
) &&
3198 "Should not invalidate callee saved info");
3200 // Round up to register pair alignment to avoid additional SP adjustment
3202 AFI
->setCalleeSavedStackSize(AlignedCSStackSize
);
3203 AFI
->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize
!= CSStackSize
);
3204 AFI
->setSVECalleeSavedStackSize(alignTo(SVECSStackSize
, 16));
3207 bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
3208 MachineFunction
&MF
, const TargetRegisterInfo
*RegInfo
,
3209 std::vector
<CalleeSavedInfo
> &CSI
, unsigned &MinCSFrameIndex
,
3210 unsigned &MaxCSFrameIndex
) const {
3211 bool NeedsWinCFI
= needsWinCFI(MF
);
3212 // To match the canonical windows frame layout, reverse the list of
3213 // callee saved registers to get them laid out by PrologEpilogInserter
3214 // in the right order. (PrologEpilogInserter allocates stack objects top
3215 // down. Windows canonical prologs store higher numbered registers at
3216 // the top, thus have the CSI array start from the highest registers.)
3218 std::reverse(CSI
.begin(), CSI
.end());
3221 return true; // Early exit if no callee saved registers are modified!
3223 // Now that we know which registers need to be saved and restored, allocate
3224 // stack slots for them.
3225 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3226 auto *AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
3228 bool UsesWinAAPCS
= isTargetWindows(MF
);
3229 if (UsesWinAAPCS
&& hasFP(MF
) && AFI
->hasSwiftAsyncContext()) {
3230 int FrameIdx
= MFI
.CreateStackObject(8, Align(16), true);
3231 AFI
->setSwiftAsyncContextFrameIdx(FrameIdx
);
3232 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
3233 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
3236 for (auto &CS
: CSI
) {
3237 Register Reg
= CS
.getReg();
3238 const TargetRegisterClass
*RC
= RegInfo
->getMinimalPhysRegClass(Reg
);
3240 unsigned Size
= RegInfo
->getSpillSize(*RC
);
3241 Align
Alignment(RegInfo
->getSpillAlign(*RC
));
3242 int FrameIdx
= MFI
.CreateStackObject(Size
, Alignment
, true);
3243 CS
.setFrameIdx(FrameIdx
);
3245 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
3246 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
3248 // Grab 8 bytes below FP for the extended asynchronous frame info.
3249 if (hasFP(MF
) && AFI
->hasSwiftAsyncContext() && !UsesWinAAPCS
&&
3250 Reg
== AArch64::FP
) {
3251 FrameIdx
= MFI
.CreateStackObject(8, Alignment
, true);
3252 AFI
->setSwiftAsyncContextFrameIdx(FrameIdx
);
3253 if ((unsigned)FrameIdx
< MinCSFrameIndex
) MinCSFrameIndex
= FrameIdx
;
3254 if ((unsigned)FrameIdx
> MaxCSFrameIndex
) MaxCSFrameIndex
= FrameIdx
;
3260 bool AArch64FrameLowering::enableStackSlotScavenging(
3261 const MachineFunction
&MF
) const {
3262 const AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
3263 // If the function has streaming-mode changes, don't scavenge a
3264 // spillslot in the callee-save area, as that might require an
3265 // 'addvl' in the streaming-mode-changing call-sequence when the
3266 // function doesn't use a FP.
3267 if (AFI
->hasStreamingModeChanges() && !hasFP(MF
))
3269 return AFI
->hasCalleeSaveStackFreeSpace();
3272 /// returns true if there are any SVE callee saves.
3273 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo
&MFI
,
3274 int &Min
, int &Max
) {
3275 Min
= std::numeric_limits
<int>::max();
3276 Max
= std::numeric_limits
<int>::min();
3278 if (!MFI
.isCalleeSavedInfoValid())
3281 const std::vector
<CalleeSavedInfo
> &CSI
= MFI
.getCalleeSavedInfo();
3282 for (auto &CS
: CSI
) {
3283 if (AArch64::ZPRRegClass
.contains(CS
.getReg()) ||
3284 AArch64::PPRRegClass
.contains(CS
.getReg())) {
3285 assert((Max
== std::numeric_limits
<int>::min() ||
3286 Max
+ 1 == CS
.getFrameIdx()) &&
3287 "SVE CalleeSaves are not consecutive");
3289 Min
= std::min(Min
, CS
.getFrameIdx());
3290 Max
= std::max(Max
, CS
.getFrameIdx());
3293 return Min
!= std::numeric_limits
<int>::max();
3296 // Process all the SVE stack objects and determine offsets for each
3297 // object. If AssignOffsets is true, the offsets get assigned.
3298 // Fills in the first and last callee-saved frame indices into
3299 // Min/MaxCSFrameIndex, respectively.
3300 // Returns the size of the stack.
3301 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo
&MFI
,
3302 int &MinCSFrameIndex
,
3303 int &MaxCSFrameIndex
,
3304 bool AssignOffsets
) {
3306 // First process all fixed stack objects.
3307 for (int I
= MFI
.getObjectIndexBegin(); I
!= 0; ++I
)
3308 assert(MFI
.getStackID(I
) != TargetStackID::ScalableVector
&&
3309 "SVE vectors should never be passed on the stack by value, only by "
3313 auto Assign
= [&MFI
](int FI
, int64_t Offset
) {
3314 LLVM_DEBUG(dbgs() << "alloc FI(" << FI
<< ") at SP[" << Offset
<< "]\n");
3315 MFI
.setObjectOffset(FI
, Offset
);
3320 // Then process all callee saved slots.
3321 if (getSVECalleeSaveSlotRange(MFI
, MinCSFrameIndex
, MaxCSFrameIndex
)) {
3322 // Assign offsets to the callee save slots.
3323 for (int I
= MinCSFrameIndex
; I
<= MaxCSFrameIndex
; ++I
) {
3324 Offset
+= MFI
.getObjectSize(I
);
3325 Offset
= alignTo(Offset
, MFI
.getObjectAlign(I
));
3331 // Ensure that the Callee-save area is aligned to 16bytes.
3332 Offset
= alignTo(Offset
, Align(16U));
3334 // Create a buffer of SVE objects to allocate and sort it.
3335 SmallVector
<int, 8> ObjectsToAllocate
;
3336 // If we have a stack protector, and we've previously decided that we have SVE
3337 // objects on the stack and thus need it to go in the SVE stack area, then it
3338 // needs to go first.
3339 int StackProtectorFI
= -1;
3340 if (MFI
.hasStackProtectorIndex()) {
3341 StackProtectorFI
= MFI
.getStackProtectorIndex();
3342 if (MFI
.getStackID(StackProtectorFI
) == TargetStackID::ScalableVector
)
3343 ObjectsToAllocate
.push_back(StackProtectorFI
);
3345 for (int I
= 0, E
= MFI
.getObjectIndexEnd(); I
!= E
; ++I
) {
3346 unsigned StackID
= MFI
.getStackID(I
);
3347 if (StackID
!= TargetStackID::ScalableVector
)
3349 if (I
== StackProtectorFI
)
3351 if (MaxCSFrameIndex
>= I
&& I
>= MinCSFrameIndex
)
3353 if (MFI
.isDeadObjectIndex(I
))
3356 ObjectsToAllocate
.push_back(I
);
3359 // Allocate all SVE locals and spills
3360 for (unsigned FI
: ObjectsToAllocate
) {
3361 Align Alignment
= MFI
.getObjectAlign(FI
);
3362 // FIXME: Given that the length of SVE vectors is not necessarily a power of
3363 // two, we'd need to align every object dynamically at runtime if the
3364 // alignment is larger than 16. This is not yet supported.
3365 if (Alignment
> Align(16))
3367 "Alignment of scalable vectors > 16 bytes is not yet supported");
3369 Offset
= alignTo(Offset
+ MFI
.getObjectSize(FI
), Alignment
);
3371 Assign(FI
, -Offset
);
3377 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
3378 MachineFrameInfo
&MFI
) const {
3379 int MinCSFrameIndex
, MaxCSFrameIndex
;
3380 return determineSVEStackObjectOffsets(MFI
, MinCSFrameIndex
, MaxCSFrameIndex
, false);
3383 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
3384 MachineFrameInfo
&MFI
, int &MinCSFrameIndex
, int &MaxCSFrameIndex
) const {
3385 return determineSVEStackObjectOffsets(MFI
, MinCSFrameIndex
, MaxCSFrameIndex
,
3389 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
3390 MachineFunction
&MF
, RegScavenger
*RS
) const {
3391 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3393 assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown
&&
3394 "Upwards growing stack unsupported");
3396 int MinCSFrameIndex
, MaxCSFrameIndex
;
3397 int64_t SVEStackSize
=
3398 assignSVEStackObjectOffsets(MFI
, MinCSFrameIndex
, MaxCSFrameIndex
);
3400 AArch64FunctionInfo
*AFI
= MF
.getInfo
<AArch64FunctionInfo
>();
3401 AFI
->setStackSizeSVE(alignTo(SVEStackSize
, 16U));
3402 AFI
->setMinMaxSVECSFrameIndex(MinCSFrameIndex
, MaxCSFrameIndex
);
3404 // If this function isn't doing Win64-style C++ EH, we don't need to do
3406 if (!MF
.hasEHFunclets())
3408 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
3409 WinEHFuncInfo
&EHInfo
= *MF
.getWinEHFuncInfo();
3411 MachineBasicBlock
&MBB
= MF
.front();
3412 auto MBBI
= MBB
.begin();
3413 while (MBBI
!= MBB
.end() && MBBI
->getFlag(MachineInstr::FrameSetup
))
3416 // Create an UnwindHelp object.
3417 // The UnwindHelp object is allocated at the start of the fixed object area
3418 int64_t FixedObject
=
3419 getFixedObjectSize(MF
, AFI
, /*IsWin64*/ true, /*IsFunclet*/ false);
3420 int UnwindHelpFI
= MFI
.CreateFixedObject(/*Size*/ 8,
3421 /*SPOffset*/ -FixedObject
,
3422 /*IsImmutable=*/false);
3423 EHInfo
.UnwindHelpFrameIdx
= UnwindHelpFI
;
3425 // We need to store -2 into the UnwindHelp object at the start of the
3428 RS
->enterBasicBlockEnd(MBB
);
3429 RS
->backward(std::prev(MBBI
));
3430 Register DstReg
= RS
->FindUnusedReg(&AArch64::GPR64commonRegClass
);
3431 assert(DstReg
&& "There must be a free register after frame setup");
3432 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::MOVi64imm
), DstReg
).addImm(-2);
3433 BuildMI(MBB
, MBBI
, DL
, TII
.get(AArch64::STURXi
))
3434 .addReg(DstReg
, getKillRegState(true))
3435 .addFrameIndex(UnwindHelpFI
)
3440 struct TagStoreInstr
{
3442 int64_t Offset
, Size
;
3443 explicit TagStoreInstr(MachineInstr
*MI
, int64_t Offset
, int64_t Size
)
3444 : MI(MI
), Offset(Offset
), Size(Size
) {}
3447 class TagStoreEdit
{
3448 MachineFunction
*MF
;
3449 MachineBasicBlock
*MBB
;
3450 MachineRegisterInfo
*MRI
;
3451 // Tag store instructions that are being replaced.
3452 SmallVector
<TagStoreInstr
, 8> TagStores
;
3453 // Combined memref arguments of the above instructions.
3454 SmallVector
<MachineMemOperand
*, 8> CombinedMemRefs
;
3456 // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
3457 // FrameRegOffset + Size) with the address tag of SP.
3459 StackOffset FrameRegOffset
;
3461 // If not std::nullopt, move FrameReg to (FrameReg + FrameRegUpdate) at the
3463 std::optional
<int64_t> FrameRegUpdate
;
3464 // MIFlags for any FrameReg updating instructions.
3465 unsigned FrameRegUpdateFlags
;
3467 // Use zeroing instruction variants.
3471 void emitUnrolled(MachineBasicBlock::iterator InsertI
);
3472 void emitLoop(MachineBasicBlock::iterator InsertI
);
3475 TagStoreEdit(MachineBasicBlock
*MBB
, bool ZeroData
)
3476 : MBB(MBB
), ZeroData(ZeroData
) {
3477 MF
= MBB
->getParent();
3478 MRI
= &MF
->getRegInfo();
3480 // Add an instruction to be replaced. Instructions must be added in the
3481 // ascending order of Offset, and have to be adjacent.
3482 void addInstruction(TagStoreInstr I
) {
3483 assert((TagStores
.empty() ||
3484 TagStores
.back().Offset
+ TagStores
.back().Size
== I
.Offset
) &&
3485 "Non-adjacent tag store instructions.");
3486 TagStores
.push_back(I
);
3488 void clear() { TagStores
.clear(); }
3489 // Emit equivalent code at the given location, and erase the current set of
3490 // instructions. May skip if the replacement is not profitable. May invalidate
3491 // the input iterator and replace it with a valid one.
3492 void emitCode(MachineBasicBlock::iterator
&InsertI
,
3493 const AArch64FrameLowering
*TFI
, bool TryMergeSPUpdate
);
3496 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI
) {
3497 const AArch64InstrInfo
*TII
=
3498 MF
->getSubtarget
<AArch64Subtarget
>().getInstrInfo();
3500 const int64_t kMinOffset
= -256 * 16;
3501 const int64_t kMaxOffset
= 255 * 16;
3503 Register BaseReg
= FrameReg
;
3504 int64_t BaseRegOffsetBytes
= FrameRegOffset
.getFixed();
3505 if (BaseRegOffsetBytes
< kMinOffset
||
3506 BaseRegOffsetBytes
+ (Size
- Size
% 32) > kMaxOffset
||
3507 // BaseReg can be FP, which is not necessarily aligned to 16-bytes. In
3508 // that case, BaseRegOffsetBytes will not be aligned to 16 bytes, which
3509 // is required for the offset of ST2G.
3510 BaseRegOffsetBytes
% 16 != 0) {
3511 Register ScratchReg
= MRI
->createVirtualRegister(&AArch64::GPR64RegClass
);
3512 emitFrameOffset(*MBB
, InsertI
, DL
, ScratchReg
, BaseReg
,
3513 StackOffset::getFixed(BaseRegOffsetBytes
), TII
);
3514 BaseReg
= ScratchReg
;
3515 BaseRegOffsetBytes
= 0;
3518 MachineInstr
*LastI
= nullptr;
3520 int64_t InstrSize
= (Size
> 16) ? 32 : 16;
3523 ? (ZeroData
? AArch64::STZGi
: AArch64::STGi
)
3524 : (ZeroData
? AArch64::STZ2Gi
: AArch64::ST2Gi
);
3525 assert(BaseRegOffsetBytes
% 16 == 0);
3526 MachineInstr
*I
= BuildMI(*MBB
, InsertI
, DL
, TII
->get(Opcode
))
3527 .addReg(AArch64::SP
)
3529 .addImm(BaseRegOffsetBytes
/ 16)
3530 .setMemRefs(CombinedMemRefs
);
3531 // A store to [BaseReg, #0] should go last for an opportunity to fold the
3532 // final SP adjustment in the epilogue.
3533 if (BaseRegOffsetBytes
== 0)
3535 BaseRegOffsetBytes
+= InstrSize
;
3540 MBB
->splice(InsertI
, MBB
, LastI
);
3543 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI
) {
3544 const AArch64InstrInfo
*TII
=
3545 MF
->getSubtarget
<AArch64Subtarget
>().getInstrInfo();
3547 Register BaseReg
= FrameRegUpdate
3549 : MRI
->createVirtualRegister(&AArch64::GPR64RegClass
);
3550 Register SizeReg
= MRI
->createVirtualRegister(&AArch64::GPR64RegClass
);
3552 emitFrameOffset(*MBB
, InsertI
, DL
, BaseReg
, FrameReg
, FrameRegOffset
, TII
);
3554 int64_t LoopSize
= Size
;
3555 // If the loop size is not a multiple of 32, split off one 16-byte store at
3556 // the end to fold BaseReg update into.
3557 if (FrameRegUpdate
&& *FrameRegUpdate
)
3558 LoopSize
-= LoopSize
% 32;
3559 MachineInstr
*LoopI
= BuildMI(*MBB
, InsertI
, DL
,
3560 TII
->get(ZeroData
? AArch64::STZGloop_wback
3561 : AArch64::STGloop_wback
))
3566 .setMemRefs(CombinedMemRefs
);
3568 LoopI
->setFlags(FrameRegUpdateFlags
);
3570 int64_t ExtraBaseRegUpdate
=
3571 FrameRegUpdate
? (*FrameRegUpdate
- FrameRegOffset
.getFixed() - Size
) : 0;
3572 if (LoopSize
< Size
) {
3573 assert(FrameRegUpdate
);
3574 assert(Size
- LoopSize
== 16);
3575 // Tag 16 more bytes at BaseReg and update BaseReg.
3576 BuildMI(*MBB
, InsertI
, DL
,
3577 TII
->get(ZeroData
? AArch64::STZGPostIndex
: AArch64::STGPostIndex
))
3581 .addImm(1 + ExtraBaseRegUpdate
/ 16)
3582 .setMemRefs(CombinedMemRefs
)
3583 .setMIFlags(FrameRegUpdateFlags
);
3584 } else if (ExtraBaseRegUpdate
) {
3588 TII
->get(ExtraBaseRegUpdate
> 0 ? AArch64::ADDXri
: AArch64::SUBXri
))
3591 .addImm(std::abs(ExtraBaseRegUpdate
))
3593 .setMIFlags(FrameRegUpdateFlags
);
3597 // Check if *II is a register update that can be merged into STGloop that ends
3598 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
3600 bool canMergeRegUpdate(MachineBasicBlock::iterator II
, unsigned Reg
,
3601 int64_t Size
, int64_t *TotalOffset
) {
3602 MachineInstr
&MI
= *II
;
3603 if ((MI
.getOpcode() == AArch64::ADDXri
||
3604 MI
.getOpcode() == AArch64::SUBXri
) &&
3605 MI
.getOperand(0).getReg() == Reg
&& MI
.getOperand(1).getReg() == Reg
) {
3606 unsigned Shift
= AArch64_AM::getShiftValue(MI
.getOperand(3).getImm());
3607 int64_t Offset
= MI
.getOperand(2).getImm() << Shift
;
3608 if (MI
.getOpcode() == AArch64::SUBXri
)
3610 int64_t AbsPostOffset
= std::abs(Offset
- Size
);
3611 const int64_t kMaxOffset
=
3612 0xFFF; // Max encoding for unshifted ADDXri / SUBXri
3613 if (AbsPostOffset
<= kMaxOffset
&& AbsPostOffset
% 16 == 0) {
3614 *TotalOffset
= Offset
;
3621 void mergeMemRefs(const SmallVectorImpl
<TagStoreInstr
> &TSE
,
3622 SmallVectorImpl
<MachineMemOperand
*> &MemRefs
) {
3624 for (auto &TS
: TSE
) {
3625 MachineInstr
*MI
= TS
.MI
;
3626 // An instruction without memory operands may access anything. Be
3627 // conservative and return an empty list.
3628 if (MI
->memoperands_empty()) {
3632 MemRefs
.append(MI
->memoperands_begin(), MI
->memoperands_end());
3636 void TagStoreEdit::emitCode(MachineBasicBlock::iterator
&InsertI
,
3637 const AArch64FrameLowering
*TFI
,
3638 bool TryMergeSPUpdate
) {
3639 if (TagStores
.empty())
3641 TagStoreInstr
&FirstTagStore
= TagStores
[0];
3642 TagStoreInstr
&LastTagStore
= TagStores
[TagStores
.size() - 1];
3643 Size
= LastTagStore
.Offset
- FirstTagStore
.Offset
+ LastTagStore
.Size
;
3644 DL
= TagStores
[0].MI
->getDebugLoc();
3647 FrameRegOffset
= TFI
->resolveFrameOffsetReference(
3648 *MF
, FirstTagStore
.Offset
, false /*isFixed*/, false /*isSVE*/, Reg
,
3649 /*PreferFP=*/false, /*ForSimm=*/true);
3651 FrameRegUpdate
= std::nullopt
;
3653 mergeMemRefs(TagStores
, CombinedMemRefs
);
3655 LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
3656 for (const auto &Instr
3657 : TagStores
) { dbgs() << " " << *Instr
.MI
; });
3659 // Size threshold where a loop becomes shorter than a linear sequence of
3660 // tagging instructions.
3661 const int kSetTagLoopThreshold
= 176;
3662 if (Size
< kSetTagLoopThreshold
) {
3663 if (TagStores
.size() < 2)
3665 emitUnrolled(InsertI
);
3667 MachineInstr
*UpdateInstr
= nullptr;
3668 int64_t TotalOffset
= 0;
3669 if (TryMergeSPUpdate
) {
3670 // See if we can merge base register update into the STGloop.
3671 // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3672 // but STGloop is way too unusual for that, and also it only
3673 // realistically happens in function epilogue. Also, STGloop is expanded
3674 // before that pass.
3675 if (InsertI
!= MBB
->end() &&
3676 canMergeRegUpdate(InsertI
, FrameReg
, FrameRegOffset
.getFixed() + Size
,
3678 UpdateInstr
= &*InsertI
++;
3679 LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n "
3684 if (!UpdateInstr
&& TagStores
.size() < 2)
3688 FrameRegUpdate
= TotalOffset
;
3689 FrameRegUpdateFlags
= UpdateInstr
->getFlags();
3693 UpdateInstr
->eraseFromParent();
3696 for (auto &TS
: TagStores
)
3697 TS
.MI
->eraseFromParent();
3700 bool isMergeableStackTaggingInstruction(MachineInstr
&MI
, int64_t &Offset
,
3701 int64_t &Size
, bool &ZeroData
) {
3702 MachineFunction
&MF
= *MI
.getParent()->getParent();
3703 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3705 unsigned Opcode
= MI
.getOpcode();
3706 ZeroData
= (Opcode
== AArch64::STZGloop
|| Opcode
== AArch64::STZGi
||
3707 Opcode
== AArch64::STZ2Gi
);
3709 if (Opcode
== AArch64::STGloop
|| Opcode
== AArch64::STZGloop
) {
3710 if (!MI
.getOperand(0).isDead() || !MI
.getOperand(1).isDead())
3712 if (!MI
.getOperand(2).isImm() || !MI
.getOperand(3).isFI())
3714 Offset
= MFI
.getObjectOffset(MI
.getOperand(3).getIndex());
3715 Size
= MI
.getOperand(2).getImm();
3719 if (Opcode
== AArch64::STGi
|| Opcode
== AArch64::STZGi
)
3721 else if (Opcode
== AArch64::ST2Gi
|| Opcode
== AArch64::STZ2Gi
)
3726 if (MI
.getOperand(0).getReg() != AArch64::SP
|| !MI
.getOperand(1).isFI())
3729 Offset
= MFI
.getObjectOffset(MI
.getOperand(1).getIndex()) +
3730 16 * MI
.getOperand(2).getImm();
3734 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3735 // and replace them with a shorter instruction sequence:
3736 // * replace STG + STG with ST2G
3737 // * replace STGloop + STGloop with STGloop
3738 // This code needs to run when stack slot offsets are already known, but before
3739 // FrameIndex operands in STG instructions are eliminated.
3740 MachineBasicBlock::iterator
tryMergeAdjacentSTG(MachineBasicBlock::iterator II
,
3741 const AArch64FrameLowering
*TFI
,
3744 int64_t Size
, Offset
;
3745 MachineInstr
&MI
= *II
;
3746 MachineBasicBlock
*MBB
= MI
.getParent();
3747 MachineBasicBlock::iterator NextI
= ++II
;
3748 if (&MI
== &MBB
->instr_back())
3750 if (!isMergeableStackTaggingInstruction(MI
, Offset
, Size
, FirstZeroData
))
3753 SmallVector
<TagStoreInstr
, 4> Instrs
;
3754 Instrs
.emplace_back(&MI
, Offset
, Size
);
3756 constexpr int kScanLimit
= 10;
3758 for (MachineBasicBlock::iterator E
= MBB
->end();
3759 NextI
!= E
&& Count
< kScanLimit
; ++NextI
) {
3760 MachineInstr
&MI
= *NextI
;
3762 int64_t Size
, Offset
;
3763 // Collect instructions that update memory tags with a FrameIndex operand
3764 // and (when applicable) constant size, and whose output registers are dead
3765 // (the latter is almost always the case in practice). Since these
3766 // instructions effectively have no inputs or outputs, we are free to skip
3767 // any non-aliasing instructions in between without tracking used registers.
3768 if (isMergeableStackTaggingInstruction(MI
, Offset
, Size
, ZeroData
)) {
3769 if (ZeroData
!= FirstZeroData
)
3771 Instrs
.emplace_back(&MI
, Offset
, Size
);
3775 // Only count non-transient, non-tagging instructions toward the scan
3777 if (!MI
.isTransient())
3780 // Just in case, stop before the epilogue code starts.
3781 if (MI
.getFlag(MachineInstr::FrameSetup
) ||
3782 MI
.getFlag(MachineInstr::FrameDestroy
))
3785 // Reject anything that may alias the collected instructions.
3786 if (MI
.mayLoadOrStore() || MI
.hasUnmodeledSideEffects())
3790 // New code will be inserted after the last tagging instruction we've found.
3791 MachineBasicBlock::iterator InsertI
= Instrs
.back().MI
;
3794 llvm::stable_sort(Instrs
,
3795 [](const TagStoreInstr
&Left
, const TagStoreInstr
&Right
) {
3796 return Left
.Offset
< Right
.Offset
;
3799 // Make sure that we don't have any overlapping stores.
3800 int64_t CurOffset
= Instrs
[0].Offset
;
3801 for (auto &Instr
: Instrs
) {
3802 if (CurOffset
> Instr
.Offset
)
3804 CurOffset
= Instr
.Offset
+ Instr
.Size
;
3807 // Find contiguous runs of tagged memory and emit shorter instruction
3808 // sequencies for them when possible.
3809 TagStoreEdit
TSE(MBB
, FirstZeroData
);
3810 std::optional
<int64_t> EndOffset
;
3811 for (auto &Instr
: Instrs
) {
3812 if (EndOffset
&& *EndOffset
!= Instr
.Offset
) {
3814 TSE
.emitCode(InsertI
, TFI
, /*TryMergeSPUpdate = */ false);
3818 TSE
.addInstruction(Instr
);
3819 EndOffset
= Instr
.Offset
+ Instr
.Size
;
3822 const MachineFunction
*MF
= MBB
->getParent();
3823 // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
3825 InsertI
, TFI
, /*TryMergeSPUpdate = */
3826 !MF
->getInfo
<AArch64FunctionInfo
>()->needsAsyncDwarfUnwindInfo(*MF
));
3832 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3833 MachineFunction
&MF
, RegScavenger
*RS
= nullptr) const {
3834 if (StackTaggingMergeSetTag
)
3836 for (MachineBasicBlock::iterator II
= BB
.begin(); II
!= BB
.end();)
3837 II
= tryMergeAdjacentSTG(II
, this, RS
);
3840 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3841 /// before the update. This is easily retrieved as it is exactly the offset
3842 /// that is set in processFunctionBeforeFrameFinalized.
3843 StackOffset
AArch64FrameLowering::getFrameIndexReferencePreferSP(
3844 const MachineFunction
&MF
, int FI
, Register
&FrameReg
,
3845 bool IgnoreSPUpdates
) const {
3846 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3847 if (IgnoreSPUpdates
) {
3848 LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI
<< " is "
3849 << MFI
.getObjectOffset(FI
) << "\n");
3850 FrameReg
= AArch64::SP
;
3851 return StackOffset::getFixed(MFI
.getObjectOffset(FI
));
3854 // Go to common code if we cannot provide sp + offset.
3855 if (MFI
.hasVarSizedObjects() ||
3856 MF
.getInfo
<AArch64FunctionInfo
>()->getStackSizeSVE() ||
3857 MF
.getSubtarget().getRegisterInfo()->hasStackRealignment(MF
))
3858 return getFrameIndexReference(MF
, FI
, FrameReg
);
3860 FrameReg
= AArch64::SP
;
3861 return getStackOffset(MF
, MFI
.getObjectOffset(FI
));
3864 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3865 /// the parent's frame pointer
3866 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3867 const MachineFunction
&MF
) const {
3871 /// Funclets only need to account for space for the callee saved registers,
3872 /// as the locals are accounted for in the parent's stack frame.
3873 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3874 const MachineFunction
&MF
) const {
3875 // This is the size of the pushed CSRs.
3877 MF
.getInfo
<AArch64FunctionInfo
>()->getCalleeSavedStackSize();
3878 // This is the amount of stack a funclet needs to allocate.
3879 return alignTo(CSSize
+ MF
.getFrameInfo().getMaxCallFrameSize(),
3884 struct FrameObject
{
3885 bool IsValid
= false;
3886 // Index of the object in MFI.
3887 int ObjectIndex
= 0;
3888 // Group ID this object belongs to.
3889 int GroupIndex
= -1;
3890 // This object should be placed first (closest to SP).
3891 bool ObjectFirst
= false;
3892 // This object's group (which always contains the object with
3893 // ObjectFirst==true) should be placed first.
3894 bool GroupFirst
= false;
3897 class GroupBuilder
{
3898 SmallVector
<int, 8> CurrentMembers
;
3899 int NextGroupIndex
= 0;
3900 std::vector
<FrameObject
> &Objects
;
3903 GroupBuilder(std::vector
<FrameObject
> &Objects
) : Objects(Objects
) {}
3904 void AddMember(int Index
) { CurrentMembers
.push_back(Index
); }
3905 void EndCurrentGroup() {
3906 if (CurrentMembers
.size() > 1) {
3907 // Create a new group with the current member list. This might remove them
3908 // from their pre-existing groups. That's OK, dealing with overlapping
3909 // groups is too hard and unlikely to make a difference.
3910 LLVM_DEBUG(dbgs() << "group:");
3911 for (int Index
: CurrentMembers
) {
3912 Objects
[Index
].GroupIndex
= NextGroupIndex
;
3913 LLVM_DEBUG(dbgs() << " " << Index
);
3915 LLVM_DEBUG(dbgs() << "\n");
3918 CurrentMembers
.clear();
3922 bool FrameObjectCompare(const FrameObject
&A
, const FrameObject
&B
) {
3923 // Objects at a lower index are closer to FP; objects at a higher index are
3926 // For consistency in our comparison, all invalid objects are placed
3927 // at the end. This also allows us to stop walking when we hit the
3928 // first invalid item after it's all sorted.
3930 // The "first" object goes first (closest to SP), followed by the members of
3931 // the "first" group.
3933 // The rest are sorted by the group index to keep the groups together.
3934 // Higher numbered groups are more likely to be around longer (i.e. untagged
3935 // in the function epilogue and not at some earlier point). Place them closer
3938 // If all else equal, sort by the object index to keep the objects in the
3940 return std::make_tuple(!A
.IsValid
, A
.ObjectFirst
, A
.GroupFirst
, A
.GroupIndex
,
3942 std::make_tuple(!B
.IsValid
, B
.ObjectFirst
, B
.GroupFirst
, B
.GroupIndex
,
3947 void AArch64FrameLowering::orderFrameObjects(
3948 const MachineFunction
&MF
, SmallVectorImpl
<int> &ObjectsToAllocate
) const {
3949 if (!OrderFrameObjects
|| ObjectsToAllocate
.empty())
3952 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3953 std::vector
<FrameObject
> FrameObjects(MFI
.getObjectIndexEnd());
3954 for (auto &Obj
: ObjectsToAllocate
) {
3955 FrameObjects
[Obj
].IsValid
= true;
3956 FrameObjects
[Obj
].ObjectIndex
= Obj
;
3959 // Identify stack slots that are tagged at the same time.
3960 GroupBuilder
GB(FrameObjects
);
3961 for (auto &MBB
: MF
) {
3962 for (auto &MI
: MBB
) {
3963 if (MI
.isDebugInstr())
3966 switch (MI
.getOpcode()) {
3967 case AArch64::STGloop
:
3968 case AArch64::STZGloop
:
3972 case AArch64::STZGi
:
3973 case AArch64::ST2Gi
:
3974 case AArch64::STZ2Gi
:
3983 const MachineOperand
&MO
= MI
.getOperand(OpIndex
);
3985 int FI
= MO
.getIndex();
3986 if (FI
>= 0 && FI
< MFI
.getObjectIndexEnd() &&
3987 FrameObjects
[FI
].IsValid
)
3992 // If this is a stack tagging instruction for a slot that is not part of a
3993 // group yet, either start a new group or add it to the current one.
3995 GB
.AddMember(TaggedFI
);
3997 GB
.EndCurrentGroup();
3999 // Groups should never span multiple basic blocks.
4000 GB
.EndCurrentGroup();
4003 // If the function's tagged base pointer is pinned to a stack slot, we want to
4004 // put that slot first when possible. This will likely place it at SP + 0,
4005 // and save one instruction when generating the base pointer because IRG does
4006 // not allow an immediate offset.
4007 const AArch64FunctionInfo
&AFI
= *MF
.getInfo
<AArch64FunctionInfo
>();
4008 std::optional
<int> TBPI
= AFI
.getTaggedBasePointerIndex();
4010 FrameObjects
[*TBPI
].ObjectFirst
= true;
4011 FrameObjects
[*TBPI
].GroupFirst
= true;
4012 int FirstGroupIndex
= FrameObjects
[*TBPI
].GroupIndex
;
4013 if (FirstGroupIndex
>= 0)
4014 for (FrameObject
&Object
: FrameObjects
)
4015 if (Object
.GroupIndex
== FirstGroupIndex
)
4016 Object
.GroupFirst
= true;
4019 llvm::stable_sort(FrameObjects
, FrameObjectCompare
);
4022 for (auto &Obj
: FrameObjects
) {
4023 // All invalid items are sorted at the end, so it's safe to stop.
4026 ObjectsToAllocate
[i
++] = Obj
.ObjectIndex
;
4029 LLVM_DEBUG(dbgs() << "Final frame order:\n"; for (auto &Obj
4033 dbgs() << " " << Obj
.ObjectIndex
<< ": group " << Obj
.GroupIndex
;
4034 if (Obj
.ObjectFirst
)
4035 dbgs() << ", first";
4037 dbgs() << ", group-first";