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