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