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