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 // |                                   |    | (frame record first)
51 // | prev_fp, prev_lr                  | <--'
52 // | (a.k.a. "frame record")           |
53 // |-----------------------------------| <- fp(=x29)
54 // |                                   |
55 // | callee-saved fp/simd/SVE regs     |
56 // |                                   |
57 // |-----------------------------------|
58 // |                                   |
59 // |        SVE stack objects          |
60 // |                                   |
61 // |-----------------------------------|
62 // |.empty.space.to.make.part.below....|
63 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
64 // |.the.standard.16-byte.alignment....|  compile time; if present)
65 // |-----------------------------------|
66 // |                                   |
67 // | local variables of fixed size     |
68 // | including spill slots             |
69 // |-----------------------------------| <- bp(not defined by ABI,
70 // |.variable-sized.local.variables....|       LLVM chooses X19)
71 // |.(VLAs)............................| (size of this area is unknown at
72 // |...................................|  compile time)
73 // |-----------------------------------| <- sp
74 // |                                   | Lower address
75 //
76 //
77 // To access the data in a frame, at-compile time, a constant offset must be
78 // computable from one of the pointers (fp, bp, sp) to access it. The size
79 // of the areas with a dotted background cannot be computed at compile-time
80 // if they are present, making it required to have all three of fp, bp and
81 // sp to be set up to be able to access all contents in the frame areas,
82 // assuming all of the frame areas are non-empty.
83 //
84 // For most functions, some of the frame areas are empty. For those functions,
85 // it may not be necessary to set up fp or bp:
86 // * A base pointer is definitely needed when there are both VLAs and local
87 //   variables with more-than-default alignment requirements.
88 // * A frame pointer is definitely needed when there are local variables with
89 //   more-than-default alignment requirements.
90 //
91 // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
92 // callee-saved area, since the unwind encoding does not allow for encoding
93 // this dynamically and existing tools depend on this layout. For other
94 // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
95 // area to allow SVE stack objects (allocated directly below the callee-saves,
96 // if available) to be accessed directly from the framepointer.
97 // The SVE spill/fill instructions have VL-scaled addressing modes such
98 // as:
99 //    ldr z8, [fp, #-7 mul vl]
100 // For SVE the size of the vector length (VL) is not known at compile-time, so
101 // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
102 // layout, we don't need to add an unscaled offset to the framepointer before
103 // accessing the SVE object in the frame.
104 //
105 // In some cases when a base pointer is not strictly needed, it is generated
106 // anyway when offsets from the frame pointer to access local variables become
107 // so large that the offset can't be encoded in the immediate fields of loads
108 // or stores.
109 //
110 // FIXME: also explain the redzone concept.
111 // FIXME: also explain the concept of reserved call frames.
112 //
113 //===----------------------------------------------------------------------===//
114 
115 #include "AArch64FrameLowering.h"
116 #include "AArch64InstrInfo.h"
117 #include "AArch64MachineFunctionInfo.h"
118 #include "AArch64RegisterInfo.h"
119 #include "AArch64StackOffset.h"
120 #include "AArch64Subtarget.h"
121 #include "AArch64TargetMachine.h"
122 #include "MCTargetDesc/AArch64AddressingModes.h"
123 #include "llvm/ADT/ScopeExit.h"
124 #include "llvm/ADT/SmallVector.h"
125 #include "llvm/ADT/Statistic.h"
126 #include "llvm/CodeGen/LivePhysRegs.h"
127 #include "llvm/CodeGen/MachineBasicBlock.h"
128 #include "llvm/CodeGen/MachineFrameInfo.h"
129 #include "llvm/CodeGen/MachineFunction.h"
130 #include "llvm/CodeGen/MachineInstr.h"
131 #include "llvm/CodeGen/MachineInstrBuilder.h"
132 #include "llvm/CodeGen/MachineMemOperand.h"
133 #include "llvm/CodeGen/MachineModuleInfo.h"
134 #include "llvm/CodeGen/MachineOperand.h"
135 #include "llvm/CodeGen/MachineRegisterInfo.h"
136 #include "llvm/CodeGen/RegisterScavenging.h"
137 #include "llvm/CodeGen/TargetInstrInfo.h"
138 #include "llvm/CodeGen/TargetRegisterInfo.h"
139 #include "llvm/CodeGen/TargetSubtargetInfo.h"
140 #include "llvm/CodeGen/WinEHFuncInfo.h"
141 #include "llvm/IR/Attributes.h"
142 #include "llvm/IR/CallingConv.h"
143 #include "llvm/IR/DataLayout.h"
144 #include "llvm/IR/DebugLoc.h"
145 #include "llvm/IR/Function.h"
146 #include "llvm/MC/MCAsmInfo.h"
147 #include "llvm/MC/MCDwarf.h"
148 #include "llvm/Support/CommandLine.h"
149 #include "llvm/Support/Debug.h"
150 #include "llvm/Support/ErrorHandling.h"
151 #include "llvm/Support/MathExtras.h"
152 #include "llvm/Support/raw_ostream.h"
153 #include "llvm/Target/TargetMachine.h"
154 #include "llvm/Target/TargetOptions.h"
155 #include <cassert>
156 #include <cstdint>
157 #include <iterator>
158 #include <vector>
159 
160 using namespace llvm;
161 
162 #define DEBUG_TYPE "frame-info"
163 
164 static cl::opt<bool> EnableRedZone("aarch64-redzone",
165                                    cl::desc("enable use of redzone on AArch64"),
166                                    cl::init(false), cl::Hidden);
167 
168 static cl::opt<bool>
169     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
170                          cl::desc("reverse the CSR restore sequence"),
171                          cl::init(false), cl::Hidden);
172 
173 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
174 
175 /// This is the biggest offset to the stack pointer we can encode in aarch64
176 /// instructions (without using a separate calculation and a temp register).
177 /// Note that the exception here are vector stores/loads which cannot encode any
178 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
179 static const unsigned DefaultSafeSPDisplacement = 255;
180 
181 /// Look at each instruction that references stack frames and return the stack
182 /// size limit beyond which some of these instructions will require a scratch
183 /// register during their expansion later.
184 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
185   // FIXME: For now, just conservatively guestimate based on unscaled indexing
186   // range. We'll end up allocating an unnecessary spill slot a lot, but
187   // realistically that's not a big deal at this stage of the game.
188   for (MachineBasicBlock &MBB : MF) {
189     for (MachineInstr &MI : MBB) {
190       if (MI.isDebugInstr() || MI.isPseudo() ||
191           MI.getOpcode() == AArch64::ADDXri ||
192           MI.getOpcode() == AArch64::ADDSXri)
193         continue;
194 
195       for (const MachineOperand &MO : MI.operands()) {
196         if (!MO.isFI())
197           continue;
198 
199         StackOffset Offset;
200         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
201             AArch64FrameOffsetCannotUpdate)
202           return 0;
203       }
204     }
205   }
206   return DefaultSafeSPDisplacement;
207 }
208 
209 TargetStackID::Value
210 AArch64FrameLowering::getStackIDForScalableVectors() const {
211   return TargetStackID::SVEVector;
212 }
213 
214 /// Returns the size of the entire SVE stackframe (calleesaves + spills).
215 static StackOffset getSVEStackSize(const MachineFunction &MF) {
216   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
217   return {(int64_t)AFI->getStackSizeSVE(), MVT::nxv1i8};
218 }
219 
220 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
221   if (!EnableRedZone)
222     return false;
223   // Don't use the red zone if the function explicitly asks us not to.
224   // This is typically used for kernel code.
225   if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
226     return false;
227 
228   const MachineFrameInfo &MFI = MF.getFrameInfo();
229   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
230   uint64_t NumBytes = AFI->getLocalStackSize();
231 
232   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128 ||
233            getSVEStackSize(MF));
234 }
235 
236 /// hasFP - Return true if the specified function should have a dedicated frame
237 /// pointer register.
238 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
239   const MachineFrameInfo &MFI = MF.getFrameInfo();
240   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
241   // Win64 EH requires a frame pointer if funclets are present, as the locals
242   // are accessed off the frame pointer in both the parent function and the
243   // funclets.
244   if (MF.hasEHFunclets())
245     return true;
246   // Retain behavior of always omitting the FP for leaf functions when possible.
247   if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
248     return true;
249   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
250       MFI.hasStackMap() || MFI.hasPatchPoint() ||
251       RegInfo->needsStackRealignment(MF))
252     return true;
253   // With large callframes around we may need to use FP to access the scavenging
254   // emergency spillslot.
255   //
256   // Unfortunately some calls to hasFP() like machine verifier ->
257   // getReservedReg() -> hasFP in the middle of global isel are too early
258   // to know the max call frame size. Hopefully conservatively returning "true"
259   // in those cases is fine.
260   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
261   if (!MFI.isMaxCallFrameSizeComputed() ||
262       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
263     return true;
264 
265   return false;
266 }
267 
268 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
269 /// not required, we reserve argument space for call sites in the function
270 /// immediately on entry to the current function.  This eliminates the need for
271 /// add/sub sp brackets around call sites.  Returns true if the call frame is
272 /// included as part of the stack frame.
273 bool
274 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
275   return !MF.getFrameInfo().hasVarSizedObjects();
276 }
277 
278 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
279     MachineFunction &MF, MachineBasicBlock &MBB,
280     MachineBasicBlock::iterator I) const {
281   const AArch64InstrInfo *TII =
282       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
283   DebugLoc DL = I->getDebugLoc();
284   unsigned Opc = I->getOpcode();
285   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
286   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
287 
288   if (!hasReservedCallFrame(MF)) {
289     unsigned Align = getStackAlignment();
290 
291     int64_t Amount = I->getOperand(0).getImm();
292     Amount = alignTo(Amount, Align);
293     if (!IsDestroy)
294       Amount = -Amount;
295 
296     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
297     // doesn't have to pop anything), then the first operand will be zero too so
298     // this adjustment is a no-op.
299     if (CalleePopAmount == 0) {
300       // FIXME: in-function stack adjustment for calls is limited to 24-bits
301       // because there's no guaranteed temporary register available.
302       //
303       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
304       // 1) For offset <= 12-bit, we use LSL #0
305       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
306       // LSL #0, and the other uses LSL #12.
307       //
308       // Most call frames will be allocated at the start of a function so
309       // this is OK, but it is a limitation that needs dealing with.
310       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
311       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, {Amount, MVT::i8},
312                       TII);
313     }
314   } else if (CalleePopAmount != 0) {
315     // If the calling convention demands that the callee pops arguments from the
316     // stack, we want to add it back if we have a reserved call frame.
317     assert(CalleePopAmount < 0xffffff && "call frame too large");
318     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
319                     {-(int64_t)CalleePopAmount, MVT::i8}, TII);
320   }
321   return MBB.erase(I);
322 }
323 
324 static bool ShouldSignReturnAddress(MachineFunction &MF) {
325   // The function should be signed in the following situations:
326   // - sign-return-address=all
327   // - sign-return-address=non-leaf and the functions spills the LR
328 
329   const Function &F = MF.getFunction();
330   if (!F.hasFnAttribute("sign-return-address"))
331     return false;
332 
333   StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString();
334   if (Scope.equals("none"))
335     return false;
336 
337   if (Scope.equals("all"))
338     return true;
339 
340   assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf");
341 
342   for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo())
343     if (Info.getReg() == AArch64::LR)
344       return true;
345 
346   return false;
347 }
348 
349 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
350     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
351   MachineFunction &MF = *MBB.getParent();
352   MachineFrameInfo &MFI = MF.getFrameInfo();
353   const TargetSubtargetInfo &STI = MF.getSubtarget();
354   const MCRegisterInfo *MRI = STI.getRegisterInfo();
355   const TargetInstrInfo *TII = STI.getInstrInfo();
356   DebugLoc DL = MBB.findDebugLoc(MBBI);
357 
358   // Add callee saved registers to move list.
359   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
360   if (CSI.empty())
361     return;
362 
363   for (const auto &Info : CSI) {
364     unsigned Reg = Info.getReg();
365     int64_t Offset =
366         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
367     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
368     unsigned CFIIndex = MF.addFrameInst(
369         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
370     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
371         .addCFIIndex(CFIIndex)
372         .setMIFlags(MachineInstr::FrameSetup);
373   }
374 }
375 
376 // Find a scratch register that we can use at the start of the prologue to
377 // re-align the stack pointer.  We avoid using callee-save registers since they
378 // may appear to be free when this is called from canUseAsPrologue (during
379 // shrink wrapping), but then no longer be free when this is called from
380 // emitPrologue.
381 //
382 // FIXME: This is a bit conservative, since in the above case we could use one
383 // of the callee-save registers as a scratch temp to re-align the stack pointer,
384 // but we would then have to make sure that we were in fact saving at least one
385 // callee-save register in the prologue, which is additional complexity that
386 // doesn't seem worth the benefit.
387 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
388   MachineFunction *MF = MBB->getParent();
389 
390   // If MBB is an entry block, use X9 as the scratch register
391   if (&MF->front() == MBB)
392     return AArch64::X9;
393 
394   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
395   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
396   LivePhysRegs LiveRegs(TRI);
397   LiveRegs.addLiveIns(*MBB);
398 
399   // Mark callee saved registers as used so we will not choose them.
400   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
401   for (unsigned i = 0; CSRegs[i]; ++i)
402     LiveRegs.addReg(CSRegs[i]);
403 
404   // Prefer X9 since it was historically used for the prologue scratch reg.
405   const MachineRegisterInfo &MRI = MF->getRegInfo();
406   if (LiveRegs.available(MRI, AArch64::X9))
407     return AArch64::X9;
408 
409   for (unsigned Reg : AArch64::GPR64RegClass) {
410     if (LiveRegs.available(MRI, Reg))
411       return Reg;
412   }
413   return AArch64::NoRegister;
414 }
415 
416 bool AArch64FrameLowering::canUseAsPrologue(
417     const MachineBasicBlock &MBB) const {
418   const MachineFunction *MF = MBB.getParent();
419   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
420   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
421   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
422 
423   // Don't need a scratch register if we're not going to re-align the stack.
424   if (!RegInfo->needsStackRealignment(*MF))
425     return true;
426   // Otherwise, we can use any block as long as it has a scratch register
427   // available.
428   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
429 }
430 
431 static bool windowsRequiresStackProbe(MachineFunction &MF,
432                                       uint64_t StackSizeInBytes) {
433   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
434   if (!Subtarget.isTargetWindows())
435     return false;
436   const Function &F = MF.getFunction();
437   // TODO: When implementing stack protectors, take that into account
438   // for the probe threshold.
439   unsigned StackProbeSize = 4096;
440   if (F.hasFnAttribute("stack-probe-size"))
441     F.getFnAttribute("stack-probe-size")
442         .getValueAsString()
443         .getAsInteger(0, StackProbeSize);
444   return (StackSizeInBytes >= StackProbeSize) &&
445          !F.hasFnAttribute("no-stack-arg-probe");
446 }
447 
448 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
449     MachineFunction &MF, uint64_t StackBumpBytes) const {
450   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
451   const MachineFrameInfo &MFI = MF.getFrameInfo();
452   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
453   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
454 
455   if (AFI->getLocalStackSize() == 0)
456     return false;
457 
458   // 512 is the maximum immediate for stp/ldp that will be used for
459   // callee-save save/restores
460   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
461     return false;
462 
463   if (MFI.hasVarSizedObjects())
464     return false;
465 
466   if (RegInfo->needsStackRealignment(MF))
467     return false;
468 
469   // This isn't strictly necessary, but it simplifies things a bit since the
470   // current RedZone handling code assumes the SP is adjusted by the
471   // callee-save save/restore code.
472   if (canUseRedZone(MF))
473     return false;
474 
475   // When there is an SVE area on the stack, always allocate the
476   // callee-saves and spills/locals separately.
477   if (getSVEStackSize(MF))
478     return false;
479 
480   return true;
481 }
482 
483 // Given a load or a store instruction, generate an appropriate unwinding SEH
484 // code on Windows.
485 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
486                                              const TargetInstrInfo &TII,
487                                              MachineInstr::MIFlag Flag) {
488   unsigned Opc = MBBI->getOpcode();
489   MachineBasicBlock *MBB = MBBI->getParent();
490   MachineFunction &MF = *MBB->getParent();
491   DebugLoc DL = MBBI->getDebugLoc();
492   unsigned ImmIdx = MBBI->getNumOperands() - 1;
493   int Imm = MBBI->getOperand(ImmIdx).getImm();
494   MachineInstrBuilder MIB;
495   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
496   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
497 
498   switch (Opc) {
499   default:
500     llvm_unreachable("No SEH Opcode for this instruction");
501   case AArch64::LDPDpost:
502     Imm = -Imm;
503     LLVM_FALLTHROUGH;
504   case AArch64::STPDpre: {
505     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
506     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
507     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
508               .addImm(Reg0)
509               .addImm(Reg1)
510               .addImm(Imm * 8)
511               .setMIFlag(Flag);
512     break;
513   }
514   case AArch64::LDPXpost:
515     Imm = -Imm;
516     LLVM_FALLTHROUGH;
517   case AArch64::STPXpre: {
518     Register Reg0 = MBBI->getOperand(1).getReg();
519     Register Reg1 = MBBI->getOperand(2).getReg();
520     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
521       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
522                 .addImm(Imm * 8)
523                 .setMIFlag(Flag);
524     else
525       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
526                 .addImm(RegInfo->getSEHRegNum(Reg0))
527                 .addImm(RegInfo->getSEHRegNum(Reg1))
528                 .addImm(Imm * 8)
529                 .setMIFlag(Flag);
530     break;
531   }
532   case AArch64::LDRDpost:
533     Imm = -Imm;
534     LLVM_FALLTHROUGH;
535   case AArch64::STRDpre: {
536     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
537     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
538               .addImm(Reg)
539               .addImm(Imm)
540               .setMIFlag(Flag);
541     break;
542   }
543   case AArch64::LDRXpost:
544     Imm = -Imm;
545     LLVM_FALLTHROUGH;
546   case AArch64::STRXpre: {
547     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
548     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
549               .addImm(Reg)
550               .addImm(Imm)
551               .setMIFlag(Flag);
552     break;
553   }
554   case AArch64::STPDi:
555   case AArch64::LDPDi: {
556     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
557     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
558     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
559               .addImm(Reg0)
560               .addImm(Reg1)
561               .addImm(Imm * 8)
562               .setMIFlag(Flag);
563     break;
564   }
565   case AArch64::STPXi:
566   case AArch64::LDPXi: {
567     Register Reg0 = MBBI->getOperand(0).getReg();
568     Register Reg1 = MBBI->getOperand(1).getReg();
569     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
570       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
571                 .addImm(Imm * 8)
572                 .setMIFlag(Flag);
573     else
574       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
575                 .addImm(RegInfo->getSEHRegNum(Reg0))
576                 .addImm(RegInfo->getSEHRegNum(Reg1))
577                 .addImm(Imm * 8)
578                 .setMIFlag(Flag);
579     break;
580   }
581   case AArch64::STRXui:
582   case AArch64::LDRXui: {
583     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
584     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
585               .addImm(Reg)
586               .addImm(Imm * 8)
587               .setMIFlag(Flag);
588     break;
589   }
590   case AArch64::STRDui:
591   case AArch64::LDRDui: {
592     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
593     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
594               .addImm(Reg)
595               .addImm(Imm * 8)
596               .setMIFlag(Flag);
597     break;
598   }
599   }
600   auto I = MBB->insertAfter(MBBI, MIB);
601   return I;
602 }
603 
604 // Fix up the SEH opcode associated with the save/restore instruction.
605 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
606                            unsigned LocalStackSize) {
607   MachineOperand *ImmOpnd = nullptr;
608   unsigned ImmIdx = MBBI->getNumOperands() - 1;
609   switch (MBBI->getOpcode()) {
610   default:
611     llvm_unreachable("Fix the offset in the SEH instruction");
612   case AArch64::SEH_SaveFPLR:
613   case AArch64::SEH_SaveRegP:
614   case AArch64::SEH_SaveReg:
615   case AArch64::SEH_SaveFRegP:
616   case AArch64::SEH_SaveFReg:
617     ImmOpnd = &MBBI->getOperand(ImmIdx);
618     break;
619   }
620   if (ImmOpnd)
621     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
622 }
623 
624 // Convert callee-save register save/restore instruction to do stack pointer
625 // decrement/increment to allocate/deallocate the callee-save stack area by
626 // converting store/load to use pre/post increment version.
627 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
628     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
629     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
630     bool NeedsWinCFI, bool *HasWinCFI, bool InProlog = true) {
631   // Ignore instructions that do not operate on SP, i.e. shadow call stack
632   // instructions and associated CFI instruction.
633   while (MBBI->getOpcode() == AArch64::STRXpost ||
634          MBBI->getOpcode() == AArch64::LDRXpre ||
635          MBBI->getOpcode() == AArch64::CFI_INSTRUCTION) {
636     if (MBBI->getOpcode() != AArch64::CFI_INSTRUCTION)
637       assert(MBBI->getOperand(0).getReg() != AArch64::SP);
638     ++MBBI;
639   }
640   unsigned NewOpc;
641   int Scale = 1;
642   switch (MBBI->getOpcode()) {
643   default:
644     llvm_unreachable("Unexpected callee-save save/restore opcode!");
645   case AArch64::STPXi:
646     NewOpc = AArch64::STPXpre;
647     Scale = 8;
648     break;
649   case AArch64::STPDi:
650     NewOpc = AArch64::STPDpre;
651     Scale = 8;
652     break;
653   case AArch64::STPQi:
654     NewOpc = AArch64::STPQpre;
655     Scale = 16;
656     break;
657   case AArch64::STRXui:
658     NewOpc = AArch64::STRXpre;
659     break;
660   case AArch64::STRDui:
661     NewOpc = AArch64::STRDpre;
662     break;
663   case AArch64::STRQui:
664     NewOpc = AArch64::STRQpre;
665     break;
666   case AArch64::LDPXi:
667     NewOpc = AArch64::LDPXpost;
668     Scale = 8;
669     break;
670   case AArch64::LDPDi:
671     NewOpc = AArch64::LDPDpost;
672     Scale = 8;
673     break;
674   case AArch64::LDPQi:
675     NewOpc = AArch64::LDPQpost;
676     Scale = 16;
677     break;
678   case AArch64::LDRXui:
679     NewOpc = AArch64::LDRXpost;
680     break;
681   case AArch64::LDRDui:
682     NewOpc = AArch64::LDRDpost;
683     break;
684   case AArch64::LDRQui:
685     NewOpc = AArch64::LDRQpost;
686     break;
687   }
688   // Get rid of the SEH code associated with the old instruction.
689   if (NeedsWinCFI) {
690     auto SEH = std::next(MBBI);
691     if (AArch64InstrInfo::isSEHInstruction(*SEH))
692       SEH->eraseFromParent();
693   }
694 
695   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
696   MIB.addReg(AArch64::SP, RegState::Define);
697 
698   // Copy all operands other than the immediate offset.
699   unsigned OpndIdx = 0;
700   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
701        ++OpndIdx)
702     MIB.add(MBBI->getOperand(OpndIdx));
703 
704   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
705          "Unexpected immediate offset in first/last callee-save save/restore "
706          "instruction!");
707   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
708          "Unexpected base register in callee-save save/restore instruction!");
709   assert(CSStackSizeInc % Scale == 0);
710   MIB.addImm(CSStackSizeInc / Scale);
711 
712   MIB.setMIFlags(MBBI->getFlags());
713   MIB.setMemRefs(MBBI->memoperands());
714 
715   // Generate a new SEH code that corresponds to the new instruction.
716   if (NeedsWinCFI) {
717     *HasWinCFI = true;
718     InsertSEH(*MIB, *TII,
719               InProlog ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy);
720   }
721 
722   return std::prev(MBB.erase(MBBI));
723 }
724 
725 // Fixup callee-save register save/restore instructions to take into account
726 // combined SP bump by adding the local stack size to the stack offsets.
727 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
728                                               uint64_t LocalStackSize,
729                                               bool NeedsWinCFI,
730                                               bool *HasWinCFI) {
731   if (AArch64InstrInfo::isSEHInstruction(MI))
732     return;
733 
734   unsigned Opc = MI.getOpcode();
735 
736   // Ignore instructions that do not operate on SP, i.e. shadow call stack
737   // instructions and associated CFI instruction.
738   if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre ||
739       Opc == AArch64::CFI_INSTRUCTION) {
740     if (Opc != AArch64::CFI_INSTRUCTION)
741       assert(MI.getOperand(0).getReg() != AArch64::SP);
742     return;
743   }
744 
745   unsigned Scale;
746   switch (Opc) {
747   case AArch64::STPXi:
748   case AArch64::STRXui:
749   case AArch64::STPDi:
750   case AArch64::STRDui:
751   case AArch64::LDPXi:
752   case AArch64::LDRXui:
753   case AArch64::LDPDi:
754   case AArch64::LDRDui:
755     Scale = 8;
756     break;
757   case AArch64::STPQi:
758   case AArch64::STRQui:
759   case AArch64::LDPQi:
760   case AArch64::LDRQui:
761     Scale = 16;
762     break;
763   default:
764     llvm_unreachable("Unexpected callee-save save/restore opcode!");
765   }
766 
767   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
768   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
769          "Unexpected base register in callee-save save/restore instruction!");
770   // Last operand is immediate offset that needs fixing.
771   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
772   // All generated opcodes have scaled offsets.
773   assert(LocalStackSize % Scale == 0);
774   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
775 
776   if (NeedsWinCFI) {
777     *HasWinCFI = true;
778     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
779     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
780     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
781            "Expecting a SEH instruction");
782     fixupSEHOpcode(MBBI, LocalStackSize);
783   }
784 }
785 
786 static void adaptForLdStOpt(MachineBasicBlock &MBB,
787                             MachineBasicBlock::iterator FirstSPPopI,
788                             MachineBasicBlock::iterator LastPopI) {
789   // Sometimes (when we restore in the same order as we save), we can end up
790   // with code like this:
791   //
792   // ldp      x26, x25, [sp]
793   // ldp      x24, x23, [sp, #16]
794   // ldp      x22, x21, [sp, #32]
795   // ldp      x20, x19, [sp, #48]
796   // add      sp, sp, #64
797   //
798   // In this case, it is always better to put the first ldp at the end, so
799   // that the load-store optimizer can run and merge the ldp and the add into
800   // a post-index ldp.
801   // If we managed to grab the first pop instruction, move it to the end.
802   if (ReverseCSRRestoreSeq)
803     MBB.splice(FirstSPPopI, &MBB, LastPopI);
804   // We should end up with something like this now:
805   //
806   // ldp      x24, x23, [sp, #16]
807   // ldp      x22, x21, [sp, #32]
808   // ldp      x20, x19, [sp, #48]
809   // ldp      x26, x25, [sp]
810   // add      sp, sp, #64
811   //
812   // and the load-store optimizer can merge the last two instructions into:
813   //
814   // ldp      x26, x25, [sp], #64
815   //
816 }
817 
818 static bool ShouldSignWithAKey(MachineFunction &MF) {
819   const Function &F = MF.getFunction();
820   if (!F.hasFnAttribute("sign-return-address-key"))
821     return true;
822 
823   const StringRef Key =
824       F.getFnAttribute("sign-return-address-key").getValueAsString();
825   assert(Key.equals_lower("a_key") || Key.equals_lower("b_key"));
826   return Key.equals_lower("a_key");
827 }
828 
829 static bool needsWinCFI(const MachineFunction &MF) {
830   const Function &F = MF.getFunction();
831   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
832          F.needsUnwindTableEntry();
833 }
834 
835 static bool isTargetDarwin(const MachineFunction &MF) {
836   return MF.getSubtarget<AArch64Subtarget>().isTargetDarwin();
837 }
838 
839 // Convenience function to determine whether I is an SVE callee save.
840 bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
841   switch (I->getOpcode()) {
842   default:
843     return false;
844   case AArch64::STR_ZXI:
845   case AArch64::STR_PXI:
846   case AArch64::LDR_ZXI:
847   case AArch64::LDR_PXI:
848     return I->getFlag(MachineInstr::FrameSetup) ||
849            I->getFlag(MachineInstr::FrameDestroy);
850   }
851 }
852 
853 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
854                                         MachineBasicBlock &MBB) const {
855   MachineBasicBlock::iterator MBBI = MBB.begin();
856   const MachineFrameInfo &MFI = MF.getFrameInfo();
857   const Function &F = MF.getFunction();
858   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
859   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
860   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
861   MachineModuleInfo &MMI = MF.getMMI();
862   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
863   bool needsFrameMoves =
864       MF.needsFrameMoves() && !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
865   bool HasFP = hasFP(MF);
866   bool NeedsWinCFI = needsWinCFI(MF);
867   bool HasWinCFI = false;
868   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
869 
870   bool IsFunclet = MBB.isEHFuncletEntry();
871 
872   // At this point, we're going to decide whether or not the function uses a
873   // redzone. In most cases, the function doesn't have a redzone so let's
874   // assume that's false and set it to true in the case that there's a redzone.
875   AFI->setHasRedZone(false);
876 
877   // Debug location must be unknown since the first debug location is used
878   // to determine the end of the prologue.
879   DebugLoc DL;
880 
881   if (ShouldSignReturnAddress(MF)) {
882     if (ShouldSignWithAKey(MF))
883       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
884           .setMIFlag(MachineInstr::FrameSetup);
885     else {
886       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
887           .setMIFlag(MachineInstr::FrameSetup);
888       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIBSP))
889           .setMIFlag(MachineInstr::FrameSetup);
890     }
891 
892     unsigned CFIIndex =
893         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
894     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
895         .addCFIIndex(CFIIndex)
896         .setMIFlags(MachineInstr::FrameSetup);
897   }
898 
899   // All calls are tail calls in GHC calling conv, and functions have no
900   // prologue/epilogue.
901   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
902     return;
903 
904   // Set tagged base pointer to the bottom of the stack frame.
905   // Ideally it should match SP value after prologue.
906   AFI->setTaggedBasePointerOffset(MFI.getStackSize());
907 
908   const StackOffset &SVEStackSize = getSVEStackSize(MF);
909 
910   // getStackSize() includes all the locals in its size calculation. We don't
911   // include these locals when computing the stack size of a funclet, as they
912   // are allocated in the parent's stack frame and accessed via the frame
913   // pointer from the funclet.  We only save the callee saved registers in the
914   // funclet, which are really the callee saved registers of the parent
915   // function, including the funclet.
916   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
917                                : MFI.getStackSize();
918   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
919     assert(!HasFP && "unexpected function without stack frame but with FP");
920     assert(!SVEStackSize &&
921            "unexpected function without stack frame but with SVE objects");
922     // All of the stack allocation is for locals.
923     AFI->setLocalStackSize(NumBytes);
924     if (!NumBytes)
925       return;
926     // REDZONE: If the stack size is less than 128 bytes, we don't need
927     // to actually allocate.
928     if (canUseRedZone(MF)) {
929       AFI->setHasRedZone(true);
930       ++NumRedZoneFunctions;
931     } else {
932       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
933                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
934                       false, NeedsWinCFI, &HasWinCFI);
935       if (!NeedsWinCFI && needsFrameMoves) {
936         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
937         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
938           // Encode the stack size of the leaf function.
939           unsigned CFIIndex = MF.addFrameInst(
940               MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
941           BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
942               .addCFIIndex(CFIIndex)
943               .setMIFlags(MachineInstr::FrameSetup);
944       }
945     }
946 
947     if (NeedsWinCFI) {
948       HasWinCFI = true;
949       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
950           .setMIFlag(MachineInstr::FrameSetup);
951     }
952 
953     return;
954   }
955 
956   bool IsWin64 =
957       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
958   // Var args are accounted for in the containing function, so don't
959   // include them for funclets.
960   unsigned FixedObject = (IsWin64 && !IsFunclet) ?
961                          alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
962 
963   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
964   // All of the remaining stack allocations are for locals.
965   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
966   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
967   if (CombineSPBump) {
968     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
969     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
970                     {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup, false,
971                     NeedsWinCFI, &HasWinCFI);
972     NumBytes = 0;
973   } else if (PrologueSaveSize != 0) {
974     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
975         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI);
976     NumBytes -= PrologueSaveSize;
977   }
978   assert(NumBytes >= 0 && "Negative stack allocation size!?");
979 
980   // Move past the saves of the callee-saved registers, fixing up the offsets
981   // and pre-inc if we decided to combine the callee-save and local stack
982   // pointer bump above.
983   MachineBasicBlock::iterator End = MBB.end();
984   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
985          !IsSVECalleeSave(MBBI)) {
986     if (CombineSPBump)
987       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
988                                         NeedsWinCFI, &HasWinCFI);
989     ++MBBI;
990   }
991 
992   // The code below is not applicable to funclets. We have emitted all the SEH
993   // opcodes that we needed to emit.  The FP and BP belong to the containing
994   // function.
995   if (IsFunclet) {
996     if (NeedsWinCFI) {
997       HasWinCFI = true;
998       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
999           .setMIFlag(MachineInstr::FrameSetup);
1000     }
1001 
1002     // SEH funclets are passed the frame pointer in X1.  If the parent
1003     // function uses the base register, then the base register is used
1004     // directly, and is not retrieved from X1.
1005     if (F.hasPersonalityFn()) {
1006       EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
1007       if (isAsynchronousEHPersonality(Per)) {
1008         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
1009             .addReg(AArch64::X1).setMIFlag(MachineInstr::FrameSetup);
1010         MBB.addLiveIn(AArch64::X1);
1011       }
1012     }
1013 
1014     return;
1015   }
1016 
1017   if (HasFP) {
1018     // Only set up FP if we actually need to.
1019     int64_t FPOffset = isTargetDarwin(MF) ? (AFI->getCalleeSavedStackSize() - 16) : 0;
1020 
1021     if (CombineSPBump)
1022       FPOffset += AFI->getLocalStackSize();
1023 
1024     // Issue    sub fp, sp, FPOffset or
1025     //          mov fp,sp          when FPOffset is zero.
1026     // Note: All stores of callee-saved registers are marked as "FrameSetup".
1027     // This code marks the instruction(s) that set the FP also.
1028     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
1029                     {FPOffset, MVT::i8}, TII, MachineInstr::FrameSetup, false,
1030                     NeedsWinCFI, &HasWinCFI);
1031   }
1032 
1033   if (windowsRequiresStackProbe(MF, NumBytes)) {
1034     uint64_t NumWords = NumBytes >> 4;
1035     if (NeedsWinCFI) {
1036       HasWinCFI = true;
1037       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1038       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
1039       // This is at most two instructions, MOVZ follwed by MOVK.
1040       // TODO: Fix to use multiple stack alloc unwind codes for stacks
1041       // exceeding 256MB in size.
1042       if (NumBytes >= (1 << 28))
1043         report_fatal_error("Stack size cannot exceed 256MB for stack "
1044                             "unwinding purposes");
1045 
1046       uint32_t LowNumWords = NumWords & 0xFFFF;
1047       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
1048             .addImm(LowNumWords)
1049             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1050             .setMIFlag(MachineInstr::FrameSetup);
1051       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1052             .setMIFlag(MachineInstr::FrameSetup);
1053       if ((NumWords & 0xFFFF0000) != 0) {
1054           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
1055               .addReg(AArch64::X15)
1056               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
1057               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
1058               .setMIFlag(MachineInstr::FrameSetup);
1059           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1060             .setMIFlag(MachineInstr::FrameSetup);
1061       }
1062     } else {
1063       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
1064           .addImm(NumWords)
1065           .setMIFlags(MachineInstr::FrameSetup);
1066     }
1067 
1068     switch (MF.getTarget().getCodeModel()) {
1069     case CodeModel::Tiny:
1070     case CodeModel::Small:
1071     case CodeModel::Medium:
1072     case CodeModel::Kernel:
1073       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
1074           .addExternalSymbol("__chkstk")
1075           .addReg(AArch64::X15, RegState::Implicit)
1076           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1077           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1078           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1079           .setMIFlags(MachineInstr::FrameSetup);
1080       if (NeedsWinCFI) {
1081         HasWinCFI = true;
1082         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1083             .setMIFlag(MachineInstr::FrameSetup);
1084       }
1085       break;
1086     case CodeModel::Large:
1087       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1088           .addReg(AArch64::X16, RegState::Define)
1089           .addExternalSymbol("__chkstk")
1090           .addExternalSymbol("__chkstk")
1091           .setMIFlags(MachineInstr::FrameSetup);
1092       if (NeedsWinCFI) {
1093         HasWinCFI = true;
1094         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1095             .setMIFlag(MachineInstr::FrameSetup);
1096       }
1097 
1098       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
1099           .addReg(AArch64::X16, RegState::Kill)
1100           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1101           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1102           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1103           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1104           .setMIFlags(MachineInstr::FrameSetup);
1105       if (NeedsWinCFI) {
1106         HasWinCFI = true;
1107         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1108             .setMIFlag(MachineInstr::FrameSetup);
1109       }
1110       break;
1111     }
1112 
1113     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1114         .addReg(AArch64::SP, RegState::Kill)
1115         .addReg(AArch64::X15, RegState::Kill)
1116         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1117         .setMIFlags(MachineInstr::FrameSetup);
1118     if (NeedsWinCFI) {
1119       HasWinCFI = true;
1120       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1121           .addImm(NumBytes)
1122           .setMIFlag(MachineInstr::FrameSetup);
1123     }
1124     NumBytes = 0;
1125   }
1126 
1127   StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
1128   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
1129 
1130   // Process the SVE callee-saves to determine what space needs to be
1131   // allocated.
1132   if (AFI->getSVECalleeSavedStackSize()) {
1133     // Find callee save instructions in frame.
1134     CalleeSavesBegin = MBBI;
1135     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
1136     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
1137       ++MBBI;
1138     CalleeSavesEnd = MBBI;
1139 
1140     int64_t OffsetToFirstCalleeSaveFromSP =
1141         MFI.getObjectOffset(AFI->getMaxSVECSFrameIndex());
1142     StackOffset OffsetToCalleeSavesFromSP =
1143         StackOffset(OffsetToFirstCalleeSaveFromSP, MVT::nxv1i8) + SVEStackSize;
1144     AllocateBefore -= OffsetToCalleeSavesFromSP;
1145     AllocateAfter = SVEStackSize - AllocateBefore;
1146   }
1147 
1148   // Allocate space for the callee saves (if any).
1149   emitFrameOffset(MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP,
1150                   -AllocateBefore, TII,
1151                   MachineInstr::FrameSetup);
1152 
1153   // Finally allocate remaining SVE stack space.
1154   emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
1155                   -AllocateAfter, TII,
1156                   MachineInstr::FrameSetup);
1157 
1158   // Allocate space for the rest of the frame.
1159   if (NumBytes) {
1160     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
1161     unsigned scratchSPReg = AArch64::SP;
1162 
1163     if (NeedsRealignment) {
1164       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1165       assert(scratchSPReg != AArch64::NoRegister);
1166     }
1167 
1168     // If we're a leaf function, try using the red zone.
1169     if (!canUseRedZone(MF))
1170       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1171       // the correct value here, as NumBytes also includes padding bytes,
1172       // which shouldn't be counted here.
1173       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP,
1174                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
1175                       false, NeedsWinCFI, &HasWinCFI);
1176 
1177     if (NeedsRealignment) {
1178       const unsigned Alignment = MFI.getMaxAlignment();
1179       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
1180       assert(NrBitsToZero > 1);
1181       assert(scratchSPReg != AArch64::SP);
1182 
1183       // SUB X9, SP, NumBytes
1184       //   -- X9 is temporary register, so shouldn't contain any live data here,
1185       //   -- free to use. This is already produced by emitFrameOffset above.
1186       // AND SP, X9, 0b11111...0000
1187       // The logical immediates have a non-trivial encoding. The following
1188       // formula computes the encoded immediate with all ones but
1189       // NrBitsToZero zero bits as least significant bits.
1190       uint32_t andMaskEncoded = (1 << 12)                         // = N
1191                                 | ((64 - NrBitsToZero) << 6)      // immr
1192                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1193 
1194       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1195           .addReg(scratchSPReg, RegState::Kill)
1196           .addImm(andMaskEncoded);
1197       AFI->setStackRealigned(true);
1198       if (NeedsWinCFI) {
1199         HasWinCFI = true;
1200         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1201             .addImm(NumBytes & andMaskEncoded)
1202             .setMIFlag(MachineInstr::FrameSetup);
1203       }
1204     }
1205   }
1206 
1207   // If we need a base pointer, set it up here. It's whatever the value of the
1208   // stack pointer is at this point. Any variable size objects will be allocated
1209   // after this, so we can still use the base pointer to reference locals.
1210   //
1211   // FIXME: Clarify FrameSetup flags here.
1212   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1213   // needed.
1214   if (RegInfo->hasBasePointer(MF)) {
1215     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1216                      false);
1217     if (NeedsWinCFI) {
1218       HasWinCFI = true;
1219       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1220           .setMIFlag(MachineInstr::FrameSetup);
1221     }
1222   }
1223 
1224   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1225   // SEH opcode indicating the prologue end.
1226   if (NeedsWinCFI && HasWinCFI) {
1227     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1228         .setMIFlag(MachineInstr::FrameSetup);
1229   }
1230 
1231   if (needsFrameMoves) {
1232     const DataLayout &TD = MF.getDataLayout();
1233     const int StackGrowth = isTargetDarwin(MF)
1234                                 ? (2 * -TD.getPointerSize(0))
1235                                 : -AFI->getCalleeSavedStackSize();
1236     Register FramePtr = RegInfo->getFrameRegister(MF);
1237     // An example of the prologue:
1238     //
1239     //     .globl __foo
1240     //     .align 2
1241     //  __foo:
1242     // Ltmp0:
1243     //     .cfi_startproc
1244     //     .cfi_personality 155, ___gxx_personality_v0
1245     // Leh_func_begin:
1246     //     .cfi_lsda 16, Lexception33
1247     //
1248     //     stp  xa,bx, [sp, -#offset]!
1249     //     ...
1250     //     stp  x28, x27, [sp, #offset-32]
1251     //     stp  fp, lr, [sp, #offset-16]
1252     //     add  fp, sp, #offset - 16
1253     //     sub  sp, sp, #1360
1254     //
1255     // The Stack:
1256     //       +-------------------------------------------+
1257     // 10000 | ........ | ........ | ........ | ........ |
1258     // 10004 | ........ | ........ | ........ | ........ |
1259     //       +-------------------------------------------+
1260     // 10008 | ........ | ........ | ........ | ........ |
1261     // 1000c | ........ | ........ | ........ | ........ |
1262     //       +===========================================+
1263     // 10010 |                X28 Register               |
1264     // 10014 |                X28 Register               |
1265     //       +-------------------------------------------+
1266     // 10018 |                X27 Register               |
1267     // 1001c |                X27 Register               |
1268     //       +===========================================+
1269     // 10020 |                Frame Pointer              |
1270     // 10024 |                Frame Pointer              |
1271     //       +-------------------------------------------+
1272     // 10028 |                Link Register              |
1273     // 1002c |                Link Register              |
1274     //       +===========================================+
1275     // 10030 | ........ | ........ | ........ | ........ |
1276     // 10034 | ........ | ........ | ........ | ........ |
1277     //       +-------------------------------------------+
1278     // 10038 | ........ | ........ | ........ | ........ |
1279     // 1003c | ........ | ........ | ........ | ........ |
1280     //       +-------------------------------------------+
1281     //
1282     //     [sp] = 10030        ::    >>initial value<<
1283     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1284     //     fp = sp == 10020    ::  mov fp, sp
1285     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1286     //     sp == 10010         ::    >>final value<<
1287     //
1288     // The frame pointer (w29) points to address 10020. If we use an offset of
1289     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1290     // for w27, and -32 for w28:
1291     //
1292     //  Ltmp1:
1293     //     .cfi_def_cfa w29, 16
1294     //  Ltmp2:
1295     //     .cfi_offset w30, -8
1296     //  Ltmp3:
1297     //     .cfi_offset w29, -16
1298     //  Ltmp4:
1299     //     .cfi_offset w27, -24
1300     //  Ltmp5:
1301     //     .cfi_offset w28, -32
1302 
1303     if (HasFP) {
1304       // Define the current CFA rule to use the provided FP.
1305       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1306       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
1307           nullptr, Reg, StackGrowth - FixedObject));
1308       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1309           .addCFIIndex(CFIIndex)
1310           .setMIFlags(MachineInstr::FrameSetup);
1311     } else {
1312       // Encode the stack size of the leaf function.
1313       unsigned CFIIndex = MF.addFrameInst(
1314           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
1315       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1316           .addCFIIndex(CFIIndex)
1317           .setMIFlags(MachineInstr::FrameSetup);
1318     }
1319 
1320     // Now emit the moves for whatever callee saved regs we have (including FP,
1321     // LR if those are saved).
1322     emitCalleeSavedFrameMoves(MBB, MBBI);
1323   }
1324 }
1325 
1326 static void InsertReturnAddressAuth(MachineFunction &MF,
1327                                     MachineBasicBlock &MBB) {
1328   if (!ShouldSignReturnAddress(MF))
1329     return;
1330   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1331   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1332 
1333   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1334   DebugLoc DL;
1335   if (MBBI != MBB.end())
1336     DL = MBBI->getDebugLoc();
1337 
1338   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1339   // this instruction can safely used for any v8a architecture.
1340   // From v8.3a onwards there are optimised authenticate LR and return
1341   // instructions, namely RETA{A,B}, that can be used instead.
1342   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1343       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1344     BuildMI(MBB, MBBI, DL,
1345             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1346         .copyImplicitOps(*MBBI);
1347     MBB.erase(MBBI);
1348   } else {
1349     BuildMI(
1350         MBB, MBBI, DL,
1351         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1352         .setMIFlag(MachineInstr::FrameDestroy);
1353   }
1354 }
1355 
1356 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1357   switch (MI.getOpcode()) {
1358   default:
1359     return false;
1360   case AArch64::CATCHRET:
1361   case AArch64::CLEANUPRET:
1362     return true;
1363   }
1364 }
1365 
1366 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1367                                         MachineBasicBlock &MBB) const {
1368   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1369   MachineFrameInfo &MFI = MF.getFrameInfo();
1370   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1371   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1372   DebugLoc DL;
1373   bool IsTailCallReturn = false;
1374   bool NeedsWinCFI = needsWinCFI(MF);
1375   bool HasWinCFI = false;
1376   bool IsFunclet = false;
1377   auto WinCFI = make_scope_exit([&]() {
1378     if (!MF.hasWinCFI())
1379       MF.setHasWinCFI(HasWinCFI);
1380   });
1381 
1382   if (MBB.end() != MBBI) {
1383     DL = MBBI->getDebugLoc();
1384     unsigned RetOpcode = MBBI->getOpcode();
1385     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
1386                        RetOpcode == AArch64::TCRETURNri ||
1387                        RetOpcode == AArch64::TCRETURNriBTI;
1388     IsFunclet = isFuncletReturnInstr(*MBBI);
1389   }
1390 
1391   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1392                                : MFI.getStackSize();
1393   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1394 
1395   // All calls are tail calls in GHC calling conv, and functions have no
1396   // prologue/epilogue.
1397   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1398     return;
1399 
1400   // Initial and residual are named for consistency with the prologue. Note that
1401   // in the epilogue, the residual adjustment is executed first.
1402   uint64_t ArgumentPopSize = 0;
1403   if (IsTailCallReturn) {
1404     MachineOperand &StackAdjust = MBBI->getOperand(1);
1405 
1406     // For a tail-call in a callee-pops-arguments environment, some or all of
1407     // the stack may actually be in use for the call's arguments, this is
1408     // calculated during LowerCall and consumed here...
1409     ArgumentPopSize = StackAdjust.getImm();
1410   } else {
1411     // ... otherwise the amount to pop is *all* of the argument space,
1412     // conveniently stored in the MachineFunctionInfo by
1413     // LowerFormalArguments. This will, of course, be zero for the C calling
1414     // convention.
1415     ArgumentPopSize = AFI->getArgumentStackToRestore();
1416   }
1417 
1418   // The stack frame should be like below,
1419   //
1420   //      ----------------------                     ---
1421   //      |                    |                      |
1422   //      | BytesInStackArgArea|              CalleeArgStackSize
1423   //      | (NumReusableBytes) |                (of tail call)
1424   //      |                    |                     ---
1425   //      |                    |                      |
1426   //      ---------------------|        ---           |
1427   //      |                    |         |            |
1428   //      |   CalleeSavedReg   |         |            |
1429   //      | (CalleeSavedStackSize)|      |            |
1430   //      |                    |         |            |
1431   //      ---------------------|         |         NumBytes
1432   //      |                    |     StackSize  (StackAdjustUp)
1433   //      |   LocalStackSize   |         |            |
1434   //      | (covering callee   |         |            |
1435   //      |       args)        |         |            |
1436   //      |                    |         |            |
1437   //      ----------------------        ---          ---
1438   //
1439   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1440   //             = StackSize + ArgumentPopSize
1441   //
1442   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1443   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1444 
1445   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1446 
1447   bool IsWin64 =
1448       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1449   // Var args are accounted for in the containing function, so don't
1450   // include them for funclets.
1451   unsigned FixedObject =
1452       (IsWin64 && !IsFunclet) ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1453 
1454   uint64_t AfterCSRPopSize = ArgumentPopSize;
1455   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1456   // We cannot rely on the local stack size set in emitPrologue if the function
1457   // has funclets, as funclets have different local stack size requirements, and
1458   // the current value set in emitPrologue may be that of the containing
1459   // function.
1460   if (MF.hasEHFunclets())
1461     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1462   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1463   // Assume we can't combine the last pop with the sp restore.
1464 
1465   if (!CombineSPBump && PrologueSaveSize != 0) {
1466     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1467     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1468       Pop = std::prev(Pop);
1469     // Converting the last ldp to a post-index ldp is valid only if the last
1470     // ldp's offset is 0.
1471     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1472     // If the offset is 0, convert it to a post-index ldp.
1473     if (OffsetOp.getImm() == 0)
1474       convertCalleeSaveRestoreToSPPrePostIncDec(
1475           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, false);
1476     else {
1477       // If not, make sure to emit an add after the last ldp.
1478       // We're doing this by transfering the size to be restored from the
1479       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1480       // pops.
1481       AfterCSRPopSize += PrologueSaveSize;
1482     }
1483   }
1484 
1485   // Move past the restores of the callee-saved registers.
1486   // If we plan on combining the sp bump of the local stack size and the callee
1487   // save stack size, we might need to adjust the CSR save and restore offsets.
1488   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1489   MachineBasicBlock::iterator Begin = MBB.begin();
1490   while (LastPopI != Begin) {
1491     --LastPopI;
1492     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
1493         IsSVECalleeSave(LastPopI)) {
1494       ++LastPopI;
1495       break;
1496     } else if (CombineSPBump)
1497       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1498                                         NeedsWinCFI, &HasWinCFI);
1499   }
1500 
1501   if (NeedsWinCFI) {
1502     HasWinCFI = true;
1503     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1504         .setMIFlag(MachineInstr::FrameDestroy);
1505   }
1506 
1507   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1508 
1509   // If there is a single SP update, insert it before the ret and we're done.
1510   if (CombineSPBump) {
1511     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1512     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1513                     {NumBytes + (int64_t)AfterCSRPopSize, MVT::i8}, TII,
1514                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1515     if (NeedsWinCFI && HasWinCFI)
1516       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1517               TII->get(AArch64::SEH_EpilogEnd))
1518           .setMIFlag(MachineInstr::FrameDestroy);
1519     return;
1520   }
1521 
1522   NumBytes -= PrologueSaveSize;
1523   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1524 
1525   // Process the SVE callee-saves to determine what space needs to be
1526   // deallocated.
1527   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
1528   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
1529   if (AFI->getSVECalleeSavedStackSize()) {
1530     RestoreBegin = std::prev(RestoreEnd);;
1531     while (IsSVECalleeSave(RestoreBegin) &&
1532            RestoreBegin != MBB.begin())
1533       --RestoreBegin;
1534     ++RestoreBegin;
1535 
1536     assert(IsSVECalleeSave(RestoreBegin) &&
1537            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
1538 
1539     int64_t OffsetToFirstCalleeSaveFromSP =
1540         MFI.getObjectOffset(AFI->getMaxSVECSFrameIndex());
1541     StackOffset OffsetToCalleeSavesFromSP =
1542         StackOffset(OffsetToFirstCalleeSaveFromSP, MVT::nxv1i8) + SVEStackSize;
1543     DeallocateBefore = OffsetToCalleeSavesFromSP;
1544     DeallocateAfter = SVEStackSize - DeallocateBefore;
1545   }
1546 
1547   // Deallocate the SVE area.
1548   if (SVEStackSize) {
1549     if (AFI->isStackRealigned()) {
1550       if (AFI->getSVECalleeSavedStackSize())
1551         // Set SP to start of SVE area, from which the callee-save reloads
1552         // can be done. The code below will deallocate the stack space
1553         // space by moving FP -> SP.
1554         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
1555                         -SVEStackSize, TII, MachineInstr::FrameDestroy);
1556     } else {
1557       if (AFI->getSVECalleeSavedStackSize()) {
1558         // Deallocate the non-SVE locals first before we can deallocate (and
1559         // restore callee saves) from the SVE area.
1560         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1561                         {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy);
1562         NumBytes = 0;
1563       }
1564 
1565       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1566                       DeallocateBefore, TII, MachineInstr::FrameDestroy);
1567 
1568       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
1569                       DeallocateAfter, TII, MachineInstr::FrameDestroy);
1570     }
1571   }
1572 
1573   if (!hasFP(MF)) {
1574     bool RedZone = canUseRedZone(MF);
1575     // If this was a redzone leaf function, we don't need to restore the
1576     // stack pointer (but we may need to pop stack args for fastcc).
1577     if (RedZone && AfterCSRPopSize == 0)
1578       return;
1579 
1580     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1581     int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
1582     if (NoCalleeSaveRestore)
1583       StackRestoreBytes += AfterCSRPopSize;
1584 
1585     // If we were able to combine the local stack pop with the argument pop,
1586     // then we're done.
1587     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1588 
1589     // If we're done after this, make sure to help the load store optimizer.
1590     if (Done)
1591       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1592 
1593     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1594                     {StackRestoreBytes, MVT::i8}, TII,
1595                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1596     if (Done) {
1597       if (NeedsWinCFI) {
1598         HasWinCFI = true;
1599         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1600                 TII->get(AArch64::SEH_EpilogEnd))
1601             .setMIFlag(MachineInstr::FrameDestroy);
1602       }
1603       return;
1604     }
1605 
1606     NumBytes = 0;
1607   }
1608 
1609   // Restore the original stack pointer.
1610   // FIXME: Rather than doing the math here, we should instead just use
1611   // non-post-indexed loads for the restores if we aren't actually going to
1612   // be able to save any instructions.
1613   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
1614     int64_t OffsetToFrameRecord =
1615         isTargetDarwin(MF) ? (-(int64_t)AFI->getCalleeSavedStackSize() + 16) : 0;
1616     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1617                     {OffsetToFrameRecord, MVT::i8},
1618                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
1619   } else if (NumBytes)
1620     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1621                     {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy, false,
1622                     NeedsWinCFI);
1623 
1624   // This must be placed after the callee-save restore code because that code
1625   // assumes the SP is at the same location as it was after the callee-save save
1626   // code in the prologue.
1627   if (AfterCSRPopSize) {
1628     // Find an insertion point for the first ldp so that it goes before the
1629     // shadow call stack epilog instruction. This ensures that the restore of
1630     // lr from x18 is placed after the restore from sp.
1631     auto FirstSPPopI = MBB.getFirstTerminator();
1632     while (FirstSPPopI != Begin) {
1633       auto Prev = std::prev(FirstSPPopI);
1634       if (Prev->getOpcode() != AArch64::LDRXpre ||
1635           Prev->getOperand(0).getReg() == AArch64::SP)
1636         break;
1637       FirstSPPopI = Prev;
1638     }
1639 
1640     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1641 
1642     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1643                     {(int64_t)AfterCSRPopSize, MVT::i8}, TII,
1644                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1645   }
1646   if (NeedsWinCFI && HasWinCFI)
1647     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1648         .setMIFlag(MachineInstr::FrameDestroy);
1649 
1650   MF.setHasWinCFI(HasWinCFI);
1651 }
1652 
1653 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1654 /// debug info.  It's the same as what we use for resolving the code-gen
1655 /// references for now.  FIXME: This can go wrong when references are
1656 /// SP-relative and simple call frames aren't used.
1657 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1658                                                  int FI,
1659                                                  unsigned &FrameReg) const {
1660   return resolveFrameIndexReference(
1661              MF, FI, FrameReg,
1662              /*PreferFP=*/
1663              MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
1664              /*ForSimm=*/false)
1665       .getBytes();
1666 }
1667 
1668 int AArch64FrameLowering::getNonLocalFrameIndexReference(
1669   const MachineFunction &MF, int FI) const {
1670   return getSEHFrameIndexOffset(MF, FI);
1671 }
1672 
1673 static StackOffset getFPOffset(const MachineFunction &MF, int64_t ObjectOffset) {
1674   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1675   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1676   bool IsWin64 =
1677       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1678   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1679   unsigned FPAdjust = isTargetDarwin(MF)
1680                         ? 16 : AFI->getCalleeSavedStackSize(MF.getFrameInfo());
1681   return {ObjectOffset + FixedObject + FPAdjust, MVT::i8};
1682 }
1683 
1684 static StackOffset getStackOffset(const MachineFunction &MF, int64_t ObjectOffset) {
1685   const auto &MFI = MF.getFrameInfo();
1686   return {ObjectOffset + (int64_t)MFI.getStackSize(), MVT::i8};
1687 }
1688 
1689 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
1690                                                  int FI) const {
1691   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1692       MF.getSubtarget().getRegisterInfo());
1693   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
1694   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
1695              ? getFPOffset(MF, ObjectOffset).getBytes()
1696              : getStackOffset(MF, ObjectOffset).getBytes();
1697 }
1698 
1699 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
1700     const MachineFunction &MF, int FI, unsigned &FrameReg, bool PreferFP,
1701     bool ForSimm) const {
1702   const auto &MFI = MF.getFrameInfo();
1703   int64_t ObjectOffset = MFI.getObjectOffset(FI);
1704   bool isFixed = MFI.isFixedObjectIndex(FI);
1705   bool isSVE = MFI.getStackID(FI) == TargetStackID::SVEVector;
1706   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
1707                                      PreferFP, ForSimm);
1708 }
1709 
1710 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
1711     const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
1712     unsigned &FrameReg, bool PreferFP, bool ForSimm) const {
1713   const auto &MFI = MF.getFrameInfo();
1714   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1715       MF.getSubtarget().getRegisterInfo());
1716   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1717   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1718 
1719   int64_t FPOffset = getFPOffset(MF, ObjectOffset).getBytes();
1720   int64_t Offset = getStackOffset(MF, ObjectOffset).getBytes();
1721   bool isCSR =
1722       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
1723 
1724   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1725 
1726   // Use frame pointer to reference fixed objects. Use it for locals if
1727   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1728   // reliable as a base). Make sure useFPForScavengingIndex() does the
1729   // right thing for the emergency spill slot.
1730   bool UseFP = false;
1731   if (AFI->hasStackFrame() && !isSVE) {
1732     // We shouldn't prefer using the FP when there is an SVE area
1733     // in between the FP and the non-SVE locals/spills.
1734     PreferFP &= !SVEStackSize;
1735 
1736     // Note: Keeping the following as multiple 'if' statements rather than
1737     // merging to a single expression for readability.
1738     //
1739     // Argument access should always use the FP.
1740     if (isFixed) {
1741       UseFP = hasFP(MF);
1742     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1743       // References to the CSR area must use FP if we're re-aligning the stack
1744       // since the dynamically-sized alignment padding is between the SP/BP and
1745       // the CSR area.
1746       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1747       UseFP = true;
1748     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1749       // If the FPOffset is negative and we're producing a signed immediate, we
1750       // have to keep in mind that the available offset range for negative
1751       // offsets is smaller than for positive ones. If an offset is available
1752       // via the FP and the SP, use whichever is closest.
1753       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
1754       PreferFP |= Offset > -FPOffset;
1755 
1756       if (MFI.hasVarSizedObjects()) {
1757         // If we have variable sized objects, we can use either FP or BP, as the
1758         // SP offset is unknown. We can use the base pointer if we have one and
1759         // FP is not preferred. If not, we're stuck with using FP.
1760         bool CanUseBP = RegInfo->hasBasePointer(MF);
1761         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1762           UseFP = PreferFP;
1763         else if (!CanUseBP) { // Can't use BP. Forced to use FP.
1764           assert(!SVEStackSize && "Expected BP to be available");
1765           UseFP = true;
1766         }
1767         // else we can use BP and FP, but the offset from FP won't fit.
1768         // That will make us scavenge registers which we can probably avoid by
1769         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1770       } else if (FPOffset >= 0) {
1771         // Use SP or FP, whichever gives us the best chance of the offset
1772         // being in range for direct access. If the FPOffset is positive,
1773         // that'll always be best, as the SP will be even further away.
1774         UseFP = true;
1775       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1776         // Funclets access the locals contained in the parent's stack frame
1777         // via the frame pointer, so we have to use the FP in the parent
1778         // function.
1779         (void) Subtarget;
1780         assert(
1781             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1782             "Funclets should only be present on Win64");
1783         UseFP = true;
1784       } else {
1785         // We have the choice between FP and (SP or BP).
1786         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1787           UseFP = true;
1788       }
1789     }
1790   }
1791 
1792   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1793          "In the presence of dynamic stack pointer realignment, "
1794          "non-argument/CSR objects cannot be accessed through the frame pointer");
1795 
1796   if (isSVE) {
1797     int64_t OffsetToSVEArea =
1798         MFI.getStackSize() - AFI->getCalleeSavedStackSize();
1799     StackOffset FPOffset = {ObjectOffset, MVT::nxv1i8};
1800     StackOffset SPOffset = SVEStackSize +
1801                            StackOffset(ObjectOffset, MVT::nxv1i8) +
1802                            StackOffset(OffsetToSVEArea, MVT::i8);
1803     // Always use the FP for SVE spills if available and beneficial.
1804     if (hasFP(MF) &&
1805         (SPOffset.getBytes() ||
1806          FPOffset.getScalableBytes() < SPOffset.getScalableBytes() ||
1807          RegInfo->needsStackRealignment(MF))) {
1808       FrameReg = RegInfo->getFrameRegister(MF);
1809       return FPOffset;
1810     }
1811 
1812     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
1813                                            : (unsigned)AArch64::SP;
1814     return SPOffset;
1815   }
1816 
1817   StackOffset ScalableOffset = {};
1818   if (UseFP && !(isFixed || isCSR))
1819     ScalableOffset = -SVEStackSize;
1820   if (!UseFP && (isFixed || isCSR))
1821     ScalableOffset = SVEStackSize;
1822 
1823   if (UseFP) {
1824     FrameReg = RegInfo->getFrameRegister(MF);
1825     return StackOffset(FPOffset, MVT::i8) + ScalableOffset;
1826   }
1827 
1828   // Use the base pointer if we have one.
1829   if (RegInfo->hasBasePointer(MF))
1830     FrameReg = RegInfo->getBaseRegister();
1831   else {
1832     assert(!MFI.hasVarSizedObjects() &&
1833            "Can't use SP when we have var sized objects.");
1834     FrameReg = AArch64::SP;
1835     // If we're using the red zone for this function, the SP won't actually
1836     // be adjusted, so the offsets will be negative. They're also all
1837     // within range of the signed 9-bit immediate instructions.
1838     if (canUseRedZone(MF))
1839       Offset -= AFI->getLocalStackSize();
1840   }
1841 
1842   return StackOffset(Offset, MVT::i8) + ScalableOffset;
1843 }
1844 
1845 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1846   // Do not set a kill flag on values that are also marked as live-in. This
1847   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1848   // callee saved registers.
1849   // Omitting the kill flags is conservatively correct even if the live-in
1850   // is not used after all.
1851   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1852   return getKillRegState(!IsLiveIn);
1853 }
1854 
1855 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1856   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1857   AttributeList Attrs = MF.getFunction().getAttributes();
1858   return Subtarget.isTargetMachO() &&
1859          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1860            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1861 }
1862 
1863 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1864                                              bool NeedsWinCFI) {
1865   // If we are generating register pairs for a Windows function that requires
1866   // EH support, then pair consecutive registers only.  There are no unwind
1867   // opcodes for saves/restores of non-consectuve register pairs.
1868   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1869   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1870 
1871   // TODO: LR can be paired with any register.  We don't support this yet in
1872   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1873   if (!NeedsWinCFI)
1874     return false;
1875   if (Reg2 == Reg1 + 1)
1876     return false;
1877   return true;
1878 }
1879 
1880 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
1881 /// WindowsCFI requires that only consecutive registers can be paired.
1882 /// LR and FP need to be allocated together when the frame needs to save
1883 /// the frame-record. This means any other register pairing with LR is invalid.
1884 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
1885                                       bool NeedsWinCFI, bool NeedsFrameRecord) {
1886   if (NeedsWinCFI)
1887     return invalidateWindowsRegisterPairing(Reg1, Reg2, true);
1888 
1889   // If we need to store the frame record, don't pair any register
1890   // with LR other than FP.
1891   if (NeedsFrameRecord)
1892     return Reg2 == AArch64::LR;
1893 
1894   return false;
1895 }
1896 
1897 namespace {
1898 
1899 struct RegPairInfo {
1900   unsigned Reg1 = AArch64::NoRegister;
1901   unsigned Reg2 = AArch64::NoRegister;
1902   int FrameIdx;
1903   int Offset;
1904   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
1905 
1906   RegPairInfo() = default;
1907 
1908   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1909 
1910   unsigned getScale() const {
1911     switch (Type) {
1912     case PPR:
1913       return 2;
1914     case GPR:
1915     case FPR64:
1916       return 8;
1917     case ZPR:
1918     case FPR128:
1919       return 16;
1920     }
1921     llvm_unreachable("Unsupported type");
1922   }
1923 
1924   bool isScalable() const { return Type == PPR || Type == ZPR; }
1925 };
1926 
1927 } // end anonymous namespace
1928 
1929 static void computeCalleeSaveRegisterPairs(
1930     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1931     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1932     bool &NeedShadowCallStackProlog, bool NeedsFrameRecord) {
1933 
1934   if (CSI.empty())
1935     return;
1936 
1937   bool NeedsWinCFI = needsWinCFI(MF);
1938   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1939   MachineFrameInfo &MFI = MF.getFrameInfo();
1940   CallingConv::ID CC = MF.getFunction().getCallingConv();
1941   unsigned Count = CSI.size();
1942   (void)CC;
1943   // MachO's compact unwind format relies on all registers being stored in
1944   // pairs.
1945   assert((!produceCompactUnwindFrame(MF) ||
1946           CC == CallingConv::PreserveMost ||
1947           (Count & 1) == 0) &&
1948          "Odd number of callee-saved regs to spill!");
1949   int ByteOffset = AFI->getCalleeSavedStackSize();
1950   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
1951   // On Linux, we will have either one or zero non-paired register.  On Windows
1952   // with CFI, we can have multiple unpaired registers in order to utilize the
1953   // available unwind codes.  This flag assures that the alignment fixup is done
1954   // only once, as intened.
1955   bool FixupDone = false;
1956   for (unsigned i = 0; i < Count; ++i) {
1957     RegPairInfo RPI;
1958     RPI.Reg1 = CSI[i].getReg();
1959 
1960     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1961       RPI.Type = RegPairInfo::GPR;
1962     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1963       RPI.Type = RegPairInfo::FPR64;
1964     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1965       RPI.Type = RegPairInfo::FPR128;
1966     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
1967       RPI.Type = RegPairInfo::ZPR;
1968     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
1969       RPI.Type = RegPairInfo::PPR;
1970     else
1971       llvm_unreachable("Unsupported register class.");
1972 
1973     // Add the next reg to the pair if it is in the same register class.
1974     if (i + 1 < Count) {
1975       unsigned NextReg = CSI[i + 1].getReg();
1976       switch (RPI.Type) {
1977       case RegPairInfo::GPR:
1978         if (AArch64::GPR64RegClass.contains(NextReg) &&
1979             !invalidateRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
1980                                        NeedsFrameRecord))
1981           RPI.Reg2 = NextReg;
1982         break;
1983       case RegPairInfo::FPR64:
1984         if (AArch64::FPR64RegClass.contains(NextReg) &&
1985             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1986           RPI.Reg2 = NextReg;
1987         break;
1988       case RegPairInfo::FPR128:
1989         if (AArch64::FPR128RegClass.contains(NextReg))
1990           RPI.Reg2 = NextReg;
1991         break;
1992       case RegPairInfo::PPR:
1993       case RegPairInfo::ZPR:
1994         break;
1995       }
1996     }
1997 
1998     // If either of the registers to be saved is the lr register, it means that
1999     // we also need to save lr in the shadow call stack.
2000     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
2001         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
2002       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
2003         report_fatal_error("Must reserve x18 to use shadow call stack");
2004       NeedShadowCallStackProlog = true;
2005     }
2006 
2007     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2008     // list to come in sorted by frame index so that we can issue the store
2009     // pair instructions directly. Assert if we see anything otherwise.
2010     //
2011     // The order of the registers in the list is controlled by
2012     // getCalleeSavedRegs(), so they will always be in-order, as well.
2013     assert((!RPI.isPaired() ||
2014             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
2015            "Out of order callee saved regs!");
2016 
2017     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2018             RPI.Reg1 == AArch64::LR) &&
2019            "FrameRecord must be allocated together with LR");
2020 
2021     // MachO's compact unwind format relies on all registers being stored in
2022     // adjacent register pairs.
2023     assert((!produceCompactUnwindFrame(MF) ||
2024             CC == CallingConv::PreserveMost ||
2025             (RPI.isPaired() &&
2026              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2027               RPI.Reg1 + 1 == RPI.Reg2))) &&
2028            "Callee-save registers not saved as adjacent register pair!");
2029 
2030     RPI.FrameIdx = CSI[i].getFrameIdx();
2031 
2032     int Scale = RPI.getScale();
2033     if (RPI.isScalable())
2034       ScalableByteOffset -= Scale;
2035     else
2036       ByteOffset -= RPI.isPaired() ? 2 * Scale : Scale;
2037 
2038     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2039            "Paired spill/fill instructions don't exist for SVE vectors");
2040 
2041     // Round up size of non-pair to pair size if we need to pad the
2042     // callee-save area to ensure 16-byte alignment.
2043     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
2044         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2045         !RPI.isPaired()) {
2046       FixupDone = true;
2047       ByteOffset -= 8;
2048       assert(ByteOffset % 16 == 0);
2049       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
2050       MFI.setObjectAlignment(RPI.FrameIdx, 16);
2051     }
2052 
2053     int Offset = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2054     assert(Offset % Scale == 0);
2055     RPI.Offset = Offset / Scale;
2056 
2057     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2058             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2059            "Offset out of bounds for LDP/STP immediate");
2060 
2061     RegPairs.push_back(RPI);
2062     if (RPI.isPaired())
2063       ++i;
2064   }
2065 }
2066 
2067 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2068     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2069     const std::vector<CalleeSavedInfo> &CSI,
2070     const TargetRegisterInfo *TRI) const {
2071   MachineFunction &MF = *MBB.getParent();
2072   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2073   bool NeedsWinCFI = needsWinCFI(MF);
2074   DebugLoc DL;
2075   SmallVector<RegPairInfo, 8> RegPairs;
2076 
2077   bool NeedShadowCallStackProlog = false;
2078   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2079                                  NeedShadowCallStackProlog, hasFP(MF));
2080   const MachineRegisterInfo &MRI = MF.getRegInfo();
2081 
2082   if (NeedShadowCallStackProlog) {
2083     // Shadow call stack prolog: str x30, [x18], #8
2084     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
2085         .addReg(AArch64::X18, RegState::Define)
2086         .addReg(AArch64::LR)
2087         .addReg(AArch64::X18)
2088         .addImm(8)
2089         .setMIFlag(MachineInstr::FrameSetup);
2090 
2091     if (NeedsWinCFI)
2092       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
2093           .setMIFlag(MachineInstr::FrameSetup);
2094 
2095     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
2096       // Emit a CFI instruction that causes 8 to be subtracted from the value of
2097       // x18 when unwinding past this frame.
2098       static const char CFIInst[] = {
2099           dwarf::DW_CFA_val_expression,
2100           18, // register
2101           2,  // length
2102           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
2103           static_cast<char>(-8) & 0x7f, // addend (sleb128)
2104       };
2105       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
2106           nullptr, StringRef(CFIInst, sizeof(CFIInst))));
2107       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
2108           .addCFIIndex(CFIIndex)
2109           .setMIFlag(MachineInstr::FrameSetup);
2110     }
2111 
2112     // This instruction also makes x18 live-in to the entry block.
2113     MBB.addLiveIn(AArch64::X18);
2114   }
2115 
2116   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
2117        ++RPII) {
2118     RegPairInfo RPI = *RPII;
2119     unsigned Reg1 = RPI.Reg1;
2120     unsigned Reg2 = RPI.Reg2;
2121     unsigned StrOpc;
2122 
2123     // Issue sequence of spills for cs regs.  The first spill may be converted
2124     // to a pre-decrement store later by emitPrologue if the callee-save stack
2125     // area allocation can't be combined with the local stack area allocation.
2126     // For example:
2127     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2128     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2129     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2130     // Rationale: This sequence saves uop updates compared to a sequence of
2131     // pre-increment spills like stp xi,xj,[sp,#-16]!
2132     // Note: Similar rationale and sequence for restores in epilog.
2133     unsigned Size, Align;
2134     switch (RPI.Type) {
2135     case RegPairInfo::GPR:
2136        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2137        Size = 8;
2138        Align = 8;
2139        break;
2140     case RegPairInfo::FPR64:
2141        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2142        Size = 8;
2143        Align = 8;
2144        break;
2145     case RegPairInfo::FPR128:
2146        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2147        Size = 16;
2148        Align = 16;
2149        break;
2150     case RegPairInfo::ZPR:
2151        StrOpc = AArch64::STR_ZXI;
2152        Size = 16;
2153        Align = 16;
2154        break;
2155     case RegPairInfo::PPR:
2156        StrOpc = AArch64::STR_PXI;
2157        Size = 2;
2158        Align = 2;
2159        break;
2160     }
2161     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2162                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2163                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2164                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2165                dbgs() << ")\n");
2166 
2167     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2168            "Windows unwdinding requires a consecutive (FP,LR) pair");
2169     // Windows unwind codes require consecutive registers if registers are
2170     // paired.  Make the switch here, so that the code below will save (x,x+1)
2171     // and not (x+1,x).
2172     unsigned FrameIdxReg1 = RPI.FrameIdx;
2173     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2174     if (NeedsWinCFI && RPI.isPaired()) {
2175       std::swap(Reg1, Reg2);
2176       std::swap(FrameIdxReg1, FrameIdxReg2);
2177     }
2178     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2179     if (!MRI.isReserved(Reg1))
2180       MBB.addLiveIn(Reg1);
2181     if (RPI.isPaired()) {
2182       if (!MRI.isReserved(Reg2))
2183         MBB.addLiveIn(Reg2);
2184       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2185       MIB.addMemOperand(MF.getMachineMemOperand(
2186           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2187           MachineMemOperand::MOStore, Size, Align));
2188     }
2189     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2190         .addReg(AArch64::SP)
2191         .addImm(RPI.Offset) // [sp, #offset*scale],
2192                             // where factor*scale is implicit
2193         .setMIFlag(MachineInstr::FrameSetup);
2194     MIB.addMemOperand(MF.getMachineMemOperand(
2195         MachinePointerInfo::getFixedStack(MF,FrameIdxReg1),
2196         MachineMemOperand::MOStore, Size, Align));
2197     if (NeedsWinCFI)
2198       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2199 
2200     // Update the StackIDs of the SVE stack slots.
2201     MachineFrameInfo &MFI = MF.getFrameInfo();
2202     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2203       MFI.setStackID(RPI.FrameIdx, TargetStackID::SVEVector);
2204 
2205   }
2206   return true;
2207 }
2208 
2209 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2210     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2211     std::vector<CalleeSavedInfo> &CSI,
2212     const TargetRegisterInfo *TRI) const {
2213   MachineFunction &MF = *MBB.getParent();
2214   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2215   DebugLoc DL;
2216   SmallVector<RegPairInfo, 8> RegPairs;
2217   bool NeedsWinCFI = needsWinCFI(MF);
2218 
2219   if (MI != MBB.end())
2220     DL = MI->getDebugLoc();
2221 
2222   bool NeedShadowCallStackProlog = false;
2223   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2224                                  NeedShadowCallStackProlog, hasFP(MF));
2225 
2226   auto EmitMI = [&](const RegPairInfo &RPI) {
2227     unsigned Reg1 = RPI.Reg1;
2228     unsigned Reg2 = RPI.Reg2;
2229 
2230     // Issue sequence of restores for cs regs. The last restore may be converted
2231     // to a post-increment load later by emitEpilogue if the callee-save stack
2232     // area allocation can't be combined with the local stack area allocation.
2233     // For example:
2234     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2235     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2236     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2237     // Note: see comment in spillCalleeSavedRegisters()
2238     unsigned LdrOpc;
2239     unsigned Size, Align;
2240     switch (RPI.Type) {
2241     case RegPairInfo::GPR:
2242        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2243        Size = 8;
2244        Align = 8;
2245        break;
2246     case RegPairInfo::FPR64:
2247        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2248        Size = 8;
2249        Align = 8;
2250        break;
2251     case RegPairInfo::FPR128:
2252        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2253        Size = 16;
2254        Align = 16;
2255        break;
2256     case RegPairInfo::ZPR:
2257        LdrOpc = AArch64::LDR_ZXI;
2258        Size = 16;
2259        Align = 16;
2260        break;
2261     case RegPairInfo::PPR:
2262        LdrOpc = AArch64::LDR_PXI;
2263        Size = 2;
2264        Align = 2;
2265        break;
2266     }
2267     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2268                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2269                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2270                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2271                dbgs() << ")\n");
2272 
2273     // Windows unwind codes require consecutive registers if registers are
2274     // paired.  Make the switch here, so that the code below will save (x,x+1)
2275     // and not (x+1,x).
2276     unsigned FrameIdxReg1 = RPI.FrameIdx;
2277     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2278     if (NeedsWinCFI && RPI.isPaired()) {
2279       std::swap(Reg1, Reg2);
2280       std::swap(FrameIdxReg1, FrameIdxReg2);
2281     }
2282     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
2283     if (RPI.isPaired()) {
2284       MIB.addReg(Reg2, getDefRegState(true));
2285       MIB.addMemOperand(MF.getMachineMemOperand(
2286           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2287           MachineMemOperand::MOLoad, Size, Align));
2288     }
2289     MIB.addReg(Reg1, getDefRegState(true))
2290         .addReg(AArch64::SP)
2291         .addImm(RPI.Offset) // [sp, #offset*scale]
2292                             // where factor*scale is implicit
2293         .setMIFlag(MachineInstr::FrameDestroy);
2294     MIB.addMemOperand(MF.getMachineMemOperand(
2295         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2296         MachineMemOperand::MOLoad, Size, Align));
2297     if (NeedsWinCFI)
2298       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2299   };
2300 
2301   // SVE objects are always restored in reverse order.
2302   for (const RegPairInfo &RPI : reverse(RegPairs))
2303     if (RPI.isScalable())
2304       EmitMI(RPI);
2305 
2306   if (ReverseCSRRestoreSeq) {
2307     for (const RegPairInfo &RPI : reverse(RegPairs))
2308       if (!RPI.isScalable())
2309         EmitMI(RPI);
2310   } else
2311     for (const RegPairInfo &RPI : RegPairs)
2312       if (!RPI.isScalable())
2313         EmitMI(RPI);
2314 
2315   if (NeedShadowCallStackProlog) {
2316     // Shadow call stack epilog: ldr x30, [x18, #-8]!
2317     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
2318         .addReg(AArch64::X18, RegState::Define)
2319         .addReg(AArch64::LR, RegState::Define)
2320         .addReg(AArch64::X18)
2321         .addImm(-8)
2322         .setMIFlag(MachineInstr::FrameDestroy);
2323   }
2324 
2325   return true;
2326 }
2327 
2328 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2329                                                 BitVector &SavedRegs,
2330                                                 RegScavenger *RS) const {
2331   // All calls are tail calls in GHC calling conv, and functions have no
2332   // prologue/epilogue.
2333   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2334     return;
2335 
2336   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2337   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2338       MF.getSubtarget().getRegisterInfo());
2339   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2340   unsigned UnspilledCSGPR = AArch64::NoRegister;
2341   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2342 
2343   MachineFrameInfo &MFI = MF.getFrameInfo();
2344   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2345 
2346   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2347                                 ? RegInfo->getBaseRegister()
2348                                 : (unsigned)AArch64::NoRegister;
2349 
2350   unsigned ExtraCSSpill = 0;
2351   // Figure out which callee-saved registers to save/restore.
2352   for (unsigned i = 0; CSRegs[i]; ++i) {
2353     const unsigned Reg = CSRegs[i];
2354 
2355     // Add the base pointer register to SavedRegs if it is callee-save.
2356     if (Reg == BasePointerReg)
2357       SavedRegs.set(Reg);
2358 
2359     bool RegUsed = SavedRegs.test(Reg);
2360     unsigned PairedReg = AArch64::NoRegister;
2361     if (AArch64::GPR64RegClass.contains(Reg) ||
2362         AArch64::FPR64RegClass.contains(Reg) ||
2363         AArch64::FPR128RegClass.contains(Reg))
2364       PairedReg = CSRegs[i ^ 1];
2365 
2366     if (!RegUsed) {
2367       if (AArch64::GPR64RegClass.contains(Reg) &&
2368           !RegInfo->isReservedReg(MF, Reg)) {
2369         UnspilledCSGPR = Reg;
2370         UnspilledCSGPRPaired = PairedReg;
2371       }
2372       continue;
2373     }
2374 
2375     // MachO's compact unwind format relies on all registers being stored in
2376     // pairs.
2377     // FIXME: the usual format is actually better if unwinding isn't needed.
2378     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
2379         !SavedRegs.test(PairedReg)) {
2380       SavedRegs.set(PairedReg);
2381       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2382           !RegInfo->isReservedReg(MF, PairedReg))
2383         ExtraCSSpill = PairedReg;
2384     }
2385   }
2386 
2387   // Calculates the callee saved stack size.
2388   unsigned CSStackSize = 0;
2389   unsigned SVECSStackSize = 0;
2390   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2391   const MachineRegisterInfo &MRI = MF.getRegInfo();
2392   for (unsigned Reg : SavedRegs.set_bits()) {
2393     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
2394     if (AArch64::PPRRegClass.contains(Reg) ||
2395         AArch64::ZPRRegClass.contains(Reg))
2396       SVECSStackSize += RegSize;
2397     else
2398       CSStackSize += RegSize;
2399   }
2400 
2401   // Save number of saved regs, so we can easily update CSStackSize later.
2402   unsigned NumSavedRegs = SavedRegs.count();
2403 
2404   // The frame record needs to be created by saving the appropriate registers
2405   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
2406   if (hasFP(MF) ||
2407       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2408     SavedRegs.set(AArch64::FP);
2409     SavedRegs.set(AArch64::LR);
2410   }
2411 
2412   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2413              for (unsigned Reg
2414                   : SavedRegs.set_bits()) dbgs()
2415              << ' ' << printReg(Reg, RegInfo);
2416              dbgs() << "\n";);
2417 
2418   // If any callee-saved registers are used, the frame cannot be eliminated.
2419   int64_t SVEStackSize =
2420       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
2421   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2422 
2423   // The CSR spill slots have not been allocated yet, so estimateStackSize
2424   // won't include them.
2425   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2426 
2427   // Conservatively always assume BigStack when there are SVE spills.
2428   bool BigStack = SVEStackSize ||
2429                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2430   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2431     AFI->setHasStackFrame(true);
2432 
2433   // Estimate if we might need to scavenge a register at some point in order
2434   // to materialize a stack offset. If so, either spill one additional
2435   // callee-saved register or reserve a special spill slot to facilitate
2436   // register scavenging. If we already spilled an extra callee-saved register
2437   // above to keep the number of spills even, we don't need to do anything else
2438   // here.
2439   if (BigStack) {
2440     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2441       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2442                         << " to get a scratch register.\n");
2443       SavedRegs.set(UnspilledCSGPR);
2444       // MachO's compact unwind format relies on all registers being stored in
2445       // pairs, so if we need to spill one extra for BigStack, then we need to
2446       // store the pair.
2447       if (produceCompactUnwindFrame(MF))
2448         SavedRegs.set(UnspilledCSGPRPaired);
2449       ExtraCSSpill = UnspilledCSGPR;
2450     }
2451 
2452     // If we didn't find an extra callee-saved register to spill, create
2453     // an emergency spill slot.
2454     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2455       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2456       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2457       unsigned Size = TRI->getSpillSize(RC);
2458       unsigned Align = TRI->getSpillAlignment(RC);
2459       int FI = MFI.CreateStackObject(Size, Align, false);
2460       RS->addScavengingFrameIndex(FI);
2461       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2462                         << " as the emergency spill slot.\n");
2463     }
2464   }
2465 
2466   // Adding the size of additional 64bit GPR saves.
2467   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2468   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
2469   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2470                << EstimatedStackSize + AlignedCSStackSize
2471                << " bytes.\n");
2472 
2473   assert((!MFI.isCalleeSavedInfoValid() ||
2474           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2475          "Should not invalidate callee saved info");
2476 
2477   // Round up to register pair alignment to avoid additional SP adjustment
2478   // instructions.
2479   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2480   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2481   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
2482 }
2483 
2484 bool AArch64FrameLowering::enableStackSlotScavenging(
2485     const MachineFunction &MF) const {
2486   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2487   return AFI->hasCalleeSaveStackFreeSpace();
2488 }
2489 
2490 /// returns true if there are any SVE callee saves.
2491 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
2492                                       int &Min, int &Max) {
2493   Min = std::numeric_limits<int>::max();
2494   Max = std::numeric_limits<int>::min();
2495 
2496   if (!MFI.isCalleeSavedInfoValid())
2497     return false;
2498 
2499   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2500   for (auto &CS : CSI) {
2501     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
2502         AArch64::PPRRegClass.contains(CS.getReg())) {
2503       assert((Max == std::numeric_limits<int>::min() ||
2504               Max + 1 == CS.getFrameIdx()) &&
2505              "SVE CalleeSaves are not consecutive");
2506 
2507       Min = std::min(Min, CS.getFrameIdx());
2508       Max = std::max(Max, CS.getFrameIdx());
2509     }
2510   }
2511   return Min != std::numeric_limits<int>::max();
2512 }
2513 
2514 // Process all the SVE stack objects and determine offsets for each
2515 // object. If AssignOffsets is true, the offsets get assigned.
2516 // Fills in the first and last callee-saved frame indices into
2517 // Min/MaxCSFrameIndex, respectively.
2518 // Returns the size of the stack.
2519 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
2520                                               int &MinCSFrameIndex,
2521                                               int &MaxCSFrameIndex,
2522                                               bool AssignOffsets) {
2523   // First process all fixed stack objects.
2524   int64_t Offset = 0;
2525   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
2526     if (MFI.getStackID(I) == TargetStackID::SVEVector) {
2527       int64_t FixedOffset = -MFI.getObjectOffset(I);
2528       if (FixedOffset > Offset)
2529         Offset = FixedOffset;
2530     }
2531 
2532   auto Assign = [&MFI](int FI, int64_t Offset) {
2533     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
2534     MFI.setObjectOffset(FI, Offset);
2535   };
2536 
2537   // Then process all callee saved slots.
2538   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
2539     // Make sure to align the last callee save slot.
2540     MFI.setObjectAlignment(MaxCSFrameIndex, 16U);
2541 
2542     // Assign offsets to the callee save slots.
2543     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
2544       Offset += MFI.getObjectSize(I);
2545       Offset = alignTo(Offset, MFI.getObjectAlignment(I));
2546       if (AssignOffsets)
2547         Assign(I, -Offset);
2548     }
2549   }
2550 
2551   // Create a buffer of SVE objects to allocate and sort it.
2552   SmallVector<int, 8> ObjectsToAllocate;
2553   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
2554     unsigned StackID = MFI.getStackID(I);
2555     if (StackID != TargetStackID::SVEVector)
2556       continue;
2557     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
2558       continue;
2559     if (MFI.isDeadObjectIndex(I))
2560       continue;
2561 
2562     ObjectsToAllocate.push_back(I);
2563   }
2564 
2565   // Allocate all SVE locals and spills
2566   for (unsigned FI : ObjectsToAllocate) {
2567     unsigned Align = MFI.getObjectAlignment(FI);
2568     // FIXME: Given that the length of SVE vectors is not necessarily a power of
2569     // two, we'd need to align every object dynamically at runtime if the
2570     // alignment is larger than 16. This is not yet supported.
2571     if (Align > 16)
2572       report_fatal_error(
2573           "Alignment of scalable vectors > 16 bytes is not yet supported");
2574 
2575     Offset = alignTo(Offset + MFI.getObjectSize(FI), Align);
2576     if (AssignOffsets)
2577       Assign(FI, -Offset);
2578   }
2579 
2580   return Offset;
2581 }
2582 
2583 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
2584     MachineFrameInfo &MFI) const {
2585   int MinCSFrameIndex, MaxCSFrameIndex;
2586   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
2587 }
2588 
2589 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
2590     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
2591   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
2592                                         true);
2593 }
2594 
2595 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2596     MachineFunction &MF, RegScavenger *RS) const {
2597   MachineFrameInfo &MFI = MF.getFrameInfo();
2598 
2599   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
2600          "Upwards growing stack unsupported");
2601 
2602   int MinCSFrameIndex, MaxCSFrameIndex;
2603   int64_t SVEStackSize =
2604       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
2605 
2606   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2607   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
2608   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
2609 
2610   // If this function isn't doing Win64-style C++ EH, we don't need to do
2611   // anything.
2612   if (!MF.hasEHFunclets())
2613     return;
2614   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2615   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2616 
2617   MachineBasicBlock &MBB = MF.front();
2618   auto MBBI = MBB.begin();
2619   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2620     ++MBBI;
2621 
2622   // Create an UnwindHelp object.
2623   int UnwindHelpFI =
2624       MFI.CreateStackObject(/*size*/8, /*alignment*/16, false);
2625   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2626   // We need to store -2 into the UnwindHelp object at the start of the
2627   // function.
2628   DebugLoc DL;
2629   RS->enterBasicBlockEnd(MBB);
2630   RS->backward(std::prev(MBBI));
2631   unsigned DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
2632   assert(DstReg && "There must be a free register after frame setup");
2633   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2634   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2635       .addReg(DstReg, getKillRegState(true))
2636       .addFrameIndex(UnwindHelpFI)
2637       .addImm(0);
2638 }
2639 
2640 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before
2641 /// the update.  This is easily retrieved as it is exactly the offset that is set
2642 /// in processFunctionBeforeFrameFinalized.
2643 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
2644     const MachineFunction &MF, int FI, unsigned &FrameReg,
2645     bool IgnoreSPUpdates) const {
2646   const MachineFrameInfo &MFI = MF.getFrameInfo();
2647   LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
2648                     << MFI.getObjectOffset(FI) << "\n");
2649   FrameReg = AArch64::SP;
2650   return MFI.getObjectOffset(FI);
2651 }
2652 
2653 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
2654 /// the parent's frame pointer
2655 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
2656     const MachineFunction &MF) const {
2657   return 0;
2658 }
2659 
2660 /// Funclets only need to account for space for the callee saved registers,
2661 /// as the locals are accounted for in the parent's stack frame.
2662 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
2663     const MachineFunction &MF) const {
2664   // This is the size of the pushed CSRs.
2665   unsigned CSSize =
2666       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
2667   // This is the amount of stack a funclet needs to allocate.
2668   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
2669                  getStackAlignment());
2670 }
2671