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