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