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