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