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 to access fixed-sized stack objects when
2070     // there are scalable (SVE) objects in between the FP and the fixed-sized
2071     // objects.
2072     PreferFP &= !SVEStackSize;
2073 
2074     // Note: Keeping the following as multiple 'if' statements rather than
2075     // merging to a single expression for readability.
2076     //
2077     // Argument access should always use the FP.
2078     if (isFixed) {
2079       UseFP = hasFP(MF);
2080     } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
2081       // References to the CSR area must use FP if we're re-aligning the stack
2082       // since the dynamically-sized alignment padding is between the SP/BP and
2083       // the CSR area.
2084       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
2085       UseFP = true;
2086     } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
2087       // If the FPOffset is negative and we're producing a signed immediate, we
2088       // have to keep in mind that the available offset range for negative
2089       // offsets is smaller than for positive ones. If an offset is available
2090       // via the FP and the SP, use whichever is closest.
2091       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
2092       PreferFP |= Offset > -FPOffset && !SVEStackSize;
2093 
2094       if (MFI.hasVarSizedObjects()) {
2095         // If we have variable sized objects, we can use either FP or BP, as the
2096         // SP offset is unknown. We can use the base pointer if we have one and
2097         // FP is not preferred. If not, we're stuck with using FP.
2098         bool CanUseBP = RegInfo->hasBasePointer(MF);
2099         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
2100           UseFP = PreferFP;
2101         else if (!CanUseBP) // Can't use BP. Forced to use FP.
2102           UseFP = true;
2103         // else we can use BP and FP, but the offset from FP won't fit.
2104         // That will make us scavenge registers which we can probably avoid by
2105         // using BP. If it won't fit for BP either, we'll scavenge anyway.
2106       } else if (FPOffset >= 0) {
2107         // Use SP or FP, whichever gives us the best chance of the offset
2108         // being in range for direct access. If the FPOffset is positive,
2109         // that'll always be best, as the SP will be even further away.
2110         UseFP = true;
2111       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
2112         // Funclets access the locals contained in the parent's stack frame
2113         // via the frame pointer, so we have to use the FP in the parent
2114         // function.
2115         (void) Subtarget;
2116         assert(
2117             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
2118             "Funclets should only be present on Win64");
2119         UseFP = true;
2120       } else {
2121         // We have the choice between FP and (SP or BP).
2122         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
2123           UseFP = true;
2124       }
2125     }
2126   }
2127 
2128   assert(
2129       ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
2130       "In the presence of dynamic stack pointer realignment, "
2131       "non-argument/CSR objects cannot be accessed through the frame pointer");
2132 
2133   if (isSVE) {
2134     StackOffset FPOffset =
2135         StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
2136     StackOffset SPOffset =
2137         SVEStackSize +
2138         StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
2139                          ObjectOffset);
2140     // Always use the FP for SVE spills if available and beneficial.
2141     if (hasFP(MF) && (SPOffset.getFixed() ||
2142                       FPOffset.getScalable() < SPOffset.getScalable() ||
2143                       RegInfo->hasStackRealignment(MF))) {
2144       FrameReg = RegInfo->getFrameRegister(MF);
2145       return FPOffset;
2146     }
2147 
2148     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
2149                                            : (unsigned)AArch64::SP;
2150     return SPOffset;
2151   }
2152 
2153   StackOffset ScalableOffset = {};
2154   if (UseFP && !(isFixed || isCSR))
2155     ScalableOffset = -SVEStackSize;
2156   if (!UseFP && (isFixed || isCSR))
2157     ScalableOffset = SVEStackSize;
2158 
2159   if (UseFP) {
2160     FrameReg = RegInfo->getFrameRegister(MF);
2161     return StackOffset::getFixed(FPOffset) + ScalableOffset;
2162   }
2163 
2164   // Use the base pointer if we have one.
2165   if (RegInfo->hasBasePointer(MF))
2166     FrameReg = RegInfo->getBaseRegister();
2167   else {
2168     assert(!MFI.hasVarSizedObjects() &&
2169            "Can't use SP when we have var sized objects.");
2170     FrameReg = AArch64::SP;
2171     // If we're using the red zone for this function, the SP won't actually
2172     // be adjusted, so the offsets will be negative. They're also all
2173     // within range of the signed 9-bit immediate instructions.
2174     if (canUseRedZone(MF))
2175       Offset -= AFI->getLocalStackSize();
2176   }
2177 
2178   return StackOffset::getFixed(Offset) + ScalableOffset;
2179 }
2180 
2181 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
2182   // Do not set a kill flag on values that are also marked as live-in. This
2183   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2184   // callee saved registers.
2185   // Omitting the kill flags is conservatively correct even if the live-in
2186   // is not used after all.
2187   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
2188   return getKillRegState(!IsLiveIn);
2189 }
2190 
2191 static bool produceCompactUnwindFrame(MachineFunction &MF) {
2192   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2193   AttributeList Attrs = MF.getFunction().getAttributes();
2194   return Subtarget.isTargetMachO() &&
2195          !(Subtarget.getTargetLowering()->supportSwiftError() &&
2196            Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
2197          MF.getFunction().getCallingConv() != CallingConv::SwiftTail;
2198 }
2199 
2200 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
2201                                              bool NeedsWinCFI, bool IsFirst) {
2202   // If we are generating register pairs for a Windows function that requires
2203   // EH support, then pair consecutive registers only.  There are no unwind
2204   // opcodes for saves/restores of non-consectuve register pairs.
2205   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
2206   // save_lrpair.
2207   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2208 
2209   if (Reg2 == AArch64::FP)
2210     return true;
2211   if (!NeedsWinCFI)
2212     return false;
2213   if (Reg2 == Reg1 + 1)
2214     return false;
2215   // If pairing a GPR with LR, the pair can be described by the save_lrpair
2216   // opcode. If this is the first register pair, it would end up with a
2217   // predecrement, but there's no save_lrpair_x opcode, so we can only do this
2218   // if LR is paired with something else than the first register.
2219   // The save_lrpair opcode requires the first register to be an odd one.
2220   if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
2221       (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)
2222     return false;
2223   return true;
2224 }
2225 
2226 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2227 /// WindowsCFI requires that only consecutive registers can be paired.
2228 /// LR and FP need to be allocated together when the frame needs to save
2229 /// the frame-record. This means any other register pairing with LR is invalid.
2230 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
2231                                       bool UsesWinAAPCS, bool NeedsWinCFI,
2232                                       bool NeedsFrameRecord, bool IsFirst) {
2233   if (UsesWinAAPCS)
2234     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst);
2235 
2236   // If we need to store the frame record, don't pair any register
2237   // with LR other than FP.
2238   if (NeedsFrameRecord)
2239     return Reg2 == AArch64::LR;
2240 
2241   return false;
2242 }
2243 
2244 namespace {
2245 
2246 struct RegPairInfo {
2247   unsigned Reg1 = AArch64::NoRegister;
2248   unsigned Reg2 = AArch64::NoRegister;
2249   int FrameIdx;
2250   int Offset;
2251   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
2252 
2253   RegPairInfo() = default;
2254 
2255   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
2256 
2257   unsigned getScale() const {
2258     switch (Type) {
2259     case PPR:
2260       return 2;
2261     case GPR:
2262     case FPR64:
2263       return 8;
2264     case ZPR:
2265     case FPR128:
2266       return 16;
2267     }
2268     llvm_unreachable("Unsupported type");
2269   }
2270 
2271   bool isScalable() const { return Type == PPR || Type == ZPR; }
2272 };
2273 
2274 } // end anonymous namespace
2275 
2276 static void computeCalleeSaveRegisterPairs(
2277     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
2278     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
2279     bool NeedsFrameRecord) {
2280 
2281   if (CSI.empty())
2282     return;
2283 
2284   bool IsWindows = isTargetWindows(MF);
2285   bool NeedsWinCFI = needsWinCFI(MF);
2286   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2287   MachineFrameInfo &MFI = MF.getFrameInfo();
2288   CallingConv::ID CC = MF.getFunction().getCallingConv();
2289   unsigned Count = CSI.size();
2290   (void)CC;
2291   // MachO's compact unwind format relies on all registers being stored in
2292   // pairs.
2293   assert((!produceCompactUnwindFrame(MF) ||
2294           CC == CallingConv::PreserveMost || CC == CallingConv::CXX_FAST_TLS ||
2295           (Count & 1) == 0) &&
2296          "Odd number of callee-saved regs to spill!");
2297   int ByteOffset = AFI->getCalleeSavedStackSize();
2298   int StackFillDir = -1;
2299   int RegInc = 1;
2300   unsigned FirstReg = 0;
2301   if (NeedsWinCFI) {
2302     // For WinCFI, fill the stack from the bottom up.
2303     ByteOffset = 0;
2304     StackFillDir = 1;
2305     // As the CSI array is reversed to match PrologEpilogInserter, iterate
2306     // backwards, to pair up registers starting from lower numbered registers.
2307     RegInc = -1;
2308     FirstReg = Count - 1;
2309   }
2310   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2311   bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
2312 
2313   // When iterating backwards, the loop condition relies on unsigned wraparound.
2314   for (unsigned i = FirstReg; i < Count; i += RegInc) {
2315     RegPairInfo RPI;
2316     RPI.Reg1 = CSI[i].getReg();
2317 
2318     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2319       RPI.Type = RegPairInfo::GPR;
2320     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2321       RPI.Type = RegPairInfo::FPR64;
2322     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2323       RPI.Type = RegPairInfo::FPR128;
2324     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2325       RPI.Type = RegPairInfo::ZPR;
2326     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2327       RPI.Type = RegPairInfo::PPR;
2328     else
2329       llvm_unreachable("Unsupported register class.");
2330 
2331     // Add the next reg to the pair if it is in the same register class.
2332     if (unsigned(i + RegInc) < Count) {
2333       Register NextReg = CSI[i + RegInc].getReg();
2334       bool IsFirst = i == FirstReg;
2335       switch (RPI.Type) {
2336       case RegPairInfo::GPR:
2337         if (AArch64::GPR64RegClass.contains(NextReg) &&
2338             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,
2339                                        NeedsWinCFI, NeedsFrameRecord, IsFirst))
2340           RPI.Reg2 = NextReg;
2341         break;
2342       case RegPairInfo::FPR64:
2343         if (AArch64::FPR64RegClass.contains(NextReg) &&
2344             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
2345                                               IsFirst))
2346           RPI.Reg2 = NextReg;
2347         break;
2348       case RegPairInfo::FPR128:
2349         if (AArch64::FPR128RegClass.contains(NextReg))
2350           RPI.Reg2 = NextReg;
2351         break;
2352       case RegPairInfo::PPR:
2353       case RegPairInfo::ZPR:
2354         break;
2355       }
2356     }
2357 
2358     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2359     // list to come in sorted by frame index so that we can issue the store
2360     // pair instructions directly. Assert if we see anything otherwise.
2361     //
2362     // The order of the registers in the list is controlled by
2363     // getCalleeSavedRegs(), so they will always be in-order, as well.
2364     assert((!RPI.isPaired() ||
2365             (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&
2366            "Out of order callee saved regs!");
2367 
2368     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2369             RPI.Reg1 == AArch64::LR) &&
2370            "FrameRecord must be allocated together with LR");
2371 
2372     // Windows AAPCS has FP and LR reversed.
2373     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
2374             RPI.Reg2 == AArch64::LR) &&
2375            "FrameRecord must be allocated together with LR");
2376 
2377     // MachO's compact unwind format relies on all registers being stored in
2378     // adjacent register pairs.
2379     assert((!produceCompactUnwindFrame(MF) ||
2380             CC == CallingConv::PreserveMost || CC == CallingConv::CXX_FAST_TLS ||
2381             (RPI.isPaired() &&
2382              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2383               RPI.Reg1 + 1 == RPI.Reg2))) &&
2384            "Callee-save registers not saved as adjacent register pair!");
2385 
2386     RPI.FrameIdx = CSI[i].getFrameIdx();
2387     if (NeedsWinCFI &&
2388         RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair
2389       RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();
2390 
2391     int Scale = RPI.getScale();
2392 
2393     int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2394     assert(OffsetPre % Scale == 0);
2395 
2396     if (RPI.isScalable())
2397       ScalableByteOffset += StackFillDir * Scale;
2398     else
2399       ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
2400 
2401     // Swift's async context is directly before FP, so allocate an extra
2402     // 8 bytes for it.
2403     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2404         RPI.Reg2 == AArch64::FP)
2405       ByteOffset += StackFillDir * 8;
2406 
2407     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2408            "Paired spill/fill instructions don't exist for SVE vectors");
2409 
2410     // Round up size of non-pair to pair size if we need to pad the
2411     // callee-save area to ensure 16-byte alignment.
2412     if (NeedGapToAlignStack && !NeedsWinCFI &&
2413         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2414         !RPI.isPaired() && ByteOffset % 16 != 0) {
2415       ByteOffset += 8 * StackFillDir;
2416       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
2417       // A stack frame with a gap looks like this, bottom up:
2418       // d9, d8. x21, gap, x20, x19.
2419       // Set extra alignment on the x21 object to create the gap above it.
2420       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
2421       NeedGapToAlignStack = false;
2422     }
2423 
2424     int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2425     assert(OffsetPost % Scale == 0);
2426     // If filling top down (default), we want the offset after incrementing it.
2427     // If fillibg bootom up (WinCFI) we need the original offset.
2428     int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;
2429 
2430     // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
2431     // Swift context can directly precede FP.
2432     if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2433         RPI.Reg2 == AArch64::FP)
2434       Offset += 8;
2435     RPI.Offset = Offset / Scale;
2436 
2437     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2438             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2439            "Offset out of bounds for LDP/STP immediate");
2440 
2441     // Save the offset to frame record so that the FP register can point to the
2442     // innermost frame record (spilled FP and LR registers).
2443     if (NeedsFrameRecord && ((!IsWindows && RPI.Reg1 == AArch64::LR &&
2444                               RPI.Reg2 == AArch64::FP) ||
2445                              (IsWindows && RPI.Reg1 == AArch64::FP &&
2446                               RPI.Reg2 == AArch64::LR)))
2447       AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
2448 
2449     RegPairs.push_back(RPI);
2450     if (RPI.isPaired())
2451       i += RegInc;
2452   }
2453   if (NeedsWinCFI) {
2454     // If we need an alignment gap in the stack, align the topmost stack
2455     // object. A stack frame with a gap looks like this, bottom up:
2456     // x19, d8. d9, gap.
2457     // Set extra alignment on the topmost stack object (the first element in
2458     // CSI, which goes top down), to create the gap above it.
2459     if (AFI->hasCalleeSaveStackFreeSpace())
2460       MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
2461     // We iterated bottom up over the registers; flip RegPairs back to top
2462     // down order.
2463     std::reverse(RegPairs.begin(), RegPairs.end());
2464   }
2465 }
2466 
2467 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2468     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2469     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2470   MachineFunction &MF = *MBB.getParent();
2471   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2472   bool NeedsWinCFI = needsWinCFI(MF);
2473   DebugLoc DL;
2474   SmallVector<RegPairInfo, 8> RegPairs;
2475 
2476   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2477 
2478   const MachineRegisterInfo &MRI = MF.getRegInfo();
2479   if (homogeneousPrologEpilog(MF)) {
2480     auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
2481                    .setMIFlag(MachineInstr::FrameSetup);
2482 
2483     for (auto &RPI : RegPairs) {
2484       MIB.addReg(RPI.Reg1);
2485       MIB.addReg(RPI.Reg2);
2486 
2487       // Update register live in.
2488       if (!MRI.isReserved(RPI.Reg1))
2489         MBB.addLiveIn(RPI.Reg1);
2490       if (!MRI.isReserved(RPI.Reg2))
2491         MBB.addLiveIn(RPI.Reg2);
2492     }
2493     return true;
2494   }
2495   for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {
2496     unsigned Reg1 = RPI.Reg1;
2497     unsigned Reg2 = RPI.Reg2;
2498     unsigned StrOpc;
2499 
2500     // Issue sequence of spills for cs regs.  The first spill may be converted
2501     // to a pre-decrement store later by emitPrologue if the callee-save stack
2502     // area allocation can't be combined with the local stack area allocation.
2503     // For example:
2504     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2505     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2506     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2507     // Rationale: This sequence saves uop updates compared to a sequence of
2508     // pre-increment spills like stp xi,xj,[sp,#-16]!
2509     // Note: Similar rationale and sequence for restores in epilog.
2510     unsigned Size;
2511     Align Alignment;
2512     switch (RPI.Type) {
2513     case RegPairInfo::GPR:
2514        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2515        Size = 8;
2516        Alignment = Align(8);
2517        break;
2518     case RegPairInfo::FPR64:
2519        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2520        Size = 8;
2521        Alignment = Align(8);
2522        break;
2523     case RegPairInfo::FPR128:
2524        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2525        Size = 16;
2526        Alignment = Align(16);
2527        break;
2528     case RegPairInfo::ZPR:
2529        StrOpc = AArch64::STR_ZXI;
2530        Size = 16;
2531        Alignment = Align(16);
2532        break;
2533     case RegPairInfo::PPR:
2534        StrOpc = AArch64::STR_PXI;
2535        Size = 2;
2536        Alignment = Align(2);
2537        break;
2538     }
2539     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2540                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2541                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2542                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2543                dbgs() << ")\n");
2544 
2545     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2546            "Windows unwdinding requires a consecutive (FP,LR) pair");
2547     // Windows unwind codes require consecutive registers if registers are
2548     // paired.  Make the switch here, so that the code below will save (x,x+1)
2549     // and not (x+1,x).
2550     unsigned FrameIdxReg1 = RPI.FrameIdx;
2551     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2552     if (NeedsWinCFI && RPI.isPaired()) {
2553       std::swap(Reg1, Reg2);
2554       std::swap(FrameIdxReg1, FrameIdxReg2);
2555     }
2556     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2557     if (!MRI.isReserved(Reg1))
2558       MBB.addLiveIn(Reg1);
2559     if (RPI.isPaired()) {
2560       if (!MRI.isReserved(Reg2))
2561         MBB.addLiveIn(Reg2);
2562       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2563       MIB.addMemOperand(MF.getMachineMemOperand(
2564           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2565           MachineMemOperand::MOStore, Size, Alignment));
2566     }
2567     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2568         .addReg(AArch64::SP)
2569         .addImm(RPI.Offset) // [sp, #offset*scale],
2570                             // where factor*scale is implicit
2571         .setMIFlag(MachineInstr::FrameSetup);
2572     MIB.addMemOperand(MF.getMachineMemOperand(
2573         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2574         MachineMemOperand::MOStore, Size, Alignment));
2575     if (NeedsWinCFI)
2576       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2577 
2578     // Update the StackIDs of the SVE stack slots.
2579     MachineFrameInfo &MFI = MF.getFrameInfo();
2580     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2581       MFI.setStackID(RPI.FrameIdx, TargetStackID::ScalableVector);
2582 
2583   }
2584   return true;
2585 }
2586 
2587 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2588     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
2589     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2590   MachineFunction &MF = *MBB.getParent();
2591   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2592   DebugLoc DL;
2593   SmallVector<RegPairInfo, 8> RegPairs;
2594   bool NeedsWinCFI = needsWinCFI(MF);
2595 
2596   if (MBBI != MBB.end())
2597     DL = MBBI->getDebugLoc();
2598 
2599   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
2600 
2601   auto EmitMI = [&](const RegPairInfo &RPI) -> MachineBasicBlock::iterator {
2602     unsigned Reg1 = RPI.Reg1;
2603     unsigned Reg2 = RPI.Reg2;
2604 
2605     // Issue sequence of restores for cs regs. The last restore may be converted
2606     // to a post-increment load later by emitEpilogue if the callee-save stack
2607     // area allocation can't be combined with the local stack area allocation.
2608     // For example:
2609     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2610     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2611     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2612     // Note: see comment in spillCalleeSavedRegisters()
2613     unsigned LdrOpc;
2614     unsigned Size;
2615     Align Alignment;
2616     switch (RPI.Type) {
2617     case RegPairInfo::GPR:
2618        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2619        Size = 8;
2620        Alignment = Align(8);
2621        break;
2622     case RegPairInfo::FPR64:
2623        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2624        Size = 8;
2625        Alignment = Align(8);
2626        break;
2627     case RegPairInfo::FPR128:
2628        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2629        Size = 16;
2630        Alignment = Align(16);
2631        break;
2632     case RegPairInfo::ZPR:
2633        LdrOpc = AArch64::LDR_ZXI;
2634        Size = 16;
2635        Alignment = Align(16);
2636        break;
2637     case RegPairInfo::PPR:
2638        LdrOpc = AArch64::LDR_PXI;
2639        Size = 2;
2640        Alignment = Align(2);
2641        break;
2642     }
2643     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2644                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2645                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2646                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2647                dbgs() << ")\n");
2648 
2649     // Windows unwind codes require consecutive registers if registers are
2650     // paired.  Make the switch here, so that the code below will save (x,x+1)
2651     // and not (x+1,x).
2652     unsigned FrameIdxReg1 = RPI.FrameIdx;
2653     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2654     if (NeedsWinCFI && RPI.isPaired()) {
2655       std::swap(Reg1, Reg2);
2656       std::swap(FrameIdxReg1, FrameIdxReg2);
2657     }
2658     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
2659     if (RPI.isPaired()) {
2660       MIB.addReg(Reg2, getDefRegState(true));
2661       MIB.addMemOperand(MF.getMachineMemOperand(
2662           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2663           MachineMemOperand::MOLoad, Size, Alignment));
2664     }
2665     MIB.addReg(Reg1, getDefRegState(true))
2666         .addReg(AArch64::SP)
2667         .addImm(RPI.Offset) // [sp, #offset*scale]
2668                             // where factor*scale is implicit
2669         .setMIFlag(MachineInstr::FrameDestroy);
2670     MIB.addMemOperand(MF.getMachineMemOperand(
2671         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2672         MachineMemOperand::MOLoad, Size, Alignment));
2673     if (NeedsWinCFI)
2674       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2675     return MIB->getIterator();
2676   };
2677 
2678   // SVE objects are always restored in reverse order.
2679   for (const RegPairInfo &RPI : reverse(RegPairs))
2680     if (RPI.isScalable())
2681       EmitMI(RPI);
2682 
2683   if (homogeneousPrologEpilog(MF, &MBB)) {
2684     auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
2685                    .setMIFlag(MachineInstr::FrameDestroy);
2686     for (auto &RPI : RegPairs) {
2687       MIB.addReg(RPI.Reg1, RegState::Define);
2688       MIB.addReg(RPI.Reg2, RegState::Define);
2689     }
2690     return true;
2691   }
2692 
2693   if (ReverseCSRRestoreSeq) {
2694     MachineBasicBlock::iterator First = MBB.end();
2695     for (const RegPairInfo &RPI : reverse(RegPairs)) {
2696       if (RPI.isScalable())
2697         continue;
2698       MachineBasicBlock::iterator It = EmitMI(RPI);
2699       if (First == MBB.end())
2700         First = It;
2701     }
2702     if (First != MBB.end())
2703       MBB.splice(MBBI, &MBB, First);
2704   } else {
2705     for (const RegPairInfo &RPI : RegPairs) {
2706       if (RPI.isScalable())
2707         continue;
2708       (void)EmitMI(RPI);
2709     }
2710   }
2711 
2712   return true;
2713 }
2714 
2715 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2716                                                 BitVector &SavedRegs,
2717                                                 RegScavenger *RS) const {
2718   // All calls are tail calls in GHC calling conv, and functions have no
2719   // prologue/epilogue.
2720   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2721     return;
2722 
2723   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2724   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2725       MF.getSubtarget().getRegisterInfo());
2726   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2727   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2728   unsigned UnspilledCSGPR = AArch64::NoRegister;
2729   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2730 
2731   MachineFrameInfo &MFI = MF.getFrameInfo();
2732   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2733 
2734   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2735                                 ? RegInfo->getBaseRegister()
2736                                 : (unsigned)AArch64::NoRegister;
2737 
2738   unsigned ExtraCSSpill = 0;
2739   // Figure out which callee-saved registers to save/restore.
2740   for (unsigned i = 0; CSRegs[i]; ++i) {
2741     const unsigned Reg = CSRegs[i];
2742 
2743     // Add the base pointer register to SavedRegs if it is callee-save.
2744     if (Reg == BasePointerReg)
2745       SavedRegs.set(Reg);
2746 
2747     bool RegUsed = SavedRegs.test(Reg);
2748     unsigned PairedReg = AArch64::NoRegister;
2749     if (AArch64::GPR64RegClass.contains(Reg) ||
2750         AArch64::FPR64RegClass.contains(Reg) ||
2751         AArch64::FPR128RegClass.contains(Reg))
2752       PairedReg = CSRegs[i ^ 1];
2753 
2754     if (!RegUsed) {
2755       if (AArch64::GPR64RegClass.contains(Reg) &&
2756           !RegInfo->isReservedReg(MF, Reg)) {
2757         UnspilledCSGPR = Reg;
2758         UnspilledCSGPRPaired = PairedReg;
2759       }
2760       continue;
2761     }
2762 
2763     // MachO's compact unwind format relies on all registers being stored in
2764     // pairs.
2765     // FIXME: the usual format is actually better if unwinding isn't needed.
2766     if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&
2767         !SavedRegs.test(PairedReg)) {
2768       SavedRegs.set(PairedReg);
2769       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2770           !RegInfo->isReservedReg(MF, PairedReg))
2771         ExtraCSSpill = PairedReg;
2772     }
2773   }
2774 
2775   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
2776       !Subtarget.isTargetWindows()) {
2777     // For Windows calling convention on a non-windows OS, where X18 is treated
2778     // as reserved, back up X18 when entering non-windows code (marked with the
2779     // Windows calling convention) and restore when returning regardless of
2780     // whether the individual function uses it - it might call other functions
2781     // that clobber it.
2782     SavedRegs.set(AArch64::X18);
2783   }
2784 
2785   // Calculates the callee saved stack size.
2786   unsigned CSStackSize = 0;
2787   unsigned SVECSStackSize = 0;
2788   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2789   const MachineRegisterInfo &MRI = MF.getRegInfo();
2790   for (unsigned Reg : SavedRegs.set_bits()) {
2791     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
2792     if (AArch64::PPRRegClass.contains(Reg) ||
2793         AArch64::ZPRRegClass.contains(Reg))
2794       SVECSStackSize += RegSize;
2795     else
2796       CSStackSize += RegSize;
2797   }
2798 
2799   // Save number of saved regs, so we can easily update CSStackSize later.
2800   unsigned NumSavedRegs = SavedRegs.count();
2801 
2802   // The frame record needs to be created by saving the appropriate registers
2803   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
2804   if (hasFP(MF) ||
2805       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2806     SavedRegs.set(AArch64::FP);
2807     SavedRegs.set(AArch64::LR);
2808   }
2809 
2810   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2811              for (unsigned Reg
2812                   : SavedRegs.set_bits()) dbgs()
2813              << ' ' << printReg(Reg, RegInfo);
2814              dbgs() << "\n";);
2815 
2816   // If any callee-saved registers are used, the frame cannot be eliminated.
2817   int64_t SVEStackSize =
2818       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
2819   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2820 
2821   // The CSR spill slots have not been allocated yet, so estimateStackSize
2822   // won't include them.
2823   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2824 
2825   // Conservatively always assume BigStack when there are SVE spills.
2826   bool BigStack = SVEStackSize ||
2827                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2828   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2829     AFI->setHasStackFrame(true);
2830 
2831   // Estimate if we might need to scavenge a register at some point in order
2832   // to materialize a stack offset. If so, either spill one additional
2833   // callee-saved register or reserve a special spill slot to facilitate
2834   // register scavenging. If we already spilled an extra callee-saved register
2835   // above to keep the number of spills even, we don't need to do anything else
2836   // here.
2837   if (BigStack) {
2838     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2839       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2840                         << " to get a scratch register.\n");
2841       SavedRegs.set(UnspilledCSGPR);
2842       // MachO's compact unwind format relies on all registers being stored in
2843       // pairs, so if we need to spill one extra for BigStack, then we need to
2844       // store the pair.
2845       if (producePairRegisters(MF))
2846         SavedRegs.set(UnspilledCSGPRPaired);
2847       ExtraCSSpill = UnspilledCSGPR;
2848     }
2849 
2850     // If we didn't find an extra callee-saved register to spill, create
2851     // an emergency spill slot.
2852     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2853       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2854       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2855       unsigned Size = TRI->getSpillSize(RC);
2856       Align Alignment = TRI->getSpillAlign(RC);
2857       int FI = MFI.CreateStackObject(Size, Alignment, false);
2858       RS->addScavengingFrameIndex(FI);
2859       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2860                         << " as the emergency spill slot.\n");
2861     }
2862   }
2863 
2864   // Adding the size of additional 64bit GPR saves.
2865   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2866 
2867   // A Swift asynchronous context extends the frame record with a pointer
2868   // directly before FP.
2869   if (hasFP(MF) && AFI->hasSwiftAsyncContext())
2870     CSStackSize += 8;
2871 
2872   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
2873   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2874                << EstimatedStackSize + AlignedCSStackSize
2875                << " bytes.\n");
2876 
2877   assert((!MFI.isCalleeSavedInfoValid() ||
2878           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2879          "Should not invalidate callee saved info");
2880 
2881   // Round up to register pair alignment to avoid additional SP adjustment
2882   // instructions.
2883   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2884   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2885   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
2886 }
2887 
2888 bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
2889     MachineFunction &MF, const TargetRegisterInfo *RegInfo,
2890     std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,
2891     unsigned &MaxCSFrameIndex) const {
2892   bool NeedsWinCFI = needsWinCFI(MF);
2893   // To match the canonical windows frame layout, reverse the list of
2894   // callee saved registers to get them laid out by PrologEpilogInserter
2895   // in the right order. (PrologEpilogInserter allocates stack objects top
2896   // down. Windows canonical prologs store higher numbered registers at
2897   // the top, thus have the CSI array start from the highest registers.)
2898   if (NeedsWinCFI)
2899     std::reverse(CSI.begin(), CSI.end());
2900 
2901   if (CSI.empty())
2902     return true; // Early exit if no callee saved registers are modified!
2903 
2904   // Now that we know which registers need to be saved and restored, allocate
2905   // stack slots for them.
2906   MachineFrameInfo &MFI = MF.getFrameInfo();
2907   auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2908   for (auto &CS : CSI) {
2909     Register Reg = CS.getReg();
2910     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
2911 
2912     unsigned Size = RegInfo->getSpillSize(*RC);
2913     Align Alignment(RegInfo->getSpillAlign(*RC));
2914     int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
2915     CS.setFrameIdx(FrameIdx);
2916 
2917     if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
2918     if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
2919 
2920     // Grab 8 bytes below FP for the extended asynchronous frame info.
2921     if (hasFP(MF) && AFI->hasSwiftAsyncContext() && Reg == AArch64::FP) {
2922       FrameIdx = MFI.CreateStackObject(8, Alignment, true);
2923       AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
2924       if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
2925       if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
2926     }
2927   }
2928   return true;
2929 }
2930 
2931 bool AArch64FrameLowering::enableStackSlotScavenging(
2932     const MachineFunction &MF) const {
2933   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2934   return AFI->hasCalleeSaveStackFreeSpace();
2935 }
2936 
2937 /// returns true if there are any SVE callee saves.
2938 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
2939                                       int &Min, int &Max) {
2940   Min = std::numeric_limits<int>::max();
2941   Max = std::numeric_limits<int>::min();
2942 
2943   if (!MFI.isCalleeSavedInfoValid())
2944     return false;
2945 
2946   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2947   for (auto &CS : CSI) {
2948     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
2949         AArch64::PPRRegClass.contains(CS.getReg())) {
2950       assert((Max == std::numeric_limits<int>::min() ||
2951               Max + 1 == CS.getFrameIdx()) &&
2952              "SVE CalleeSaves are not consecutive");
2953 
2954       Min = std::min(Min, CS.getFrameIdx());
2955       Max = std::max(Max, CS.getFrameIdx());
2956     }
2957   }
2958   return Min != std::numeric_limits<int>::max();
2959 }
2960 
2961 // Process all the SVE stack objects and determine offsets for each
2962 // object. If AssignOffsets is true, the offsets get assigned.
2963 // Fills in the first and last callee-saved frame indices into
2964 // Min/MaxCSFrameIndex, respectively.
2965 // Returns the size of the stack.
2966 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
2967                                               int &MinCSFrameIndex,
2968                                               int &MaxCSFrameIndex,
2969                                               bool AssignOffsets) {
2970 #ifndef NDEBUG
2971   // First process all fixed stack objects.
2972   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
2973     assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&
2974            "SVE vectors should never be passed on the stack by value, only by "
2975            "reference.");
2976 #endif
2977 
2978   auto Assign = [&MFI](int FI, int64_t Offset) {
2979     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
2980     MFI.setObjectOffset(FI, Offset);
2981   };
2982 
2983   int64_t Offset = 0;
2984 
2985   // Then process all callee saved slots.
2986   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
2987     // Assign offsets to the callee save slots.
2988     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
2989       Offset += MFI.getObjectSize(I);
2990       Offset = alignTo(Offset, MFI.getObjectAlign(I));
2991       if (AssignOffsets)
2992         Assign(I, -Offset);
2993     }
2994   }
2995 
2996   // Ensure that the Callee-save area is aligned to 16bytes.
2997   Offset = alignTo(Offset, Align(16U));
2998 
2999   // Create a buffer of SVE objects to allocate and sort it.
3000   SmallVector<int, 8> ObjectsToAllocate;
3001   // If we have a stack protector, and we've previously decided that we have SVE
3002   // objects on the stack and thus need it to go in the SVE stack area, then it
3003   // needs to go first.
3004   int StackProtectorFI = -1;
3005   if (MFI.hasStackProtectorIndex()) {
3006     StackProtectorFI = MFI.getStackProtectorIndex();
3007     if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
3008       ObjectsToAllocate.push_back(StackProtectorFI);
3009   }
3010   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
3011     unsigned StackID = MFI.getStackID(I);
3012     if (StackID != TargetStackID::ScalableVector)
3013       continue;
3014     if (I == StackProtectorFI)
3015       continue;
3016     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
3017       continue;
3018     if (MFI.isDeadObjectIndex(I))
3019       continue;
3020 
3021     ObjectsToAllocate.push_back(I);
3022   }
3023 
3024   // Allocate all SVE locals and spills
3025   for (unsigned FI : ObjectsToAllocate) {
3026     Align Alignment = MFI.getObjectAlign(FI);
3027     // FIXME: Given that the length of SVE vectors is not necessarily a power of
3028     // two, we'd need to align every object dynamically at runtime if the
3029     // alignment is larger than 16. This is not yet supported.
3030     if (Alignment > Align(16))
3031       report_fatal_error(
3032           "Alignment of scalable vectors > 16 bytes is not yet supported");
3033 
3034     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
3035     if (AssignOffsets)
3036       Assign(FI, -Offset);
3037   }
3038 
3039   return Offset;
3040 }
3041 
3042 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
3043     MachineFrameInfo &MFI) const {
3044   int MinCSFrameIndex, MaxCSFrameIndex;
3045   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
3046 }
3047 
3048 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
3049     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
3050   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
3051                                         true);
3052 }
3053 
3054 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
3055     MachineFunction &MF, RegScavenger *RS) const {
3056   MachineFrameInfo &MFI = MF.getFrameInfo();
3057 
3058   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
3059          "Upwards growing stack unsupported");
3060 
3061   int MinCSFrameIndex, MaxCSFrameIndex;
3062   int64_t SVEStackSize =
3063       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
3064 
3065   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
3066   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
3067   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
3068 
3069   // If this function isn't doing Win64-style C++ EH, we don't need to do
3070   // anything.
3071   if (!MF.hasEHFunclets())
3072     return;
3073   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
3074   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3075 
3076   MachineBasicBlock &MBB = MF.front();
3077   auto MBBI = MBB.begin();
3078   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3079     ++MBBI;
3080 
3081   // Create an UnwindHelp object.
3082   // The UnwindHelp object is allocated at the start of the fixed object area
3083   int64_t FixedObject =
3084       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
3085   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
3086                                            /*SPOffset*/ -FixedObject,
3087                                            /*IsImmutable=*/false);
3088   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3089 
3090   // We need to store -2 into the UnwindHelp object at the start of the
3091   // function.
3092   DebugLoc DL;
3093   RS->enterBasicBlockEnd(MBB);
3094   RS->backward(std::prev(MBBI));
3095   Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
3096   assert(DstReg && "There must be a free register after frame setup");
3097   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
3098   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
3099       .addReg(DstReg, getKillRegState(true))
3100       .addFrameIndex(UnwindHelpFI)
3101       .addImm(0);
3102 }
3103 
3104 namespace {
3105 struct TagStoreInstr {
3106   MachineInstr *MI;
3107   int64_t Offset, Size;
3108   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
3109       : MI(MI), Offset(Offset), Size(Size) {}
3110 };
3111 
3112 class TagStoreEdit {
3113   MachineFunction *MF;
3114   MachineBasicBlock *MBB;
3115   MachineRegisterInfo *MRI;
3116   // Tag store instructions that are being replaced.
3117   SmallVector<TagStoreInstr, 8> TagStores;
3118   // Combined memref arguments of the above instructions.
3119   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
3120 
3121   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
3122   // FrameRegOffset + Size) with the address tag of SP.
3123   Register FrameReg;
3124   StackOffset FrameRegOffset;
3125   int64_t Size;
3126   // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
3127   Optional<int64_t> FrameRegUpdate;
3128   // MIFlags for any FrameReg updating instructions.
3129   unsigned FrameRegUpdateFlags;
3130 
3131   // Use zeroing instruction variants.
3132   bool ZeroData;
3133   DebugLoc DL;
3134 
3135   void emitUnrolled(MachineBasicBlock::iterator InsertI);
3136   void emitLoop(MachineBasicBlock::iterator InsertI);
3137 
3138 public:
3139   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
3140       : MBB(MBB), ZeroData(ZeroData) {
3141     MF = MBB->getParent();
3142     MRI = &MF->getRegInfo();
3143   }
3144   // Add an instruction to be replaced. Instructions must be added in the
3145   // ascending order of Offset, and have to be adjacent.
3146   void addInstruction(TagStoreInstr I) {
3147     assert((TagStores.empty() ||
3148             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
3149            "Non-adjacent tag store instructions.");
3150     TagStores.push_back(I);
3151   }
3152   void clear() { TagStores.clear(); }
3153   // Emit equivalent code at the given location, and erase the current set of
3154   // instructions. May skip if the replacement is not profitable. May invalidate
3155   // the input iterator and replace it with a valid one.
3156   void emitCode(MachineBasicBlock::iterator &InsertI,
3157                 const AArch64FrameLowering *TFI, bool IsLast);
3158 };
3159 
3160 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
3161   const AArch64InstrInfo *TII =
3162       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3163 
3164   const int64_t kMinOffset = -256 * 16;
3165   const int64_t kMaxOffset = 255 * 16;
3166 
3167   Register BaseReg = FrameReg;
3168   int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
3169   if (BaseRegOffsetBytes < kMinOffset ||
3170       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
3171     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3172     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
3173                     StackOffset::getFixed(BaseRegOffsetBytes), TII);
3174     BaseReg = ScratchReg;
3175     BaseRegOffsetBytes = 0;
3176   }
3177 
3178   MachineInstr *LastI = nullptr;
3179   while (Size) {
3180     int64_t InstrSize = (Size > 16) ? 32 : 16;
3181     unsigned Opcode =
3182         InstrSize == 16
3183             ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
3184             : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
3185     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
3186                           .addReg(AArch64::SP)
3187                           .addReg(BaseReg)
3188                           .addImm(BaseRegOffsetBytes / 16)
3189                           .setMemRefs(CombinedMemRefs);
3190     // A store to [BaseReg, #0] should go last for an opportunity to fold the
3191     // final SP adjustment in the epilogue.
3192     if (BaseRegOffsetBytes == 0)
3193       LastI = I;
3194     BaseRegOffsetBytes += InstrSize;
3195     Size -= InstrSize;
3196   }
3197 
3198   if (LastI)
3199     MBB->splice(InsertI, MBB, LastI);
3200 }
3201 
3202 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
3203   const AArch64InstrInfo *TII =
3204       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3205 
3206   Register BaseReg = FrameRegUpdate
3207                          ? FrameReg
3208                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3209   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3210 
3211   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
3212 
3213   int64_t LoopSize = Size;
3214   // If the loop size is not a multiple of 32, split off one 16-byte store at
3215   // the end to fold BaseReg update into.
3216   if (FrameRegUpdate && *FrameRegUpdate)
3217     LoopSize -= LoopSize % 32;
3218   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
3219                                 TII->get(ZeroData ? AArch64::STZGloop_wback
3220                                                   : AArch64::STGloop_wback))
3221                             .addDef(SizeReg)
3222                             .addDef(BaseReg)
3223                             .addImm(LoopSize)
3224                             .addReg(BaseReg)
3225                             .setMemRefs(CombinedMemRefs);
3226   if (FrameRegUpdate)
3227     LoopI->setFlags(FrameRegUpdateFlags);
3228 
3229   int64_t ExtraBaseRegUpdate =
3230       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
3231   if (LoopSize < Size) {
3232     assert(FrameRegUpdate);
3233     assert(Size - LoopSize == 16);
3234     // Tag 16 more bytes at BaseReg and update BaseReg.
3235     BuildMI(*MBB, InsertI, DL,
3236             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
3237         .addDef(BaseReg)
3238         .addReg(BaseReg)
3239         .addReg(BaseReg)
3240         .addImm(1 + ExtraBaseRegUpdate / 16)
3241         .setMemRefs(CombinedMemRefs)
3242         .setMIFlags(FrameRegUpdateFlags);
3243   } else if (ExtraBaseRegUpdate) {
3244     // Update BaseReg.
3245     BuildMI(
3246         *MBB, InsertI, DL,
3247         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
3248         .addDef(BaseReg)
3249         .addReg(BaseReg)
3250         .addImm(std::abs(ExtraBaseRegUpdate))
3251         .addImm(0)
3252         .setMIFlags(FrameRegUpdateFlags);
3253   }
3254 }
3255 
3256 // Check if *II is a register update that can be merged into STGloop that ends
3257 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
3258 // end of the loop.
3259 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
3260                        int64_t Size, int64_t *TotalOffset) {
3261   MachineInstr &MI = *II;
3262   if ((MI.getOpcode() == AArch64::ADDXri ||
3263        MI.getOpcode() == AArch64::SUBXri) &&
3264       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
3265     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
3266     int64_t Offset = MI.getOperand(2).getImm() << Shift;
3267     if (MI.getOpcode() == AArch64::SUBXri)
3268       Offset = -Offset;
3269     int64_t AbsPostOffset = std::abs(Offset - Size);
3270     const int64_t kMaxOffset =
3271         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
3272     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
3273       *TotalOffset = Offset;
3274       return true;
3275     }
3276   }
3277   return false;
3278 }
3279 
3280 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
3281                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
3282   MemRefs.clear();
3283   for (auto &TS : TSE) {
3284     MachineInstr *MI = TS.MI;
3285     // An instruction without memory operands may access anything. Be
3286     // conservative and return an empty list.
3287     if (MI->memoperands_empty()) {
3288       MemRefs.clear();
3289       return;
3290     }
3291     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
3292   }
3293 }
3294 
3295 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
3296                             const AArch64FrameLowering *TFI, bool IsLast) {
3297   if (TagStores.empty())
3298     return;
3299   TagStoreInstr &FirstTagStore = TagStores[0];
3300   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
3301   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
3302   DL = TagStores[0].MI->getDebugLoc();
3303 
3304   Register Reg;
3305   FrameRegOffset = TFI->resolveFrameOffsetReference(
3306       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
3307       /*PreferFP=*/false, /*ForSimm=*/true);
3308   FrameReg = Reg;
3309   FrameRegUpdate = None;
3310 
3311   mergeMemRefs(TagStores, CombinedMemRefs);
3312 
3313   LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
3314              for (const auto &Instr
3315                   : TagStores) { dbgs() << "  " << *Instr.MI; });
3316 
3317   // Size threshold where a loop becomes shorter than a linear sequence of
3318   // tagging instructions.
3319   const int kSetTagLoopThreshold = 176;
3320   if (Size < kSetTagLoopThreshold) {
3321     if (TagStores.size() < 2)
3322       return;
3323     emitUnrolled(InsertI);
3324   } else {
3325     MachineInstr *UpdateInstr = nullptr;
3326     int64_t TotalOffset;
3327     if (IsLast) {
3328       // See if we can merge base register update into the STGloop.
3329       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3330       // but STGloop is way too unusual for that, and also it only
3331       // realistically happens in function epilogue. Also, STGloop is expanded
3332       // before that pass.
3333       if (InsertI != MBB->end() &&
3334           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,
3335                             &TotalOffset)) {
3336         UpdateInstr = &*InsertI++;
3337         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
3338                           << *UpdateInstr);
3339       }
3340     }
3341 
3342     if (!UpdateInstr && TagStores.size() < 2)
3343       return;
3344 
3345     if (UpdateInstr) {
3346       FrameRegUpdate = TotalOffset;
3347       FrameRegUpdateFlags = UpdateInstr->getFlags();
3348     }
3349     emitLoop(InsertI);
3350     if (UpdateInstr)
3351       UpdateInstr->eraseFromParent();
3352   }
3353 
3354   for (auto &TS : TagStores)
3355     TS.MI->eraseFromParent();
3356 }
3357 
3358 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
3359                                         int64_t &Size, bool &ZeroData) {
3360   MachineFunction &MF = *MI.getParent()->getParent();
3361   const MachineFrameInfo &MFI = MF.getFrameInfo();
3362 
3363   unsigned Opcode = MI.getOpcode();
3364   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
3365               Opcode == AArch64::STZ2GOffset);
3366 
3367   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
3368     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
3369       return false;
3370     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
3371       return false;
3372     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
3373     Size = MI.getOperand(2).getImm();
3374     return true;
3375   }
3376 
3377   if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
3378     Size = 16;
3379   else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
3380     Size = 32;
3381   else
3382     return false;
3383 
3384   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3385     return false;
3386 
3387   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3388            16 * MI.getOperand(2).getImm();
3389   return true;
3390 }
3391 
3392 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3393 // and replace them with a shorter instruction sequence:
3394 // * replace STG + STG with ST2G
3395 // * replace STGloop + STGloop with STGloop
3396 // This code needs to run when stack slot offsets are already known, but before
3397 // FrameIndex operands in STG instructions are eliminated.
3398 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
3399                                                 const AArch64FrameLowering *TFI,
3400                                                 RegScavenger *RS) {
3401   bool FirstZeroData;
3402   int64_t Size, Offset;
3403   MachineInstr &MI = *II;
3404   MachineBasicBlock *MBB = MI.getParent();
3405   MachineBasicBlock::iterator NextI = ++II;
3406   if (&MI == &MBB->instr_back())
3407     return II;
3408   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3409     return II;
3410 
3411   SmallVector<TagStoreInstr, 4> Instrs;
3412   Instrs.emplace_back(&MI, Offset, Size);
3413 
3414   constexpr int kScanLimit = 10;
3415   int Count = 0;
3416   for (MachineBasicBlock::iterator E = MBB->end();
3417        NextI != E && Count < kScanLimit; ++NextI) {
3418     MachineInstr &MI = *NextI;
3419     bool ZeroData;
3420     int64_t Size, Offset;
3421     // Collect instructions that update memory tags with a FrameIndex operand
3422     // and (when applicable) constant size, and whose output registers are dead
3423     // (the latter is almost always the case in practice). Since these
3424     // instructions effectively have no inputs or outputs, we are free to skip
3425     // any non-aliasing instructions in between without tracking used registers.
3426     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3427       if (ZeroData != FirstZeroData)
3428         break;
3429       Instrs.emplace_back(&MI, Offset, Size);
3430       continue;
3431     }
3432 
3433     // Only count non-transient, non-tagging instructions toward the scan
3434     // limit.
3435     if (!MI.isTransient())
3436       ++Count;
3437 
3438     // Just in case, stop before the epilogue code starts.
3439     if (MI.getFlag(MachineInstr::FrameSetup) ||
3440         MI.getFlag(MachineInstr::FrameDestroy))
3441       break;
3442 
3443     // Reject anything that may alias the collected instructions.
3444     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
3445       break;
3446   }
3447 
3448   // New code will be inserted after the last tagging instruction we've found.
3449   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3450   InsertI++;
3451 
3452   llvm::stable_sort(Instrs,
3453                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3454                       return Left.Offset < Right.Offset;
3455                     });
3456 
3457   // Make sure that we don't have any overlapping stores.
3458   int64_t CurOffset = Instrs[0].Offset;
3459   for (auto &Instr : Instrs) {
3460     if (CurOffset > Instr.Offset)
3461       return NextI;
3462     CurOffset = Instr.Offset + Instr.Size;
3463   }
3464 
3465   // Find contiguous runs of tagged memory and emit shorter instruction
3466   // sequencies for them when possible.
3467   TagStoreEdit TSE(MBB, FirstZeroData);
3468   Optional<int64_t> EndOffset;
3469   for (auto &Instr : Instrs) {
3470     if (EndOffset && *EndOffset != Instr.Offset) {
3471       // Found a gap.
3472       TSE.emitCode(InsertI, TFI, /*IsLast = */ false);
3473       TSE.clear();
3474     }
3475 
3476     TSE.addInstruction(Instr);
3477     EndOffset = Instr.Offset + Instr.Size;
3478   }
3479 
3480   TSE.emitCode(InsertI, TFI, /*IsLast = */ true);
3481 
3482   return InsertI;
3483 }
3484 } // namespace
3485 
3486 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3487     MachineFunction &MF, RegScavenger *RS = nullptr) const {
3488   if (StackTaggingMergeSetTag)
3489     for (auto &BB : MF)
3490       for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
3491         II = tryMergeAdjacentSTG(II, this, RS);
3492 }
3493 
3494 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3495 /// before the update.  This is easily retrieved as it is exactly the offset
3496 /// that is set in processFunctionBeforeFrameFinalized.
3497 StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(
3498     const MachineFunction &MF, int FI, Register &FrameReg,
3499     bool IgnoreSPUpdates) const {
3500   const MachineFrameInfo &MFI = MF.getFrameInfo();
3501   if (IgnoreSPUpdates) {
3502     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3503                       << MFI.getObjectOffset(FI) << "\n");
3504     FrameReg = AArch64::SP;
3505     return StackOffset::getFixed(MFI.getObjectOffset(FI));
3506   }
3507 
3508   // Go to common code if we cannot provide sp + offset.
3509   if (MFI.hasVarSizedObjects() ||
3510       MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||
3511       MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))
3512     return getFrameIndexReference(MF, FI, FrameReg);
3513 
3514   FrameReg = AArch64::SP;
3515   return getStackOffset(MF, MFI.getObjectOffset(FI));
3516 }
3517 
3518 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3519 /// the parent's frame pointer
3520 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3521     const MachineFunction &MF) const {
3522   return 0;
3523 }
3524 
3525 /// Funclets only need to account for space for the callee saved registers,
3526 /// as the locals are accounted for in the parent's stack frame.
3527 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3528     const MachineFunction &MF) const {
3529   // This is the size of the pushed CSRs.
3530   unsigned CSSize =
3531       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3532   // This is the amount of stack a funclet needs to allocate.
3533   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3534                  getStackAlign());
3535 }
3536 
3537 namespace {
3538 struct FrameObject {
3539   bool IsValid = false;
3540   // Index of the object in MFI.
3541   int ObjectIndex = 0;
3542   // Group ID this object belongs to.
3543   int GroupIndex = -1;
3544   // This object should be placed first (closest to SP).
3545   bool ObjectFirst = false;
3546   // This object's group (which always contains the object with
3547   // ObjectFirst==true) should be placed first.
3548   bool GroupFirst = false;
3549 };
3550 
3551 class GroupBuilder {
3552   SmallVector<int, 8> CurrentMembers;
3553   int NextGroupIndex = 0;
3554   std::vector<FrameObject> &Objects;
3555 
3556 public:
3557   GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
3558   void AddMember(int Index) { CurrentMembers.push_back(Index); }
3559   void EndCurrentGroup() {
3560     if (CurrentMembers.size() > 1) {
3561       // Create a new group with the current member list. This might remove them
3562       // from their pre-existing groups. That's OK, dealing with overlapping
3563       // groups is too hard and unlikely to make a difference.
3564       LLVM_DEBUG(dbgs() << "group:");
3565       for (int Index : CurrentMembers) {
3566         Objects[Index].GroupIndex = NextGroupIndex;
3567         LLVM_DEBUG(dbgs() << " " << Index);
3568       }
3569       LLVM_DEBUG(dbgs() << "\n");
3570       NextGroupIndex++;
3571     }
3572     CurrentMembers.clear();
3573   }
3574 };
3575 
3576 bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
3577   // Objects at a lower index are closer to FP; objects at a higher index are
3578   // closer to SP.
3579   //
3580   // For consistency in our comparison, all invalid objects are placed
3581   // at the end. This also allows us to stop walking when we hit the
3582   // first invalid item after it's all sorted.
3583   //
3584   // The "first" object goes first (closest to SP), followed by the members of
3585   // the "first" group.
3586   //
3587   // The rest are sorted by the group index to keep the groups together.
3588   // Higher numbered groups are more likely to be around longer (i.e. untagged
3589   // in the function epilogue and not at some earlier point). Place them closer
3590   // to SP.
3591   //
3592   // If all else equal, sort by the object index to keep the objects in the
3593   // original order.
3594   return std::make_tuple(!A.IsValid, A.ObjectFirst, A.GroupFirst, A.GroupIndex,
3595                          A.ObjectIndex) <
3596          std::make_tuple(!B.IsValid, B.ObjectFirst, B.GroupFirst, B.GroupIndex,
3597                          B.ObjectIndex);
3598 }
3599 } // namespace
3600 
3601 void AArch64FrameLowering::orderFrameObjects(
3602     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3603   if (!OrderFrameObjects || ObjectsToAllocate.empty())
3604     return;
3605 
3606   const MachineFrameInfo &MFI = MF.getFrameInfo();
3607   std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
3608   for (auto &Obj : ObjectsToAllocate) {
3609     FrameObjects[Obj].IsValid = true;
3610     FrameObjects[Obj].ObjectIndex = Obj;
3611   }
3612 
3613   // Identify stack slots that are tagged at the same time.
3614   GroupBuilder GB(FrameObjects);
3615   for (auto &MBB : MF) {
3616     for (auto &MI : MBB) {
3617       if (MI.isDebugInstr())
3618         continue;
3619       int OpIndex;
3620       switch (MI.getOpcode()) {
3621       case AArch64::STGloop:
3622       case AArch64::STZGloop:
3623         OpIndex = 3;
3624         break;
3625       case AArch64::STGOffset:
3626       case AArch64::STZGOffset:
3627       case AArch64::ST2GOffset:
3628       case AArch64::STZ2GOffset:
3629         OpIndex = 1;
3630         break;
3631       default:
3632         OpIndex = -1;
3633       }
3634 
3635       int TaggedFI = -1;
3636       if (OpIndex >= 0) {
3637         const MachineOperand &MO = MI.getOperand(OpIndex);
3638         if (MO.isFI()) {
3639           int FI = MO.getIndex();
3640           if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
3641               FrameObjects[FI].IsValid)
3642             TaggedFI = FI;
3643         }
3644       }
3645 
3646       // If this is a stack tagging instruction for a slot that is not part of a
3647       // group yet, either start a new group or add it to the current one.
3648       if (TaggedFI >= 0)
3649         GB.AddMember(TaggedFI);
3650       else
3651         GB.EndCurrentGroup();
3652     }
3653     // Groups should never span multiple basic blocks.
3654     GB.EndCurrentGroup();
3655   }
3656 
3657   // If the function's tagged base pointer is pinned to a stack slot, we want to
3658   // put that slot first when possible. This will likely place it at SP + 0,
3659   // and save one instruction when generating the base pointer because IRG does
3660   // not allow an immediate offset.
3661   const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
3662   Optional<int> TBPI = AFI.getTaggedBasePointerIndex();
3663   if (TBPI) {
3664     FrameObjects[*TBPI].ObjectFirst = true;
3665     FrameObjects[*TBPI].GroupFirst = true;
3666     int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
3667     if (FirstGroupIndex >= 0)
3668       for (FrameObject &Object : FrameObjects)
3669         if (Object.GroupIndex == FirstGroupIndex)
3670           Object.GroupFirst = true;
3671   }
3672 
3673   llvm::stable_sort(FrameObjects, FrameObjectCompare);
3674 
3675   int i = 0;
3676   for (auto &Obj : FrameObjects) {
3677     // All invalid items are sorted at the end, so it's safe to stop.
3678     if (!Obj.IsValid)
3679       break;
3680     ObjectsToAllocate[i++] = Obj.ObjectIndex;
3681   }
3682 
3683   LLVM_DEBUG(dbgs() << "Final frame order:\n"; for (auto &Obj
3684                                                     : FrameObjects) {
3685     if (!Obj.IsValid)
3686       break;
3687     dbgs() << "  " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
3688     if (Obj.ObjectFirst)
3689       dbgs() << ", first";
3690     if (Obj.GroupFirst)
3691       dbgs() << ", group-first";
3692     dbgs() << "\n";
3693   });
3694 }
3695