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