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 isTargetWindows(const MachineFunction &MF) {
1028   return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();
1029 }
1030 
1031 // Convenience function to determine whether I is an SVE callee save.
1032 static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
1033   switch (I->getOpcode()) {
1034   default:
1035     return false;
1036   case AArch64::STR_ZXI:
1037   case AArch64::STR_PXI:
1038   case AArch64::LDR_ZXI:
1039   case AArch64::LDR_PXI:
1040     return I->getFlag(MachineInstr::FrameSetup) ||
1041            I->getFlag(MachineInstr::FrameDestroy);
1042   }
1043 }
1044 
1045 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
1046                                         MachineBasicBlock &MBB) const {
1047   MachineBasicBlock::iterator MBBI = MBB.begin();
1048   const MachineFrameInfo &MFI = MF.getFrameInfo();
1049   const Function &F = MF.getFunction();
1050   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1051   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1052   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1053   MachineModuleInfo &MMI = MF.getMMI();
1054   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1055   bool needsFrameMoves =
1056       MF.needsFrameMoves() && !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1057   bool HasFP = hasFP(MF);
1058   bool NeedsWinCFI = needsWinCFI(MF);
1059   bool HasWinCFI = false;
1060   auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
1061 
1062   bool IsFunclet = MBB.isEHFuncletEntry();
1063 
1064   // At this point, we're going to decide whether or not the function uses a
1065   // redzone. In most cases, the function doesn't have a redzone so let's
1066   // assume that's false and set it to true in the case that there's a redzone.
1067   AFI->setHasRedZone(false);
1068 
1069   // Debug location must be unknown since the first debug location is used
1070   // to determine the end of the prologue.
1071   DebugLoc DL;
1072 
1073   if (ShouldSignReturnAddress(MF)) {
1074     if (ShouldSignWithAKey(MF))
1075       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
1076           .setMIFlag(MachineInstr::FrameSetup);
1077     else {
1078       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
1079           .setMIFlag(MachineInstr::FrameSetup);
1080       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIBSP))
1081           .setMIFlag(MachineInstr::FrameSetup);
1082     }
1083 
1084     unsigned CFIIndex =
1085         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
1086     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1087         .addCFIIndex(CFIIndex)
1088         .setMIFlags(MachineInstr::FrameSetup);
1089   }
1090 
1091   // All calls are tail calls in GHC calling conv, and functions have no
1092   // prologue/epilogue.
1093   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1094     return;
1095 
1096   // Set tagged base pointer to the bottom of the stack frame.
1097   // Ideally it should match SP value after prologue.
1098   AFI->setTaggedBasePointerOffset(MFI.getStackSize());
1099 
1100   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1101 
1102   // getStackSize() includes all the locals in its size calculation. We don't
1103   // include these locals when computing the stack size of a funclet, as they
1104   // are allocated in the parent's stack frame and accessed via the frame
1105   // pointer from the funclet.  We only save the callee saved registers in the
1106   // funclet, which are really the callee saved registers of the parent
1107   // function, including the funclet.
1108   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1109                                : MFI.getStackSize();
1110   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
1111     assert(!HasFP && "unexpected function without stack frame but with FP");
1112     assert(!SVEStackSize &&
1113            "unexpected function without stack frame but with SVE objects");
1114     // All of the stack allocation is for locals.
1115     AFI->setLocalStackSize(NumBytes);
1116     if (!NumBytes)
1117       return;
1118     // REDZONE: If the stack size is less than 128 bytes, we don't need
1119     // to actually allocate.
1120     if (canUseRedZone(MF)) {
1121       AFI->setHasRedZone(true);
1122       ++NumRedZoneFunctions;
1123     } else {
1124       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1125                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
1126                       false, NeedsWinCFI, &HasWinCFI);
1127       if (!NeedsWinCFI && needsFrameMoves) {
1128         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
1129         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
1130           // Encode the stack size of the leaf function.
1131         unsigned CFIIndex = MF.addFrameInst(
1132             MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));
1133         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1134             .addCFIIndex(CFIIndex)
1135             .setMIFlags(MachineInstr::FrameSetup);
1136       }
1137     }
1138 
1139     if (NeedsWinCFI) {
1140       HasWinCFI = true;
1141       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1142           .setMIFlag(MachineInstr::FrameSetup);
1143     }
1144 
1145     return;
1146   }
1147 
1148   bool IsWin64 =
1149       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1150   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1151 
1152   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1153   // All of the remaining stack allocations are for locals.
1154   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1155   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1156   if (CombineSPBump) {
1157     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1158     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
1159                     {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup, false,
1160                     NeedsWinCFI, &HasWinCFI);
1161     NumBytes = 0;
1162   } else if (PrologueSaveSize != 0) {
1163     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
1164         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI);
1165     NumBytes -= PrologueSaveSize;
1166   }
1167   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1168 
1169   // Move past the saves of the callee-saved registers, fixing up the offsets
1170   // and pre-inc if we decided to combine the callee-save and local stack
1171   // pointer bump above.
1172   MachineBasicBlock::iterator End = MBB.end();
1173   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
1174          !IsSVECalleeSave(MBBI)) {
1175     if (CombineSPBump)
1176       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
1177                                         NeedsWinCFI, &HasWinCFI);
1178     ++MBBI;
1179   }
1180 
1181   // For funclets the FP belongs to the containing function.
1182   if (!IsFunclet && HasFP) {
1183     // Only set up FP if we actually need to.
1184     int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();
1185 
1186     if (CombineSPBump)
1187       FPOffset += AFI->getLocalStackSize();
1188 
1189     // Issue    sub fp, sp, FPOffset or
1190     //          mov fp,sp          when FPOffset is zero.
1191     // Note: All stores of callee-saved registers are marked as "FrameSetup".
1192     // This code marks the instruction(s) that set the FP also.
1193     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
1194                     {FPOffset, MVT::i8}, TII, MachineInstr::FrameSetup, false,
1195                     NeedsWinCFI, &HasWinCFI);
1196   }
1197 
1198   if (windowsRequiresStackProbe(MF, NumBytes)) {
1199     uint64_t NumWords = NumBytes >> 4;
1200     if (NeedsWinCFI) {
1201       HasWinCFI = true;
1202       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
1203       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
1204       // This is at most two instructions, MOVZ follwed by MOVK.
1205       // TODO: Fix to use multiple stack alloc unwind codes for stacks
1206       // exceeding 256MB in size.
1207       if (NumBytes >= (1 << 28))
1208         report_fatal_error("Stack size cannot exceed 256MB for stack "
1209                             "unwinding purposes");
1210 
1211       uint32_t LowNumWords = NumWords & 0xFFFF;
1212       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
1213             .addImm(LowNumWords)
1214             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1215             .setMIFlag(MachineInstr::FrameSetup);
1216       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1217             .setMIFlag(MachineInstr::FrameSetup);
1218       if ((NumWords & 0xFFFF0000) != 0) {
1219           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
1220               .addReg(AArch64::X15)
1221               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
1222               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
1223               .setMIFlag(MachineInstr::FrameSetup);
1224           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1225             .setMIFlag(MachineInstr::FrameSetup);
1226       }
1227     } else {
1228       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
1229           .addImm(NumWords)
1230           .setMIFlags(MachineInstr::FrameSetup);
1231     }
1232 
1233     switch (MF.getTarget().getCodeModel()) {
1234     case CodeModel::Tiny:
1235     case CodeModel::Small:
1236     case CodeModel::Medium:
1237     case CodeModel::Kernel:
1238       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
1239           .addExternalSymbol("__chkstk")
1240           .addReg(AArch64::X15, RegState::Implicit)
1241           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1242           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1243           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1244           .setMIFlags(MachineInstr::FrameSetup);
1245       if (NeedsWinCFI) {
1246         HasWinCFI = true;
1247         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1248             .setMIFlag(MachineInstr::FrameSetup);
1249       }
1250       break;
1251     case CodeModel::Large:
1252       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1253           .addReg(AArch64::X16, RegState::Define)
1254           .addExternalSymbol("__chkstk")
1255           .addExternalSymbol("__chkstk")
1256           .setMIFlags(MachineInstr::FrameSetup);
1257       if (NeedsWinCFI) {
1258         HasWinCFI = true;
1259         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1260             .setMIFlag(MachineInstr::FrameSetup);
1261       }
1262 
1263       BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))
1264           .addReg(AArch64::X16, RegState::Kill)
1265           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1266           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1267           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1268           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1269           .setMIFlags(MachineInstr::FrameSetup);
1270       if (NeedsWinCFI) {
1271         HasWinCFI = true;
1272         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1273             .setMIFlag(MachineInstr::FrameSetup);
1274       }
1275       break;
1276     }
1277 
1278     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1279         .addReg(AArch64::SP, RegState::Kill)
1280         .addReg(AArch64::X15, RegState::Kill)
1281         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1282         .setMIFlags(MachineInstr::FrameSetup);
1283     if (NeedsWinCFI) {
1284       HasWinCFI = true;
1285       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1286           .addImm(NumBytes)
1287           .setMIFlag(MachineInstr::FrameSetup);
1288     }
1289     NumBytes = 0;
1290   }
1291 
1292   StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
1293   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
1294 
1295   // Process the SVE callee-saves to determine what space needs to be
1296   // allocated.
1297   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
1298     // Find callee save instructions in frame.
1299     CalleeSavesBegin = MBBI;
1300     assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
1301     while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
1302       ++MBBI;
1303     CalleeSavesEnd = MBBI;
1304 
1305     AllocateBefore = {CalleeSavedSize, MVT::nxv1i8};
1306     AllocateAfter = SVEStackSize - AllocateBefore;
1307   }
1308 
1309   // Allocate space for the callee saves (if any).
1310   emitFrameOffset(MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP,
1311                   -AllocateBefore, TII,
1312                   MachineInstr::FrameSetup);
1313 
1314   // Finally allocate remaining SVE stack space.
1315   emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
1316                   -AllocateAfter, TII,
1317                   MachineInstr::FrameSetup);
1318 
1319   // Allocate space for the rest of the frame.
1320   if (NumBytes) {
1321     // Alignment is required for the parent frame, not the funclet
1322     const bool NeedsRealignment =
1323         !IsFunclet && RegInfo->needsStackRealignment(MF);
1324     unsigned scratchSPReg = AArch64::SP;
1325 
1326     if (NeedsRealignment) {
1327       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1328       assert(scratchSPReg != AArch64::NoRegister);
1329     }
1330 
1331     // If we're a leaf function, try using the red zone.
1332     if (!canUseRedZone(MF))
1333       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1334       // the correct value here, as NumBytes also includes padding bytes,
1335       // which shouldn't be counted here.
1336       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP,
1337                       {-NumBytes, MVT::i8}, TII, MachineInstr::FrameSetup,
1338                       false, NeedsWinCFI, &HasWinCFI);
1339 
1340     if (NeedsRealignment) {
1341       const unsigned NrBitsToZero = Log2(MFI.getMaxAlign());
1342       assert(NrBitsToZero > 1);
1343       assert(scratchSPReg != AArch64::SP);
1344 
1345       // SUB X9, SP, NumBytes
1346       //   -- X9 is temporary register, so shouldn't contain any live data here,
1347       //   -- free to use. This is already produced by emitFrameOffset above.
1348       // AND SP, X9, 0b11111...0000
1349       // The logical immediates have a non-trivial encoding. The following
1350       // formula computes the encoded immediate with all ones but
1351       // NrBitsToZero zero bits as least significant bits.
1352       uint32_t andMaskEncoded = (1 << 12)                         // = N
1353                                 | ((64 - NrBitsToZero) << 6)      // immr
1354                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1355 
1356       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1357           .addReg(scratchSPReg, RegState::Kill)
1358           .addImm(andMaskEncoded);
1359       AFI->setStackRealigned(true);
1360       if (NeedsWinCFI) {
1361         HasWinCFI = true;
1362         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1363             .addImm(NumBytes & andMaskEncoded)
1364             .setMIFlag(MachineInstr::FrameSetup);
1365       }
1366     }
1367   }
1368 
1369   // If we need a base pointer, set it up here. It's whatever the value of the
1370   // stack pointer is at this point. Any variable size objects will be allocated
1371   // after this, so we can still use the base pointer to reference locals.
1372   //
1373   // FIXME: Clarify FrameSetup flags here.
1374   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1375   // needed.
1376   // For funclets the BP belongs to the containing function.
1377   if (!IsFunclet && RegInfo->hasBasePointer(MF)) {
1378     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1379                      false);
1380     if (NeedsWinCFI) {
1381       HasWinCFI = true;
1382       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1383           .setMIFlag(MachineInstr::FrameSetup);
1384     }
1385   }
1386 
1387   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1388   // SEH opcode indicating the prologue end.
1389   if (NeedsWinCFI && HasWinCFI) {
1390     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1391         .setMIFlag(MachineInstr::FrameSetup);
1392   }
1393 
1394   // SEH funclets are passed the frame pointer in X1.  If the parent
1395   // function uses the base register, then the base register is used
1396   // directly, and is not retrieved from X1.
1397   if (IsFunclet && F.hasPersonalityFn()) {
1398     EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
1399     if (isAsynchronousEHPersonality(Per)) {
1400       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
1401           .addReg(AArch64::X1)
1402           .setMIFlag(MachineInstr::FrameSetup);
1403       MBB.addLiveIn(AArch64::X1);
1404     }
1405   }
1406 
1407   if (needsFrameMoves) {
1408     // An example of the prologue:
1409     //
1410     //     .globl __foo
1411     //     .align 2
1412     //  __foo:
1413     // Ltmp0:
1414     //     .cfi_startproc
1415     //     .cfi_personality 155, ___gxx_personality_v0
1416     // Leh_func_begin:
1417     //     .cfi_lsda 16, Lexception33
1418     //
1419     //     stp  xa,bx, [sp, -#offset]!
1420     //     ...
1421     //     stp  x28, x27, [sp, #offset-32]
1422     //     stp  fp, lr, [sp, #offset-16]
1423     //     add  fp, sp, #offset - 16
1424     //     sub  sp, sp, #1360
1425     //
1426     // The Stack:
1427     //       +-------------------------------------------+
1428     // 10000 | ........ | ........ | ........ | ........ |
1429     // 10004 | ........ | ........ | ........ | ........ |
1430     //       +-------------------------------------------+
1431     // 10008 | ........ | ........ | ........ | ........ |
1432     // 1000c | ........ | ........ | ........ | ........ |
1433     //       +===========================================+
1434     // 10010 |                X28 Register               |
1435     // 10014 |                X28 Register               |
1436     //       +-------------------------------------------+
1437     // 10018 |                X27 Register               |
1438     // 1001c |                X27 Register               |
1439     //       +===========================================+
1440     // 10020 |                Frame Pointer              |
1441     // 10024 |                Frame Pointer              |
1442     //       +-------------------------------------------+
1443     // 10028 |                Link Register              |
1444     // 1002c |                Link Register              |
1445     //       +===========================================+
1446     // 10030 | ........ | ........ | ........ | ........ |
1447     // 10034 | ........ | ........ | ........ | ........ |
1448     //       +-------------------------------------------+
1449     // 10038 | ........ | ........ | ........ | ........ |
1450     // 1003c | ........ | ........ | ........ | ........ |
1451     //       +-------------------------------------------+
1452     //
1453     //     [sp] = 10030        ::    >>initial value<<
1454     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1455     //     fp = sp == 10020    ::  mov fp, sp
1456     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1457     //     sp == 10010         ::    >>final value<<
1458     //
1459     // The frame pointer (w29) points to address 10020. If we use an offset of
1460     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1461     // for w27, and -32 for w28:
1462     //
1463     //  Ltmp1:
1464     //     .cfi_def_cfa w29, 16
1465     //  Ltmp2:
1466     //     .cfi_offset w30, -8
1467     //  Ltmp3:
1468     //     .cfi_offset w29, -16
1469     //  Ltmp4:
1470     //     .cfi_offset w27, -24
1471     //  Ltmp5:
1472     //     .cfi_offset w28, -32
1473 
1474     if (HasFP) {
1475       const int OffsetToFirstCalleeSaveFromFP =
1476           AFI->getCalleeSaveBaseToFrameRecordOffset() -
1477           AFI->getCalleeSavedStackSize();
1478       Register FramePtr = RegInfo->getFrameRegister(MF);
1479 
1480       // Define the current CFA rule to use the provided FP.
1481       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1482       unsigned CFIIndex = MF.addFrameInst(
1483           MCCFIInstruction::cfiDefCfa(nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));
1484       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1485           .addCFIIndex(CFIIndex)
1486           .setMIFlags(MachineInstr::FrameSetup);
1487     } else {
1488       unsigned CFIIndex;
1489       if (SVEStackSize) {
1490         const TargetSubtargetInfo &STI = MF.getSubtarget();
1491         const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1492         StackOffset TotalSize =
1493             SVEStackSize + StackOffset((int64_t)MFI.getStackSize(), MVT::i8);
1494         CFIIndex = MF.addFrameInst(createDefCFAExpressionFromSP(TRI, TotalSize));
1495       } else {
1496         // Encode the stack size of the leaf function.
1497         CFIIndex = MF.addFrameInst(
1498             MCCFIInstruction::cfiDefCfaOffset(nullptr, MFI.getStackSize()));
1499       }
1500       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1501           .addCFIIndex(CFIIndex)
1502           .setMIFlags(MachineInstr::FrameSetup);
1503     }
1504 
1505     // Now emit the moves for whatever callee saved regs we have (including FP,
1506     // LR if those are saved).
1507     emitCalleeSavedFrameMoves(MBB, MBBI);
1508   }
1509 }
1510 
1511 static void InsertReturnAddressAuth(MachineFunction &MF,
1512                                     MachineBasicBlock &MBB) {
1513   if (!ShouldSignReturnAddress(MF))
1514     return;
1515   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1516   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1517 
1518   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1519   DebugLoc DL;
1520   if (MBBI != MBB.end())
1521     DL = MBBI->getDebugLoc();
1522 
1523   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1524   // this instruction can safely used for any v8a architecture.
1525   // From v8.3a onwards there are optimised authenticate LR and return
1526   // instructions, namely RETA{A,B}, that can be used instead.
1527   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1528       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1529     BuildMI(MBB, MBBI, DL,
1530             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1531         .copyImplicitOps(*MBBI);
1532     MBB.erase(MBBI);
1533   } else {
1534     BuildMI(
1535         MBB, MBBI, DL,
1536         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1537         .setMIFlag(MachineInstr::FrameDestroy);
1538   }
1539 }
1540 
1541 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1542   switch (MI.getOpcode()) {
1543   default:
1544     return false;
1545   case AArch64::CATCHRET:
1546   case AArch64::CLEANUPRET:
1547     return true;
1548   }
1549 }
1550 
1551 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1552                                         MachineBasicBlock &MBB) const {
1553   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1554   MachineFrameInfo &MFI = MF.getFrameInfo();
1555   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1556   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1557   DebugLoc DL;
1558   bool NeedsWinCFI = needsWinCFI(MF);
1559   bool HasWinCFI = false;
1560   bool IsFunclet = false;
1561   auto WinCFI = make_scope_exit([&]() {
1562     if (!MF.hasWinCFI())
1563       MF.setHasWinCFI(HasWinCFI);
1564   });
1565 
1566   if (MBB.end() != MBBI) {
1567     DL = MBBI->getDebugLoc();
1568     IsFunclet = isFuncletReturnInstr(*MBBI);
1569   }
1570 
1571   int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
1572                                : MFI.getStackSize();
1573   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1574 
1575   // All calls are tail calls in GHC calling conv, and functions have no
1576   // prologue/epilogue.
1577   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1578     return;
1579 
1580   // Initial and residual are named for consistency with the prologue. Note that
1581   // in the epilogue, the residual adjustment is executed first.
1582   uint64_t ArgumentPopSize = getArgumentPopSize(MF, MBB);
1583 
1584   // The stack frame should be like below,
1585   //
1586   //      ----------------------                     ---
1587   //      |                    |                      |
1588   //      | BytesInStackArgArea|              CalleeArgStackSize
1589   //      | (NumReusableBytes) |                (of tail call)
1590   //      |                    |                     ---
1591   //      |                    |                      |
1592   //      ---------------------|        ---           |
1593   //      |                    |         |            |
1594   //      |   CalleeSavedReg   |         |            |
1595   //      | (CalleeSavedStackSize)|      |            |
1596   //      |                    |         |            |
1597   //      ---------------------|         |         NumBytes
1598   //      |                    |     StackSize  (StackAdjustUp)
1599   //      |   LocalStackSize   |         |            |
1600   //      | (covering callee   |         |            |
1601   //      |       args)        |         |            |
1602   //      |                    |         |            |
1603   //      ----------------------        ---          ---
1604   //
1605   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1606   //             = StackSize + ArgumentPopSize
1607   //
1608   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1609   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1610 
1611   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1612 
1613   bool IsWin64 =
1614       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1615   unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
1616 
1617   uint64_t AfterCSRPopSize = ArgumentPopSize;
1618   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1619   // We cannot rely on the local stack size set in emitPrologue if the function
1620   // has funclets, as funclets have different local stack size requirements, and
1621   // the current value set in emitPrologue may be that of the containing
1622   // function.
1623   if (MF.hasEHFunclets())
1624     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1625   bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);
1626   // Assume we can't combine the last pop with the sp restore.
1627 
1628   if (!CombineSPBump && PrologueSaveSize != 0) {
1629     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1630     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1631       Pop = std::prev(Pop);
1632     // Converting the last ldp to a post-index ldp is valid only if the last
1633     // ldp's offset is 0.
1634     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1635     // If the offset is 0, convert it to a post-index ldp.
1636     if (OffsetOp.getImm() == 0)
1637       convertCalleeSaveRestoreToSPPrePostIncDec(
1638           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, false);
1639     else {
1640       // If not, make sure to emit an add after the last ldp.
1641       // We're doing this by transfering the size to be restored from the
1642       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1643       // pops.
1644       AfterCSRPopSize += PrologueSaveSize;
1645     }
1646   }
1647 
1648   // Move past the restores of the callee-saved registers.
1649   // If we plan on combining the sp bump of the local stack size and the callee
1650   // save stack size, we might need to adjust the CSR save and restore offsets.
1651   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1652   MachineBasicBlock::iterator Begin = MBB.begin();
1653   while (LastPopI != Begin) {
1654     --LastPopI;
1655     if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
1656         IsSVECalleeSave(LastPopI)) {
1657       ++LastPopI;
1658       break;
1659     } else if (CombineSPBump)
1660       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1661                                         NeedsWinCFI, &HasWinCFI);
1662   }
1663 
1664   if (NeedsWinCFI) {
1665     HasWinCFI = true;
1666     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1667         .setMIFlag(MachineInstr::FrameDestroy);
1668   }
1669 
1670   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1671 
1672   // If there is a single SP update, insert it before the ret and we're done.
1673   if (CombineSPBump) {
1674     assert(!SVEStackSize && "Cannot combine SP bump with SVE");
1675     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1676                     {NumBytes + (int64_t)AfterCSRPopSize, MVT::i8}, TII,
1677                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1678     if (NeedsWinCFI && HasWinCFI)
1679       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1680               TII->get(AArch64::SEH_EpilogEnd))
1681           .setMIFlag(MachineInstr::FrameDestroy);
1682     return;
1683   }
1684 
1685   NumBytes -= PrologueSaveSize;
1686   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1687 
1688   // Process the SVE callee-saves to determine what space needs to be
1689   // deallocated.
1690   StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
1691   MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
1692   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
1693     RestoreBegin = std::prev(RestoreEnd);
1694     while (RestoreBegin != MBB.begin() &&
1695            IsSVECalleeSave(std::prev(RestoreBegin)))
1696       --RestoreBegin;
1697 
1698     assert(IsSVECalleeSave(RestoreBegin) &&
1699            IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
1700 
1701     StackOffset CalleeSavedSizeAsOffset = {CalleeSavedSize, MVT::nxv1i8};
1702     DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;
1703     DeallocateAfter = CalleeSavedSizeAsOffset;
1704   }
1705 
1706   // Deallocate the SVE area.
1707   if (SVEStackSize) {
1708     if (AFI->isStackRealigned()) {
1709       if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize())
1710         // Set SP to start of SVE callee-save area from which they can
1711         // be reloaded. The code below will deallocate the stack space
1712         // space by moving FP -> SP.
1713         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
1714                         {-CalleeSavedSize, MVT::nxv1i8}, TII,
1715                         MachineInstr::FrameDestroy);
1716     } else {
1717       if (AFI->getSVECalleeSavedStackSize()) {
1718         // Deallocate the non-SVE locals first before we can deallocate (and
1719         // restore callee saves) from the SVE area.
1720         emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1721                         {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy);
1722         NumBytes = 0;
1723       }
1724 
1725       emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
1726                       DeallocateBefore, TII, MachineInstr::FrameDestroy);
1727 
1728       emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
1729                       DeallocateAfter, TII, MachineInstr::FrameDestroy);
1730     }
1731   }
1732 
1733   if (!hasFP(MF)) {
1734     bool RedZone = canUseRedZone(MF);
1735     // If this was a redzone leaf function, we don't need to restore the
1736     // stack pointer (but we may need to pop stack args for fastcc).
1737     if (RedZone && AfterCSRPopSize == 0)
1738       return;
1739 
1740     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1741     int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
1742     if (NoCalleeSaveRestore)
1743       StackRestoreBytes += AfterCSRPopSize;
1744 
1745     // If we were able to combine the local stack pop with the argument pop,
1746     // then we're done.
1747     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1748 
1749     // If we're done after this, make sure to help the load store optimizer.
1750     if (Done)
1751       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1752 
1753     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1754                     {StackRestoreBytes, MVT::i8}, TII,
1755                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1756     if (Done) {
1757       if (NeedsWinCFI) {
1758         HasWinCFI = true;
1759         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1760                 TII->get(AArch64::SEH_EpilogEnd))
1761             .setMIFlag(MachineInstr::FrameDestroy);
1762       }
1763       return;
1764     }
1765 
1766     NumBytes = 0;
1767   }
1768 
1769   // Restore the original stack pointer.
1770   // FIXME: Rather than doing the math here, we should instead just use
1771   // non-post-indexed loads for the restores if we aren't actually going to
1772   // be able to save any instructions.
1773   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
1774     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1775                     {-AFI->getCalleeSaveBaseToFrameRecordOffset(), MVT::i8},
1776                     TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
1777   } else if (NumBytes)
1778     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1779                     {NumBytes, MVT::i8}, TII, MachineInstr::FrameDestroy, false,
1780                     NeedsWinCFI);
1781 
1782   // This must be placed after the callee-save restore code because that code
1783   // assumes the SP is at the same location as it was after the callee-save save
1784   // code in the prologue.
1785   if (AfterCSRPopSize) {
1786     // Find an insertion point for the first ldp so that it goes before the
1787     // shadow call stack epilog instruction. This ensures that the restore of
1788     // lr from x18 is placed after the restore from sp.
1789     auto FirstSPPopI = MBB.getFirstTerminator();
1790     while (FirstSPPopI != Begin) {
1791       auto Prev = std::prev(FirstSPPopI);
1792       if (Prev->getOpcode() != AArch64::LDRXpre ||
1793           Prev->getOperand(0).getReg() == AArch64::SP)
1794         break;
1795       FirstSPPopI = Prev;
1796     }
1797 
1798     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1799 
1800     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1801                     {(int64_t)AfterCSRPopSize, MVT::i8}, TII,
1802                     MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI);
1803   }
1804   if (NeedsWinCFI && HasWinCFI)
1805     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1806         .setMIFlag(MachineInstr::FrameDestroy);
1807 
1808   MF.setHasWinCFI(HasWinCFI);
1809 }
1810 
1811 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1812 /// debug info.  It's the same as what we use for resolving the code-gen
1813 /// references for now.  FIXME: This can go wrong when references are
1814 /// SP-relative and simple call frames aren't used.
1815 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1816                                                  int FI,
1817                                                  Register &FrameReg) const {
1818   return resolveFrameIndexReference(
1819              MF, FI, FrameReg,
1820              /*PreferFP=*/
1821              MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
1822              /*ForSimm=*/false)
1823       .getBytes();
1824 }
1825 
1826 int AArch64FrameLowering::getNonLocalFrameIndexReference(
1827   const MachineFunction &MF, int FI) const {
1828   return getSEHFrameIndexOffset(MF, FI);
1829 }
1830 
1831 static StackOffset getFPOffset(const MachineFunction &MF, int64_t ObjectOffset) {
1832   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1833   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1834   bool IsWin64 =
1835       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1836   unsigned FixedObject =
1837       getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
1838   int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
1839   int64_t FPAdjust =
1840       CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
1841   return {ObjectOffset + FixedObject + FPAdjust, MVT::i8};
1842 }
1843 
1844 static StackOffset getStackOffset(const MachineFunction &MF, int64_t ObjectOffset) {
1845   const auto &MFI = MF.getFrameInfo();
1846   return {ObjectOffset + (int64_t)MFI.getStackSize(), MVT::i8};
1847 }
1848 
1849 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
1850                                                  int FI) const {
1851   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1852       MF.getSubtarget().getRegisterInfo());
1853   int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
1854   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
1855              ? getFPOffset(MF, ObjectOffset).getBytes()
1856              : getStackOffset(MF, ObjectOffset).getBytes();
1857 }
1858 
1859 StackOffset AArch64FrameLowering::resolveFrameIndexReference(
1860     const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
1861     bool ForSimm) const {
1862   const auto &MFI = MF.getFrameInfo();
1863   int64_t ObjectOffset = MFI.getObjectOffset(FI);
1864   bool isFixed = MFI.isFixedObjectIndex(FI);
1865   bool isSVE = MFI.getStackID(FI) == TargetStackID::SVEVector;
1866   return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
1867                                      PreferFP, ForSimm);
1868 }
1869 
1870 StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
1871     const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
1872     Register &FrameReg, bool PreferFP, bool ForSimm) const {
1873   const auto &MFI = MF.getFrameInfo();
1874   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1875       MF.getSubtarget().getRegisterInfo());
1876   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1877   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1878 
1879   int64_t FPOffset = getFPOffset(MF, ObjectOffset).getBytes();
1880   int64_t Offset = getStackOffset(MF, ObjectOffset).getBytes();
1881   bool isCSR =
1882       !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
1883 
1884   const StackOffset &SVEStackSize = getSVEStackSize(MF);
1885 
1886   // Use frame pointer to reference fixed objects. Use it for locals if
1887   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1888   // reliable as a base). Make sure useFPForScavengingIndex() does the
1889   // right thing for the emergency spill slot.
1890   bool UseFP = false;
1891   if (AFI->hasStackFrame() && !isSVE) {
1892     // We shouldn't prefer using the FP when there is an SVE area
1893     // in between the FP and the non-SVE locals/spills.
1894     PreferFP &= !SVEStackSize;
1895 
1896     // Note: Keeping the following as multiple 'if' statements rather than
1897     // merging to a single expression for readability.
1898     //
1899     // Argument access should always use the FP.
1900     if (isFixed) {
1901       UseFP = hasFP(MF);
1902     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1903       // References to the CSR area must use FP if we're re-aligning the stack
1904       // since the dynamically-sized alignment padding is between the SP/BP and
1905       // the CSR area.
1906       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1907       UseFP = true;
1908     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1909       // If the FPOffset is negative and we're producing a signed immediate, we
1910       // have to keep in mind that the available offset range for negative
1911       // offsets is smaller than for positive ones. If an offset is available
1912       // via the FP and the SP, use whichever is closest.
1913       bool FPOffsetFits = !ForSimm || FPOffset >= -256;
1914       PreferFP |= Offset > -FPOffset;
1915 
1916       if (MFI.hasVarSizedObjects()) {
1917         // If we have variable sized objects, we can use either FP or BP, as the
1918         // SP offset is unknown. We can use the base pointer if we have one and
1919         // FP is not preferred. If not, we're stuck with using FP.
1920         bool CanUseBP = RegInfo->hasBasePointer(MF);
1921         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1922           UseFP = PreferFP;
1923         else if (!CanUseBP) // Can't use BP. Forced to use FP.
1924           UseFP = true;
1925         // else we can use BP and FP, but the offset from FP won't fit.
1926         // That will make us scavenge registers which we can probably avoid by
1927         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1928       } else if (FPOffset >= 0) {
1929         // Use SP or FP, whichever gives us the best chance of the offset
1930         // being in range for direct access. If the FPOffset is positive,
1931         // that'll always be best, as the SP will be even further away.
1932         UseFP = true;
1933       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1934         // Funclets access the locals contained in the parent's stack frame
1935         // via the frame pointer, so we have to use the FP in the parent
1936         // function.
1937         (void) Subtarget;
1938         assert(
1939             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1940             "Funclets should only be present on Win64");
1941         UseFP = true;
1942       } else {
1943         // We have the choice between FP and (SP or BP).
1944         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1945           UseFP = true;
1946       }
1947     }
1948   }
1949 
1950   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1951          "In the presence of dynamic stack pointer realignment, "
1952          "non-argument/CSR objects cannot be accessed through the frame pointer");
1953 
1954   if (isSVE) {
1955     int64_t OffsetFromSPToSVEArea =
1956         MFI.getStackSize() - AFI->getCalleeSavedStackSize();
1957     int64_t OffsetFromFPToSVEArea =
1958         -AFI->getCalleeSaveBaseToFrameRecordOffset();
1959     StackOffset FPOffset = StackOffset(OffsetFromFPToSVEArea, MVT::i8) +
1960                            StackOffset(ObjectOffset, MVT::nxv1i8);
1961     StackOffset SPOffset = SVEStackSize +
1962                            StackOffset(ObjectOffset, MVT::nxv1i8) +
1963                            StackOffset(OffsetFromSPToSVEArea, MVT::i8);
1964     // Always use the FP for SVE spills if available and beneficial.
1965     if (hasFP(MF) &&
1966         (SPOffset.getBytes() ||
1967          FPOffset.getScalableBytes() < SPOffset.getScalableBytes() ||
1968          RegInfo->needsStackRealignment(MF))) {
1969       FrameReg = RegInfo->getFrameRegister(MF);
1970       return FPOffset;
1971     }
1972 
1973     FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
1974                                            : (unsigned)AArch64::SP;
1975     return SPOffset;
1976   }
1977 
1978   StackOffset ScalableOffset = {};
1979   if (UseFP && !(isFixed || isCSR))
1980     ScalableOffset = -SVEStackSize;
1981   if (!UseFP && (isFixed || isCSR))
1982     ScalableOffset = SVEStackSize;
1983 
1984   if (UseFP) {
1985     FrameReg = RegInfo->getFrameRegister(MF);
1986     return StackOffset(FPOffset, MVT::i8) + ScalableOffset;
1987   }
1988 
1989   // Use the base pointer if we have one.
1990   if (RegInfo->hasBasePointer(MF))
1991     FrameReg = RegInfo->getBaseRegister();
1992   else {
1993     assert(!MFI.hasVarSizedObjects() &&
1994            "Can't use SP when we have var sized objects.");
1995     FrameReg = AArch64::SP;
1996     // If we're using the red zone for this function, the SP won't actually
1997     // be adjusted, so the offsets will be negative. They're also all
1998     // within range of the signed 9-bit immediate instructions.
1999     if (canUseRedZone(MF))
2000       Offset -= AFI->getLocalStackSize();
2001   }
2002 
2003   return StackOffset(Offset, MVT::i8) + ScalableOffset;
2004 }
2005 
2006 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
2007   // Do not set a kill flag on values that are also marked as live-in. This
2008   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
2009   // callee saved registers.
2010   // Omitting the kill flags is conservatively correct even if the live-in
2011   // is not used after all.
2012   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
2013   return getKillRegState(!IsLiveIn);
2014 }
2015 
2016 static bool produceCompactUnwindFrame(MachineFunction &MF) {
2017   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2018   AttributeList Attrs = MF.getFunction().getAttributes();
2019   return Subtarget.isTargetMachO() &&
2020          !(Subtarget.getTargetLowering()->supportSwiftError() &&
2021            Attrs.hasAttrSomewhere(Attribute::SwiftError));
2022 }
2023 
2024 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
2025                                              bool NeedsWinCFI) {
2026   // If we are generating register pairs for a Windows function that requires
2027   // EH support, then pair consecutive registers only.  There are no unwind
2028   // opcodes for saves/restores of non-consectuve register pairs.
2029   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
2030   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
2031 
2032   // TODO: LR can be paired with any register.  We don't support this yet in
2033   // the MCLayer.  We need to add support for the save_lrpair unwind code.
2034   if (Reg2 == AArch64::FP)
2035     return true;
2036   if (!NeedsWinCFI)
2037     return false;
2038   if (Reg2 == Reg1 + 1)
2039     return false;
2040   return true;
2041 }
2042 
2043 /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
2044 /// WindowsCFI requires that only consecutive registers can be paired.
2045 /// LR and FP need to be allocated together when the frame needs to save
2046 /// the frame-record. This means any other register pairing with LR is invalid.
2047 static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
2048                                       bool UsesWinAAPCS, bool NeedsWinCFI, bool NeedsFrameRecord) {
2049   if (UsesWinAAPCS)
2050     return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI);
2051 
2052   // If we need to store the frame record, don't pair any register
2053   // with LR other than FP.
2054   if (NeedsFrameRecord)
2055     return Reg2 == AArch64::LR;
2056 
2057   return false;
2058 }
2059 
2060 namespace {
2061 
2062 struct RegPairInfo {
2063   unsigned Reg1 = AArch64::NoRegister;
2064   unsigned Reg2 = AArch64::NoRegister;
2065   int FrameIdx;
2066   int Offset;
2067   enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
2068 
2069   RegPairInfo() = default;
2070 
2071   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
2072 
2073   unsigned getScale() const {
2074     switch (Type) {
2075     case PPR:
2076       return 2;
2077     case GPR:
2078     case FPR64:
2079       return 8;
2080     case ZPR:
2081     case FPR128:
2082       return 16;
2083     }
2084     llvm_unreachable("Unsupported type");
2085   }
2086 
2087   bool isScalable() const { return Type == PPR || Type == ZPR; }
2088 };
2089 
2090 } // end anonymous namespace
2091 
2092 static void computeCalleeSaveRegisterPairs(
2093     MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
2094     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
2095     bool &NeedShadowCallStackProlog, bool NeedsFrameRecord) {
2096 
2097   if (CSI.empty())
2098     return;
2099 
2100   bool IsWindows = isTargetWindows(MF);
2101   bool NeedsWinCFI = needsWinCFI(MF);
2102   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2103   MachineFrameInfo &MFI = MF.getFrameInfo();
2104   CallingConv::ID CC = MF.getFunction().getCallingConv();
2105   unsigned Count = CSI.size();
2106   (void)CC;
2107   // MachO's compact unwind format relies on all registers being stored in
2108   // pairs.
2109   assert((!produceCompactUnwindFrame(MF) ||
2110           CC == CallingConv::PreserveMost ||
2111           (Count & 1) == 0) &&
2112          "Odd number of callee-saved regs to spill!");
2113   int ByteOffset = AFI->getCalleeSavedStackSize();
2114   int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
2115   // On Linux, we will have either one or zero non-paired register.  On Windows
2116   // with CFI, we can have multiple unpaired registers in order to utilize the
2117   // available unwind codes.  This flag assures that the alignment fixup is done
2118   // only once, as intened.
2119   bool FixupDone = false;
2120 
2121   for (unsigned i = 0; i < Count; ++i) {
2122     RegPairInfo RPI;
2123     RPI.Reg1 = CSI[i].getReg();
2124 
2125     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
2126       RPI.Type = RegPairInfo::GPR;
2127     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
2128       RPI.Type = RegPairInfo::FPR64;
2129     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
2130       RPI.Type = RegPairInfo::FPR128;
2131     else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
2132       RPI.Type = RegPairInfo::ZPR;
2133     else if (AArch64::PPRRegClass.contains(RPI.Reg1))
2134       RPI.Type = RegPairInfo::PPR;
2135     else
2136       llvm_unreachable("Unsupported register class.");
2137 
2138     // Add the next reg to the pair if it is in the same register class.
2139     if (i + 1 < Count) {
2140       unsigned NextReg = CSI[i + 1].getReg();
2141       switch (RPI.Type) {
2142       case RegPairInfo::GPR:
2143         if (AArch64::GPR64RegClass.contains(NextReg) &&
2144             !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows, NeedsWinCFI,
2145                                        NeedsFrameRecord))
2146           RPI.Reg2 = NextReg;
2147         break;
2148       case RegPairInfo::FPR64:
2149         if (AArch64::FPR64RegClass.contains(NextReg) &&
2150             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
2151           RPI.Reg2 = NextReg;
2152         break;
2153       case RegPairInfo::FPR128:
2154         if (AArch64::FPR128RegClass.contains(NextReg))
2155           RPI.Reg2 = NextReg;
2156         break;
2157       case RegPairInfo::PPR:
2158       case RegPairInfo::ZPR:
2159         break;
2160       }
2161     }
2162 
2163     // If either of the registers to be saved is the lr register, it means that
2164     // we also need to save lr in the shadow call stack.
2165     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
2166         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
2167       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
2168         report_fatal_error("Must reserve x18 to use shadow call stack");
2169       NeedShadowCallStackProlog = true;
2170     }
2171 
2172     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
2173     // list to come in sorted by frame index so that we can issue the store
2174     // pair instructions directly. Assert if we see anything otherwise.
2175     //
2176     // The order of the registers in the list is controlled by
2177     // getCalleeSavedRegs(), so they will always be in-order, as well.
2178     assert((!RPI.isPaired() ||
2179             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
2180            "Out of order callee saved regs!");
2181 
2182     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
2183             RPI.Reg1 == AArch64::LR) &&
2184            "FrameRecord must be allocated together with LR");
2185 
2186     // Windows AAPCS has FP and LR reversed.
2187     assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
2188             RPI.Reg2 == AArch64::LR) &&
2189            "FrameRecord must be allocated together with LR");
2190 
2191     // MachO's compact unwind format relies on all registers being stored in
2192     // adjacent register pairs.
2193     assert((!produceCompactUnwindFrame(MF) ||
2194             CC == CallingConv::PreserveMost ||
2195             (RPI.isPaired() &&
2196              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
2197               RPI.Reg1 + 1 == RPI.Reg2))) &&
2198            "Callee-save registers not saved as adjacent register pair!");
2199 
2200     RPI.FrameIdx = CSI[i].getFrameIdx();
2201 
2202     int Scale = RPI.getScale();
2203     if (RPI.isScalable())
2204       ScalableByteOffset -= Scale;
2205     else
2206       ByteOffset -= RPI.isPaired() ? 2 * Scale : Scale;
2207 
2208     assert(!(RPI.isScalable() && RPI.isPaired()) &&
2209            "Paired spill/fill instructions don't exist for SVE vectors");
2210 
2211     // Round up size of non-pair to pair size if we need to pad the
2212     // callee-save area to ensure 16-byte alignment.
2213     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
2214         !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
2215         !RPI.isPaired()) {
2216       FixupDone = true;
2217       ByteOffset -= 8;
2218       assert(ByteOffset % 16 == 0);
2219       assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
2220       MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
2221     }
2222 
2223     int Offset = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
2224     assert(Offset % Scale == 0);
2225     RPI.Offset = Offset / Scale;
2226 
2227     assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
2228             (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
2229            "Offset out of bounds for LDP/STP immediate");
2230 
2231     // Save the offset to frame record so that the FP register can point to the
2232     // innermost frame record (spilled FP and LR registers).
2233     if (NeedsFrameRecord && ((!IsWindows && RPI.Reg1 == AArch64::LR &&
2234                               RPI.Reg2 == AArch64::FP) ||
2235                              (IsWindows && RPI.Reg1 == AArch64::FP &&
2236                               RPI.Reg2 == AArch64::LR)))
2237       AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
2238 
2239     RegPairs.push_back(RPI);
2240     if (RPI.isPaired())
2241       ++i;
2242   }
2243 }
2244 
2245 bool AArch64FrameLowering::spillCalleeSavedRegisters(
2246     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2247     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2248   MachineFunction &MF = *MBB.getParent();
2249   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2250   bool NeedsWinCFI = needsWinCFI(MF);
2251   DebugLoc DL;
2252   SmallVector<RegPairInfo, 8> RegPairs;
2253 
2254   bool NeedShadowCallStackProlog = false;
2255   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2256                                  NeedShadowCallStackProlog, hasFP(MF));
2257   const MachineRegisterInfo &MRI = MF.getRegInfo();
2258 
2259   if (NeedShadowCallStackProlog) {
2260     // Shadow call stack prolog: str x30, [x18], #8
2261     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
2262         .addReg(AArch64::X18, RegState::Define)
2263         .addReg(AArch64::LR)
2264         .addReg(AArch64::X18)
2265         .addImm(8)
2266         .setMIFlag(MachineInstr::FrameSetup);
2267 
2268     if (NeedsWinCFI)
2269       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
2270           .setMIFlag(MachineInstr::FrameSetup);
2271 
2272     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
2273       // Emit a CFI instruction that causes 8 to be subtracted from the value of
2274       // x18 when unwinding past this frame.
2275       static const char CFIInst[] = {
2276           dwarf::DW_CFA_val_expression,
2277           18, // register
2278           2,  // length
2279           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
2280           static_cast<char>(-8) & 0x7f, // addend (sleb128)
2281       };
2282       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
2283           nullptr, StringRef(CFIInst, sizeof(CFIInst))));
2284       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
2285           .addCFIIndex(CFIIndex)
2286           .setMIFlag(MachineInstr::FrameSetup);
2287     }
2288 
2289     // This instruction also makes x18 live-in to the entry block.
2290     MBB.addLiveIn(AArch64::X18);
2291   }
2292 
2293   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
2294        ++RPII) {
2295     RegPairInfo RPI = *RPII;
2296     unsigned Reg1 = RPI.Reg1;
2297     unsigned Reg2 = RPI.Reg2;
2298     unsigned StrOpc;
2299 
2300     // Issue sequence of spills for cs regs.  The first spill may be converted
2301     // to a pre-decrement store later by emitPrologue if the callee-save stack
2302     // area allocation can't be combined with the local stack area allocation.
2303     // For example:
2304     //    stp     x22, x21, [sp, #0]     // addImm(+0)
2305     //    stp     x20, x19, [sp, #16]    // addImm(+2)
2306     //    stp     fp, lr, [sp, #32]      // addImm(+4)
2307     // Rationale: This sequence saves uop updates compared to a sequence of
2308     // pre-increment spills like stp xi,xj,[sp,#-16]!
2309     // Note: Similar rationale and sequence for restores in epilog.
2310     unsigned Size;
2311     Align Alignment;
2312     switch (RPI.Type) {
2313     case RegPairInfo::GPR:
2314        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2315        Size = 8;
2316        Alignment = Align(8);
2317        break;
2318     case RegPairInfo::FPR64:
2319        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2320        Size = 8;
2321        Alignment = Align(8);
2322        break;
2323     case RegPairInfo::FPR128:
2324        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2325        Size = 16;
2326        Alignment = Align(16);
2327        break;
2328     case RegPairInfo::ZPR:
2329        StrOpc = AArch64::STR_ZXI;
2330        Size = 16;
2331        Alignment = Align(16);
2332        break;
2333     case RegPairInfo::PPR:
2334        StrOpc = AArch64::STR_PXI;
2335        Size = 2;
2336        Alignment = Align(2);
2337        break;
2338     }
2339     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
2340                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2341                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2342                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2343                dbgs() << ")\n");
2344 
2345     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2346            "Windows unwdinding requires a consecutive (FP,LR) pair");
2347     // Windows unwind codes require consecutive registers if registers are
2348     // paired.  Make the switch here, so that the code below will save (x,x+1)
2349     // and not (x+1,x).
2350     unsigned FrameIdxReg1 = RPI.FrameIdx;
2351     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2352     if (NeedsWinCFI && RPI.isPaired()) {
2353       std::swap(Reg1, Reg2);
2354       std::swap(FrameIdxReg1, FrameIdxReg2);
2355     }
2356     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2357     if (!MRI.isReserved(Reg1))
2358       MBB.addLiveIn(Reg1);
2359     if (RPI.isPaired()) {
2360       if (!MRI.isReserved(Reg2))
2361         MBB.addLiveIn(Reg2);
2362       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2363       MIB.addMemOperand(MF.getMachineMemOperand(
2364           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2365           MachineMemOperand::MOStore, Size, Alignment));
2366     }
2367     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2368         .addReg(AArch64::SP)
2369         .addImm(RPI.Offset) // [sp, #offset*scale],
2370                             // where factor*scale is implicit
2371         .setMIFlag(MachineInstr::FrameSetup);
2372     MIB.addMemOperand(MF.getMachineMemOperand(
2373         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2374         MachineMemOperand::MOStore, Size, Alignment));
2375     if (NeedsWinCFI)
2376       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
2377 
2378     // Update the StackIDs of the SVE stack slots.
2379     MachineFrameInfo &MFI = MF.getFrameInfo();
2380     if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
2381       MFI.setStackID(RPI.FrameIdx, TargetStackID::SVEVector);
2382 
2383   }
2384   return true;
2385 }
2386 
2387 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
2388     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2389     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2390   MachineFunction &MF = *MBB.getParent();
2391   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2392   DebugLoc DL;
2393   SmallVector<RegPairInfo, 8> RegPairs;
2394   bool NeedsWinCFI = needsWinCFI(MF);
2395 
2396   if (MI != MBB.end())
2397     DL = MI->getDebugLoc();
2398 
2399   bool NeedShadowCallStackProlog = false;
2400   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
2401                                  NeedShadowCallStackProlog, hasFP(MF));
2402 
2403   auto EmitMI = [&](const RegPairInfo &RPI) {
2404     unsigned Reg1 = RPI.Reg1;
2405     unsigned Reg2 = RPI.Reg2;
2406 
2407     // Issue sequence of restores for cs regs. The last restore may be converted
2408     // to a post-increment load later by emitEpilogue if the callee-save stack
2409     // area allocation can't be combined with the local stack area allocation.
2410     // For example:
2411     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
2412     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
2413     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
2414     // Note: see comment in spillCalleeSavedRegisters()
2415     unsigned LdrOpc;
2416     unsigned Size;
2417     Align Alignment;
2418     switch (RPI.Type) {
2419     case RegPairInfo::GPR:
2420        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2421        Size = 8;
2422        Alignment = Align(8);
2423        break;
2424     case RegPairInfo::FPR64:
2425        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2426        Size = 8;
2427        Alignment = Align(8);
2428        break;
2429     case RegPairInfo::FPR128:
2430        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2431        Size = 16;
2432        Alignment = Align(16);
2433        break;
2434     case RegPairInfo::ZPR:
2435        LdrOpc = AArch64::LDR_ZXI;
2436        Size = 16;
2437        Alignment = Align(16);
2438        break;
2439     case RegPairInfo::PPR:
2440        LdrOpc = AArch64::LDR_PXI;
2441        Size = 2;
2442        Alignment = Align(2);
2443        break;
2444     }
2445     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
2446                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
2447                dbgs() << ") -> fi#(" << RPI.FrameIdx;
2448                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
2449                dbgs() << ")\n");
2450 
2451     // Windows unwind codes require consecutive registers if registers are
2452     // paired.  Make the switch here, so that the code below will save (x,x+1)
2453     // and not (x+1,x).
2454     unsigned FrameIdxReg1 = RPI.FrameIdx;
2455     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
2456     if (NeedsWinCFI && RPI.isPaired()) {
2457       std::swap(Reg1, Reg2);
2458       std::swap(FrameIdxReg1, FrameIdxReg2);
2459     }
2460     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
2461     if (RPI.isPaired()) {
2462       MIB.addReg(Reg2, getDefRegState(true));
2463       MIB.addMemOperand(MF.getMachineMemOperand(
2464           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
2465           MachineMemOperand::MOLoad, Size, Alignment));
2466     }
2467     MIB.addReg(Reg1, getDefRegState(true))
2468         .addReg(AArch64::SP)
2469         .addImm(RPI.Offset) // [sp, #offset*scale]
2470                             // where factor*scale is implicit
2471         .setMIFlag(MachineInstr::FrameDestroy);
2472     MIB.addMemOperand(MF.getMachineMemOperand(
2473         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
2474         MachineMemOperand::MOLoad, Size, Alignment));
2475     if (NeedsWinCFI)
2476       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
2477   };
2478 
2479   // SVE objects are always restored in reverse order.
2480   for (const RegPairInfo &RPI : reverse(RegPairs))
2481     if (RPI.isScalable())
2482       EmitMI(RPI);
2483 
2484   if (ReverseCSRRestoreSeq) {
2485     for (const RegPairInfo &RPI : reverse(RegPairs))
2486       if (!RPI.isScalable())
2487         EmitMI(RPI);
2488   } else
2489     for (const RegPairInfo &RPI : RegPairs)
2490       if (!RPI.isScalable())
2491         EmitMI(RPI);
2492 
2493   if (NeedShadowCallStackProlog) {
2494     // Shadow call stack epilog: ldr x30, [x18, #-8]!
2495     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
2496         .addReg(AArch64::X18, RegState::Define)
2497         .addReg(AArch64::LR, RegState::Define)
2498         .addReg(AArch64::X18)
2499         .addImm(-8)
2500         .setMIFlag(MachineInstr::FrameDestroy);
2501   }
2502 
2503   return true;
2504 }
2505 
2506 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
2507                                                 BitVector &SavedRegs,
2508                                                 RegScavenger *RS) const {
2509   // All calls are tail calls in GHC calling conv, and functions have no
2510   // prologue/epilogue.
2511   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
2512     return;
2513 
2514   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2515   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2516       MF.getSubtarget().getRegisterInfo());
2517   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2518   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2519   unsigned UnspilledCSGPR = AArch64::NoRegister;
2520   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2521 
2522   MachineFrameInfo &MFI = MF.getFrameInfo();
2523   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2524 
2525   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2526                                 ? RegInfo->getBaseRegister()
2527                                 : (unsigned)AArch64::NoRegister;
2528 
2529   unsigned ExtraCSSpill = 0;
2530   // Figure out which callee-saved registers to save/restore.
2531   for (unsigned i = 0; CSRegs[i]; ++i) {
2532     const unsigned Reg = CSRegs[i];
2533 
2534     // Add the base pointer register to SavedRegs if it is callee-save.
2535     if (Reg == BasePointerReg)
2536       SavedRegs.set(Reg);
2537 
2538     bool RegUsed = SavedRegs.test(Reg);
2539     unsigned PairedReg = AArch64::NoRegister;
2540     if (AArch64::GPR64RegClass.contains(Reg) ||
2541         AArch64::FPR64RegClass.contains(Reg) ||
2542         AArch64::FPR128RegClass.contains(Reg))
2543       PairedReg = CSRegs[i ^ 1];
2544 
2545     if (!RegUsed) {
2546       if (AArch64::GPR64RegClass.contains(Reg) &&
2547           !RegInfo->isReservedReg(MF, Reg)) {
2548         UnspilledCSGPR = Reg;
2549         UnspilledCSGPRPaired = PairedReg;
2550       }
2551       continue;
2552     }
2553 
2554     // MachO's compact unwind format relies on all registers being stored in
2555     // pairs.
2556     // FIXME: the usual format is actually better if unwinding isn't needed.
2557     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
2558         !SavedRegs.test(PairedReg)) {
2559       SavedRegs.set(PairedReg);
2560       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2561           !RegInfo->isReservedReg(MF, PairedReg))
2562         ExtraCSSpill = PairedReg;
2563     }
2564   }
2565 
2566   if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
2567       !Subtarget.isTargetWindows()) {
2568     // For Windows calling convention on a non-windows OS, where X18 is treated
2569     // as reserved, back up X18 when entering non-windows code (marked with the
2570     // Windows calling convention) and restore when returning regardless of
2571     // whether the individual function uses it - it might call other functions
2572     // that clobber it.
2573     SavedRegs.set(AArch64::X18);
2574   }
2575 
2576   // Calculates the callee saved stack size.
2577   unsigned CSStackSize = 0;
2578   unsigned SVECSStackSize = 0;
2579   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2580   const MachineRegisterInfo &MRI = MF.getRegInfo();
2581   for (unsigned Reg : SavedRegs.set_bits()) {
2582     auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
2583     if (AArch64::PPRRegClass.contains(Reg) ||
2584         AArch64::ZPRRegClass.contains(Reg))
2585       SVECSStackSize += RegSize;
2586     else
2587       CSStackSize += RegSize;
2588   }
2589 
2590   // Save number of saved regs, so we can easily update CSStackSize later.
2591   unsigned NumSavedRegs = SavedRegs.count();
2592 
2593   // The frame record needs to be created by saving the appropriate registers
2594   uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
2595   if (hasFP(MF) ||
2596       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2597     SavedRegs.set(AArch64::FP);
2598     SavedRegs.set(AArch64::LR);
2599   }
2600 
2601   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2602              for (unsigned Reg
2603                   : SavedRegs.set_bits()) dbgs()
2604              << ' ' << printReg(Reg, RegInfo);
2605              dbgs() << "\n";);
2606 
2607   // If any callee-saved registers are used, the frame cannot be eliminated.
2608   int64_t SVEStackSize =
2609       alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
2610   bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2611 
2612   // The CSR spill slots have not been allocated yet, so estimateStackSize
2613   // won't include them.
2614   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2615 
2616   // Conservatively always assume BigStack when there are SVE spills.
2617   bool BigStack = SVEStackSize ||
2618                   (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2619   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2620     AFI->setHasStackFrame(true);
2621 
2622   // Estimate if we might need to scavenge a register at some point in order
2623   // to materialize a stack offset. If so, either spill one additional
2624   // callee-saved register or reserve a special spill slot to facilitate
2625   // register scavenging. If we already spilled an extra callee-saved register
2626   // above to keep the number of spills even, we don't need to do anything else
2627   // here.
2628   if (BigStack) {
2629     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2630       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2631                         << " to get a scratch register.\n");
2632       SavedRegs.set(UnspilledCSGPR);
2633       // MachO's compact unwind format relies on all registers being stored in
2634       // pairs, so if we need to spill one extra for BigStack, then we need to
2635       // store the pair.
2636       if (produceCompactUnwindFrame(MF))
2637         SavedRegs.set(UnspilledCSGPRPaired);
2638       ExtraCSSpill = UnspilledCSGPR;
2639     }
2640 
2641     // If we didn't find an extra callee-saved register to spill, create
2642     // an emergency spill slot.
2643     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2644       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2645       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2646       unsigned Size = TRI->getSpillSize(RC);
2647       Align Alignment = TRI->getSpillAlign(RC);
2648       int FI = MFI.CreateStackObject(Size, Alignment, false);
2649       RS->addScavengingFrameIndex(FI);
2650       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2651                         << " as the emergency spill slot.\n");
2652     }
2653   }
2654 
2655   // Adding the size of additional 64bit GPR saves.
2656   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2657   uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
2658   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2659                << EstimatedStackSize + AlignedCSStackSize
2660                << " bytes.\n");
2661 
2662   assert((!MFI.isCalleeSavedInfoValid() ||
2663           AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2664          "Should not invalidate callee saved info");
2665 
2666   // Round up to register pair alignment to avoid additional SP adjustment
2667   // instructions.
2668   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2669   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2670   AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
2671 }
2672 
2673 bool AArch64FrameLowering::enableStackSlotScavenging(
2674     const MachineFunction &MF) const {
2675   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2676   return AFI->hasCalleeSaveStackFreeSpace();
2677 }
2678 
2679 /// returns true if there are any SVE callee saves.
2680 static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
2681                                       int &Min, int &Max) {
2682   Min = std::numeric_limits<int>::max();
2683   Max = std::numeric_limits<int>::min();
2684 
2685   if (!MFI.isCalleeSavedInfoValid())
2686     return false;
2687 
2688   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
2689   for (auto &CS : CSI) {
2690     if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
2691         AArch64::PPRRegClass.contains(CS.getReg())) {
2692       assert((Max == std::numeric_limits<int>::min() ||
2693               Max + 1 == CS.getFrameIdx()) &&
2694              "SVE CalleeSaves are not consecutive");
2695 
2696       Min = std::min(Min, CS.getFrameIdx());
2697       Max = std::max(Max, CS.getFrameIdx());
2698     }
2699   }
2700   return Min != std::numeric_limits<int>::max();
2701 }
2702 
2703 // Process all the SVE stack objects and determine offsets for each
2704 // object. If AssignOffsets is true, the offsets get assigned.
2705 // Fills in the first and last callee-saved frame indices into
2706 // Min/MaxCSFrameIndex, respectively.
2707 // Returns the size of the stack.
2708 static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
2709                                               int &MinCSFrameIndex,
2710                                               int &MaxCSFrameIndex,
2711                                               bool AssignOffsets) {
2712 #ifndef NDEBUG
2713   // First process all fixed stack objects.
2714   for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
2715     assert(MFI.getStackID(I) != TargetStackID::SVEVector &&
2716            "SVE vectors should never be passed on the stack by value, only by "
2717            "reference.");
2718 #endif
2719 
2720   auto Assign = [&MFI](int FI, int64_t Offset) {
2721     LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
2722     MFI.setObjectOffset(FI, Offset);
2723   };
2724 
2725   int64_t Offset = 0;
2726 
2727   // Then process all callee saved slots.
2728   if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
2729     // Assign offsets to the callee save slots.
2730     for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
2731       Offset += MFI.getObjectSize(I);
2732       Offset = alignTo(Offset, MFI.getObjectAlign(I));
2733       if (AssignOffsets)
2734         Assign(I, -Offset);
2735     }
2736   }
2737 
2738   // Ensure that the Callee-save area is aligned to 16bytes.
2739   Offset = alignTo(Offset, Align(16U));
2740 
2741   // Create a buffer of SVE objects to allocate and sort it.
2742   SmallVector<int, 8> ObjectsToAllocate;
2743   for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
2744     unsigned StackID = MFI.getStackID(I);
2745     if (StackID != TargetStackID::SVEVector)
2746       continue;
2747     if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
2748       continue;
2749     if (MFI.isDeadObjectIndex(I))
2750       continue;
2751 
2752     ObjectsToAllocate.push_back(I);
2753   }
2754 
2755   // Allocate all SVE locals and spills
2756   for (unsigned FI : ObjectsToAllocate) {
2757     Align Alignment = MFI.getObjectAlign(FI);
2758     // FIXME: Given that the length of SVE vectors is not necessarily a power of
2759     // two, we'd need to align every object dynamically at runtime if the
2760     // alignment is larger than 16. This is not yet supported.
2761     if (Alignment > Align(16))
2762       report_fatal_error(
2763           "Alignment of scalable vectors > 16 bytes is not yet supported");
2764 
2765     Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
2766     if (AssignOffsets)
2767       Assign(FI, -Offset);
2768   }
2769 
2770   return Offset;
2771 }
2772 
2773 int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
2774     MachineFrameInfo &MFI) const {
2775   int MinCSFrameIndex, MaxCSFrameIndex;
2776   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
2777 }
2778 
2779 int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
2780     MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
2781   return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
2782                                         true);
2783 }
2784 
2785 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2786     MachineFunction &MF, RegScavenger *RS) const {
2787   MachineFrameInfo &MFI = MF.getFrameInfo();
2788 
2789   assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
2790          "Upwards growing stack unsupported");
2791 
2792   int MinCSFrameIndex, MaxCSFrameIndex;
2793   int64_t SVEStackSize =
2794       assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
2795 
2796   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2797   AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
2798   AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
2799 
2800   // If this function isn't doing Win64-style C++ EH, we don't need to do
2801   // anything.
2802   if (!MF.hasEHFunclets())
2803     return;
2804   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2805   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2806 
2807   MachineBasicBlock &MBB = MF.front();
2808   auto MBBI = MBB.begin();
2809   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2810     ++MBBI;
2811 
2812   // Create an UnwindHelp object.
2813   // The UnwindHelp object is allocated at the start of the fixed object area
2814   int64_t FixedObject =
2815       getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
2816   int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
2817                                            /*SPOffset*/ -FixedObject,
2818                                            /*IsImmutable=*/false);
2819   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2820 
2821   // We need to store -2 into the UnwindHelp object at the start of the
2822   // function.
2823   DebugLoc DL;
2824   RS->enterBasicBlockEnd(MBB);
2825   RS->backward(std::prev(MBBI));
2826   unsigned DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
2827   assert(DstReg && "There must be a free register after frame setup");
2828   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2829   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2830       .addReg(DstReg, getKillRegState(true))
2831       .addFrameIndex(UnwindHelpFI)
2832       .addImm(0);
2833 }
2834 
2835 namespace {
2836 struct TagStoreInstr {
2837   MachineInstr *MI;
2838   int64_t Offset, Size;
2839   explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
2840       : MI(MI), Offset(Offset), Size(Size) {}
2841 };
2842 
2843 class TagStoreEdit {
2844   MachineFunction *MF;
2845   MachineBasicBlock *MBB;
2846   MachineRegisterInfo *MRI;
2847   // Tag store instructions that are being replaced.
2848   SmallVector<TagStoreInstr, 8> TagStores;
2849   // Combined memref arguments of the above instructions.
2850   SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
2851 
2852   // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
2853   // FrameRegOffset + Size) with the address tag of SP.
2854   Register FrameReg;
2855   StackOffset FrameRegOffset;
2856   int64_t Size;
2857   // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
2858   Optional<int64_t> FrameRegUpdate;
2859   // MIFlags for any FrameReg updating instructions.
2860   unsigned FrameRegUpdateFlags;
2861 
2862   // Use zeroing instruction variants.
2863   bool ZeroData;
2864   DebugLoc DL;
2865 
2866   void emitUnrolled(MachineBasicBlock::iterator InsertI);
2867   void emitLoop(MachineBasicBlock::iterator InsertI);
2868 
2869 public:
2870   TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
2871       : MBB(MBB), ZeroData(ZeroData) {
2872     MF = MBB->getParent();
2873     MRI = &MF->getRegInfo();
2874   }
2875   // Add an instruction to be replaced. Instructions must be added in the
2876   // ascending order of Offset, and have to be adjacent.
2877   void addInstruction(TagStoreInstr I) {
2878     assert((TagStores.empty() ||
2879             TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
2880            "Non-adjacent tag store instructions.");
2881     TagStores.push_back(I);
2882   }
2883   void clear() { TagStores.clear(); }
2884   // Emit equivalent code at the given location, and erase the current set of
2885   // instructions. May skip if the replacement is not profitable. May invalidate
2886   // the input iterator and replace it with a valid one.
2887   void emitCode(MachineBasicBlock::iterator &InsertI,
2888                 const AArch64FrameLowering *TFI, bool IsLast);
2889 };
2890 
2891 void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
2892   const AArch64InstrInfo *TII =
2893       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
2894 
2895   const int64_t kMinOffset = -256 * 16;
2896   const int64_t kMaxOffset = 255 * 16;
2897 
2898   Register BaseReg = FrameReg;
2899   int64_t BaseRegOffsetBytes = FrameRegOffset.getBytes();
2900   if (BaseRegOffsetBytes < kMinOffset ||
2901       BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
2902     Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2903     emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
2904                     {BaseRegOffsetBytes, MVT::i8}, TII);
2905     BaseReg = ScratchReg;
2906     BaseRegOffsetBytes = 0;
2907   }
2908 
2909   MachineInstr *LastI = nullptr;
2910   while (Size) {
2911     int64_t InstrSize = (Size > 16) ? 32 : 16;
2912     unsigned Opcode =
2913         InstrSize == 16
2914             ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
2915             : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
2916     MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
2917                           .addReg(AArch64::SP)
2918                           .addReg(BaseReg)
2919                           .addImm(BaseRegOffsetBytes / 16)
2920                           .setMemRefs(CombinedMemRefs);
2921     // A store to [BaseReg, #0] should go last for an opportunity to fold the
2922     // final SP adjustment in the epilogue.
2923     if (BaseRegOffsetBytes == 0)
2924       LastI = I;
2925     BaseRegOffsetBytes += InstrSize;
2926     Size -= InstrSize;
2927   }
2928 
2929   if (LastI)
2930     MBB->splice(InsertI, MBB, LastI);
2931 }
2932 
2933 void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
2934   const AArch64InstrInfo *TII =
2935       MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
2936 
2937   Register BaseReg = FrameRegUpdate
2938                          ? FrameReg
2939                          : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2940   Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
2941 
2942   emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
2943 
2944   int64_t LoopSize = Size;
2945   // If the loop size is not a multiple of 32, split off one 16-byte store at
2946   // the end to fold BaseReg update into.
2947   if (FrameRegUpdate && *FrameRegUpdate)
2948     LoopSize -= LoopSize % 32;
2949   MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
2950                                 TII->get(ZeroData ? AArch64::STZGloop_wback
2951                                                   : AArch64::STGloop_wback))
2952                             .addDef(SizeReg)
2953                             .addDef(BaseReg)
2954                             .addImm(LoopSize)
2955                             .addReg(BaseReg)
2956                             .setMemRefs(CombinedMemRefs);
2957   if (FrameRegUpdate)
2958     LoopI->setFlags(FrameRegUpdateFlags);
2959 
2960   int64_t ExtraBaseRegUpdate =
2961       FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getBytes() - Size) : 0;
2962   if (LoopSize < Size) {
2963     assert(FrameRegUpdate);
2964     assert(Size - LoopSize == 16);
2965     // Tag 16 more bytes at BaseReg and update BaseReg.
2966     BuildMI(*MBB, InsertI, DL,
2967             TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
2968         .addDef(BaseReg)
2969         .addReg(BaseReg)
2970         .addReg(BaseReg)
2971         .addImm(1 + ExtraBaseRegUpdate / 16)
2972         .setMemRefs(CombinedMemRefs)
2973         .setMIFlags(FrameRegUpdateFlags);
2974   } else if (ExtraBaseRegUpdate) {
2975     // Update BaseReg.
2976     BuildMI(
2977         *MBB, InsertI, DL,
2978         TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
2979         .addDef(BaseReg)
2980         .addReg(BaseReg)
2981         .addImm(std::abs(ExtraBaseRegUpdate))
2982         .addImm(0)
2983         .setMIFlags(FrameRegUpdateFlags);
2984   }
2985 }
2986 
2987 // Check if *II is a register update that can be merged into STGloop that ends
2988 // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
2989 // end of the loop.
2990 bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
2991                        int64_t Size, int64_t *TotalOffset) {
2992   MachineInstr &MI = *II;
2993   if ((MI.getOpcode() == AArch64::ADDXri ||
2994        MI.getOpcode() == AArch64::SUBXri) &&
2995       MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
2996     unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
2997     int64_t Offset = MI.getOperand(2).getImm() << Shift;
2998     if (MI.getOpcode() == AArch64::SUBXri)
2999       Offset = -Offset;
3000     int64_t AbsPostOffset = std::abs(Offset - Size);
3001     const int64_t kMaxOffset =
3002         0xFFF; // Max encoding for unshifted ADDXri / SUBXri
3003     if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
3004       *TotalOffset = Offset;
3005       return true;
3006     }
3007   }
3008   return false;
3009 }
3010 
3011 void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
3012                   SmallVectorImpl<MachineMemOperand *> &MemRefs) {
3013   MemRefs.clear();
3014   for (auto &TS : TSE) {
3015     MachineInstr *MI = TS.MI;
3016     // An instruction without memory operands may access anything. Be
3017     // conservative and return an empty list.
3018     if (MI->memoperands_empty()) {
3019       MemRefs.clear();
3020       return;
3021     }
3022     MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
3023   }
3024 }
3025 
3026 void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
3027                             const AArch64FrameLowering *TFI, bool IsLast) {
3028   if (TagStores.empty())
3029     return;
3030   TagStoreInstr &FirstTagStore = TagStores[0];
3031   TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
3032   Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
3033   DL = TagStores[0].MI->getDebugLoc();
3034 
3035   Register Reg;
3036   FrameRegOffset = TFI->resolveFrameOffsetReference(
3037       *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
3038       /*PreferFP=*/false, /*ForSimm=*/true);
3039   FrameReg = Reg;
3040   FrameRegUpdate = None;
3041 
3042   mergeMemRefs(TagStores, CombinedMemRefs);
3043 
3044   LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
3045              for (const auto &Instr
3046                   : TagStores) { dbgs() << "  " << *Instr.MI; });
3047 
3048   // Size threshold where a loop becomes shorter than a linear sequence of
3049   // tagging instructions.
3050   const int kSetTagLoopThreshold = 176;
3051   if (Size < kSetTagLoopThreshold) {
3052     if (TagStores.size() < 2)
3053       return;
3054     emitUnrolled(InsertI);
3055   } else {
3056     MachineInstr *UpdateInstr = nullptr;
3057     int64_t TotalOffset;
3058     if (IsLast) {
3059       // See if we can merge base register update into the STGloop.
3060       // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3061       // but STGloop is way too unusual for that, and also it only
3062       // realistically happens in function epilogue. Also, STGloop is expanded
3063       // before that pass.
3064       if (InsertI != MBB->end() &&
3065           canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getBytes() + Size,
3066                             &TotalOffset)) {
3067         UpdateInstr = &*InsertI++;
3068         LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n  "
3069                           << *UpdateInstr);
3070       }
3071     }
3072 
3073     if (!UpdateInstr && TagStores.size() < 2)
3074       return;
3075 
3076     if (UpdateInstr) {
3077       FrameRegUpdate = TotalOffset;
3078       FrameRegUpdateFlags = UpdateInstr->getFlags();
3079     }
3080     emitLoop(InsertI);
3081     if (UpdateInstr)
3082       UpdateInstr->eraseFromParent();
3083   }
3084 
3085   for (auto &TS : TagStores)
3086     TS.MI->eraseFromParent();
3087 }
3088 
3089 bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
3090                                         int64_t &Size, bool &ZeroData) {
3091   MachineFunction &MF = *MI.getParent()->getParent();
3092   const MachineFrameInfo &MFI = MF.getFrameInfo();
3093 
3094   unsigned Opcode = MI.getOpcode();
3095   ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
3096               Opcode == AArch64::STZ2GOffset);
3097 
3098   if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
3099     if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
3100       return false;
3101     if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
3102       return false;
3103     Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
3104     Size = MI.getOperand(2).getImm();
3105     return true;
3106   }
3107 
3108   if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
3109     Size = 16;
3110   else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
3111     Size = 32;
3112   else
3113     return false;
3114 
3115   if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3116     return false;
3117 
3118   Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3119            16 * MI.getOperand(2).getImm();
3120   return true;
3121 }
3122 
3123 // Detect a run of memory tagging instructions for adjacent stack frame slots,
3124 // and replace them with a shorter instruction sequence:
3125 // * replace STG + STG with ST2G
3126 // * replace STGloop + STGloop with STGloop
3127 // This code needs to run when stack slot offsets are already known, but before
3128 // FrameIndex operands in STG instructions are eliminated.
3129 MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
3130                                                 const AArch64FrameLowering *TFI,
3131                                                 RegScavenger *RS) {
3132   bool FirstZeroData;
3133   int64_t Size, Offset;
3134   MachineInstr &MI = *II;
3135   MachineBasicBlock *MBB = MI.getParent();
3136   MachineBasicBlock::iterator NextI = ++II;
3137   if (&MI == &MBB->instr_back())
3138     return II;
3139   if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3140     return II;
3141 
3142   SmallVector<TagStoreInstr, 4> Instrs;
3143   Instrs.emplace_back(&MI, Offset, Size);
3144 
3145   constexpr int kScanLimit = 10;
3146   int Count = 0;
3147   for (MachineBasicBlock::iterator E = MBB->end();
3148        NextI != E && Count < kScanLimit; ++NextI) {
3149     MachineInstr &MI = *NextI;
3150     bool ZeroData;
3151     int64_t Size, Offset;
3152     // Collect instructions that update memory tags with a FrameIndex operand
3153     // and (when applicable) constant size, and whose output registers are dead
3154     // (the latter is almost always the case in practice). Since these
3155     // instructions effectively have no inputs or outputs, we are free to skip
3156     // any non-aliasing instructions in between without tracking used registers.
3157     if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3158       if (ZeroData != FirstZeroData)
3159         break;
3160       Instrs.emplace_back(&MI, Offset, Size);
3161       continue;
3162     }
3163 
3164     // Only count non-transient, non-tagging instructions toward the scan
3165     // limit.
3166     if (!MI.isTransient())
3167       ++Count;
3168 
3169     // Just in case, stop before the epilogue code starts.
3170     if (MI.getFlag(MachineInstr::FrameSetup) ||
3171         MI.getFlag(MachineInstr::FrameDestroy))
3172       break;
3173 
3174     // Reject anything that may alias the collected instructions.
3175     if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
3176       break;
3177   }
3178 
3179   // New code will be inserted after the last tagging instruction we've found.
3180   MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3181   InsertI++;
3182 
3183   llvm::stable_sort(Instrs,
3184                     [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3185                       return Left.Offset < Right.Offset;
3186                     });
3187 
3188   // Make sure that we don't have any overlapping stores.
3189   int64_t CurOffset = Instrs[0].Offset;
3190   for (auto &Instr : Instrs) {
3191     if (CurOffset > Instr.Offset)
3192       return NextI;
3193     CurOffset = Instr.Offset + Instr.Size;
3194   }
3195 
3196   // Find contiguous runs of tagged memory and emit shorter instruction
3197   // sequencies for them when possible.
3198   TagStoreEdit TSE(MBB, FirstZeroData);
3199   Optional<int64_t> EndOffset;
3200   for (auto &Instr : Instrs) {
3201     if (EndOffset && *EndOffset != Instr.Offset) {
3202       // Found a gap.
3203       TSE.emitCode(InsertI, TFI, /*IsLast = */ false);
3204       TSE.clear();
3205     }
3206 
3207     TSE.addInstruction(Instr);
3208     EndOffset = Instr.Offset + Instr.Size;
3209   }
3210 
3211   TSE.emitCode(InsertI, TFI, /*IsLast = */ true);
3212 
3213   return InsertI;
3214 }
3215 } // namespace
3216 
3217 void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3218     MachineFunction &MF, RegScavenger *RS = nullptr) const {
3219   if (StackTaggingMergeSetTag)
3220     for (auto &BB : MF)
3221       for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
3222         II = tryMergeAdjacentSTG(II, this, RS);
3223 }
3224 
3225 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3226 /// before the update.  This is easily retrieved as it is exactly the offset
3227 /// that is set in processFunctionBeforeFrameFinalized.
3228 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
3229     const MachineFunction &MF, int FI, Register &FrameReg,
3230     bool IgnoreSPUpdates) const {
3231   const MachineFrameInfo &MFI = MF.getFrameInfo();
3232   if (IgnoreSPUpdates) {
3233     LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3234                       << MFI.getObjectOffset(FI) << "\n");
3235     FrameReg = AArch64::SP;
3236     return MFI.getObjectOffset(FI);
3237   }
3238 
3239   return getFrameIndexReference(MF, FI, FrameReg);
3240 }
3241 
3242 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3243 /// the parent's frame pointer
3244 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
3245     const MachineFunction &MF) const {
3246   return 0;
3247 }
3248 
3249 /// Funclets only need to account for space for the callee saved registers,
3250 /// as the locals are accounted for in the parent's stack frame.
3251 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
3252     const MachineFunction &MF) const {
3253   // This is the size of the pushed CSRs.
3254   unsigned CSSize =
3255       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3256   // This is the amount of stack a funclet needs to allocate.
3257   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3258                  getStackAlign());
3259 }
3260