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