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