1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the AArch64 implementation of TargetFrameLowering class.
10 //
11 // On AArch64, stack frames are structured as follows:
12 //
13 // The stack grows downward.
14 //
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
17 // in the frame.
18 //
19 // At function entry, the "frame" looks as follows:
20 //
21 // |                                   | Higher address
22 // |-----------------------------------|
23 // |                                   |
24 // | arguments passed on the stack     |
25 // |                                   |
26 // |-----------------------------------| <- sp
27 // |                                   | Lower address
28 //
29 //
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
34 // for completeness.
35 //
36 // |                                   | Higher address
37 // |-----------------------------------|
38 // |                                   |
39 // | arguments passed on the stack     |
40 // |                                   |
41 // |-----------------------------------|
42 // |                                   |
43 // | (Win64 only) varargs from reg     |
44 // |                                   |
45 // |-----------------------------------|
46 // |                                   |
47 // | callee-saved gpr registers        | <--.
48 // |                                   |    | On Darwin platforms these
49 // |- - - - - - - - - - - - - - - - - -|    | callee saves are swapped,
50 // | prev_lr                           |    | (frame record first)
51 // | prev_fp                           | <--'
52 // | async context if needed           |
53 // | (a.k.a. "frame record")           |
54 // |-----------------------------------| <- fp(=x29)
55 // |                                   |
56 // | callee-saved fp/simd/SVE regs     |
57 // |                                   |
58 // |-----------------------------------|
59 // |                                   |
60 // |        SVE stack objects          |
61 // |                                   |
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 // |-----------------------------------|
67 // |                                   |
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
75 // |                                   | Lower address
76 //
77 //
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.
84 //
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.
91 //
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
99 // as:
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.
105 //
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
109 // or stores.
110 //
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.
117 //
118 // FIXME: also explain the redzone concept.
119 //
120 // An example of the prologue:
121 //
122 //     .globl __foo
123 //     .align 2
124 //  __foo:
125 // Ltmp0:
126 //     .cfi_startproc
127 //     .cfi_personality 155, ___gxx_personality_v0
128 // Leh_func_begin:
129 //     .cfi_lsda 16, Lexception33
130 //
131 //     stp  xa,bx, [sp, -#offset]!
132 //     ...
133 //     stp  x28, x27, [sp, #offset-32]
134 //     stp  fp, lr, [sp, #offset-16]
135 //     add  fp, sp, #offset - 16
136 //     sub  sp, sp, #1360
137 //
138 // The Stack:
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 //       +-------------------------------------------+
164 //
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<<
170 //
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:
174 //
175 //  Ltmp1:
176 //     .cfi_def_cfa w29, 16
177 //  Ltmp2:
178 //     .cfi_offset w30, -8
179 //  Ltmp3:
180 //     .cfi_offset w29, -16
181 //  Ltmp4:
182 //     .cfi_offset w27, -24
183 //  Ltmp5:
184 //     .cfi_offset w28, -32
185 //
186 //===----------------------------------------------------------------------===//
187 
188 #include "AArch64FrameLowering.h"
189 #include "AArch64InstrInfo.h"
190 #include "AArch64MachineFunctionInfo.h"
191 #include "AArch64RegisterInfo.h"
192 #include "AArch64ReturnProtectorLowering.h"
193 #include "AArch64Subtarget.h"
194 #include "AArch64TargetMachine.h"
195 #include "MCTargetDesc/AArch64AddressingModes.h"
196 #include "MCTargetDesc/AArch64MCTargetDesc.h"
197 #include "llvm/ADT/ScopeExit.h"
198 #include "llvm/ADT/SmallVector.h"
199 #include "llvm/ADT/Statistic.h"
200 #include "llvm/CodeGen/LivePhysRegs.h"
201 #include "llvm/CodeGen/MachineBasicBlock.h"
202 #include "llvm/CodeGen/MachineFrameInfo.h"
203 #include "llvm/CodeGen/MachineFunction.h"
204 #include "llvm/CodeGen/MachineInstr.h"
205 #include "llvm/CodeGen/MachineInstrBuilder.h"
206 #include "llvm/CodeGen/MachineMemOperand.h"
207 #include "llvm/CodeGen/MachineModuleInfo.h"
208 #include "llvm/CodeGen/MachineOperand.h"
209 #include "llvm/CodeGen/MachineRegisterInfo.h"
210 #include "llvm/CodeGen/RegisterScavenging.h"
211 #include "llvm/CodeGen/TargetInstrInfo.h"
212 #include "llvm/CodeGen/TargetRegisterInfo.h"
213 #include "llvm/CodeGen/TargetSubtargetInfo.h"
214 #include "llvm/CodeGen/WinEHFuncInfo.h"
215 #include "llvm/IR/Attributes.h"
216 #include "llvm/IR/CallingConv.h"
217 #include "llvm/IR/DataLayout.h"
218 #include "llvm/IR/DebugLoc.h"
219 #include "llvm/IR/Function.h"
220 #include "llvm/MC/MCAsmInfo.h"
221 #include "llvm/MC/MCDwarf.h"
222 #include "llvm/Support/CommandLine.h"
223 #include "llvm/Support/Debug.h"
224 #include "llvm/Support/ErrorHandling.h"
225 #include "llvm/Support/MathExtras.h"
226 #include "llvm/Support/raw_ostream.h"
227 #include "llvm/Target/TargetMachine.h"
228 #include "llvm/Target/TargetOptions.h"
229 #include <cassert>
230 #include <cstdint>
231 #include <iterator>
232 #include <optional>
233 #include <vector>
234 
235 using namespace llvm;
236 
237 #define DEBUG_TYPE "frame-info"
238 
239 static cl::opt<bool> EnableRedZone("aarch64-redzone",
240                                    cl::desc("enable use of redzone on AArch64"),
241                                    cl::init(false), cl::Hidden);
242 
243 static cl::opt<bool>
244     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
245                          cl::desc("reverse the CSR restore sequence"),
246                          cl::init(false), cl::Hidden);
247 
248 static cl::opt<bool> StackTaggingMergeSetTag(
249     "stack-tagging-merge-settag",
250     cl::desc("merge settag instruction in function epilog"), cl::init(true),
251     cl::Hidden);
252 
253 static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects",
254                                        cl::desc("sort stack allocations"),
255                                        cl::init(true), cl::Hidden);
256 
257 cl::opt<bool> EnableHomogeneousPrologEpilog(
258     "homogeneous-prolog-epilog", cl::Hidden,
259     cl::desc("Emit homogeneous prologue and epilogue for the size "
260              "optimization (default = off)"));
261 
262 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
263 
264 /// Returns how much of the incoming argument stack area (in bytes) we should
265 /// clean up in an epilogue. For the C calling convention this will be 0, for
266 /// guaranteed tail call conventions it can be positive (a normal return or a
267 /// tail call to a function that uses less stack space for arguments) or
268 /// negative (for a tail call to a function that needs more stack space than us
269 /// for arguments).
getArgumentStackToRestore(MachineFunction & MF,MachineBasicBlock & MBB)270 static int64_t getArgumentStackToRestore(MachineFunction &MF,
271                                          MachineBasicBlock &MBB) {
272   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
273   bool IsTailCallReturn = false;
274   if (MBB.end() != MBBI) {
275     unsigned RetOpcode = MBBI->getOpcode();
276     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
277                        RetOpcode == AArch64::TCRETURNri ||
278                        RetOpcode == AArch64::TCRETURNriBTI;
279   }
280   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
281 
282   int64_t ArgumentPopSize = 0;
283   if (IsTailCallReturn) {
284     MachineOperand &StackAdjust = MBBI->getOperand(1);
285 
286     // For a tail-call in a callee-pops-arguments environment, some or all of
287     // the stack may actually be in use for the call's arguments, this is
288     // calculated during LowerCall and consumed here...
289     ArgumentPopSize = StackAdjust.getImm();
290   } else {
291     // ... otherwise the amount to pop is *all* of the argument space,
292     // conveniently stored in the MachineFunctionInfo by
293     // LowerFormalArguments. This will, of course, be zero for the C calling
294     // convention.
295     ArgumentPopSize = AFI->getArgumentStackToRestore();
296   }
297 
298   return ArgumentPopSize;
299 }
300 
301 static bool produceCompactUnwindFrame(MachineFunction &MF);
302 static bool needsWinCFI(const MachineFunction &MF);
303 static StackOffset getSVEStackSize(const MachineFunction &MF);
304 static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF);
305 
306 /// Returns true if a homogeneous prolog or epilog code can be emitted
307 /// for the size optimization. If possible, a frame helper call is injected.
308 /// When Exit block is given, this check is for epilog.
homogeneousPrologEpilog(MachineFunction & MF,MachineBasicBlock * Exit) const309 bool AArch64FrameLowering::homogeneousPrologEpilog(
310     MachineFunction &MF, MachineBasicBlock *Exit) const {
311   if (!MF.getFunction().hasMinSize())
312     return false;
313   if (!EnableHomogeneousPrologEpilog)
314     return false;
315   if (ReverseCSRRestoreSeq)
316     return false;
317   if (EnableRedZone)
318     return false;
319 
320   // TODO: Window is supported yet.
321   if (needsWinCFI(MF))
322     return false;
323   // TODO: SVE is not supported yet.
324   if (getSVEStackSize(MF))
325     return false;
326 
327   // Bail on stack adjustment needed on return for simplicity.
328   const MachineFrameInfo &MFI = MF.getFrameInfo();
329   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
330   if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))
331     return false;
332   if (Exit && getArgumentStackToRestore(MF, *Exit))
333     return false;
334 
335   return true;
336 }
337 
338 /// Returns true if CSRs should be paired.
producePairRegisters(MachineFunction & MF) const339 bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {
340   return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF);
341 }
342 
343 /// This is the biggest offset to the stack pointer we can encode in aarch64
344 /// instructions (without using a separate calculation and a temp register).
345 /// Note that the exception here are vector stores/loads which cannot encode any
346 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
347 static const unsigned DefaultSafeSPDisplacement = 255;
348 
349 /// Look at each instruction that references stack frames and return the stack
350 /// size limit beyond which some of these instructions will require a scratch
351 /// register during their expansion later.
estimateRSStackSizeLimit(MachineFunction & MF)352 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
353   // FIXME: For now, just conservatively guestimate based on unscaled indexing
354   // range. We'll end up allocating an unnecessary spill slot a lot, but
355   // realistically that's not a big deal at this stage of the game.
356   for (MachineBasicBlock &MBB : MF) {
357     for (MachineInstr &MI : MBB) {
358       if (MI.isDebugInstr() || MI.isPseudo() ||
359           MI.getOpcode() == AArch64::ADDXri ||
360           MI.getOpcode() == AArch64::ADDSXri)
361         continue;
362 
363       for (const MachineOperand &MO : MI.operands()) {
364         if (!MO.isFI())
365           continue;
366 
367         StackOffset Offset;
368         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
369             AArch64FrameOffsetCannotUpdate)
370           return 0;
371       }
372     }
373   }
374   return DefaultSafeSPDisplacement;
375 }
376 
377 TargetStackID::Value
getStackIDForScalableVectors() const378 AArch64FrameLowering::getStackIDForScalableVectors() const {
379   return TargetStackID::ScalableVector;
380 }
381 
382 /// Returns the size of the fixed object area (allocated next to sp on entry)
383 /// On Win64 this may include a var args area and an UnwindHelp object for EH.
getFixedObjectSize(const MachineFunction & MF,const AArch64FunctionInfo * AFI,bool IsWin64,bool IsFunclet)384 static unsigned getFixedObjectSize(const MachineFunction &MF,
385                                    const AArch64FunctionInfo *AFI, bool IsWin64,
386                                    bool IsFunclet) {
387   if (!IsWin64 || IsFunclet) {
388     return AFI->getTailCallReservedStack();
389   } else {
390     if (AFI->getTailCallReservedStack() != 0)
391       report_fatal_error("cannot generate ABI-changing tail call for Win64");
392     // Var args are stored here in the primary function.
393     const unsigned VarArgsArea = AFI->getVarArgsGPRSize();
394     // To support EH funclets we allocate an UnwindHelp object
395     const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0);
396     return alignTo(VarArgsArea + UnwindHelpObject, 16);
397   }
398 }
399 
400 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
getSVEStackSize(const MachineFunction & MF)401 static StackOffset getSVEStackSize(const MachineFunction &MF) {
402   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
403   return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE());
404 }
405 
canUseRedZone(const MachineFunction & MF) const406 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
407   if (!EnableRedZone)
408     return false;
409 
410   // Don't use the red zone if the function explicitly asks us not to.
411   // This is typically used for kernel code.
412   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
413   const unsigned RedZoneSize =
414       Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
415   if (!RedZoneSize)
416     return false;
417 
418   const MachineFrameInfo &MFI = MF.getFrameInfo();
419   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
420   uint64_t NumBytes = AFI->getLocalStackSize();
421 
422   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||
423            getSVEStackSize(MF));
424 }
425 
426 /// hasFP - Return true if the specified function should have a dedicated frame
427 /// pointer register.
hasFP(const MachineFunction & MF) const428 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
429   const MachineFrameInfo &MFI = MF.getFrameInfo();
430   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
431   // Win64 EH requires a frame pointer if funclets are present, as the locals
432   // are accessed off the frame pointer in both the parent function and the
433   // funclets.
434   if (MF.hasEHFunclets())
435     return true;
436   // Retain behavior of always omitting the FP for leaf functions when possible.
437   if (MF.getTarget().Options.DisableFramePointerElim(MF))
438     return true;
439   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
440       MFI.hasStackMap() || MFI.hasPatchPoint() ||
441       RegInfo->hasStackRealignment(MF))
442     return true;
443   // With large callframes around we may need to use FP to access the scavenging
444   // emergency spillslot.
445   //
446   // Unfortunately some calls to hasFP() like machine verifier ->
447   // getReservedReg() -> hasFP in the middle of global isel are too early
448   // to know the max call frame size. Hopefully conservatively returning "true"
449   // in those cases is fine.
450   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
451   if (!MFI.isMaxCallFrameSizeComputed() ||
452       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
453     return true;
454 
455   return false;
456 }
457 
458 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
459 /// not required, we reserve argument space for call sites in the function
460 /// immediately on entry to the current function.  This eliminates the need for
461 /// add/sub sp brackets around call sites.  Returns true if the call frame is
462 /// included as part of the stack frame.
463 bool
hasReservedCallFrame(const MachineFunction & MF) const464 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
465   return !MF.getFrameInfo().hasVarSizedObjects();
466 }
467 
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const468 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
469     MachineFunction &MF, MachineBasicBlock &MBB,
470     MachineBasicBlock::iterator I) const {
471   const AArch64InstrInfo *TII =
472       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
473   DebugLoc DL = I->getDebugLoc();
474   unsigned Opc = I->getOpcode();
475   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
476   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
477 
478   if (!hasReservedCallFrame(MF)) {
479     int64_t Amount = I->getOperand(0).getImm();
480     Amount = alignTo(Amount, getStackAlign());
481     if (!IsDestroy)
482       Amount = -Amount;
483 
484     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
485     // doesn't have to pop anything), then the first operand will be zero too so
486     // this adjustment is a no-op.
487     if (CalleePopAmount == 0) {
488       // FIXME: in-function stack adjustment for calls is limited to 24-bits
489       // because there's no guaranteed temporary register available.
490       //
491       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
492       // 1) For offset <= 12-bit, we use LSL #0
493       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
494       // LSL #0, and the other uses LSL #12.
495       //
496       // Most call frames will be allocated at the start of a function so
497       // this is OK, but it is a limitation that needs dealing with.
498       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
499       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
500                       StackOffset::getFixed(Amount), TII);
501     }
502   } else if (CalleePopAmount != 0) {
503     // If the calling convention demands that the callee pops arguments from the
504     // stack, we want to add it back if we have a reserved call frame.
505     assert(CalleePopAmount < 0xffffff && "call frame too large");
506     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
507                     StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);
508   }
509   return MBB.erase(I);
510 }
511 
emitCalleeSavedGPRLocations(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI) const512 void AArch64FrameLowering::emitCalleeSavedGPRLocations(
513     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
514   MachineFunction &MF = *MBB.getParent();
515   MachineFrameInfo &MFI = MF.getFrameInfo();
516 
517   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
518   if (CSI.empty())
519     return;
520 
521   const TargetSubtargetInfo &STI = MF.getSubtarget();
522   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
523   const TargetInstrInfo &TII = *STI.getInstrInfo();
524   DebugLoc DL = MBB.findDebugLoc(MBBI);
525 
526   for (const auto &Info : CSI) {
527     if (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector)
528       continue;
529 
530     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
531     unsigned DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true);
532 
533     int64_t Offset =
534         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
535     unsigned CFIIndex = MF.addFrameInst(
536         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
537     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
538         .addCFIIndex(CFIIndex)
539         .setMIFlags(MachineInstr::FrameSetup);
540   }
541 }
542 
emitCalleeSavedSVELocations(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI) const543 void AArch64FrameLowering::emitCalleeSavedSVELocations(
544     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
545   MachineFunction &MF = *MBB.getParent();
546   MachineFrameInfo &MFI = MF.getFrameInfo();
547 
548   // Add callee saved registers to move list.
549   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
550   if (CSI.empty())
551     return;
552 
553   const TargetSubtargetInfo &STI = MF.getSubtarget();
554   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
555   const TargetInstrInfo &TII = *STI.getInstrInfo();
556   DebugLoc DL = MBB.findDebugLoc(MBBI);
557   AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
558 
559   for (const auto &Info : CSI) {
560     if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
561       continue;
562 
563     // Not all unwinders may know about SVE registers, so assume the lowest
564     // common demoninator.
565     assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
566     unsigned Reg = Info.getReg();
567     if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
568       continue;
569 
570     StackOffset Offset =
571         StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) -
572         StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI));
573 
574     unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset));
575     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
576         .addCFIIndex(CFIIndex)
577         .setMIFlags(MachineInstr::FrameSetup);
578   }
579 }
580 
insertCFISameValue(const MCInstrDesc & Desc,MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertPt,unsigned DwarfReg)581 static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF,
582                                MachineBasicBlock &MBB,
583                                MachineBasicBlock::iterator InsertPt,
584                                unsigned DwarfReg) {
585   unsigned CFIIndex =
586       MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg));
587   BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex);
588 }
589 
resetCFIToInitialState(MachineBasicBlock & MBB) const590 void AArch64FrameLowering::resetCFIToInitialState(
591     MachineBasicBlock &MBB) const {
592 
593   MachineFunction &MF = *MBB.getParent();
594   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
595   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
596   const auto &TRI =
597       static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo());
598   const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
599 
600   const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION);
601   DebugLoc DL;
602 
603   // Reset the CFA to `SP + 0`.
604   MachineBasicBlock::iterator InsertPt = MBB.begin();
605   unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
606       nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0));
607   BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
608 
609   // Flip the RA sign state.
610   if (MFI.shouldSignReturnAddress(MF)) {
611     CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
612     BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
613   }
614 
615   // Shadow call stack uses X18, reset it.
616   if (needsShadowCallStackPrologueEpilogue(MF))
617     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
618                        TRI.getDwarfRegNum(AArch64::X18, true));
619 
620   // Emit .cfi_same_value for callee-saved registers.
621   const std::vector<CalleeSavedInfo> &CSI =
622       MF.getFrameInfo().getCalleeSavedInfo();
623   for (const auto &Info : CSI) {
624     unsigned Reg = Info.getReg();
625     if (!TRI.regNeedsCFI(Reg, Reg))
626       continue;
627     insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
628                        TRI.getDwarfRegNum(Reg, true));
629   }
630 }
631 
emitCalleeSavedRestores(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,bool SVE)632 static void emitCalleeSavedRestores(MachineBasicBlock &MBB,
633                                     MachineBasicBlock::iterator MBBI,
634                                     bool SVE) {
635   MachineFunction &MF = *MBB.getParent();
636   MachineFrameInfo &MFI = MF.getFrameInfo();
637 
638   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
639   if (CSI.empty())
640     return;
641 
642   const TargetSubtargetInfo &STI = MF.getSubtarget();
643   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
644   const TargetInstrInfo &TII = *STI.getInstrInfo();
645   DebugLoc DL = MBB.findDebugLoc(MBBI);
646 
647   for (const auto &Info : CSI) {
648     if (SVE !=
649         (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
650       continue;
651 
652     unsigned Reg = Info.getReg();
653     if (SVE &&
654         !static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
655       continue;
656 
657     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(
658         nullptr, TRI.getDwarfRegNum(Info.getReg(), true)));
659     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
660         .addCFIIndex(CFIIndex)
661         .setMIFlags(MachineInstr::FrameDestroy);
662   }
663 }
664 
emitCalleeSavedGPRRestores(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI) const665 void AArch64FrameLowering::emitCalleeSavedGPRRestores(
666     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
667   emitCalleeSavedRestores(MBB, MBBI, false);
668 }
669 
emitCalleeSavedSVERestores(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI) const670 void AArch64FrameLowering::emitCalleeSavedSVERestores(
671     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
672   emitCalleeSavedRestores(MBB, MBBI, true);
673 }
674 
getRegisterOrZero(MCRegister Reg,bool HasSVE)675 static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) {
676   switch (Reg.id()) {
677   default:
678     // The called routine is expected to preserve r19-r28
679     // r29 and r30 are used as frame pointer and link register resp.
680     return 0;
681 
682     // GPRs
683 #define CASE(n)                                                                \
684   case AArch64::W##n:                                                          \
685   case AArch64::X##n:                                                          \
686     return AArch64::X##n
687   CASE(0);
688   CASE(1);
689   CASE(2);
690   CASE(3);
691   CASE(4);
692   CASE(5);
693   CASE(6);
694   CASE(7);
695   CASE(8);
696   CASE(9);
697   CASE(10);
698   CASE(11);
699   CASE(12);
700   CASE(13);
701   CASE(14);
702   CASE(15);
703   CASE(16);
704   CASE(17);
705   CASE(18);
706 #undef CASE
707 
708     // FPRs
709 #define CASE(n)                                                                \
710   case AArch64::B##n:                                                          \
711   case AArch64::H##n:                                                          \
712   case AArch64::S##n:                                                          \
713   case AArch64::D##n:                                                          \
714   case AArch64::Q##n:                                                          \
715     return HasSVE ? AArch64::Z##n : AArch64::Q##n
716   CASE(0);
717   CASE(1);
718   CASE(2);
719   CASE(3);
720   CASE(4);
721   CASE(5);
722   CASE(6);
723   CASE(7);
724   CASE(8);
725   CASE(9);
726   CASE(10);
727   CASE(11);
728   CASE(12);
729   CASE(13);
730   CASE(14);
731   CASE(15);
732   CASE(16);
733   CASE(17);
734   CASE(18);
735   CASE(19);
736   CASE(20);
737   CASE(21);
738   CASE(22);
739   CASE(23);
740   CASE(24);
741   CASE(25);
742   CASE(26);
743   CASE(27);
744   CASE(28);
745   CASE(29);
746   CASE(30);
747   CASE(31);
748 #undef CASE
749   }
750 }
751 
emitZeroCallUsedRegs(BitVector RegsToZero,MachineBasicBlock & MBB) const752 void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
753                                                 MachineBasicBlock &MBB) const {
754   // Insertion point.
755   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
756 
757   // Fake a debug loc.
758   DebugLoc DL;
759   if (MBBI != MBB.end())
760     DL = MBBI->getDebugLoc();
761 
762   const MachineFunction &MF = *MBB.getParent();
763   const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
764   const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
765 
766   BitVector GPRsToZero(TRI.getNumRegs());
767   BitVector FPRsToZero(TRI.getNumRegs());
768   bool HasSVE = STI.hasSVE();
769   for (MCRegister Reg : RegsToZero.set_bits()) {
770     if (TRI.isGeneralPurposeRegister(MF, Reg)) {
771       // For GPRs, we only care to clear out the 64-bit register.
772       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
773         GPRsToZero.set(XReg);
774     } else if (AArch64::FPR128RegClass.contains(Reg) ||
775                AArch64::FPR64RegClass.contains(Reg) ||
776                AArch64::FPR32RegClass.contains(Reg) ||
777                AArch64::FPR16RegClass.contains(Reg) ||
778                AArch64::FPR8RegClass.contains(Reg)) {
779       // For FPRs,
780       if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
781         FPRsToZero.set(XReg);
782     }
783   }
784 
785   const AArch64InstrInfo &TII = *STI.getInstrInfo();
786 
787   // Zero out GPRs.
788   for (MCRegister Reg : GPRsToZero.set_bits())
789     BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), Reg).addImm(0);
790 
791   // Zero out FP/vector registers.
792   for (MCRegister Reg : FPRsToZero.set_bits())
793     if (HasSVE)
794       BuildMI(MBB, MBBI, DL, TII.get(AArch64::DUP_ZI_D), Reg)
795         .addImm(0)
796         .addImm(0);
797     else
798       BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVIv2d_ns), Reg).addImm(0);
799 
800   if (HasSVE) {
801     for (MCRegister PReg :
802          {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,
803           AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,
804           AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,
805           AArch64::P15}) {
806       if (RegsToZero[PReg])
807         BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);
808     }
809   }
810 }
811 
812 // Find a scratch register that we can use at the start of the prologue to
813 // re-align the stack pointer.  We avoid using callee-save registers since they
814 // may appear to be free when this is called from canUseAsPrologue (during
815 // shrink wrapping), but then no longer be free when this is called from
816 // emitPrologue.
817 //
818 // FIXME: This is a bit conservative, since in the above case we could use one
819 // of the callee-save registers as a scratch temp to re-align the stack pointer,
820 // but we would then have to make sure that we were in fact saving at least one
821 // callee-save register in the prologue, which is additional complexity that
822 // doesn't seem worth the benefit.
findScratchNonCalleeSaveRegister(MachineBasicBlock * MBB)823 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
824   MachineFunction *MF = MBB->getParent();
825 
826   // If MBB is an entry block, use X9 as the scratch register
827   if (&MF->front() == MBB)
828     return AArch64::X9;
829 
830   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
831   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
832   LivePhysRegs LiveRegs(TRI);
833   LiveRegs.addLiveIns(*MBB);
834 
835   // Mark callee saved registers as used so we will not choose them.
836   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
837   for (unsigned i = 0; CSRegs[i]; ++i)
838     LiveRegs.addReg(CSRegs[i]);
839 
840   // Prefer X9 since it was historically used for the prologue scratch reg.
841   const MachineRegisterInfo &MRI = MF->getRegInfo();
842   if (LiveRegs.available(MRI, AArch64::X9))
843     return AArch64::X9;
844 
845   for (unsigned Reg : AArch64::GPR64RegClass) {
846     if (LiveRegs.available(MRI, Reg))
847       return Reg;
848   }
849   return AArch64::NoRegister;
850 }
851 
canUseAsPrologue(const MachineBasicBlock & MBB) const852 bool AArch64FrameLowering::canUseAsPrologue(
853     const MachineBasicBlock &MBB) const {
854   const MachineFunction *MF = MBB.getParent();
855   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
856   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
857   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
858 
859   // Don't need a scratch register if we're not going to re-align the stack.
860   if (!RegInfo->hasStackRealignment(*MF))
861     return true;
862   // Otherwise, we can use any block as long as it has a scratch register
863   // available.
864   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
865 }
866 
windowsRequiresStackProbe(MachineFunction & MF,uint64_t StackSizeInBytes)867 static bool windowsRequiresStackProbe(MachineFunction &MF,
868                                       uint64_t StackSizeInBytes) {
869   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
870   if (!Subtarget.isTargetWindows())
871     return false;
872   const Function &F = MF.getFunction();
873   // TODO: When implementing stack protectors, take that into account
874   // for the probe threshold.
875   unsigned StackProbeSize =
876       F.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
877   return (StackSizeInBytes >= StackProbeSize) &&
878          !F.hasFnAttribute("no-stack-arg-probe");
879 }
880 
needsWinCFI(const MachineFunction & MF)881 static bool needsWinCFI(const MachineFunction &MF) {
882   const Function &F = MF.getFunction();
883   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
884          F.needsUnwindTableEntry();
885 }
886 
shouldCombineCSRLocalStackBump(MachineFunction & MF,uint64_t StackBumpBytes) const887 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
888     MachineFunction &MF, uint64_t StackBumpBytes) const {
889   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
890   const MachineFrameInfo &MFI = MF.getFrameInfo();
891   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
892   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
893   if (homogeneousPrologEpilog(MF))
894     return false;
895 
896   if (AFI->getLocalStackSize() == 0)
897     return false;
898 
899   // For WinCFI, if optimizing for size, prefer to not combine the stack bump
900   // (to force a stp with predecrement) to match the packed unwind format,
901   // provided that there actually are any callee saved registers to merge the
902   // decrement with.
903   // This is potentially marginally slower, but allows using the packed
904   // unwind format for functions that both have a local area and callee saved
905   // registers. Using the packed unwind format notably reduces the size of
906   // the unwind info.
907   if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 &&
908       MF.getFunction().hasOptSize())
909     return false;
910 
911   // 512 is the maximum immediate for stp/ldp that will be used for
912   // callee-save save/restores
913   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
914     return false;
915 
916   if (MFI.hasVarSizedObjects())
917     return false;
918 
919   if (RegInfo->hasStackRealignment(MF))
920     return false;
921 
922   // This isn't strictly necessary, but it simplifies things a bit since the
923   // current RedZone handling code assumes the SP is adjusted by the
924   // callee-save save/restore code.
925   if (canUseRedZone(MF))
926     return false;
927 
928   // When there is an SVE area on the stack, always allocate the
929   // callee-saves and spills/locals separately.
930   if (getSVEStackSize(MF))
931     return false;
932 
933   return true;
934 }
935 
shouldCombineCSRLocalStackBumpInEpilogue(MachineBasicBlock & MBB,unsigned StackBumpBytes) const936 bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(
937     MachineBasicBlock &MBB, unsigned StackBumpBytes) const {
938   if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes))
939     return false;
940 
941   if (MBB.empty())
942     return true;
943 
944   // Disable combined SP bump if the last instruction is an MTE tag store. It
945   // is almost always better to merge SP adjustment into those instructions.
946   MachineBasicBlock::iterator LastI = MBB.getFirstTerminator();
947   MachineBasicBlock::iterator Begin = MBB.begin();
948   while (LastI != Begin) {
949     --LastI;
950     if (LastI->isTransient())
951       continue;
952     if (!LastI->getFlag(MachineInstr::FrameDestroy))
953       break;
954   }
955   switch (LastI->getOpcode()) {
956   case AArch64::STGloop:
957   case AArch64::STZGloop:
958   case AArch64::STGOffset:
959   case AArch64::STZGOffset:
960   case AArch64::ST2GOffset:
961   case AArch64::STZ2GOffset:
962     return false;
963   default:
964     return true;
965   }
966   llvm_unreachable("unreachable");
967 }
968 
969 // Given a load or a store instruction, generate an appropriate unwinding SEH
970 // code on Windows.
InsertSEH(MachineBasicBlock::iterator MBBI,const TargetInstrInfo & TII,MachineInstr::MIFlag Flag)971 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
972                                              const TargetInstrInfo &TII,
973                                              MachineInstr::MIFlag Flag) {
974   unsigned Opc = MBBI->getOpcode();
975   MachineBasicBlock *MBB = MBBI->getParent();
976   MachineFunction &MF = *MBB->getParent();
977   DebugLoc DL = MBBI->getDebugLoc();
978   unsigned ImmIdx = MBBI->getNumOperands() - 1;
979   int Imm = MBBI->getOperand(ImmIdx).getImm();
980   MachineInstrBuilder MIB;
981   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
982   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
983 
984   switch (Opc) {
985   default:
986     llvm_unreachable("No SEH Opcode for this instruction");
987   case AArch64::LDPDpost:
988     Imm = -Imm;
989     [[fallthrough]];
990   case AArch64::STPDpre: {
991     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
992     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
993     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
994               .addImm(Reg0)
995               .addImm(Reg1)
996               .addImm(Imm * 8)
997               .setMIFlag(Flag);
998     break;
999   }
1000   case AArch64::LDPXpost:
1001     Imm = -Imm;
1002     [[fallthrough]];
1003   case AArch64::STPXpre: {
1004     Register Reg0 = MBBI->getOperand(1).getReg();
1005     Register Reg1 = MBBI->getOperand(2).getReg();
1006     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1007       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
1008                 .addImm(Imm * 8)
1009                 .setMIFlag(Flag);
1010     else
1011       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
1012                 .addImm(RegInfo->getSEHRegNum(Reg0))
1013                 .addImm(RegInfo->getSEHRegNum(Reg1))
1014                 .addImm(Imm * 8)
1015                 .setMIFlag(Flag);
1016     break;
1017   }
1018   case AArch64::LDRDpost:
1019     Imm = -Imm;
1020     [[fallthrough]];
1021   case AArch64::STRDpre: {
1022     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1023     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
1024               .addImm(Reg)
1025               .addImm(Imm)
1026               .setMIFlag(Flag);
1027     break;
1028   }
1029   case AArch64::LDRXpost:
1030     Imm = -Imm;
1031     [[fallthrough]];
1032   case AArch64::STRXpre: {
1033     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1034     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
1035               .addImm(Reg)
1036               .addImm(Imm)
1037               .setMIFlag(Flag);
1038     break;
1039   }
1040   case AArch64::STPDi:
1041   case AArch64::LDPDi: {
1042     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1043     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1044     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
1045               .addImm(Reg0)
1046               .addImm(Reg1)
1047               .addImm(Imm * 8)
1048               .setMIFlag(Flag);
1049     break;
1050   }
1051   case AArch64::STPXi:
1052   case AArch64::LDPXi: {
1053     Register Reg0 = MBBI->getOperand(0).getReg();
1054     Register Reg1 = MBBI->getOperand(1).getReg();
1055     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1056       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
1057                 .addImm(Imm * 8)
1058                 .setMIFlag(Flag);
1059     else
1060       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
1061                 .addImm(RegInfo->getSEHRegNum(Reg0))
1062                 .addImm(RegInfo->getSEHRegNum(Reg1))
1063                 .addImm(Imm * 8)
1064                 .setMIFlag(Flag);
1065     break;
1066   }
1067   case AArch64::STRXui:
1068   case AArch64::LDRXui: {
1069     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1070     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
1071               .addImm(Reg)
1072               .addImm(Imm * 8)
1073               .setMIFlag(Flag);
1074     break;
1075   }
1076   case AArch64::STRDui:
1077   case AArch64::LDRDui: {
1078     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1079     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
1080               .addImm(Reg)
1081               .addImm(Imm * 8)
1082               .setMIFlag(Flag);
1083     break;
1084   }
1085   }
1086   auto I = MBB->insertAfter(MBBI, MIB);
1087   return I;
1088 }
1089 
1090 // Fix up the SEH opcode associated with the save/restore instruction.
fixupSEHOpcode(MachineBasicBlock::iterator MBBI,unsigned LocalStackSize)1091 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
1092                            unsigned LocalStackSize) {
1093   MachineOperand *ImmOpnd = nullptr;
1094   unsigned ImmIdx = MBBI->getNumOperands() - 1;
1095   switch (MBBI->getOpcode()) {
1096   default:
1097     llvm_unreachable("Fix the offset in the SEH instruction");
1098   case AArch64::SEH_SaveFPLR:
1099   case AArch64::SEH_SaveRegP:
1100   case AArch64::SEH_SaveReg:
1101   case AArch64::SEH_SaveFRegP:
1102   case AArch64::SEH_SaveFReg:
1103     ImmOpnd = &MBBI->getOperand(ImmIdx);
1104     break;
1105   }
1106   if (ImmOpnd)
1107     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
1108 }
1109 
1110 // Convert callee-save register save/restore instruction to do stack pointer
1111 // decrement/increment to allocate/deallocate the callee-save stack area by
1112 // converting store/load to use pre/post increment version.
convertCalleeSaveRestoreToSPPrePostIncDec(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,const TargetInstrInfo * TII,int CSStackSizeInc,bool NeedsWinCFI,bool * HasWinCFI,bool EmitCFI,MachineInstr::MIFlag FrameFlag=MachineInstr::FrameSetup,int CFAOffset=0)1113 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
1114     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
1115     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
1116     bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI,
1117     MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup,
1118     int CFAOffset = 0) {
1119   unsigned NewOpc;
1120   switch (MBBI->getOpcode()) {
1121   default:
1122     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1123   case AArch64::STPXi:
1124     NewOpc = AArch64::STPXpre;
1125     break;
1126   case AArch64::STPDi:
1127     NewOpc = AArch64::STPDpre;
1128     break;
1129   case AArch64::STPQi:
1130     NewOpc = AArch64::STPQpre;
1131     break;
1132   case AArch64::STRXui:
1133     NewOpc = AArch64::STRXpre;
1134     break;
1135   case AArch64::STRDui:
1136     NewOpc = AArch64::STRDpre;
1137     break;
1138   case AArch64::STRQui:
1139     NewOpc = AArch64::STRQpre;
1140     break;
1141   case AArch64::LDPXi:
1142     NewOpc = AArch64::LDPXpost;
1143     break;
1144   case AArch64::LDPDi:
1145     NewOpc = AArch64::LDPDpost;
1146     break;
1147   case AArch64::LDPQi:
1148     NewOpc = AArch64::LDPQpost;
1149     break;
1150   case AArch64::LDRXui:
1151     NewOpc = AArch64::LDRXpost;
1152     break;
1153   case AArch64::LDRDui:
1154     NewOpc = AArch64::LDRDpost;
1155     break;
1156   case AArch64::LDRQui:
1157     NewOpc = AArch64::LDRQpost;
1158     break;
1159   }
1160   // Get rid of the SEH code associated with the old instruction.
1161   if (NeedsWinCFI) {
1162     auto SEH = std::next(MBBI);
1163     if (AArch64InstrInfo::isSEHInstruction(*SEH))
1164       SEH->eraseFromParent();
1165   }
1166 
1167   TypeSize Scale = TypeSize::Fixed(1);
1168   unsigned Width;
1169   int64_t MinOffset, MaxOffset;
1170   bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo(
1171       NewOpc, Scale, Width, MinOffset, MaxOffset);
1172   (void)Success;
1173   assert(Success && "unknown load/store opcode");
1174 
1175   // If the first store isn't right where we want SP then we can't fold the
1176   // update in so create a normal arithmetic instruction instead.
1177   MachineFunction &MF = *MBB.getParent();
1178   if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 ||
1179       CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) {
1180     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1181                     StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag,
1182                     false, false, nullptr, EmitCFI,
1183                     StackOffset::getFixed(CFAOffset));
1184 
1185     return std::prev(MBBI);
1186   }
1187 
1188   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1189   MIB.addReg(AArch64::SP, RegState::Define);
1190 
1191   // Copy all operands other than the immediate offset.
1192   unsigned OpndIdx = 0;
1193   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
1194        ++OpndIdx)
1195     MIB.add(MBBI->getOperand(OpndIdx));
1196 
1197   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
1198          "Unexpected immediate offset in first/last callee-save save/restore "
1199          "instruction!");
1200   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
1201          "Unexpected base register in callee-save save/restore instruction!");
1202   assert(CSStackSizeInc % Scale == 0);
1203   MIB.addImm(CSStackSizeInc / (int)Scale);
1204 
1205   MIB.setMIFlags(MBBI->getFlags());
1206   MIB.setMemRefs(MBBI->memoperands());
1207 
1208   // Generate a new SEH code that corresponds to the new instruction.
1209   if (NeedsWinCFI) {
1210     *HasWinCFI = true;
1211     InsertSEH(*MIB, *TII, FrameFlag);
1212   }
1213 
1214   if (EmitCFI) {
1215     unsigned CFIIndex = MF.addFrameInst(
1216         MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc));
1217     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1218         .addCFIIndex(CFIIndex)
1219         .setMIFlags(FrameFlag);
1220   }
1221 
1222   return std::prev(MBB.erase(MBBI));
1223 }
1224 
1225 // Fixup callee-save register save/restore instructions to take into account
1226 // combined SP bump by adding the local stack size to the stack offsets.
fixupCalleeSaveRestoreStackOffset(MachineInstr & MI,uint64_t LocalStackSize,bool NeedsWinCFI,bool * HasWinCFI)1227 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
1228                                               uint64_t LocalStackSize,
1229                                               bool NeedsWinCFI,
1230                                               bool *HasWinCFI) {
1231   if (AArch64InstrInfo::isSEHInstruction(MI))
1232     return;
1233 
1234   unsigned Opc = MI.getOpcode();
1235   unsigned Scale;
1236   switch (Opc) {
1237   case AArch64::STPXi:
1238   case AArch64::STRXui:
1239   case AArch64::STPDi:
1240   case AArch64::STRDui:
1241   case AArch64::LDPXi:
1242   case AArch64::LDRXui:
1243   case AArch64::LDPDi:
1244   case AArch64::LDRDui:
1245     Scale = 8;
1246     break;
1247   case AArch64::STPQi:
1248   case AArch64::STRQui:
1249   case AArch64::LDPQi:
1250   case AArch64::LDRQui:
1251     Scale = 16;
1252     break;
1253   default:
1254     llvm_unreachable("Unexpected callee-save save/restore opcode!");
1255   }
1256 
1257   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
1258   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
1259          "Unexpected base register in callee-save save/restore instruction!");
1260   // Last operand is immediate offset that needs fixing.
1261   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
1262   // All generated opcodes have scaled offsets.
1263   assert(LocalStackSize % Scale == 0);
1264   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
1265 
1266   if (NeedsWinCFI) {
1267     *HasWinCFI = true;
1268     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
1269     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
1270     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
1271            "Expecting a SEH instruction");
1272     fixupSEHOpcode(MBBI, LocalStackSize);
1273   }
1274 }
1275 
isTargetWindows(const MachineFunction & MF)1276 static bool isTargetWindows(const MachineFunction &MF) {
1277   return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();
1278 }
1279 
1280 // Convenience function to determine whether I is an SVE callee save.
IsSVECalleeSave(MachineBasicBlock::iterator I)1281 static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
1282   switch (I->getOpcode()) {
1283   default:
1284     return false;
1285   case AArch64::STR_ZXI:
1286   case AArch64::STR_PXI:
1287   case AArch64::LDR_ZXI:
1288   case AArch64::LDR_PXI:
1289     return I->getFlag(MachineInstr::FrameSetup) ||
1290            I->getFlag(MachineInstr::FrameDestroy);
1291   }
1292 }
1293 
needsShadowCallStackPrologueEpilogue(MachineFunction & MF)1294 static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF) {
1295   if (!(llvm::any_of(
1296             MF.getFrameInfo().getCalleeSavedInfo(),
1297             [](const auto &Info) { return Info.getReg() == AArch64::LR; }) &&
1298         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)))
1299     return false;
1300 
1301   if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
1302     report_fatal_error("Must reserve x18 to use shadow call stack");
1303 
1304   return true;
1305 }
1306 
emitShadowCallStackPrologue(const TargetInstrInfo & TII,MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,bool NeedsWinCFI,bool NeedsUnwindInfo)1307 static void emitShadowCallStackPrologue(const TargetInstrInfo &TII,
1308                                         MachineFunction &MF,
1309                                         MachineBasicBlock &MBB,
1310                                         MachineBasicBlock::iterator MBBI,
1311                                         const DebugLoc &DL, bool NeedsWinCFI,
1312                                         bool NeedsUnwindInfo) {
1313   // Shadow call stack prolog: str x30, [x18], #8
1314   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost))
1315       .addReg(AArch64::X18, RegState::Define)
1316       .addReg(AArch64::LR)
1317       .addReg(AArch64::X18)
1318       .addImm(8)
1319       .setMIFlag(MachineInstr::FrameSetup);
1320 
1321   // This instruction also makes x18 live-in to the entry block.
1322   MBB.addLiveIn(AArch64::X18);
1323 
1324   if (NeedsWinCFI)
1325     BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop))
1326         .setMIFlag(MachineInstr::FrameSetup);
1327 
1328   if (NeedsUnwindInfo) {
1329     // Emit a CFI instruction that causes 8 to be subtracted from the value of
1330     // x18 when unwinding past this frame.
1331     static const char CFIInst[] = {
1332         dwarf::DW_CFA_val_expression,
1333         18, // register
1334         2,  // length
1335         static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1336         static_cast<char>(-8) & 0x7f, // addend (sleb128)
1337     };
1338     unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
1339         nullptr, StringRef(CFIInst, sizeof(CFIInst))));
1340     BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1341         .addCFIIndex(CFIIndex)
1342         .setMIFlag(MachineInstr::FrameSetup);
1343   }
1344 }
1345 
emitShadowCallStackEpilogue(const TargetInstrInfo & TII,MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL)1346 static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII,
1347                                         MachineFunction &MF,
1348                                         MachineBasicBlock &MBB,
1349                                         MachineBasicBlock::iterator MBBI,
1350                                         const DebugLoc &DL) {
1351   // Shadow call stack epilog: ldr x30, [x18, #-8]!
1352   BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre))
1353       .addReg(AArch64::X18, RegState::Define)
1354       .addReg(AArch64::LR, RegState::Define)
1355       .addReg(AArch64::X18)
1356       .addImm(-8)
1357       .setMIFlag(MachineInstr::FrameDestroy);
1358 
1359   if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF)) {
1360     unsigned CFIIndex =
1361         MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));
1362     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1363         .addCFIIndex(CFIIndex)
1364         .setMIFlags(MachineInstr::FrameDestroy);
1365   }
1366 }
1367 
emitPrologue(MachineFunction & MF,MachineBasicBlock & MBB) const1368 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
1369                                         MachineBasicBlock &MBB) const {
1370   MachineBasicBlock::iterator MBBI = MBB.begin();
1371   const MachineFrameInfo &MFI = MF.getFrameInfo();
1372   const Function &F = MF.getFunction();
1373   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1374   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1375   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1376   MachineModuleInfo &MMI = MF.getMMI();
1377   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1378   bool EmitCFI = AFI->needsDwarfUnwindInfo(MF);
1379   bool HasFP = hasFP(MF);
1380   bool NeedsWinCFI = needsWinCFI(MF);
1381   bool HasWinCFI = false;
1382   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
1383 
1384   bool IsFunclet = MBB.isEHFuncletEntry();
1385 
1386   // At this point, we're going to decide whether or not the function uses a
1387   // redzone. In most cases, the function doesn't have a redzone so let's
1388   // assume that's false and set it to true in the case that there's a redzone.
1389   AFI->setHasRedZone(false);
1390 
1391   // Debug location must be unknown since the first debug location is used
1392   // to determine the end of the prologue.
1393   DebugLoc DL;
1394 
1395   const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
1396   if (needsShadowCallStackPrologueEpilogue(MF))
1397     emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI,
1398                                 MFnI.needsDwarfUnwindInfo(MF));
1399 
1400   if (MFnI.shouldSignReturnAddress(MF)) {
1401     if (MFnI.shouldSignWithBKey()) {
1402       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
1403           .setMIFlag(MachineInstr::FrameSetup);
1404     }
1405 
1406     // No SEH opcode for this one; it doesn't materialize into an
1407     // instruction on Windows.
1408     BuildMI(MBB, MBBI, DL,
1409             TII->get(MFnI.shouldSignWithBKey() ? AArch64::PACIBSP
1410                                                : AArch64::PACIASP))
1411         .setMIFlag(MachineInstr::FrameSetup);
1412 
1413     if (EmitCFI) {
1414       unsigned CFIIndex =
1415           MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1416       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1417           .addCFIIndex(CFIIndex)
1418           .setMIFlags(MachineInstr::FrameSetup);
1419     } else if (NeedsWinCFI) {
1420       HasWinCFI = true;
1421       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
1422           .setMIFlag(MachineInstr::FrameSetup);
1423     }
1424   }
1425   if (EmitCFI && MFnI.isMTETagged()) {
1426     BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITMTETAGGED))
1427         .setMIFlag(MachineInstr::FrameSetup);
1428   }
1429 
1430   // We signal the presence of a Swift extended frame to external tools by
1431   // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple
1432   // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI
1433   // bits so that is still true.
1434   if (HasFP && AFI->hasSwiftAsyncContext()) {
1435     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1436     case SwiftAsyncFramePointerMode::DeploymentBased:
1437       if (Subtarget.swiftAsyncContextIsDynamicallySet()) {
1438         // The special symbol below is absolute and has a *value* that can be
1439         // combined with the frame pointer to signal an extended frame.
1440         BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16)
1441             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1442                                AArch64II::MO_GOT);
1443         BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP)
1444             .addUse(AArch64::FP)
1445             .addUse(AArch64::X16)
1446             .addImm(Subtarget.isTargetILP32() ? 32 : 0);
1447         break;
1448       }
1449       [[fallthrough]];
1450 
1451     case SwiftAsyncFramePointerMode::Always:
1452       // ORR x29, x29, #0x1000_0000_0000_0000
1453       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP)
1454           .addUse(AArch64::FP)
1455           .addImm(0x1100)
1456           .setMIFlag(MachineInstr::FrameSetup);
1457       break;
1458 
1459     case SwiftAsyncFramePointerMode::Never:
1460       break;
1461     }
1462   }
1463 
1464   // All calls are tail calls in GHC calling conv, and functions have no
1465   // prologue/epilogue.
1466   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1467     return;
1468 
1469   // Set tagged base pointer to the requested stack slot.
1470   // Ideally it should match SP value after prologue.
1471   std::optional<int> TBPI = AFI->getTaggedBasePointerIndex();
1472   if (TBPI)
1473     AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI));
1474   else
1475     AFI->setTaggedBasePointerOffset(MFI.getStackSize());
1476 
1477   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1478 
1479   // getStackSize() includes all the locals in its size calculation. We don't
1480   // include these locals when computing the stack size of a funclet, as they
1481   // are allocated in the parent's stack frame and accessed via the frame
1482   // pointer from the funclet.  We only save the callee saved registers in the
1483   // funclet, which are really the callee saved registers of the parent
1484   // function, including the funclet.
1485   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1486                                : MFI.getStackSize();
1487   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
1488     assert(!HasFP && "unexpected function without stack frame but with FP");
1489     assert(!SVEStackSize &&
1490            "unexpected function without stack frame but with SVE objects");
1491     // All of the stack allocation is for locals.
1492     AFI->setLocalStackSize(NumBytes);
1493     if (!NumBytes)
1494       return;
1495     // REDZONE: If the stack size is less than 128 bytes, we don't need
1496     // to actually allocate.
1497     if (canUseRedZone(MF)) {
1498       AFI->setHasRedZone(true);
1499       ++NumRedZoneFunctions;
1500     } else {
1501       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1502                       StackOffset::getFixed(-NumBytes), TII,
1503                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
1504       if (EmitCFI) {
1505         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
1506         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
1507           // Encode the stack size of the leaf function.
1508         unsigned CFIIndex = MF.addFrameInst(
1509             MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));
1510         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1511             .addCFIIndex(CFIIndex)
1512             .setMIFlags(MachineInstr::FrameSetup);
1513       }
1514     }
1515 
1516     if (NeedsWinCFI) {
1517       HasWinCFI = true;
1518       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1519           .setMIFlag(MachineInstr::FrameSetup);
1520     }
1521 
1522     return;
1523   }
1524 
1525   bool IsWin64 =
1526       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1527   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1528 
1529   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1530   // All of the remaining stack allocations are for locals.
1531   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1532   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1533   bool HomPrologEpilog = homogeneousPrologEpilog(MF);
1534   if (CombineSPBump) {
1535     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1536     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1537                     StackOffset::getFixed(-NumBytes), TII,
1538                     MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI,
1539                     EmitCFI);
1540     NumBytes = 0;
1541   } else if (HomPrologEpilog) {
1542     // Stack has been already adjusted.
1543     NumBytes -= PrologueSaveSize;
1544   } else if (PrologueSaveSize != 0) {
1545     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
1546         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI,
1547         EmitCFI);
1548     NumBytes -= PrologueSaveSize;
1549   }
1550   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1551 
1552   // Move past the saves of the callee-saved registers, fixing up the offsets
1553   // and pre-inc if we decided to combine the callee-save and local stack
1554   // pointer bump above.
1555   MachineBasicBlock::iterator End = MBB.end();
1556   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
1557          !IsSVECalleeSave(MBBI)) {
1558     if (CombineSPBump)
1559       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
1560                                         NeedsWinCFI, &HasWinCFI);
1561     ++MBBI;
1562   }
1563 
1564   // For funclets the FP belongs to the containing function.
1565   if (!IsFunclet && HasFP) {
1566     // Only set up FP if we actually need to.
1567     int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();
1568 
1569     if (CombineSPBump)
1570       FPOffset += AFI->getLocalStackSize();
1571 
1572     if (AFI->hasSwiftAsyncContext()) {
1573       // Before we update the live FP we have to ensure there's a valid (or
1574       // null) asynchronous context in its slot just before FP in the frame
1575       // record, so store it now.
1576       const auto &Attrs = MF.getFunction().getAttributes();
1577       bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync);
1578       if (HaveInitialContext)
1579         MBB.addLiveIn(AArch64::X22);
1580       BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext))
1581           .addUse(HaveInitialContext ? AArch64::X22 : AArch64::XZR)
1582           .addUse(AArch64::SP)
1583           .addImm(FPOffset - 8)
1584           .setMIFlags(MachineInstr::FrameSetup);
1585     }
1586 
1587     if (HomPrologEpilog) {
1588       auto Prolog = MBBI;
1589       --Prolog;
1590       assert(Prolog->getOpcode() == AArch64::HOM_Prolog);
1591       Prolog->addOperand(MachineOperand::CreateImm(FPOffset));
1592     } else {
1593       // Issue    sub fp, sp, FPOffset or
1594       //          mov fp,sp          when FPOffset is zero.
1595       // Note: All stores of callee-saved registers are marked as "FrameSetup".
1596       // This code marks the instruction(s) that set the FP also.
1597       emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
1598                       StackOffset::getFixed(FPOffset), TII,
1599                       MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
1600       if (NeedsWinCFI && HasWinCFI) {
1601         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1602             .setMIFlag(MachineInstr::FrameSetup);
1603         // After setting up the FP, the rest of the prolog doesn't need to be
1604         // included in the SEH unwind info.
1605         NeedsWinCFI = false;
1606       }
1607     }
1608     if (EmitCFI) {
1609       // Define the current CFA rule to use the provided FP.
1610       const int OffsetToFirstCalleeSaveFromFP =
1611           AFI->getCalleeSaveBaseToFrameRecordOffset() -
1612           AFI->getCalleeSavedStackSize();
1613       Register FramePtr = RegInfo->getFrameRegister(MF);
1614       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1615       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
1616           nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));
1617       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1618           .addCFIIndex(CFIIndex)
1619           .setMIFlags(MachineInstr::FrameSetup);
1620     }
1621   }
1622 
1623   // Now emit the moves for whatever callee saved regs we have (including FP,
1624   // LR if those are saved). Frame instructions for SVE register are emitted
1625   // later, after the instruction which actually save SVE regs.
1626   if (EmitCFI)
1627     emitCalleeSavedGPRLocations(MBB, MBBI);
1628 
1629   // Alignment is required for the parent frame, not the funclet
1630   const bool NeedsRealignment =
1631       NumBytes && !IsFunclet && RegInfo->hasStackRealignment(MF);
1632   int64_t RealignmentPadding =
1633       (NeedsRealignment && MFI.getMaxAlign() > Align(16))
1634           ? MFI.getMaxAlign().value() - 16
1635           : 0;
1636 
1637   if (windowsRequiresStackProbe(MF, NumBytes + RealignmentPadding)) {
1638     uint64_t NumWords = (NumBytes + RealignmentPadding) >> 4;
1639     if (NeedsWinCFI) {
1640       HasWinCFI = true;
1641       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1642       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
1643       // This is at most two instructions, MOVZ follwed by MOVK.
1644       // TODO: Fix to use multiple stack alloc unwind codes for stacks
1645       // exceeding 256MB in size.
1646       if (NumBytes >= (1 << 28))
1647         report_fatal_error("Stack size cannot exceed 256MB for stack "
1648                             "unwinding purposes");
1649 
1650       uint32_t LowNumWords = NumWords & 0xFFFF;
1651       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
1652             .addImm(LowNumWords)
1653             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1654             .setMIFlag(MachineInstr::FrameSetup);
1655       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1656             .setMIFlag(MachineInstr::FrameSetup);
1657       if ((NumWords & 0xFFFF0000) != 0) {
1658           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
1659               .addReg(AArch64::X15)
1660               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
1661               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
1662               .setMIFlag(MachineInstr::FrameSetup);
1663           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1664             .setMIFlag(MachineInstr::FrameSetup);
1665       }
1666     } else {
1667       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
1668           .addImm(NumWords)
1669           .setMIFlags(MachineInstr::FrameSetup);
1670     }
1671 
1672     const char* ChkStk = Subtarget.getChkStkName();
1673     switch (MF.getTarget().getCodeModel()) {
1674     case CodeModel::Tiny:
1675     case CodeModel::Small:
1676     case CodeModel::Medium:
1677     case CodeModel::Kernel:
1678       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
1679           .addExternalSymbol(ChkStk)
1680           .addReg(AArch64::X15, RegState::Implicit)
1681           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1682           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1683           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1684           .setMIFlags(MachineInstr::FrameSetup);
1685       if (NeedsWinCFI) {
1686         HasWinCFI = true;
1687         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1688             .setMIFlag(MachineInstr::FrameSetup);
1689       }
1690       break;
1691     case CodeModel::Large:
1692       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1693           .addReg(AArch64::X16, RegState::Define)
1694           .addExternalSymbol(ChkStk)
1695           .addExternalSymbol(ChkStk)
1696           .setMIFlags(MachineInstr::FrameSetup);
1697       if (NeedsWinCFI) {
1698         HasWinCFI = true;
1699         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1700             .setMIFlag(MachineInstr::FrameSetup);
1701       }
1702 
1703       BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))
1704           .addReg(AArch64::X16, RegState::Kill)
1705           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1706           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1707           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1708           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1709           .setMIFlags(MachineInstr::FrameSetup);
1710       if (NeedsWinCFI) {
1711         HasWinCFI = true;
1712         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1713             .setMIFlag(MachineInstr::FrameSetup);
1714       }
1715       break;
1716     }
1717 
1718     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1719         .addReg(AArch64::SP, RegState::Kill)
1720         .addReg(AArch64::X15, RegState::Kill)
1721         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1722         .setMIFlags(MachineInstr::FrameSetup);
1723     if (NeedsWinCFI) {
1724       HasWinCFI = true;
1725       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1726           .addImm(NumBytes)
1727           .setMIFlag(MachineInstr::FrameSetup);
1728     }
1729     NumBytes = 0;
1730 
1731     if (RealignmentPadding > 0) {
1732       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXri), AArch64::X15)
1733           .addReg(AArch64::SP)
1734           .addImm(RealignmentPadding)
1735           .addImm(0);
1736 
1737       uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);
1738       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1739           .addReg(AArch64::X15, RegState::Kill)
1740           .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));
1741       AFI->setStackRealigned(true);
1742 
1743       // No need for SEH instructions here; if we're realigning the stack,
1744       // we've set a frame pointer and already finished the SEH prologue.
1745       assert(!NeedsWinCFI);
1746     }
1747   }
1748 
1749   StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
1750   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
1751 
1752   // Process the SVE callee-saves to determine what space needs to be
1753   // allocated.
1754   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
1755     // Find callee save instructions in frame.
1756     CalleeSavesBegin = MBBI;
1757     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
1758     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
1759       ++MBBI;
1760     CalleeSavesEnd = MBBI;
1761 
1762     AllocateBefore = StackOffset::getScalable(CalleeSavedSize);
1763     AllocateAfter = SVEStackSize - AllocateBefore;
1764   }
1765 
1766   // Allocate space for the callee saves (if any).
1767   emitFrameOffset(
1768       MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP, -AllocateBefore, TII,
1769       MachineInstr::FrameSetup, false, false, nullptr,
1770       EmitCFI && !HasFP && AllocateBefore,
1771       StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
1772 
1773   if (EmitCFI)
1774     emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
1775 
1776   // Finally allocate remaining SVE stack space.
1777   emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
1778                   -AllocateAfter, TII, MachineInstr::FrameSetup, false, false,
1779                   nullptr, EmitCFI && !HasFP && AllocateAfter,
1780                   AllocateBefore + StackOffset::getFixed(
1781                                        (int64_t)MFI.getStackSize() - NumBytes));
1782 
1783   // Allocate space for the rest of the frame.
1784   if (NumBytes) {
1785     unsigned scratchSPReg = AArch64::SP;
1786 
1787     if (NeedsRealignment) {
1788       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1789       assert(scratchSPReg != AArch64::NoRegister);
1790     }
1791 
1792     // If we're a leaf function, try using the red zone.
1793     if (!canUseRedZone(MF)) {
1794       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1795       // the correct value here, as NumBytes also includes padding bytes,
1796       // which shouldn't be counted here.
1797       emitFrameOffset(
1798           MBB, MBBI, DL, scratchSPReg, AArch64::SP,
1799           StackOffset::getFixed(-NumBytes), TII, MachineInstr::FrameSetup,
1800           false, NeedsWinCFI, &HasWinCFI, EmitCFI && !HasFP,
1801           SVEStackSize +
1802               StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
1803     }
1804     if (NeedsRealignment) {
1805       assert(MFI.getMaxAlign() > Align(1));
1806       assert(scratchSPReg != AArch64::SP);
1807 
1808       // SUB X9, SP, NumBytes
1809       //   -- X9 is temporary register, so shouldn't contain any live data here,
1810       //   -- free to use. This is already produced by emitFrameOffset above.
1811       // AND SP, X9, 0b11111...0000
1812       uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);
1813 
1814       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1815           .addReg(scratchSPReg, RegState::Kill)
1816           .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));
1817       AFI->setStackRealigned(true);
1818 
1819       // No need for SEH instructions here; if we're realigning the stack,
1820       // we've set a frame pointer and already finished the SEH prologue.
1821       assert(!NeedsWinCFI);
1822     }
1823   }
1824 
1825   // If we need a base pointer, set it up here. It's whatever the value of the
1826   // stack pointer is at this point. Any variable size objects will be allocated
1827   // after this, so we can still use the base pointer to reference locals.
1828   //
1829   // FIXME: Clarify FrameSetup flags here.
1830   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1831   // needed.
1832   // For funclets the BP belongs to the containing function.
1833   if (!IsFunclet && RegInfo->hasBasePointer(MF)) {
1834     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1835                      false);
1836     if (NeedsWinCFI) {
1837       HasWinCFI = true;
1838       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1839           .setMIFlag(MachineInstr::FrameSetup);
1840     }
1841   }
1842 
1843   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1844   // SEH opcode indicating the prologue end.
1845   if (NeedsWinCFI && HasWinCFI) {
1846     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1847         .setMIFlag(MachineInstr::FrameSetup);
1848   }
1849 
1850   // SEH funclets are passed the frame pointer in X1.  If the parent
1851   // function uses the base register, then the base register is used
1852   // directly, and is not retrieved from X1.
1853   if (IsFunclet && F.hasPersonalityFn()) {
1854     EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
1855     if (isAsynchronousEHPersonality(Per)) {
1856       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
1857           .addReg(AArch64::X1)
1858           .setMIFlag(MachineInstr::FrameSetup);
1859       MBB.addLiveIn(AArch64::X1);
1860     }
1861   }
1862 }
1863 
InsertReturnAddressAuth(MachineFunction & MF,MachineBasicBlock & MBB,bool NeedsWinCFI,bool * HasWinCFI)1864 static void InsertReturnAddressAuth(MachineFunction &MF, MachineBasicBlock &MBB,
1865                                     bool NeedsWinCFI, bool *HasWinCFI) {
1866   const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
1867   if (!MFI.shouldSignReturnAddress(MF))
1868     return;
1869   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1870   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1871 
1872   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1873   DebugLoc DL;
1874   if (MBBI != MBB.end())
1875     DL = MBBI->getDebugLoc();
1876 
1877   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1878   // this instruction can safely used for any v8a architecture.
1879   // From v8.3a onwards there are optimised authenticate LR and return
1880   // instructions, namely RETA{A,B}, that can be used instead. In this case the
1881   // DW_CFA_AARCH64_negate_ra_state can't be emitted.
1882   if (Subtarget.hasPAuth() &&
1883       !MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack) &&
1884       MBBI != MBB.end() && MBBI->getOpcode() == AArch64::RET_ReallyLR &&
1885       !NeedsWinCFI) {
1886     BuildMI(MBB, MBBI, DL,
1887             TII->get(MFI.shouldSignWithBKey() ? AArch64::RETAB : AArch64::RETAA))
1888         .copyImplicitOps(*MBBI);
1889     MBB.erase(MBBI);
1890   } else {
1891     BuildMI(
1892         MBB, MBBI, DL,
1893         TII->get(MFI.shouldSignWithBKey() ? AArch64::AUTIBSP : AArch64::AUTIASP))
1894         .setMIFlag(MachineInstr::FrameDestroy);
1895 
1896     unsigned CFIIndex =
1897         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1898     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1899         .addCFIIndex(CFIIndex)
1900         .setMIFlags(MachineInstr::FrameDestroy);
1901     if (NeedsWinCFI) {
1902       *HasWinCFI = true;
1903       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
1904           .setMIFlag(MachineInstr::FrameDestroy);
1905     }
1906   }
1907 }
1908 
isFuncletReturnInstr(const MachineInstr & MI)1909 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1910   switch (MI.getOpcode()) {
1911   default:
1912     return false;
1913   case AArch64::CATCHRET:
1914   case AArch64::CLEANUPRET:
1915     return true;
1916   }
1917 }
1918 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const1919 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1920                                         MachineBasicBlock &MBB) const {
1921   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1922   MachineFrameInfo &MFI = MF.getFrameInfo();
1923   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1924   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1925   DebugLoc DL;
1926   bool NeedsWinCFI = needsWinCFI(MF);
1927   bool EmitCFI =
1928       MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF);
1929   bool HasWinCFI = false;
1930   bool IsFunclet = false;
1931   auto WinCFI = make_scope_exit([&]() { assert(HasWinCFI == MF.hasWinCFI()); });
1932 
1933   if (MBB.end() != MBBI) {
1934     DL = MBBI->getDebugLoc();
1935     IsFunclet = isFuncletReturnInstr(*MBBI);
1936   }
1937 
1938   auto FinishingTouches = make_scope_exit([&]() {
1939     InsertReturnAddressAuth(MF, MBB, NeedsWinCFI, &HasWinCFI);
1940     if (needsShadowCallStackPrologueEpilogue(MF))
1941       emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL);
1942     if (EmitCFI)
1943       emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator());
1944     if (HasWinCFI)
1945       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1946               TII->get(AArch64::SEH_EpilogEnd))
1947           .setMIFlag(MachineInstr::FrameDestroy);
1948   });
1949 
1950   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1951                                : MFI.getStackSize();
1952   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1953 
1954   // All calls are tail calls in GHC calling conv, and functions have no
1955   // prologue/epilogue.
1956   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1957     return;
1958 
1959   // How much of the stack used by incoming arguments this function is expected
1960   // to restore in this particular epilogue.
1961   int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB);
1962   bool IsWin64 =
1963       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1964   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1965 
1966   int64_t AfterCSRPopSize = ArgumentStackToRestore;
1967   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1968   // We cannot rely on the local stack size set in emitPrologue if the function
1969   // has funclets, as funclets have different local stack size requirements, and
1970   // the current value set in emitPrologue may be that of the containing
1971   // function.
1972   if (MF.hasEHFunclets())
1973     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1974   if (homogeneousPrologEpilog(MF, &MBB)) {
1975     assert(!NeedsWinCFI);
1976     auto LastPopI = MBB.getFirstTerminator();
1977     if (LastPopI != MBB.begin()) {
1978       auto HomogeneousEpilog = std::prev(LastPopI);
1979       if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog)
1980         LastPopI = HomogeneousEpilog;
1981     }
1982 
1983     // Adjust local stack
1984     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1985                     StackOffset::getFixed(AFI->getLocalStackSize()), TII,
1986                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1987 
1988     // SP has been already adjusted while restoring callee save regs.
1989     // We've bailed-out the case with adjusting SP for arguments.
1990     assert(AfterCSRPopSize == 0);
1991     return;
1992   }
1993   bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);
1994   // Assume we can't combine the last pop with the sp restore.
1995 
1996   bool CombineAfterCSRBump = false;
1997   if (!CombineSPBump && PrologueSaveSize != 0) {
1998     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1999     while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
2000            AArch64InstrInfo::isSEHInstruction(*Pop))
2001       Pop = std::prev(Pop);
2002     // Converting the last ldp to a post-index ldp is valid only if the last
2003     // ldp's offset is 0.
2004     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
2005     // If the offset is 0 and the AfterCSR pop is not actually trying to
2006     // allocate more stack for arguments (in space that an untimely interrupt
2007     // may clobber), convert it to a post-index ldp.
2008     if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) {
2009       convertCalleeSaveRestoreToSPPrePostIncDec(
2010           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI,
2011           MachineInstr::FrameDestroy, PrologueSaveSize);
2012     } else {
2013       // If not, make sure to emit an add after the last ldp.
2014       // We're doing this by transfering the size to be restored from the
2015       // adjustment *before* the CSR pops to the adjustment *after* the CSR
2016       // pops.
2017       AfterCSRPopSize += PrologueSaveSize;
2018       CombineAfterCSRBump = true;
2019     }
2020   }
2021 
2022   // Move past the restores of the callee-saved registers.
2023   // If we plan on combining the sp bump of the local stack size and the callee
2024   // save stack size, we might need to adjust the CSR save and restore offsets.
2025   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
2026   MachineBasicBlock::iterator Begin = MBB.begin();
2027   while (LastPopI != Begin) {
2028     --LastPopI;
2029     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
2030         IsSVECalleeSave(LastPopI)) {
2031       ++LastPopI;
2032       break;
2033     } else if (CombineSPBump)
2034       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
2035                                         NeedsWinCFI, &HasWinCFI);
2036   }
2037 
2038   if (MF.hasWinCFI()) {
2039     // If the prologue didn't contain any SEH opcodes and didn't set the
2040     // MF.hasWinCFI() flag, assume the epilogue won't either, and skip the
2041     // EpilogStart - to avoid generating CFI for functions that don't need it.
2042     // (And as we didn't generate any prologue at all, it would be asymmetrical
2043     // to the epilogue.) By the end of the function, we assert that
2044     // HasWinCFI is equal to MF.hasWinCFI(), to verify this assumption.
2045     HasWinCFI = true;
2046     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
2047         .setMIFlag(MachineInstr::FrameDestroy);
2048   }
2049 
2050   if (hasFP(MF) && AFI->hasSwiftAsyncContext()) {
2051     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
2052     case SwiftAsyncFramePointerMode::DeploymentBased:
2053       // Avoid the reload as it is GOT relative, and instead fall back to the
2054       // hardcoded value below.  This allows a mismatch between the OS and
2055       // application without immediately terminating on the difference.
2056       [[fallthrough]];
2057     case SwiftAsyncFramePointerMode::Always:
2058       // We need to reset FP to its untagged state on return. Bit 60 is
2059       // currently used to show the presence of an extended frame.
2060 
2061       // BIC x29, x29, #0x1000_0000_0000_0000
2062       BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri),
2063               AArch64::FP)
2064           .addUse(AArch64::FP)
2065           .addImm(0x10fe)
2066           .setMIFlag(MachineInstr::FrameDestroy);
2067       break;
2068 
2069     case SwiftAsyncFramePointerMode::Never:
2070       break;
2071     }
2072   }
2073 
2074   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2075 
2076   // If there is a single SP update, insert it before the ret and we're done.
2077   if (CombineSPBump) {
2078     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
2079 
2080     // When we are about to restore the CSRs, the CFA register is SP again.
2081     if (EmitCFI && hasFP(MF)) {
2082       const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2083       unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2084       unsigned CFIIndex =
2085           MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes));
2086       BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2087           .addCFIIndex(CFIIndex)
2088           .setMIFlags(MachineInstr::FrameDestroy);
2089     }
2090 
2091     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2092                     StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize),
2093                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI,
2094                     &HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes));
2095     return;
2096   }
2097 
2098   NumBytes -= PrologueSaveSize;
2099   assert(NumBytes >= 0 && "Negative stack allocation size!?");
2100 
2101   // Process the SVE callee-saves to determine what space needs to be
2102   // deallocated.
2103   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
2104   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
2105   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2106     RestoreBegin = std::prev(RestoreEnd);
2107     while (RestoreBegin != MBB.begin() &&
2108            IsSVECalleeSave(std::prev(RestoreBegin)))
2109       --RestoreBegin;
2110 
2111     assert(IsSVECalleeSave(RestoreBegin) &&
2112            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
2113 
2114     StackOffset CalleeSavedSizeAsOffset =
2115         StackOffset::getScalable(CalleeSavedSize);
2116     DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;
2117     DeallocateAfter = CalleeSavedSizeAsOffset;
2118   }
2119 
2120   // Deallocate the SVE area.
2121   if (SVEStackSize) {
2122     // If we have stack realignment or variable sized objects on the stack,
2123     // restore the stack pointer from the frame pointer prior to SVE CSR
2124     // restoration.
2125     if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) {
2126       if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
2127         // Set SP to start of SVE callee-save area from which they can
2128         // be reloaded. The code below will deallocate the stack space
2129         // space by moving FP -> SP.
2130         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
2131                         StackOffset::getScalable(-CalleeSavedSize), TII,
2132                         MachineInstr::FrameDestroy);
2133       }
2134     } else {
2135       if (AFI->getSVECalleeSavedStackSize()) {
2136         // Deallocate the non-SVE locals first before we can deallocate (and
2137         // restore callee saves) from the SVE area.
2138         emitFrameOffset(
2139             MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2140             StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy,
2141             false, false, nullptr, EmitCFI && !hasFP(MF),
2142             SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize));
2143         NumBytes = 0;
2144       }
2145 
2146       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
2147                       DeallocateBefore, TII, MachineInstr::FrameDestroy, false,
2148                       false, nullptr, EmitCFI && !hasFP(MF),
2149                       SVEStackSize +
2150                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2151 
2152       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
2153                       DeallocateAfter, TII, MachineInstr::FrameDestroy, false,
2154                       false, nullptr, EmitCFI && !hasFP(MF),
2155                       DeallocateAfter +
2156                           StackOffset::getFixed(NumBytes + PrologueSaveSize));
2157     }
2158     if (EmitCFI)
2159       emitCalleeSavedSVERestores(MBB, RestoreEnd);
2160   }
2161 
2162   if (!hasFP(MF)) {
2163     bool RedZone = canUseRedZone(MF);
2164     // If this was a redzone leaf function, we don't need to restore the
2165     // stack pointer (but we may need to pop stack args for fastcc).
2166     if (RedZone && AfterCSRPopSize == 0)
2167       return;
2168 
2169     // Pop the local variables off the stack. If there are no callee-saved
2170     // registers, it means we are actually positioned at the terminator and can
2171     // combine stack increment for the locals and the stack increment for
2172     // callee-popped arguments into (possibly) a single instruction and be done.
2173     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
2174     int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
2175     if (NoCalleeSaveRestore)
2176       StackRestoreBytes += AfterCSRPopSize;
2177 
2178     emitFrameOffset(
2179         MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2180         StackOffset::getFixed(StackRestoreBytes), TII,
2181         MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2182         StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize));
2183 
2184     // If we were able to combine the local stack pop with the argument pop,
2185     // then we're done.
2186     if (NoCalleeSaveRestore || AfterCSRPopSize == 0) {
2187       return;
2188     }
2189 
2190     NumBytes = 0;
2191   }
2192 
2193   // Restore the original stack pointer.
2194   // FIXME: Rather than doing the math here, we should instead just use
2195   // non-post-indexed loads for the restores if we aren't actually going to
2196   // be able to save any instructions.
2197   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
2198     emitFrameOffset(
2199         MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
2200         StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()),
2201         TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
2202   } else if (NumBytes)
2203     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
2204                     StackOffset::getFixed(NumBytes), TII,
2205                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
2206 
2207   // When we are about to restore the CSRs, the CFA register is SP again.
2208   if (EmitCFI && hasFP(MF)) {
2209     const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
2210     unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
2211     unsigned CFIIndex = MF.addFrameInst(
2212         MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize));
2213     BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2214         .addCFIIndex(CFIIndex)
2215         .setMIFlags(MachineInstr::FrameDestroy);
2216   }
2217 
2218   // This must be placed after the callee-save restore code because that code
2219   // assumes the SP is at the same location as it was after the callee-save save
2220   // code in the prologue.
2221   if (AfterCSRPopSize) {
2222     assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an "
2223                                   "interrupt may have clobbered");
2224 
2225     emitFrameOffset(
2226         MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
2227         StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy,
2228         false, NeedsWinCFI, &HasWinCFI, EmitCFI,
2229         StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0));
2230   }
2231 }
2232 
2233 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
2234 /// debug info.  It's the same as what we use for resolving the code-gen
2235 /// references for now.  FIXME: This can go wrong when references are
2236 /// SP-relative and simple call frames aren't used.
2237 StackOffset
getFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg) const2238 AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
2239                                              Register &FrameReg) const {
2240   return resolveFrameIndexReference(
2241       MF, FI, FrameReg,
2242       /*PreferFP=*/
2243       MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
2244       /*ForSimm=*/false);
2245 }
2246 
2247 StackOffset
getNonLocalFrameIndexReference(const MachineFunction & MF,int FI) const2248 AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
2249                                                      int FI) const {
2250   return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI));
2251 }
2252 
getFPOffset(const MachineFunction & MF,int64_t ObjectOffset)2253 static StackOffset getFPOffset(const MachineFunction &MF,
2254                                int64_t ObjectOffset) {
2255   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2256   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2257   bool IsWin64 =
2258       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
2259   unsigned FixedObject =
2260       getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
2261   int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
2262   int64_t FPAdjust =
2263       CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
2264   return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);
2265 }
2266 
getStackOffset(const MachineFunction & MF,int64_t ObjectOffset)2267 static StackOffset getStackOffset(const MachineFunction &MF,
2268                                   int64_t ObjectOffset) {
2269   const auto &MFI = MF.getFrameInfo();
2270   return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());
2271 }
2272 
2273   // TODO: This function currently does not work for scalable vectors.
getSEHFrameIndexOffset(const MachineFunction & MF,int FI) const2274 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
2275                                                  int FI) const {
2276   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2277       MF.getSubtarget().getRegisterInfo());
2278   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
2279   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
2280              ? getFPOffset(MF, ObjectOffset).getFixed()
2281              : getStackOffset(MF, ObjectOffset).getFixed();
2282 }
2283 
resolveFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg,bool PreferFP,bool ForSimm) const2284 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
2285     const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
2286     bool ForSimm) const {
2287   const auto &MFI = MF.getFrameInfo();
2288   int64_t ObjectOffset = MFI.getObjectOffset(FI);
2289   bool isFixed = MFI.isFixedObjectIndex(FI);
2290   bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector;
2291   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
2292                                      PreferFP, ForSimm);
2293 }
2294 
resolveFrameOffsetReference(const MachineFunction & MF,int64_t ObjectOffset,bool isFixed,bool isSVE,Register & FrameReg,bool PreferFP,bool ForSimm) const2295 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
2296     const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
2297     Register &FrameReg, bool PreferFP, bool ForSimm) const {
2298   const auto &MFI = MF.getFrameInfo();
2299   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
2300       MF.getSubtarget().getRegisterInfo());
2301   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2302   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2303 
2304   int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();
2305   int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();
2306   bool isCSR =
2307       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
2308 
2309   const StackOffset &SVEStackSize = getSVEStackSize(MF);
2310 
2311   // Use frame pointer to reference fixed objects. Use it for locals if
2312   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
2313   // reliable as a base). Make sure useFPForScavengingIndex() does the
2314   // right thing for the emergency spill slot.
2315   bool UseFP = false;
2316   if (AFI->hasStackFrame() && !isSVE) {
2317     // We shouldn't prefer using the FP to access fixed-sized stack objects when
2318     // there are scalable (SVE) objects in between the FP and the fixed-sized
2319     // objects.
2320     PreferFP &= !SVEStackSize;
2321 
2322     // Note: Keeping the following as multiple 'if' statements rather than
2323     // merging to a single expression for readability.
2324     //
2325     // Argument access should always use the FP.
2326     if (isFixed) {
2327       UseFP = hasFP(MF);
2328     } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
2329       // References to the CSR area must use FP if we're re-aligning the stack
2330       // since the dynamically-sized alignment padding is between the SP/BP and
2331       // the CSR area.
2332       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
2333       UseFP = true;
2334     } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
2335       // If the FPOffset is negative and we're producing a signed immediate, we
2336       // have to keep in mind that the available offset range for negative
2337       // offsets is smaller than for positive ones. If an offset is available
2338       // via the FP and the SP, use whichever is closest.
2339       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
2340       PreferFP |= Offset > -FPOffset && !SVEStackSize;
2341 
2342       if (MFI.hasVarSizedObjects()) {
2343         // If we have variable sized objects, we can use either FP or BP, as the
2344         // SP offset is unknown. We can use the base pointer if we have one and
2345         // FP is not preferred. If not, we're stuck with using FP.
2346         bool CanUseBP = RegInfo->hasBasePointer(MF);
2347         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
2348           UseFP = PreferFP;
2349         else if (!CanUseBP) // Can't use BP. Forced to use FP.
2350           UseFP = true;
2351         // else we can use BP and FP, but the offset from FP won't fit.
2352         // That will make us scavenge registers which we can probably avoid by
2353         // using BP. If it won't fit for BP either, we'll scavenge anyway.
2354       } else if (FPOffset >= 0) {
2355         // Use SP or FP, whichever gives us the best chance of the offset
2356         // being in range for direct access. If the FPOffset is positive,
2357         // that'll always be best, as the SP will be even further away.
2358         UseFP = true;
2359       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
2360         // Funclets access the locals contained in the parent's stack frame
2361         // via the frame pointer, so we have to use the FP in the parent
2362         // function.
2363         (void) Subtarget;
2364         assert(
2365             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
2366             "Funclets should only be present on Win64");
2367         UseFP = true;
2368       } else {
2369         // We have the choice between FP and (SP or BP).
2370         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
2371           UseFP = true;
2372       }
2373     }
2374   }
2375 
2376   assert(
2377       ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
2378       "In the presence of dynamic stack pointer realignment, "
2379       "non-argument/CSR objects cannot be accessed through the frame pointer");
2380 
2381   if (isSVE) {
2382     StackOffset FPOffset =
2383         StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
2384     StackOffset SPOffset =
2385         SVEStackSize +
2386         StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
2387                          ObjectOffset);
2388     // Always use the FP for SVE spills if available and beneficial.
2389     if (hasFP(MF) && (SPOffset.getFixed() ||
2390                       FPOffset.getScalable() < SPOffset.getScalable() ||
2391                       RegInfo->hasStackRealignment(MF))) {
2392       FrameReg = RegInfo->getFrameRegister(MF);
2393       return FPOffset;
2394     }
2395 
2396     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
2397                                            : (unsigned)AArch64::SP;
2398     return SPOffset;
2399   }
2400 
2401   StackOffset ScalableOffset = {};
2402   if (UseFP && !(isFixed || isCSR))
2403     ScalableOffset = -SVEStackSize;
2404   if (!UseFP && (isFixed || isCSR))
2405     ScalableOffset = SVEStackSize;
2406 
2407   if (UseFP) {
2408     FrameReg = RegInfo->getFrameRegister(MF);
2409     return StackOffset::getFixed(FPOffset) + ScalableOffset;
2410   }
2411 
2412   // Use the base pointer if we have one.
2413   if (RegInfo->hasBasePointer(MF))
2414     FrameReg = RegInfo->getBaseRegister();
2415   else {
2416     assert(!MFI.hasVarSizedObjects() &&
2417            "Can't use SP when we have var sized objects.");
2418     FrameReg = AArch64::SP;
2419     // If we're using the red zone for this function, the SP won't actually
2420     // be adjusted, so the offsets will be negative. They're also all
2421     // within range of the signed 9-bit immediate instructions.
2422     if (canUseRedZone(MF))
2423       Offset -= AFI->getLocalStackSize();
2424   }
2425 
2426   return StackOffset::getFixed(Offset) + ScalableOffset;
2427 }
2428 
getPrologueDeath(MachineFunction & MF,unsigned Reg)2429 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
2430   // Do not set a kill flag on values that are also marked as live-in. This
2431   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2432   // callee saved registers.
2433   // Omitting the kill flags is conservatively correct even if the live-in
2434   // is not used after all.
2435   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
2436   return getKillRegState(!IsLiveIn);
2437 }
2438 
produceCompactUnwindFrame(MachineFunction & MF)2439 static bool produceCompactUnwindFrame(MachineFunction &MF) {
2440   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2441   AttributeList Attrs = MF.getFunction().getAttributes();
2442   return Subtarget.isTargetMachO() &&
2443          !(Subtarget.getTargetLowering()->supportSwiftError() &&
2444            Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
2445          MF.getFunction().getCallingConv() != CallingConv::SwiftTail;
2446 }
2447 
invalidateWindowsRegisterPairing(unsigned Reg1,unsigned Reg2,bool NeedsWinCFI,bool IsFirst,const TargetRegisterInfo * TRI)2448 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
2449                                              bool NeedsWinCFI, bool IsFirst,
2450                                              const TargetRegisterInfo *TRI) {
2451   // If we are generating register pairs for a Windows function that requires
2452   // EH support, then pair consecutive registers only.  There are no unwind
2453   // opcodes for saves/restores of non-consectuve register pairs.
2454   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
2455   // save_lrpair.
2456   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2457 
2458   if (Reg2 == AArch64::FP)
2459     return true;
2460   if (!NeedsWinCFI)
2461     return false;
2462   if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1)
2463     return false;
2464   // If pairing a GPR with LR, the pair can be described by the save_lrpair
2465   // opcode. If this is the first register pair, it would end up with a
2466   // predecrement, but there's no save_lrpair_x opcode, so we can only do this
2467   // if LR is paired with something else than the first register.
2468   // The save_lrpair opcode requires the first register to be an odd one.
2469   if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
2470       (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)
2471     return false;
2472   return true;
2473 }
2474 
2475 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2476 /// WindowsCFI requires that only consecutive registers can be paired.
2477 /// LR and FP need to be allocated together when the frame needs to save
2478 /// the frame-record. This means any other register pairing with LR is invalid.
invalidateRegisterPairing(unsigned Reg1,unsigned Reg2,bool UsesWinAAPCS,bool NeedsWinCFI,bool NeedsFrameRecord,bool IsFirst,const TargetRegisterInfo * TRI)2479 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
2480                                       bool UsesWinAAPCS, bool NeedsWinCFI,
2481                                       bool NeedsFrameRecord, bool IsFirst,
2482                                       const TargetRegisterInfo *TRI) {
2483   if (UsesWinAAPCS)
2484     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst,
2485                                             TRI);
2486 
2487   // If we need to store the frame record, don't pair any register
2488   // with LR other than FP.
2489   if (NeedsFrameRecord)
2490     return Reg2 == AArch64::LR;
2491 
2492   return false;
2493 }
2494 
2495 namespace {
2496 
2497 struct RegPairInfo {
2498   unsigned Reg1 = AArch64::NoRegister;
2499   unsigned Reg2 = AArch64::NoRegister;
2500   int FrameIdx;
2501   int Offset;
2502   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
2503 
2504   RegPairInfo() = default;
2505 
isPaired__anon61e914860511::RegPairInfo2506   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
2507 
getScale__anon61e914860511::RegPairInfo2508   unsigned getScale() const {
2509     switch (Type) {
2510     case PPR:
2511       return 2;
2512     case GPR:
2513     case FPR64:
2514       return 8;
2515     case ZPR:
2516     case FPR128:
2517       return 16;
2518     }
2519     llvm_unreachable("Unsupported type");
2520   }
2521 
isScalable__anon61e914860511::RegPairInfo2522   bool isScalable() const { return Type == PPR || Type == ZPR; }
2523 };
2524 
2525 } // end anonymous namespace
2526 
computeCalleeSaveRegisterPairs(MachineFunction & MF,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI,SmallVectorImpl<RegPairInfo> & RegPairs,bool NeedsFrameRecord)2527 static void computeCalleeSaveRegisterPairs(
2528     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
2529     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
2530     bool NeedsFrameRecord) {
2531 
2532   if (CSI.empty())
2533     return;
2534 
2535   bool IsWindows = isTargetWindows(MF);
2536   bool NeedsWinCFI = needsWinCFI(MF);
2537   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2538   MachineFrameInfo &MFI = MF.getFrameInfo();
2539   CallingConv::ID CC = MF.getFunction().getCallingConv();
2540   unsigned Count = CSI.size();
2541   (void)CC;
2542   // MachO's compact unwind format relies on all registers being stored in
2543   // pairs.
2544   assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
2545           CC == CallingConv::CXX_FAST_TLS || CC == CallingConv::Win64 ||
2546           (Count & 1) == 0) &&
2547          "Odd number of callee-saved regs to spill!");
2548   int ByteOffset = AFI->getCalleeSavedStackSize();
2549   int StackFillDir = -1;
2550   int RegInc = 1;
2551   unsigned FirstReg = 0;
2552   if (NeedsWinCFI) {
2553     // For WinCFI, fill the stack from the bottom up.
2554     ByteOffset = 0;
2555     StackFillDir = 1;
2556     // As the CSI array is reversed to match PrologEpilogInserter, iterate
2557     // backwards, to pair up registers starting from lower numbered registers.
2558     RegInc = -1;
2559     FirstReg = Count - 1;
2560   }
2561   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2562   bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
2563 
2564   // When iterating backwards, the loop condition relies on unsigned wraparound.
2565   for (unsigned i = FirstReg; i < Count; i += RegInc) {
2566     RegPairInfo RPI;
2567     RPI.Reg1 = CSI[i].getReg();
2568 
2569     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2570       RPI.Type = RegPairInfo::GPR;
2571     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2572       RPI.Type = RegPairInfo::FPR64;
2573     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2574       RPI.Type = RegPairInfo::FPR128;
2575     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2576       RPI.Type = RegPairInfo::ZPR;
2577     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2578       RPI.Type = RegPairInfo::PPR;
2579     else
2580       llvm_unreachable("Unsupported register class.");
2581 
2582     // Add the next reg to the pair if it is in the same register class.
2583     if (unsigned(i + RegInc) < Count) {
2584       Register NextReg = CSI[i + RegInc].getReg();
2585       bool IsFirst = i == FirstReg;
2586       switch (RPI.Type) {
2587       case RegPairInfo::GPR:
2588         if (AArch64::GPR64RegClass.contains(NextReg) &&
2589             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,
2590                                        NeedsWinCFI, NeedsFrameRecord, IsFirst,
2591                                        TRI))
2592           RPI.Reg2 = NextReg;
2593         break;
2594       case RegPairInfo::FPR64:
2595         if (AArch64::FPR64RegClass.contains(NextReg) &&
2596             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
2597                                               IsFirst, TRI))
2598           RPI.Reg2 = NextReg;
2599         break;
2600       case RegPairInfo::FPR128:
2601         if (AArch64::FPR128RegClass.contains(NextReg))
2602           RPI.Reg2 = NextReg;
2603         break;
2604       case RegPairInfo::PPR:
2605       case RegPairInfo::ZPR:
2606         break;
2607       }
2608     }
2609 
2610     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2611     // list to come in sorted by frame index so that we can issue the store
2612     // pair instructions directly. Assert if we see anything otherwise.
2613     //
2614     // The order of the registers in the list is controlled by
2615     // getCalleeSavedRegs(), so they will always be in-order, as well.
2616     assert((!RPI.isPaired() ||
2617             (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&
2618            "Out of order callee saved regs!");
2619 
2620     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2621             RPI.Reg1 == AArch64::LR) &&
2622            "FrameRecord must be allocated together with LR");
2623 
2624     // Windows AAPCS has FP and LR reversed.
2625     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
2626             RPI.Reg2 == AArch64::LR) &&
2627            "FrameRecord must be allocated together with LR");
2628 
2629     // MachO's compact unwind format relies on all registers being stored in
2630     // adjacent register pairs.
2631     assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
2632             CC == CallingConv::CXX_FAST_TLS || CC == CallingConv::Win64 ||
2633             (RPI.isPaired() &&
2634              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2635               RPI.Reg1 + 1 == RPI.Reg2))) &&
2636            "Callee-save registers not saved as adjacent register pair!");
2637 
2638     RPI.FrameIdx = CSI[i].getFrameIdx();
2639     if (NeedsWinCFI &&
2640         RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair
2641       RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();
2642 
2643     int Scale = RPI.getScale();
2644 
2645     int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2646     assert(OffsetPre % Scale == 0);
2647 
2648     if (RPI.isScalable())
2649       ScalableByteOffset += StackFillDir * Scale;
2650     else
2651       ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
2652 
2653     // Swift's async context is directly before FP, so allocate an extra
2654     // 8 bytes for it.
2655     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2656         RPI.Reg2 == AArch64::FP)
2657       ByteOffset += StackFillDir * 8;
2658 
2659     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2660            "Paired spill/fill instructions don't exist for SVE vectors");
2661 
2662     // Round up size of non-pair to pair size if we need to pad the
2663     // callee-save area to ensure 16-byte alignment.
2664     if (NeedGapToAlignStack && !NeedsWinCFI &&
2665         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2666         !RPI.isPaired() && ByteOffset % 16 != 0) {
2667       ByteOffset += 8 * StackFillDir;
2668       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
2669       // A stack frame with a gap looks like this, bottom up:
2670       // d9, d8. x21, gap, x20, x19.
2671       // Set extra alignment on the x21 object to create the gap above it.
2672       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
2673       NeedGapToAlignStack = false;
2674     }
2675 
2676     int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2677     assert(OffsetPost % Scale == 0);
2678     // If filling top down (default), we want the offset after incrementing it.
2679     // If fillibg bootom up (WinCFI) we need the original offset.
2680     int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;
2681 
2682     // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
2683     // Swift context can directly precede FP.
2684     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2685         RPI.Reg2 == AArch64::FP)
2686       Offset += 8;
2687     RPI.Offset = Offset / Scale;
2688 
2689     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2690             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2691            "Offset out of bounds for LDP/STP immediate");
2692 
2693     // Save the offset to frame record so that the FP register can point to the
2694     // innermost frame record (spilled FP and LR registers).
2695     if (NeedsFrameRecord && ((!IsWindows && RPI.Reg1 == AArch64::LR &&
2696                               RPI.Reg2 == AArch64::FP) ||
2697                              (IsWindows && RPI.Reg1 == AArch64::FP &&
2698                               RPI.Reg2 == AArch64::LR)))
2699       AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
2700 
2701     RegPairs.push_back(RPI);
2702     if (RPI.isPaired())
2703       i += RegInc;
2704   }
2705   if (NeedsWinCFI) {
2706     // If we need an alignment gap in the stack, align the topmost stack
2707     // object. A stack frame with a gap looks like this, bottom up:
2708     // x19, d8. d9, gap.
2709     // Set extra alignment on the topmost stack object (the first element in
2710     // CSI, which goes top down), to create the gap above it.
2711     if (AFI->hasCalleeSaveStackFreeSpace())
2712       MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
2713     // We iterated bottom up over the registers; flip RegPairs back to top
2714     // down order.
2715     std::reverse(RegPairs.begin(), RegPairs.end());
2716   }
2717 }
2718 
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const2719 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2720     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2721     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2722   MachineFunction &MF = *MBB.getParent();
2723   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2724   bool NeedsWinCFI = needsWinCFI(MF);
2725   DebugLoc DL;
2726   SmallVector<RegPairInfo, 8> RegPairs;
2727 
2728   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2729 
2730   const MachineRegisterInfo &MRI = MF.getRegInfo();
2731   if (homogeneousPrologEpilog(MF)) {
2732     auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
2733                    .setMIFlag(MachineInstr::FrameSetup);
2734 
2735     for (auto &RPI : RegPairs) {
2736       MIB.addReg(RPI.Reg1);
2737       MIB.addReg(RPI.Reg2);
2738 
2739       // Update register live in.
2740       if (!MRI.isReserved(RPI.Reg1))
2741         MBB.addLiveIn(RPI.Reg1);
2742       if (!MRI.isReserved(RPI.Reg2))
2743         MBB.addLiveIn(RPI.Reg2);
2744     }
2745     return true;
2746   }
2747   for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {
2748     unsigned Reg1 = RPI.Reg1;
2749     unsigned Reg2 = RPI.Reg2;
2750     unsigned StrOpc;
2751 
2752     // Issue sequence of spills for cs regs.  The first spill may be converted
2753     // to a pre-decrement store later by emitPrologue if the callee-save stack
2754     // area allocation can't be combined with the local stack area allocation.
2755     // For example:
2756     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2757     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2758     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2759     // Rationale: This sequence saves uop updates compared to a sequence of
2760     // pre-increment spills like stp xi,xj,[sp,#-16]!
2761     // Note: Similar rationale and sequence for restores in epilog.
2762     unsigned Size;
2763     Align Alignment;
2764     switch (RPI.Type) {
2765     case RegPairInfo::GPR:
2766        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2767        Size = 8;
2768        Alignment = Align(8);
2769        break;
2770     case RegPairInfo::FPR64:
2771        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2772        Size = 8;
2773        Alignment = Align(8);
2774        break;
2775     case RegPairInfo::FPR128:
2776        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2777        Size = 16;
2778        Alignment = Align(16);
2779        break;
2780     case RegPairInfo::ZPR:
2781        StrOpc = AArch64::STR_ZXI;
2782        Size = 16;
2783        Alignment = Align(16);
2784        break;
2785     case RegPairInfo::PPR:
2786        StrOpc = AArch64::STR_PXI;
2787        Size = 2;
2788        Alignment = Align(2);
2789        break;
2790     }
2791     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2792                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2793                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2794                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2795                dbgs() << ")\n");
2796 
2797     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2798            "Windows unwdinding requires a consecutive (FP,LR) pair");
2799     // Windows unwind codes require consecutive registers if registers are
2800     // paired.  Make the switch here, so that the code below will save (x,x+1)
2801     // and not (x+1,x).
2802     unsigned FrameIdxReg1 = RPI.FrameIdx;
2803     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2804     if (NeedsWinCFI && RPI.isPaired()) {
2805       std::swap(Reg1, Reg2);
2806       std::swap(FrameIdxReg1, FrameIdxReg2);
2807     }
2808     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2809     if (!MRI.isReserved(Reg1))
2810       MBB.addLiveIn(Reg1);
2811     if (RPI.isPaired()) {
2812       if (!MRI.isReserved(Reg2))
2813         MBB.addLiveIn(Reg2);
2814       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2815       MIB.addMemOperand(MF.getMachineMemOperand(
2816           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2817           MachineMemOperand::MOStore, Size, Alignment));
2818     }
2819     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2820         .addReg(AArch64::SP)
2821         .addImm(RPI.Offset) // [sp, #offset*scale],
2822                             // where factor*scale is implicit
2823         .setMIFlag(MachineInstr::FrameSetup);
2824     MIB.addMemOperand(MF.getMachineMemOperand(
2825         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2826         MachineMemOperand::MOStore, Size, Alignment));
2827     if (NeedsWinCFI)
2828       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2829 
2830     // Update the StackIDs of the SVE stack slots.
2831     MachineFrameInfo &MFI = MF.getFrameInfo();
2832     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2833       MFI.setStackID(RPI.FrameIdx, TargetStackID::ScalableVector);
2834 
2835   }
2836   return true;
2837 }
2838 
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,MutableArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const2839 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2840     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
2841     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2842   MachineFunction &MF = *MBB.getParent();
2843   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2844   DebugLoc DL;
2845   SmallVector<RegPairInfo, 8> RegPairs;
2846   bool NeedsWinCFI = needsWinCFI(MF);
2847 
2848   if (MBBI != MBB.end())
2849     DL = MBBI->getDebugLoc();
2850 
2851   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2852 
2853   auto EmitMI = [&](const RegPairInfo &RPI) -> MachineBasicBlock::iterator {
2854     unsigned Reg1 = RPI.Reg1;
2855     unsigned Reg2 = RPI.Reg2;
2856 
2857     // Issue sequence of restores for cs regs. The last restore may be converted
2858     // to a post-increment load later by emitEpilogue if the callee-save stack
2859     // area allocation can't be combined with the local stack area allocation.
2860     // For example:
2861     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2862     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2863     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2864     // Note: see comment in spillCalleeSavedRegisters()
2865     unsigned LdrOpc;
2866     unsigned Size;
2867     Align Alignment;
2868     switch (RPI.Type) {
2869     case RegPairInfo::GPR:
2870        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2871        Size = 8;
2872        Alignment = Align(8);
2873        break;
2874     case RegPairInfo::FPR64:
2875        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2876        Size = 8;
2877        Alignment = Align(8);
2878        break;
2879     case RegPairInfo::FPR128:
2880        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2881        Size = 16;
2882        Alignment = Align(16);
2883        break;
2884     case RegPairInfo::ZPR:
2885        LdrOpc = AArch64::LDR_ZXI;
2886        Size = 16;
2887        Alignment = Align(16);
2888        break;
2889     case RegPairInfo::PPR:
2890        LdrOpc = AArch64::LDR_PXI;
2891        Size = 2;
2892        Alignment = Align(2);
2893        break;
2894     }
2895     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2896                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2897                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2898                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2899                dbgs() << ")\n");
2900 
2901     // Windows unwind codes require consecutive registers if registers are
2902     // paired.  Make the switch here, so that the code below will save (x,x+1)
2903     // and not (x+1,x).
2904     unsigned FrameIdxReg1 = RPI.FrameIdx;
2905     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2906     if (NeedsWinCFI && RPI.isPaired()) {
2907       std::swap(Reg1, Reg2);
2908       std::swap(FrameIdxReg1, FrameIdxReg2);
2909     }
2910     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
2911     if (RPI.isPaired()) {
2912       MIB.addReg(Reg2, getDefRegState(true));
2913       MIB.addMemOperand(MF.getMachineMemOperand(
2914           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2915           MachineMemOperand::MOLoad, Size, Alignment));
2916     }
2917     MIB.addReg(Reg1, getDefRegState(true))
2918         .addReg(AArch64::SP)
2919         .addImm(RPI.Offset) // [sp, #offset*scale]
2920                             // where factor*scale is implicit
2921         .setMIFlag(MachineInstr::FrameDestroy);
2922     MIB.addMemOperand(MF.getMachineMemOperand(
2923         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2924         MachineMemOperand::MOLoad, Size, Alignment));
2925     if (NeedsWinCFI)
2926       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2927 
2928     return MIB->getIterator();
2929   };
2930 
2931   // SVE objects are always restored in reverse order.
2932   for (const RegPairInfo &RPI : reverse(RegPairs))
2933     if (RPI.isScalable())
2934       EmitMI(RPI);
2935 
2936   if (homogeneousPrologEpilog(MF, &MBB)) {
2937     auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
2938                    .setMIFlag(MachineInstr::FrameDestroy);
2939     for (auto &RPI : RegPairs) {
2940       MIB.addReg(RPI.Reg1, RegState::Define);
2941       MIB.addReg(RPI.Reg2, RegState::Define);
2942     }
2943     return true;
2944   }
2945 
2946   if (ReverseCSRRestoreSeq) {
2947     MachineBasicBlock::iterator First = MBB.end();
2948     for (const RegPairInfo &RPI : reverse(RegPairs)) {
2949       if (RPI.isScalable())
2950         continue;
2951       MachineBasicBlock::iterator It = EmitMI(RPI);
2952       if (First == MBB.end())
2953         First = It;
2954     }
2955     if (First != MBB.end())
2956       MBB.splice(MBBI, &MBB, First);
2957   } else {
2958     for (const RegPairInfo &RPI : RegPairs) {
2959       if (RPI.isScalable())
2960         continue;
2961       (void)EmitMI(RPI);
2962     }
2963   }
2964 
2965   return true;
2966 }
2967 
determineCalleeSaves(MachineFunction & MF,BitVector & SavedRegs,RegScavenger * RS) const2968 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2969                                                 BitVector &SavedRegs,
2970                                                 RegScavenger *RS) const {
2971   // All calls are tail calls in GHC calling conv, and functions have no
2972   // prologue/epilogue.
2973   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2974     return;
2975 
2976   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2977   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2978       MF.getSubtarget().getRegisterInfo());
2979   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2980   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2981   unsigned UnspilledCSGPR = AArch64::NoRegister;
2982   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2983 
2984   MachineFrameInfo &MFI = MF.getFrameInfo();
2985   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2986 
2987   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2988                                 ? RegInfo->getBaseRegister()
2989                                 : (unsigned)AArch64::NoRegister;
2990 
2991   if (MFI.hasReturnProtectorRegister() && MFI.getReturnProtectorNeedsStore()) {
2992     SavedRegs.set(MFI.getReturnProtectorRegister());
2993   }
2994 
2995   unsigned ExtraCSSpill = 0;
2996   // Figure out which callee-saved registers to save/restore.
2997   for (unsigned i = 0; CSRegs[i]; ++i) {
2998     const unsigned Reg = CSRegs[i];
2999 
3000     // Add the base pointer register to SavedRegs if it is callee-save.
3001     if (Reg == BasePointerReg)
3002       SavedRegs.set(Reg);
3003 
3004     bool RegUsed = SavedRegs.test(Reg);
3005     unsigned PairedReg = AArch64::NoRegister;
3006     if (AArch64::GPR64RegClass.contains(Reg) ||
3007         AArch64::FPR64RegClass.contains(Reg) ||
3008         AArch64::FPR128RegClass.contains(Reg))
3009       PairedReg = CSRegs[i ^ 1];
3010 
3011     if (!RegUsed) {
3012       if (AArch64::GPR64RegClass.contains(Reg) &&
3013           !RegInfo->isReservedReg(MF, Reg)) {
3014         UnspilledCSGPR = Reg;
3015         UnspilledCSGPRPaired = PairedReg;
3016       }
3017       continue;
3018     }
3019 
3020     // MachO's compact unwind format relies on all registers being stored in
3021     // pairs.
3022     // FIXME: the usual format is actually better if unwinding isn't needed.
3023     if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&
3024         !SavedRegs.test(PairedReg)) {
3025       SavedRegs.set(PairedReg);
3026       if (AArch64::GPR64RegClass.contains(PairedReg) &&
3027           !RegInfo->isReservedReg(MF, PairedReg))
3028         ExtraCSSpill = PairedReg;
3029     }
3030   }
3031 
3032   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
3033       !Subtarget.isTargetWindows()) {
3034     // For Windows calling convention on a non-windows OS, where X18 is treated
3035     // as reserved, back up X18 when entering non-windows code (marked with the
3036     // Windows calling convention) and restore when returning regardless of
3037     // whether the individual function uses it - it might call other functions
3038     // that clobber it.
3039     SavedRegs.set(AArch64::X18);
3040   }
3041 
3042   // Calculates the callee saved stack size.
3043   unsigned CSStackSize = 0;
3044   unsigned SVECSStackSize = 0;
3045   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3046   const MachineRegisterInfo &MRI = MF.getRegInfo();
3047   for (unsigned Reg : SavedRegs.set_bits()) {
3048     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
3049     if (AArch64::PPRRegClass.contains(Reg) ||
3050         AArch64::ZPRRegClass.contains(Reg))
3051       SVECSStackSize += RegSize;
3052     else
3053       CSStackSize += RegSize;
3054   }
3055 
3056   // Save number of saved regs, so we can easily update CSStackSize later.
3057   unsigned NumSavedRegs = SavedRegs.count();
3058 
3059   // The frame record needs to be created by saving the appropriate registers
3060   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
3061   if (hasFP(MF) ||
3062       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
3063     SavedRegs.set(AArch64::FP);
3064     SavedRegs.set(AArch64::LR);
3065   }
3066 
3067   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
3068              for (unsigned Reg
3069                   : SavedRegs.set_bits()) dbgs()
3070              << ' ' << printReg(Reg, RegInfo);
3071              dbgs() << "\n";);
3072 
3073   // If any callee-saved registers are used, the frame cannot be eliminated.
3074   int64_t SVEStackSize =
3075       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
3076   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
3077 
3078   // The CSR spill slots have not been allocated yet, so estimateStackSize
3079   // won't include them.
3080   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
3081 
3082   // Conservatively always assume BigStack when there are SVE spills.
3083   bool BigStack = SVEStackSize ||
3084                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
3085   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
3086     AFI->setHasStackFrame(true);
3087 
3088   // Estimate if we might need to scavenge a register at some point in order
3089   // to materialize a stack offset. If so, either spill one additional
3090   // callee-saved register or reserve a special spill slot to facilitate
3091   // register scavenging. If we already spilled an extra callee-saved register
3092   // above to keep the number of spills even, we don't need to do anything else
3093   // here.
3094   if (BigStack) {
3095     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
3096       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
3097                         << " to get a scratch register.\n");
3098       SavedRegs.set(UnspilledCSGPR);
3099       // MachO's compact unwind format relies on all registers being stored in
3100       // pairs, so if we need to spill one extra for BigStack, then we need to
3101       // store the pair.
3102       if (producePairRegisters(MF))
3103         SavedRegs.set(UnspilledCSGPRPaired);
3104       ExtraCSSpill = UnspilledCSGPR;
3105     }
3106 
3107     // If we didn't find an extra callee-saved register to spill, create
3108     // an emergency spill slot.
3109     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
3110       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3111       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
3112       unsigned Size = TRI->getSpillSize(RC);
3113       Align Alignment = TRI->getSpillAlign(RC);
3114       int FI = MFI.CreateStackObject(Size, Alignment, false);
3115       RS->addScavengingFrameIndex(FI);
3116       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
3117                         << " as the emergency spill slot.\n");
3118     }
3119   }
3120 
3121   // Adding the size of additional 64bit GPR saves.
3122   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
3123 
3124   // A Swift asynchronous context extends the frame record with a pointer
3125   // directly before FP.
3126   if (hasFP(MF) && AFI->hasSwiftAsyncContext())
3127     CSStackSize += 8;
3128 
3129   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
3130   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
3131                << EstimatedStackSize + AlignedCSStackSize
3132                << " bytes.\n");
3133 
3134   assert((!MFI.isCalleeSavedInfoValid() ||
3135           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
3136          "Should not invalidate callee saved info");
3137 
3138   // Round up to register pair alignment to avoid additional SP adjustment
3139   // instructions.
3140   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
3141   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
3142   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
3143 }
3144 
assignCalleeSavedSpillSlots(MachineFunction & MF,const TargetRegisterInfo * RegInfo,std::vector<CalleeSavedInfo> & CSI,unsigned & MinCSFrameIndex,unsigned & MaxCSFrameIndex) const3145 bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
3146     MachineFunction &MF, const TargetRegisterInfo *RegInfo,
3147     std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,
3148     unsigned &MaxCSFrameIndex) const {
3149   bool NeedsWinCFI = needsWinCFI(MF);
3150   // To match the canonical windows frame layout, reverse the list of
3151   // callee saved registers to get them laid out by PrologEpilogInserter
3152   // in the right order. (PrologEpilogInserter allocates stack objects top
3153   // down. Windows canonical prologs store higher numbered registers at
3154   // the top, thus have the CSI array start from the highest registers.)
3155   if (NeedsWinCFI)
3156     std::reverse(CSI.begin(), CSI.end());
3157 
3158   if (CSI.empty())
3159     return true; // Early exit if no callee saved registers are modified!
3160 
3161   // Now that we know which registers need to be saved and restored, allocate
3162   // stack slots for them.
3163   MachineFrameInfo &MFI = MF.getFrameInfo();
3164   auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3165 
3166   bool UsesWinAAPCS = isTargetWindows(MF);
3167   if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) {
3168     int FrameIdx = MFI.CreateStackObject(8, Align(16), true);
3169     AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3170     if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3171     if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3172   }
3173 
3174   for (auto &CS : CSI) {
3175     Register Reg = CS.getReg();
3176     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
3177 
3178     unsigned Size = RegInfo->getSpillSize(*RC);
3179     Align Alignment(RegInfo->getSpillAlign(*RC));
3180     int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
3181     CS.setFrameIdx(FrameIdx);
3182 
3183     if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3184     if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3185 
3186     // Grab 8 bytes below FP for the extended asynchronous frame info.
3187     if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS &&
3188         Reg == AArch64::FP) {
3189       FrameIdx = MFI.CreateStackObject(8, Alignment, true);
3190       AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3191       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
3192       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
3193     }
3194   }
3195   return true;
3196 }
3197 
enableStackSlotScavenging(const MachineFunction & MF) const3198 bool AArch64FrameLowering::enableStackSlotScavenging(
3199     const MachineFunction &MF) const {
3200   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3201   return AFI->hasCalleeSaveStackFreeSpace();
3202 }
3203 
3204 /// returns true if there are any SVE callee saves.
getSVECalleeSaveSlotRange(const MachineFrameInfo & MFI,int & Min,int & Max)3205 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
3206                                       int &Min, int &Max) {
3207   Min = std::numeric_limits<int>::max();
3208   Max = std::numeric_limits<int>::min();
3209 
3210   if (!MFI.isCalleeSavedInfoValid())
3211     return false;
3212 
3213   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
3214   for (auto &CS : CSI) {
3215     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
3216         AArch64::PPRRegClass.contains(CS.getReg())) {
3217       assert((Max == std::numeric_limits<int>::min() ||
3218               Max + 1 == CS.getFrameIdx()) &&
3219              "SVE CalleeSaves are not consecutive");
3220 
3221       Min = std::min(Min, CS.getFrameIdx());
3222       Max = std::max(Max, CS.getFrameIdx());
3223     }
3224   }
3225   return Min != std::numeric_limits<int>::max();
3226 }
3227 
3228 // Process all the SVE stack objects and determine offsets for each
3229 // object. If AssignOffsets is true, the offsets get assigned.
3230 // Fills in the first and last callee-saved frame indices into
3231 // Min/MaxCSFrameIndex, respectively.
3232 // Returns the size of the stack.
determineSVEStackObjectOffsets(MachineFrameInfo & MFI,int & MinCSFrameIndex,int & MaxCSFrameIndex,bool AssignOffsets)3233 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
3234                                               int &MinCSFrameIndex,
3235                                               int &MaxCSFrameIndex,
3236                                               bool AssignOffsets) {
3237 #ifndef NDEBUG
3238   // First process all fixed stack objects.
3239   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
3240     assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&
3241            "SVE vectors should never be passed on the stack by value, only by "
3242            "reference.");
3243 #endif
3244 
3245   auto Assign = [&MFI](int FI, int64_t Offset) {
3246     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
3247     MFI.setObjectOffset(FI, Offset);
3248   };
3249 
3250   int64_t Offset = 0;
3251 
3252   // Then process all callee saved slots.
3253   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
3254     // Assign offsets to the callee save slots.
3255     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
3256       Offset += MFI.getObjectSize(I);
3257       Offset = alignTo(Offset, MFI.getObjectAlign(I));
3258       if (AssignOffsets)
3259         Assign(I, -Offset);
3260     }
3261   }
3262 
3263   // Ensure that the Callee-save area is aligned to 16bytes.
3264   Offset = alignTo(Offset, Align(16U));
3265 
3266   // Create a buffer of SVE objects to allocate and sort it.
3267   SmallVector<int, 8> ObjectsToAllocate;
3268   // If we have a stack protector, and we've previously decided that we have SVE
3269   // objects on the stack and thus need it to go in the SVE stack area, then it
3270   // needs to go first.
3271   int StackProtectorFI = -1;
3272   if (MFI.hasStackProtectorIndex()) {
3273     StackProtectorFI = MFI.getStackProtectorIndex();
3274     if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
3275       ObjectsToAllocate.push_back(StackProtectorFI);
3276   }
3277   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
3278     unsigned StackID = MFI.getStackID(I);
3279     if (StackID != TargetStackID::ScalableVector)
3280       continue;
3281     if (I == StackProtectorFI)
3282       continue;
3283     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
3284       continue;
3285     if (MFI.isDeadObjectIndex(I))
3286       continue;
3287 
3288     ObjectsToAllocate.push_back(I);
3289   }
3290 
3291   // Allocate all SVE locals and spills
3292   for (unsigned FI : ObjectsToAllocate) {
3293     Align Alignment = MFI.getObjectAlign(FI);
3294     // FIXME: Given that the length of SVE vectors is not necessarily a power of
3295     // two, we'd need to align every object dynamically at runtime if the
3296     // alignment is larger than 16. This is not yet supported.
3297     if (Alignment > Align(16))
3298       report_fatal_error(
3299           "Alignment of scalable vectors > 16 bytes is not yet supported");
3300 
3301     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
3302     if (AssignOffsets)
3303       Assign(FI, -Offset);
3304   }
3305 
3306   return Offset;
3307 }
3308 
estimateSVEStackObjectOffsets(MachineFrameInfo & MFI) const3309 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
3310     MachineFrameInfo &MFI) const {
3311   int MinCSFrameIndex, MaxCSFrameIndex;
3312   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
3313 }
3314 
assignSVEStackObjectOffsets(MachineFrameInfo & MFI,int & MinCSFrameIndex,int & MaxCSFrameIndex) const3315 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
3316     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
3317   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
3318                                         true);
3319 }
3320 
processFunctionBeforeFrameFinalized(MachineFunction & MF,RegScavenger * RS) const3321 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
3322     MachineFunction &MF, RegScavenger *RS) const {
3323   MachineFrameInfo &MFI = MF.getFrameInfo();
3324 
3325   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
3326          "Upwards growing stack unsupported");
3327 
3328   int MinCSFrameIndex, MaxCSFrameIndex;
3329   int64_t SVEStackSize =
3330       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
3331 
3332   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3333   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
3334   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
3335 
3336   // If this function isn't doing Win64-style C++ EH, we don't need to do
3337   // anything.
3338   if (!MF.hasEHFunclets())
3339     return;
3340   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
3341   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3342 
3343   MachineBasicBlock &MBB = MF.front();
3344   auto MBBI = MBB.begin();
3345   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3346     ++MBBI;
3347 
3348   // Create an UnwindHelp object.
3349   // The UnwindHelp object is allocated at the start of the fixed object area
3350   int64_t FixedObject =
3351       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
3352   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
3353                                            /*SPOffset*/ -FixedObject,
3354                                            /*IsImmutable=*/false);
3355   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3356 
3357   // We need to store -2 into the UnwindHelp object at the start of the
3358   // function.
3359   DebugLoc DL;
3360   RS->enterBasicBlockEnd(MBB);
3361   RS->backward(std::prev(MBBI));
3362   Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
3363   assert(DstReg && "There must be a free register after frame setup");
3364   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
3365   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
3366       .addReg(DstReg, getKillRegState(true))
3367       .addFrameIndex(UnwindHelpFI)
3368       .addImm(0);
3369 }
3370 
3371 namespace {
3372 struct TagStoreInstr {
3373   MachineInstr *MI;
3374   int64_t Offset, Size;
TagStoreInstr__anon61e914860811::TagStoreInstr3375   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
3376       : MI(MI), Offset(Offset), Size(Size) {}
3377 };
3378 
3379 class TagStoreEdit {
3380   MachineFunction *MF;
3381   MachineBasicBlock *MBB;
3382   MachineRegisterInfo *MRI;
3383   // Tag store instructions that are being replaced.
3384   SmallVector<TagStoreInstr, 8> TagStores;
3385   // Combined memref arguments of the above instructions.
3386   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
3387 
3388   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
3389   // FrameRegOffset + Size) with the address tag of SP.
3390   Register FrameReg;
3391   StackOffset FrameRegOffset;
3392   int64_t Size;
3393   // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
3394   std::optional<int64_t> FrameRegUpdate;
3395   // MIFlags for any FrameReg updating instructions.
3396   unsigned FrameRegUpdateFlags;
3397 
3398   // Use zeroing instruction variants.
3399   bool ZeroData;
3400   DebugLoc DL;
3401 
3402   void emitUnrolled(MachineBasicBlock::iterator InsertI);
3403   void emitLoop(MachineBasicBlock::iterator InsertI);
3404 
3405 public:
TagStoreEdit(MachineBasicBlock * MBB,bool ZeroData)3406   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
3407       : MBB(MBB), ZeroData(ZeroData) {
3408     MF = MBB->getParent();
3409     MRI = &MF->getRegInfo();
3410   }
3411   // Add an instruction to be replaced. Instructions must be added in the
3412   // ascending order of Offset, and have to be adjacent.
addInstruction(TagStoreInstr I)3413   void addInstruction(TagStoreInstr I) {
3414     assert((TagStores.empty() ||
3415             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
3416            "Non-adjacent tag store instructions.");
3417     TagStores.push_back(I);
3418   }
clear()3419   void clear() { TagStores.clear(); }
3420   // Emit equivalent code at the given location, and erase the current set of
3421   // instructions. May skip if the replacement is not profitable. May invalidate
3422   // the input iterator and replace it with a valid one.
3423   void emitCode(MachineBasicBlock::iterator &InsertI,
3424                 const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);
3425 };
3426 
emitUnrolled(MachineBasicBlock::iterator InsertI)3427 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
3428   const AArch64InstrInfo *TII =
3429       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3430 
3431   const int64_t kMinOffset = -256 * 16;
3432   const int64_t kMaxOffset = 255 * 16;
3433 
3434   Register BaseReg = FrameReg;
3435   int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
3436   if (BaseRegOffsetBytes < kMinOffset ||
3437       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
3438     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3439     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
3440                     StackOffset::getFixed(BaseRegOffsetBytes), TII);
3441     BaseReg = ScratchReg;
3442     BaseRegOffsetBytes = 0;
3443   }
3444 
3445   MachineInstr *LastI = nullptr;
3446   while (Size) {
3447     int64_t InstrSize = (Size > 16) ? 32 : 16;
3448     unsigned Opcode =
3449         InstrSize == 16
3450             ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
3451             : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
3452     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
3453                           .addReg(AArch64::SP)
3454                           .addReg(BaseReg)
3455                           .addImm(BaseRegOffsetBytes / 16)
3456                           .setMemRefs(CombinedMemRefs);
3457     // A store to [BaseReg, #0] should go last for an opportunity to fold the
3458     // final SP adjustment in the epilogue.
3459     if (BaseRegOffsetBytes == 0)
3460       LastI = I;
3461     BaseRegOffsetBytes += InstrSize;
3462     Size -= InstrSize;
3463   }
3464 
3465   if (LastI)
3466     MBB->splice(InsertI, MBB, LastI);
3467 }
3468 
emitLoop(MachineBasicBlock::iterator InsertI)3469 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
3470   const AArch64InstrInfo *TII =
3471       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3472 
3473   Register BaseReg = FrameRegUpdate
3474                          ? FrameReg
3475                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3476   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3477 
3478   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
3479 
3480   int64_t LoopSize = Size;
3481   // If the loop size is not a multiple of 32, split off one 16-byte store at
3482   // the end to fold BaseReg update into.
3483   if (FrameRegUpdate && *FrameRegUpdate)
3484     LoopSize -= LoopSize % 32;
3485   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
3486                                 TII->get(ZeroData ? AArch64::STZGloop_wback
3487                                                   : AArch64::STGloop_wback))
3488                             .addDef(SizeReg)
3489                             .addDef(BaseReg)
3490                             .addImm(LoopSize)
3491                             .addReg(BaseReg)
3492                             .setMemRefs(CombinedMemRefs);
3493   if (FrameRegUpdate)
3494     LoopI->setFlags(FrameRegUpdateFlags);
3495 
3496   int64_t ExtraBaseRegUpdate =
3497       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
3498   if (LoopSize < Size) {
3499     assert(FrameRegUpdate);
3500     assert(Size - LoopSize == 16);
3501     // Tag 16 more bytes at BaseReg and update BaseReg.
3502     BuildMI(*MBB, InsertI, DL,
3503             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
3504         .addDef(BaseReg)
3505         .addReg(BaseReg)
3506         .addReg(BaseReg)
3507         .addImm(1 + ExtraBaseRegUpdate / 16)
3508         .setMemRefs(CombinedMemRefs)
3509         .setMIFlags(FrameRegUpdateFlags);
3510   } else if (ExtraBaseRegUpdate) {
3511     // Update BaseReg.
3512     BuildMI(
3513         *MBB, InsertI, DL,
3514         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
3515         .addDef(BaseReg)
3516         .addReg(BaseReg)
3517         .addImm(std::abs(ExtraBaseRegUpdate))
3518         .addImm(0)
3519         .setMIFlags(FrameRegUpdateFlags);
3520   }
3521 }
3522 
3523 // Check if *II is a register update that can be merged into STGloop that ends
3524 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
3525 // end of the loop.
canMergeRegUpdate(MachineBasicBlock::iterator II,unsigned Reg,int64_t Size,int64_t * TotalOffset)3526 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
3527                        int64_t Size, int64_t *TotalOffset) {
3528   MachineInstr &MI = *II;
3529   if ((MI.getOpcode() == AArch64::ADDXri ||
3530        MI.getOpcode() == AArch64::SUBXri) &&
3531       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
3532     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
3533     int64_t Offset = MI.getOperand(2).getImm() << Shift;
3534     if (MI.getOpcode() == AArch64::SUBXri)
3535       Offset = -Offset;
3536     int64_t AbsPostOffset = std::abs(Offset - Size);
3537     const int64_t kMaxOffset =
3538         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
3539     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
3540       *TotalOffset = Offset;
3541       return true;
3542     }
3543   }
3544   return false;
3545 }
3546 
mergeMemRefs(const SmallVectorImpl<TagStoreInstr> & TSE,SmallVectorImpl<MachineMemOperand * > & MemRefs)3547 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
3548                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
3549   MemRefs.clear();
3550   for (auto &TS : TSE) {
3551     MachineInstr *MI = TS.MI;
3552     // An instruction without memory operands may access anything. Be
3553     // conservative and return an empty list.
3554     if (MI->memoperands_empty()) {
3555       MemRefs.clear();
3556       return;
3557     }
3558     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
3559   }
3560 }
3561 
emitCode(MachineBasicBlock::iterator & InsertI,const AArch64FrameLowering * TFI,bool TryMergeSPUpdate)3562 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
3563                             const AArch64FrameLowering *TFI,
3564                             bool TryMergeSPUpdate) {
3565   if (TagStores.empty())
3566     return;
3567   TagStoreInstr &FirstTagStore = TagStores[0];
3568   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
3569   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
3570   DL = TagStores[0].MI->getDebugLoc();
3571 
3572   Register Reg;
3573   FrameRegOffset = TFI->resolveFrameOffsetReference(
3574       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
3575       /*PreferFP=*/false, /*ForSimm=*/true);
3576   FrameReg = Reg;
3577   FrameRegUpdate = std::nullopt;
3578 
3579   mergeMemRefs(TagStores, CombinedMemRefs);
3580 
3581   LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
3582              for (const auto &Instr
3583                   : TagStores) { dbgs() << "  " << *Instr.MI; });
3584 
3585   // Size threshold where a loop becomes shorter than a linear sequence of
3586   // tagging instructions.
3587   const int kSetTagLoopThreshold = 176;
3588   if (Size < kSetTagLoopThreshold) {
3589     if (TagStores.size() < 2)
3590       return;
3591     emitUnrolled(InsertI);
3592   } else {
3593     MachineInstr *UpdateInstr = nullptr;
3594     int64_t TotalOffset = 0;
3595     if (TryMergeSPUpdate) {
3596       // See if we can merge base register update into the STGloop.
3597       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3598       // but STGloop is way too unusual for that, and also it only
3599       // realistically happens in function epilogue. Also, STGloop is expanded
3600       // before that pass.
3601       if (InsertI != MBB->end() &&
3602           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,
3603                             &TotalOffset)) {
3604         UpdateInstr = &*InsertI++;
3605         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
3606                           << *UpdateInstr);
3607       }
3608     }
3609 
3610     if (!UpdateInstr && TagStores.size() < 2)
3611       return;
3612 
3613     if (UpdateInstr) {
3614       FrameRegUpdate = TotalOffset;
3615       FrameRegUpdateFlags = UpdateInstr->getFlags();
3616     }
3617     emitLoop(InsertI);
3618     if (UpdateInstr)
3619       UpdateInstr->eraseFromParent();
3620   }
3621 
3622   for (auto &TS : TagStores)
3623     TS.MI->eraseFromParent();
3624 }
3625 
isMergeableStackTaggingInstruction(MachineInstr & MI,int64_t & Offset,int64_t & Size,bool & ZeroData)3626 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
3627                                         int64_t &Size, bool &ZeroData) {
3628   MachineFunction &MF = *MI.getParent()->getParent();
3629   const MachineFrameInfo &MFI = MF.getFrameInfo();
3630 
3631   unsigned Opcode = MI.getOpcode();
3632   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
3633               Opcode == AArch64::STZ2GOffset);
3634 
3635   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
3636     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
3637       return false;
3638     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
3639       return false;
3640     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
3641     Size = MI.getOperand(2).getImm();
3642     return true;
3643   }
3644 
3645   if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
3646     Size = 16;
3647   else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
3648     Size = 32;
3649   else
3650     return false;
3651 
3652   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3653     return false;
3654 
3655   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3656            16 * MI.getOperand(2).getImm();
3657   return true;
3658 }
3659 
3660 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3661 // and replace them with a shorter instruction sequence:
3662 // * replace STG + STG with ST2G
3663 // * replace STGloop + STGloop with STGloop
3664 // This code needs to run when stack slot offsets are already known, but before
3665 // FrameIndex operands in STG instructions are eliminated.
tryMergeAdjacentSTG(MachineBasicBlock::iterator II,const AArch64FrameLowering * TFI,RegScavenger * RS)3666 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
3667                                                 const AArch64FrameLowering *TFI,
3668                                                 RegScavenger *RS) {
3669   bool FirstZeroData;
3670   int64_t Size, Offset;
3671   MachineInstr &MI = *II;
3672   MachineBasicBlock *MBB = MI.getParent();
3673   MachineBasicBlock::iterator NextI = ++II;
3674   if (&MI == &MBB->instr_back())
3675     return II;
3676   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3677     return II;
3678 
3679   SmallVector<TagStoreInstr, 4> Instrs;
3680   Instrs.emplace_back(&MI, Offset, Size);
3681 
3682   constexpr int kScanLimit = 10;
3683   int Count = 0;
3684   for (MachineBasicBlock::iterator E = MBB->end();
3685        NextI != E && Count < kScanLimit; ++NextI) {
3686     MachineInstr &MI = *NextI;
3687     bool ZeroData;
3688     int64_t Size, Offset;
3689     // Collect instructions that update memory tags with a FrameIndex operand
3690     // and (when applicable) constant size, and whose output registers are dead
3691     // (the latter is almost always the case in practice). Since these
3692     // instructions effectively have no inputs or outputs, we are free to skip
3693     // any non-aliasing instructions in between without tracking used registers.
3694     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3695       if (ZeroData != FirstZeroData)
3696         break;
3697       Instrs.emplace_back(&MI, Offset, Size);
3698       continue;
3699     }
3700 
3701     // Only count non-transient, non-tagging instructions toward the scan
3702     // limit.
3703     if (!MI.isTransient())
3704       ++Count;
3705 
3706     // Just in case, stop before the epilogue code starts.
3707     if (MI.getFlag(MachineInstr::FrameSetup) ||
3708         MI.getFlag(MachineInstr::FrameDestroy))
3709       break;
3710 
3711     // Reject anything that may alias the collected instructions.
3712     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
3713       break;
3714   }
3715 
3716   // New code will be inserted after the last tagging instruction we've found.
3717   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3718   InsertI++;
3719 
3720   llvm::stable_sort(Instrs,
3721                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3722                       return Left.Offset < Right.Offset;
3723                     });
3724 
3725   // Make sure that we don't have any overlapping stores.
3726   int64_t CurOffset = Instrs[0].Offset;
3727   for (auto &Instr : Instrs) {
3728     if (CurOffset > Instr.Offset)
3729       return NextI;
3730     CurOffset = Instr.Offset + Instr.Size;
3731   }
3732 
3733   // Find contiguous runs of tagged memory and emit shorter instruction
3734   // sequencies for them when possible.
3735   TagStoreEdit TSE(MBB, FirstZeroData);
3736   std::optional<int64_t> EndOffset;
3737   for (auto &Instr : Instrs) {
3738     if (EndOffset && *EndOffset != Instr.Offset) {
3739       // Found a gap.
3740       TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);
3741       TSE.clear();
3742     }
3743 
3744     TSE.addInstruction(Instr);
3745     EndOffset = Instr.Offset + Instr.Size;
3746   }
3747 
3748   const MachineFunction *MF = MBB->getParent();
3749   // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
3750   TSE.emitCode(
3751       InsertI, TFI, /*TryMergeSPUpdate = */
3752       !MF->getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(*MF));
3753 
3754   return InsertI;
3755 }
3756 } // namespace
3757 
processFunctionBeforeFrameIndicesReplaced(MachineFunction & MF,RegScavenger * RS=nullptr) const3758 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3759     MachineFunction &MF, RegScavenger *RS = nullptr) const {
3760   if (StackTaggingMergeSetTag)
3761     for (auto &BB : MF)
3762       for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
3763         II = tryMergeAdjacentSTG(II, this, RS);
3764 }
3765 
3766 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3767 /// before the update.  This is easily retrieved as it is exactly the offset
3768 /// that is set in processFunctionBeforeFrameFinalized.
getFrameIndexReferencePreferSP(const MachineFunction & MF,int FI,Register & FrameReg,bool IgnoreSPUpdates) const3769 StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(
3770     const MachineFunction &MF, int FI, Register &FrameReg,
3771     bool IgnoreSPUpdates) const {
3772   const MachineFrameInfo &MFI = MF.getFrameInfo();
3773   if (IgnoreSPUpdates) {
3774     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3775                       << MFI.getObjectOffset(FI) << "\n");
3776     FrameReg = AArch64::SP;
3777     return StackOffset::getFixed(MFI.getObjectOffset(FI));
3778   }
3779 
3780   // Go to common code if we cannot provide sp + offset.
3781   if (MFI.hasVarSizedObjects() ||
3782       MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||
3783       MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))
3784     return getFrameIndexReference(MF, FI, FrameReg);
3785 
3786   FrameReg = AArch64::SP;
3787   return getStackOffset(MF, MFI.getObjectOffset(FI));
3788 }
3789 
3790 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3791 /// the parent's frame pointer
getWinEHParentFrameOffset(const MachineFunction & MF) const3792 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3793     const MachineFunction &MF) const {
3794   return 0;
3795 }
3796 
3797 /// Funclets only need to account for space for the callee saved registers,
3798 /// as the locals are accounted for in the parent's stack frame.
getWinEHFuncletFrameSize(const MachineFunction & MF) const3799 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3800     const MachineFunction &MF) const {
3801   // This is the size of the pushed CSRs.
3802   unsigned CSSize =
3803       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3804   // This is the amount of stack a funclet needs to allocate.
3805   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3806                  getStackAlign());
3807 }
3808 
getReturnProtector() const3809 const ReturnProtectorLowering *AArch64FrameLowering::getReturnProtector() const {
3810   return &RPL;
3811 }
3812 
3813 namespace {
3814 struct FrameObject {
3815   bool IsValid = false;
3816   // Index of the object in MFI.
3817   int ObjectIndex = 0;
3818   // Group ID this object belongs to.
3819   int GroupIndex = -1;
3820   // This object should be placed first (closest to SP).
3821   bool ObjectFirst = false;
3822   // This object's group (which always contains the object with
3823   // ObjectFirst==true) should be placed first.
3824   bool GroupFirst = false;
3825 };
3826 
3827 class GroupBuilder {
3828   SmallVector<int, 8> CurrentMembers;
3829   int NextGroupIndex = 0;
3830   std::vector<FrameObject> &Objects;
3831 
3832 public:
GroupBuilder(std::vector<FrameObject> & Objects)3833   GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
AddMember(int Index)3834   void AddMember(int Index) { CurrentMembers.push_back(Index); }
EndCurrentGroup()3835   void EndCurrentGroup() {
3836     if (CurrentMembers.size() > 1) {
3837       // Create a new group with the current member list. This might remove them
3838       // from their pre-existing groups. That's OK, dealing with overlapping
3839       // groups is too hard and unlikely to make a difference.
3840       LLVM_DEBUG(dbgs() << "group:");
3841       for (int Index : CurrentMembers) {
3842         Objects[Index].GroupIndex = NextGroupIndex;
3843         LLVM_DEBUG(dbgs() << " " << Index);
3844       }
3845       LLVM_DEBUG(dbgs() << "\n");
3846       NextGroupIndex++;
3847     }
3848     CurrentMembers.clear();
3849   }
3850 };
3851 
FrameObjectCompare(const FrameObject & A,const FrameObject & B)3852 bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
3853   // Objects at a lower index are closer to FP; objects at a higher index are
3854   // closer to SP.
3855   //
3856   // For consistency in our comparison, all invalid objects are placed
3857   // at the end. This also allows us to stop walking when we hit the
3858   // first invalid item after it's all sorted.
3859   //
3860   // The "first" object goes first (closest to SP), followed by the members of
3861   // the "first" group.
3862   //
3863   // The rest are sorted by the group index to keep the groups together.
3864   // Higher numbered groups are more likely to be around longer (i.e. untagged
3865   // in the function epilogue and not at some earlier point). Place them closer
3866   // to SP.
3867   //
3868   // If all else equal, sort by the object index to keep the objects in the
3869   // original order.
3870   return std::make_tuple(!A.IsValid, A.ObjectFirst, A.GroupFirst, A.GroupIndex,
3871                          A.ObjectIndex) <
3872          std::make_tuple(!B.IsValid, B.ObjectFirst, B.GroupFirst, B.GroupIndex,
3873                          B.ObjectIndex);
3874 }
3875 } // namespace
3876 
orderFrameObjects(const MachineFunction & MF,SmallVectorImpl<int> & ObjectsToAllocate) const3877 void AArch64FrameLowering::orderFrameObjects(
3878     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3879   if (!OrderFrameObjects || ObjectsToAllocate.empty())
3880     return;
3881 
3882   const MachineFrameInfo &MFI = MF.getFrameInfo();
3883   std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
3884   for (auto &Obj : ObjectsToAllocate) {
3885     FrameObjects[Obj].IsValid = true;
3886     FrameObjects[Obj].ObjectIndex = Obj;
3887   }
3888 
3889   // Identify stack slots that are tagged at the same time.
3890   GroupBuilder GB(FrameObjects);
3891   for (auto &MBB : MF) {
3892     for (auto &MI : MBB) {
3893       if (MI.isDebugInstr())
3894         continue;
3895       int OpIndex;
3896       switch (MI.getOpcode()) {
3897       case AArch64::STGloop:
3898       case AArch64::STZGloop:
3899         OpIndex = 3;
3900         break;
3901       case AArch64::STGOffset:
3902       case AArch64::STZGOffset:
3903       case AArch64::ST2GOffset:
3904       case AArch64::STZ2GOffset:
3905         OpIndex = 1;
3906         break;
3907       default:
3908         OpIndex = -1;
3909       }
3910 
3911       int TaggedFI = -1;
3912       if (OpIndex >= 0) {
3913         const MachineOperand &MO = MI.getOperand(OpIndex);
3914         if (MO.isFI()) {
3915           int FI = MO.getIndex();
3916           if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
3917               FrameObjects[FI].IsValid)
3918             TaggedFI = FI;
3919         }
3920       }
3921 
3922       // If this is a stack tagging instruction for a slot that is not part of a
3923       // group yet, either start a new group or add it to the current one.
3924       if (TaggedFI >= 0)
3925         GB.AddMember(TaggedFI);
3926       else
3927         GB.EndCurrentGroup();
3928     }
3929     // Groups should never span multiple basic blocks.
3930     GB.EndCurrentGroup();
3931   }
3932 
3933   // If the function's tagged base pointer is pinned to a stack slot, we want to
3934   // put that slot first when possible. This will likely place it at SP + 0,
3935   // and save one instruction when generating the base pointer because IRG does
3936   // not allow an immediate offset.
3937   const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
3938   std::optional<int> TBPI = AFI.getTaggedBasePointerIndex();
3939   if (TBPI) {
3940     FrameObjects[*TBPI].ObjectFirst = true;
3941     FrameObjects[*TBPI].GroupFirst = true;
3942     int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
3943     if (FirstGroupIndex >= 0)
3944       for (FrameObject &Object : FrameObjects)
3945         if (Object.GroupIndex == FirstGroupIndex)
3946           Object.GroupFirst = true;
3947   }
3948 
3949   llvm::stable_sort(FrameObjects, FrameObjectCompare);
3950 
3951   int i = 0;
3952   for (auto &Obj : FrameObjects) {
3953     // All invalid items are sorted at the end, so it's safe to stop.
3954     if (!Obj.IsValid)
3955       break;
3956     ObjectsToAllocate[i++] = Obj.ObjectIndex;
3957   }
3958 
3959   LLVM_DEBUG(dbgs() << "Final frame order:\n"; for (auto &Obj
3960                                                     : FrameObjects) {
3961     if (!Obj.IsValid)
3962       break;
3963     dbgs() << "  " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
3964     if (Obj.ObjectFirst)
3965       dbgs() << ", first";
3966     if (Obj.GroupFirst)
3967       dbgs() << ", group-first";
3968     dbgs() << "\n";
3969   });
3970 }
3971