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 // | prev_fp, prev_lr                  |
48 // | (a.k.a. "frame record")           |
49 // |-----------------------------------| <- fp(=x29)
50 // |                                   |
51 // | other callee-saved registers      |
52 // |                                   |
53 // |-----------------------------------|
54 // |.empty.space.to.make.part.below....|
55 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
56 // |.the.standard.16-byte.alignment....|  compile time; if present)
57 // |-----------------------------------|
58 // |                                   |
59 // | local variables of fixed size     |
60 // | including spill slots             |
61 // |-----------------------------------| <- bp(not defined by ABI,
62 // |.variable-sized.local.variables....|       LLVM chooses X19)
63 // |.(VLAs)............................| (size of this area is unknown at
64 // |...................................|  compile time)
65 // |-----------------------------------| <- sp
66 // |                                   | Lower address
67 //
68 //
69 // To access the data in a frame, at-compile time, a constant offset must be
70 // computable from one of the pointers (fp, bp, sp) to access it. The size
71 // of the areas with a dotted background cannot be computed at compile-time
72 // if they are present, making it required to have all three of fp, bp and
73 // sp to be set up to be able to access all contents in the frame areas,
74 // assuming all of the frame areas are non-empty.
75 //
76 // For most functions, some of the frame areas are empty. For those functions,
77 // it may not be necessary to set up fp or bp:
78 // * A base pointer is definitely needed when there are both VLAs and local
79 //   variables with more-than-default alignment requirements.
80 // * A frame pointer is definitely needed when there are local variables with
81 //   more-than-default alignment requirements.
82 //
83 // In some cases when a base pointer is not strictly needed, it is generated
84 // anyway when offsets from the frame pointer to access local variables become
85 // so large that the offset can't be encoded in the immediate fields of loads
86 // or stores.
87 //
88 // FIXME: also explain the redzone concept.
89 // FIXME: also explain the concept of reserved call frames.
90 //
91 //===----------------------------------------------------------------------===//
92 
93 #include "AArch64FrameLowering.h"
94 #include "AArch64InstrInfo.h"
95 #include "AArch64MachineFunctionInfo.h"
96 #include "AArch64RegisterInfo.h"
97 #include "AArch64Subtarget.h"
98 #include "AArch64TargetMachine.h"
99 #include "MCTargetDesc/AArch64AddressingModes.h"
100 #include "llvm/ADT/ScopeExit.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/Statistic.h"
103 #include "llvm/CodeGen/LivePhysRegs.h"
104 #include "llvm/CodeGen/MachineBasicBlock.h"
105 #include "llvm/CodeGen/MachineFrameInfo.h"
106 #include "llvm/CodeGen/MachineFunction.h"
107 #include "llvm/CodeGen/MachineInstr.h"
108 #include "llvm/CodeGen/MachineInstrBuilder.h"
109 #include "llvm/CodeGen/MachineMemOperand.h"
110 #include "llvm/CodeGen/MachineModuleInfo.h"
111 #include "llvm/CodeGen/MachineOperand.h"
112 #include "llvm/CodeGen/MachineRegisterInfo.h"
113 #include "llvm/CodeGen/RegisterScavenging.h"
114 #include "llvm/CodeGen/TargetInstrInfo.h"
115 #include "llvm/CodeGen/TargetRegisterInfo.h"
116 #include "llvm/CodeGen/TargetSubtargetInfo.h"
117 #include "llvm/CodeGen/WinEHFuncInfo.h"
118 #include "llvm/IR/Attributes.h"
119 #include "llvm/IR/CallingConv.h"
120 #include "llvm/IR/DataLayout.h"
121 #include "llvm/IR/DebugLoc.h"
122 #include "llvm/IR/Function.h"
123 #include "llvm/MC/MCAsmInfo.h"
124 #include "llvm/MC/MCDwarf.h"
125 #include "llvm/Support/CommandLine.h"
126 #include "llvm/Support/Debug.h"
127 #include "llvm/Support/ErrorHandling.h"
128 #include "llvm/Support/MathExtras.h"
129 #include "llvm/Support/raw_ostream.h"
130 #include "llvm/Target/TargetMachine.h"
131 #include "llvm/Target/TargetOptions.h"
132 #include <cassert>
133 #include <cstdint>
134 #include <iterator>
135 #include <vector>
136 
137 using namespace llvm;
138 
139 #define DEBUG_TYPE "frame-info"
140 
141 static cl::opt<bool> EnableRedZone("aarch64-redzone",
142                                    cl::desc("enable use of redzone on AArch64"),
143                                    cl::init(false), cl::Hidden);
144 
145 static cl::opt<bool>
146     ReverseCSRRestoreSeq("reverse-csr-restore-seq",
147                          cl::desc("reverse the CSR restore sequence"),
148                          cl::init(false), cl::Hidden);
149 
150 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
151 
152 /// This is the biggest offset to the stack pointer we can encode in aarch64
153 /// instructions (without using a separate calculation and a temp register).
154 /// Note that the exception here are vector stores/loads which cannot encode any
155 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
156 static const unsigned DefaultSafeSPDisplacement = 255;
157 
158 /// Look at each instruction that references stack frames and return the stack
159 /// size limit beyond which some of these instructions will require a scratch
160 /// register during their expansion later.
161 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
162   // FIXME: For now, just conservatively guestimate based on unscaled indexing
163   // range. We'll end up allocating an unnecessary spill slot a lot, but
164   // realistically that's not a big deal at this stage of the game.
165   for (MachineBasicBlock &MBB : MF) {
166     for (MachineInstr &MI : MBB) {
167       if (MI.isDebugInstr() || MI.isPseudo() ||
168           MI.getOpcode() == AArch64::ADDXri ||
169           MI.getOpcode() == AArch64::ADDSXri)
170         continue;
171 
172       for (const MachineOperand &MO : MI.operands()) {
173         if (!MO.isFI())
174           continue;
175 
176         int Offset = 0;
177         if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
178             AArch64FrameOffsetCannotUpdate)
179           return 0;
180       }
181     }
182   }
183   return DefaultSafeSPDisplacement;
184 }
185 
186 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
187   if (!EnableRedZone)
188     return false;
189   // Don't use the red zone if the function explicitly asks us not to.
190   // This is typically used for kernel code.
191   if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
192     return false;
193 
194   const MachineFrameInfo &MFI = MF.getFrameInfo();
195   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
196   unsigned NumBytes = AFI->getLocalStackSize();
197 
198   return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
199 }
200 
201 /// hasFP - Return true if the specified function should have a dedicated frame
202 /// pointer register.
203 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
204   const MachineFrameInfo &MFI = MF.getFrameInfo();
205   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
206   // Win64 EH requires a frame pointer if funclets are present, as the locals
207   // are accessed off the frame pointer in both the parent function and the
208   // funclets.
209   if (MF.hasEHFunclets())
210     return true;
211   // Retain behavior of always omitting the FP for leaf functions when possible.
212   if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
213     return true;
214   if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
215       MFI.hasStackMap() || MFI.hasPatchPoint() ||
216       RegInfo->needsStackRealignment(MF))
217     return true;
218   // With large callframes around we may need to use FP to access the scavenging
219   // emergency spillslot.
220   //
221   // Unfortunately some calls to hasFP() like machine verifier ->
222   // getReservedReg() -> hasFP in the middle of global isel are too early
223   // to know the max call frame size. Hopefully conservatively returning "true"
224   // in those cases is fine.
225   // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
226   if (!MFI.isMaxCallFrameSizeComputed() ||
227       MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
228     return true;
229 
230   return false;
231 }
232 
233 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
234 /// not required, we reserve argument space for call sites in the function
235 /// immediately on entry to the current function.  This eliminates the need for
236 /// add/sub sp brackets around call sites.  Returns true if the call frame is
237 /// included as part of the stack frame.
238 bool
239 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
240   return !MF.getFrameInfo().hasVarSizedObjects();
241 }
242 
243 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
244     MachineFunction &MF, MachineBasicBlock &MBB,
245     MachineBasicBlock::iterator I) const {
246   const AArch64InstrInfo *TII =
247       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
248   DebugLoc DL = I->getDebugLoc();
249   unsigned Opc = I->getOpcode();
250   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
251   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
252 
253   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
254   if (!TFI->hasReservedCallFrame(MF)) {
255     unsigned Align = getStackAlignment();
256 
257     int64_t Amount = I->getOperand(0).getImm();
258     Amount = alignTo(Amount, Align);
259     if (!IsDestroy)
260       Amount = -Amount;
261 
262     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
263     // doesn't have to pop anything), then the first operand will be zero too so
264     // this adjustment is a no-op.
265     if (CalleePopAmount == 0) {
266       // FIXME: in-function stack adjustment for calls is limited to 24-bits
267       // because there's no guaranteed temporary register available.
268       //
269       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
270       // 1) For offset <= 12-bit, we use LSL #0
271       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
272       // LSL #0, and the other uses LSL #12.
273       //
274       // Most call frames will be allocated at the start of a function so
275       // this is OK, but it is a limitation that needs dealing with.
276       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
277       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
278     }
279   } else if (CalleePopAmount != 0) {
280     // If the calling convention demands that the callee pops arguments from the
281     // stack, we want to add it back if we have a reserved call frame.
282     assert(CalleePopAmount < 0xffffff && "call frame too large");
283     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
284                     TII);
285   }
286   return MBB.erase(I);
287 }
288 
289 static bool ShouldSignReturnAddress(MachineFunction &MF) {
290   // The function should be signed in the following situations:
291   // - sign-return-address=all
292   // - sign-return-address=non-leaf and the functions spills the LR
293 
294   const Function &F = MF.getFunction();
295   if (!F.hasFnAttribute("sign-return-address"))
296     return false;
297 
298   StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString();
299   if (Scope.equals("none"))
300     return false;
301 
302   if (Scope.equals("all"))
303     return true;
304 
305   assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf");
306 
307   for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo())
308     if (Info.getReg() == AArch64::LR)
309       return true;
310 
311   return false;
312 }
313 
314 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
315     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
316   MachineFunction &MF = *MBB.getParent();
317   MachineFrameInfo &MFI = MF.getFrameInfo();
318   const TargetSubtargetInfo &STI = MF.getSubtarget();
319   const MCRegisterInfo *MRI = STI.getRegisterInfo();
320   const TargetInstrInfo *TII = STI.getInstrInfo();
321   DebugLoc DL = MBB.findDebugLoc(MBBI);
322 
323   // Add callee saved registers to move list.
324   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
325   if (CSI.empty())
326     return;
327 
328   for (const auto &Info : CSI) {
329     unsigned Reg = Info.getReg();
330     int64_t Offset =
331         MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
332     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
333     unsigned CFIIndex = MF.addFrameInst(
334         MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
335     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
336         .addCFIIndex(CFIIndex)
337         .setMIFlags(MachineInstr::FrameSetup);
338   }
339 }
340 
341 // Find a scratch register that we can use at the start of the prologue to
342 // re-align the stack pointer.  We avoid using callee-save registers since they
343 // may appear to be free when this is called from canUseAsPrologue (during
344 // shrink wrapping), but then no longer be free when this is called from
345 // emitPrologue.
346 //
347 // FIXME: This is a bit conservative, since in the above case we could use one
348 // of the callee-save registers as a scratch temp to re-align the stack pointer,
349 // but we would then have to make sure that we were in fact saving at least one
350 // callee-save register in the prologue, which is additional complexity that
351 // doesn't seem worth the benefit.
352 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
353   MachineFunction *MF = MBB->getParent();
354 
355   // If MBB is an entry block, use X9 as the scratch register
356   if (&MF->front() == MBB)
357     return AArch64::X9;
358 
359   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
360   const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
361   LivePhysRegs LiveRegs(TRI);
362   LiveRegs.addLiveIns(*MBB);
363 
364   // Mark callee saved registers as used so we will not choose them.
365   const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
366   for (unsigned i = 0; CSRegs[i]; ++i)
367     LiveRegs.addReg(CSRegs[i]);
368 
369   // Prefer X9 since it was historically used for the prologue scratch reg.
370   const MachineRegisterInfo &MRI = MF->getRegInfo();
371   if (LiveRegs.available(MRI, AArch64::X9))
372     return AArch64::X9;
373 
374   for (unsigned Reg : AArch64::GPR64RegClass) {
375     if (LiveRegs.available(MRI, Reg))
376       return Reg;
377   }
378   return AArch64::NoRegister;
379 }
380 
381 bool AArch64FrameLowering::canUseAsPrologue(
382     const MachineBasicBlock &MBB) const {
383   const MachineFunction *MF = MBB.getParent();
384   MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
385   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
386   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
387 
388   // Don't need a scratch register if we're not going to re-align the stack.
389   if (!RegInfo->needsStackRealignment(*MF))
390     return true;
391   // Otherwise, we can use any block as long as it has a scratch register
392   // available.
393   return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
394 }
395 
396 static bool windowsRequiresStackProbe(MachineFunction &MF,
397                                       unsigned StackSizeInBytes) {
398   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
399   if (!Subtarget.isTargetWindows())
400     return false;
401   const Function &F = MF.getFunction();
402   // TODO: When implementing stack protectors, take that into account
403   // for the probe threshold.
404   unsigned StackProbeSize = 4096;
405   if (F.hasFnAttribute("stack-probe-size"))
406     F.getFnAttribute("stack-probe-size")
407         .getValueAsString()
408         .getAsInteger(0, StackProbeSize);
409   return (StackSizeInBytes >= StackProbeSize) &&
410          !F.hasFnAttribute("no-stack-arg-probe");
411 }
412 
413 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
414     MachineFunction &MF, unsigned StackBumpBytes) const {
415   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
416   const MachineFrameInfo &MFI = MF.getFrameInfo();
417   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
418   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
419 
420   if (AFI->getLocalStackSize() == 0)
421     return false;
422 
423   // 512 is the maximum immediate for stp/ldp that will be used for
424   // callee-save save/restores
425   if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
426     return false;
427 
428   if (MFI.hasVarSizedObjects())
429     return false;
430 
431   if (RegInfo->needsStackRealignment(MF))
432     return false;
433 
434   // This isn't strictly necessary, but it simplifies things a bit since the
435   // current RedZone handling code assumes the SP is adjusted by the
436   // callee-save save/restore code.
437   if (canUseRedZone(MF))
438     return false;
439 
440   return true;
441 }
442 
443 // Given a load or a store instruction, generate an appropriate unwinding SEH
444 // code on Windows.
445 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
446                                              const TargetInstrInfo &TII,
447                                              MachineInstr::MIFlag Flag) {
448   unsigned Opc = MBBI->getOpcode();
449   MachineBasicBlock *MBB = MBBI->getParent();
450   MachineFunction &MF = *MBB->getParent();
451   DebugLoc DL = MBBI->getDebugLoc();
452   unsigned ImmIdx = MBBI->getNumOperands() - 1;
453   int Imm = MBBI->getOperand(ImmIdx).getImm();
454   MachineInstrBuilder MIB;
455   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
456   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
457 
458   switch (Opc) {
459   default:
460     llvm_unreachable("No SEH Opcode for this instruction");
461   case AArch64::LDPDpost:
462     Imm = -Imm;
463     LLVM_FALLTHROUGH;
464   case AArch64::STPDpre: {
465     unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
466     unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
467     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
468               .addImm(Reg0)
469               .addImm(Reg1)
470               .addImm(Imm * 8)
471               .setMIFlag(Flag);
472     break;
473   }
474   case AArch64::LDPXpost:
475     Imm = -Imm;
476     LLVM_FALLTHROUGH;
477   case AArch64::STPXpre: {
478     unsigned Reg0 = MBBI->getOperand(1).getReg();
479     unsigned Reg1 = MBBI->getOperand(2).getReg();
480     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
481       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
482                 .addImm(Imm * 8)
483                 .setMIFlag(Flag);
484     else
485       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
486                 .addImm(RegInfo->getSEHRegNum(Reg0))
487                 .addImm(RegInfo->getSEHRegNum(Reg1))
488                 .addImm(Imm * 8)
489                 .setMIFlag(Flag);
490     break;
491   }
492   case AArch64::LDRDpost:
493     Imm = -Imm;
494     LLVM_FALLTHROUGH;
495   case AArch64::STRDpre: {
496     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
497     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
498               .addImm(Reg)
499               .addImm(Imm)
500               .setMIFlag(Flag);
501     break;
502   }
503   case AArch64::LDRXpost:
504     Imm = -Imm;
505     LLVM_FALLTHROUGH;
506   case AArch64::STRXpre: {
507     unsigned Reg =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
508     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
509               .addImm(Reg)
510               .addImm(Imm)
511               .setMIFlag(Flag);
512     break;
513   }
514   case AArch64::STPDi:
515   case AArch64::LDPDi: {
516     unsigned Reg0 =  RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
517     unsigned Reg1 =  RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
518     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
519               .addImm(Reg0)
520               .addImm(Reg1)
521               .addImm(Imm * 8)
522               .setMIFlag(Flag);
523     break;
524   }
525   case AArch64::STPXi:
526   case AArch64::LDPXi: {
527     unsigned Reg0 = MBBI->getOperand(0).getReg();
528     unsigned Reg1 = MBBI->getOperand(1).getReg();
529     if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
530       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
531                 .addImm(Imm * 8)
532                 .setMIFlag(Flag);
533     else
534       MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
535                 .addImm(RegInfo->getSEHRegNum(Reg0))
536                 .addImm(RegInfo->getSEHRegNum(Reg1))
537                 .addImm(Imm * 8)
538                 .setMIFlag(Flag);
539     break;
540   }
541   case AArch64::STRXui:
542   case AArch64::LDRXui: {
543     int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
544     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
545               .addImm(Reg)
546               .addImm(Imm * 8)
547               .setMIFlag(Flag);
548     break;
549   }
550   case AArch64::STRDui:
551   case AArch64::LDRDui: {
552     unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
553     MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
554               .addImm(Reg)
555               .addImm(Imm * 8)
556               .setMIFlag(Flag);
557     break;
558   }
559   }
560   auto I = MBB->insertAfter(MBBI, MIB);
561   return I;
562 }
563 
564 // Fix up the SEH opcode associated with the save/restore instruction.
565 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
566                            unsigned LocalStackSize) {
567   MachineOperand *ImmOpnd = nullptr;
568   unsigned ImmIdx = MBBI->getNumOperands() - 1;
569   switch (MBBI->getOpcode()) {
570   default:
571     llvm_unreachable("Fix the offset in the SEH instruction");
572   case AArch64::SEH_SaveFPLR:
573   case AArch64::SEH_SaveRegP:
574   case AArch64::SEH_SaveReg:
575   case AArch64::SEH_SaveFRegP:
576   case AArch64::SEH_SaveFReg:
577     ImmOpnd = &MBBI->getOperand(ImmIdx);
578     break;
579   }
580   if (ImmOpnd)
581     ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
582 }
583 
584 // Convert callee-save register save/restore instruction to do stack pointer
585 // decrement/increment to allocate/deallocate the callee-save stack area by
586 // converting store/load to use pre/post increment version.
587 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
588     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
589     const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
590     bool NeedsWinCFI, bool InProlog = true) {
591   // Ignore instructions that do not operate on SP, i.e. shadow call stack
592   // instructions and associated CFI instruction.
593   while (MBBI->getOpcode() == AArch64::STRXpost ||
594          MBBI->getOpcode() == AArch64::LDRXpre ||
595          MBBI->getOpcode() == AArch64::CFI_INSTRUCTION) {
596     if (MBBI->getOpcode() != AArch64::CFI_INSTRUCTION)
597       assert(MBBI->getOperand(0).getReg() != AArch64::SP);
598     ++MBBI;
599   }
600   unsigned NewOpc;
601   int Scale = 1;
602   switch (MBBI->getOpcode()) {
603   default:
604     llvm_unreachable("Unexpected callee-save save/restore opcode!");
605   case AArch64::STPXi:
606     NewOpc = AArch64::STPXpre;
607     Scale = 8;
608     break;
609   case AArch64::STPDi:
610     NewOpc = AArch64::STPDpre;
611     Scale = 8;
612     break;
613   case AArch64::STPQi:
614     NewOpc = AArch64::STPQpre;
615     Scale = 16;
616     break;
617   case AArch64::STRXui:
618     NewOpc = AArch64::STRXpre;
619     break;
620   case AArch64::STRDui:
621     NewOpc = AArch64::STRDpre;
622     break;
623   case AArch64::STRQui:
624     NewOpc = AArch64::STRQpre;
625     break;
626   case AArch64::LDPXi:
627     NewOpc = AArch64::LDPXpost;
628     Scale = 8;
629     break;
630   case AArch64::LDPDi:
631     NewOpc = AArch64::LDPDpost;
632     Scale = 8;
633     break;
634   case AArch64::LDPQi:
635     NewOpc = AArch64::LDPQpost;
636     Scale = 16;
637     break;
638   case AArch64::LDRXui:
639     NewOpc = AArch64::LDRXpost;
640     break;
641   case AArch64::LDRDui:
642     NewOpc = AArch64::LDRDpost;
643     break;
644   case AArch64::LDRQui:
645     NewOpc = AArch64::LDRQpost;
646     break;
647   }
648   // Get rid of the SEH code associated with the old instruction.
649   if (NeedsWinCFI) {
650     auto SEH = std::next(MBBI);
651     if (AArch64InstrInfo::isSEHInstruction(*SEH))
652       SEH->eraseFromParent();
653   }
654 
655   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
656   MIB.addReg(AArch64::SP, RegState::Define);
657 
658   // Copy all operands other than the immediate offset.
659   unsigned OpndIdx = 0;
660   for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
661        ++OpndIdx)
662     MIB.add(MBBI->getOperand(OpndIdx));
663 
664   assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
665          "Unexpected immediate offset in first/last callee-save save/restore "
666          "instruction!");
667   assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
668          "Unexpected base register in callee-save save/restore instruction!");
669   assert(CSStackSizeInc % Scale == 0);
670   MIB.addImm(CSStackSizeInc / Scale);
671 
672   MIB.setMIFlags(MBBI->getFlags());
673   MIB.setMemRefs(MBBI->memoperands());
674 
675   // Generate a new SEH code that corresponds to the new instruction.
676   if (NeedsWinCFI)
677     InsertSEH(*MIB, *TII,
678               InProlog ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy);
679 
680   return std::prev(MBB.erase(MBBI));
681 }
682 
683 // Fixup callee-save register save/restore instructions to take into account
684 // combined SP bump by adding the local stack size to the stack offsets.
685 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
686                                               unsigned LocalStackSize,
687                                               bool NeedsWinCFI) {
688   if (AArch64InstrInfo::isSEHInstruction(MI))
689     return;
690 
691   unsigned Opc = MI.getOpcode();
692 
693   // Ignore instructions that do not operate on SP, i.e. shadow call stack
694   // instructions and associated CFI instruction.
695   if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre ||
696       Opc == AArch64::CFI_INSTRUCTION) {
697     if (Opc != AArch64::CFI_INSTRUCTION)
698       assert(MI.getOperand(0).getReg() != AArch64::SP);
699     return;
700   }
701 
702   unsigned Scale;
703   switch (Opc) {
704   case AArch64::STPXi:
705   case AArch64::STRXui:
706   case AArch64::STPDi:
707   case AArch64::STRDui:
708   case AArch64::LDPXi:
709   case AArch64::LDRXui:
710   case AArch64::LDPDi:
711   case AArch64::LDRDui:
712     Scale = 8;
713     break;
714   case AArch64::STPQi:
715   case AArch64::STRQui:
716   case AArch64::LDPQi:
717   case AArch64::LDRQui:
718     Scale = 16;
719     break;
720   default:
721     llvm_unreachable("Unexpected callee-save save/restore opcode!");
722   }
723 
724   unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
725   assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
726          "Unexpected base register in callee-save save/restore instruction!");
727   // Last operand is immediate offset that needs fixing.
728   MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
729   // All generated opcodes have scaled offsets.
730   assert(LocalStackSize % Scale == 0);
731   OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
732 
733   if (NeedsWinCFI) {
734     auto MBBI = std::next(MachineBasicBlock::iterator(MI));
735     assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
736     assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
737            "Expecting a SEH instruction");
738     fixupSEHOpcode(MBBI, LocalStackSize);
739   }
740 }
741 
742 static void adaptForLdStOpt(MachineBasicBlock &MBB,
743                             MachineBasicBlock::iterator FirstSPPopI,
744                             MachineBasicBlock::iterator LastPopI) {
745   // Sometimes (when we restore in the same order as we save), we can end up
746   // with code like this:
747   //
748   // ldp      x26, x25, [sp]
749   // ldp      x24, x23, [sp, #16]
750   // ldp      x22, x21, [sp, #32]
751   // ldp      x20, x19, [sp, #48]
752   // add      sp, sp, #64
753   //
754   // In this case, it is always better to put the first ldp at the end, so
755   // that the load-store optimizer can run and merge the ldp and the add into
756   // a post-index ldp.
757   // If we managed to grab the first pop instruction, move it to the end.
758   if (ReverseCSRRestoreSeq)
759     MBB.splice(FirstSPPopI, &MBB, LastPopI);
760   // We should end up with something like this now:
761   //
762   // ldp      x24, x23, [sp, #16]
763   // ldp      x22, x21, [sp, #32]
764   // ldp      x20, x19, [sp, #48]
765   // ldp      x26, x25, [sp]
766   // add      sp, sp, #64
767   //
768   // and the load-store optimizer can merge the last two instructions into:
769   //
770   // ldp      x26, x25, [sp], #64
771   //
772 }
773 
774 static bool ShouldSignWithAKey(MachineFunction &MF) {
775   const Function &F = MF.getFunction();
776   if (!F.hasFnAttribute("sign-return-address-key"))
777     return true;
778 
779   const StringRef Key =
780       F.getFnAttribute("sign-return-address-key").getValueAsString();
781   assert(Key.equals_lower("a_key") || Key.equals_lower("b_key"));
782   return Key.equals_lower("a_key");
783 }
784 
785 static bool needsWinCFI(const MachineFunction &MF) {
786   const Function &F = MF.getFunction();
787   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
788          F.needsUnwindTableEntry();
789 }
790 
791 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
792                                         MachineBasicBlock &MBB) const {
793   MachineBasicBlock::iterator MBBI = MBB.begin();
794   const MachineFrameInfo &MFI = MF.getFrameInfo();
795   const Function &F = MF.getFunction();
796   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
797   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
798   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
799   MachineModuleInfo &MMI = MF.getMMI();
800   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
801   bool needsFrameMoves = (MMI.hasDebugInfo() || F.needsUnwindTableEntry()) &&
802                          !MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
803   bool HasFP = hasFP(MF);
804   bool NeedsWinCFI = needsWinCFI(MF);
805   MF.setHasWinCFI(NeedsWinCFI);
806   bool IsFunclet = MBB.isEHFuncletEntry();
807 
808   // At this point, we're going to decide whether or not the function uses a
809   // redzone. In most cases, the function doesn't have a redzone so let's
810   // assume that's false and set it to true in the case that there's a redzone.
811   AFI->setHasRedZone(false);
812 
813   // Debug location must be unknown since the first debug location is used
814   // to determine the end of the prologue.
815   DebugLoc DL;
816 
817   if (ShouldSignReturnAddress(MF)) {
818     if (ShouldSignWithAKey(MF))
819       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
820           .setMIFlag(MachineInstr::FrameSetup);
821     else {
822       BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
823           .setMIFlag(MachineInstr::FrameSetup);
824       BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIBSP))
825           .setMIFlag(MachineInstr::FrameSetup);
826     }
827 
828     unsigned CFIIndex =
829         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
830     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
831         .addCFIIndex(CFIIndex)
832         .setMIFlags(MachineInstr::FrameSetup);
833   }
834 
835   // All calls are tail calls in GHC calling conv, and functions have no
836   // prologue/epilogue.
837   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
838     return;
839 
840   // getStackSize() includes all the locals in its size calculation. We don't
841   // include these locals when computing the stack size of a funclet, as they
842   // are allocated in the parent's stack frame and accessed via the frame
843   // pointer from the funclet.  We only save the callee saved registers in the
844   // funclet, which are really the callee saved registers of the parent
845   // function, including the funclet.
846   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
847                            : (int)MFI.getStackSize();
848   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
849     assert(!HasFP && "unexpected function without stack frame but with FP");
850     // All of the stack allocation is for locals.
851     AFI->setLocalStackSize(NumBytes);
852     if (!NumBytes)
853       return;
854     // REDZONE: If the stack size is less than 128 bytes, we don't need
855     // to actually allocate.
856     if (canUseRedZone(MF)) {
857       AFI->setHasRedZone(true);
858       ++NumRedZoneFunctions;
859     } else {
860       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
861                       MachineInstr::FrameSetup, false, NeedsWinCFI);
862       if (!NeedsWinCFI) {
863         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
864         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
865         // Encode the stack size of the leaf function.
866         unsigned CFIIndex = MF.addFrameInst(
867             MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
868         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
869             .addCFIIndex(CFIIndex)
870             .setMIFlags(MachineInstr::FrameSetup);
871       }
872     }
873 
874     if (NeedsWinCFI)
875       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
876           .setMIFlag(MachineInstr::FrameSetup);
877 
878     return;
879   }
880 
881   bool IsWin64 =
882       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
883   // Var args are accounted for in the containing function, so don't
884   // include them for funclets.
885   unsigned FixedObject = (IsWin64 && !IsFunclet) ?
886                          alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
887 
888   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
889   // All of the remaining stack allocations are for locals.
890   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
891   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
892   if (CombineSPBump) {
893     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
894                     MachineInstr::FrameSetup, false, NeedsWinCFI);
895     NumBytes = 0;
896   } else if (PrologueSaveSize != 0) {
897     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
898         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI);
899     NumBytes -= PrologueSaveSize;
900   }
901   assert(NumBytes >= 0 && "Negative stack allocation size!?");
902 
903   // Move past the saves of the callee-saved registers, fixing up the offsets
904   // and pre-inc if we decided to combine the callee-save and local stack
905   // pointer bump above.
906   MachineBasicBlock::iterator End = MBB.end();
907   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
908     if (CombineSPBump)
909       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
910                                         NeedsWinCFI);
911     ++MBBI;
912   }
913 
914   // The code below is not applicable to funclets. We have emitted all the SEH
915   // opcodes that we needed to emit.  The FP and BP belong to the containing
916   // function.
917   if (IsFunclet) {
918     if (NeedsWinCFI)
919       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
920           .setMIFlag(MachineInstr::FrameSetup);
921 
922     // SEH funclets are passed the frame pointer in X1.  If the parent
923     // function uses the base register, then the base register is used
924     // directly, and is not retrieved from X1.
925     if (F.hasPersonalityFn()) {
926       EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
927       if (isAsynchronousEHPersonality(Per)) {
928         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
929             .addReg(AArch64::X1).setMIFlag(MachineInstr::FrameSetup);
930         MBB.addLiveIn(AArch64::X1);
931       }
932     }
933 
934     return;
935   }
936 
937   if (HasFP) {
938     // Only set up FP if we actually need to. Frame pointer is fp =
939     // sp - fixedobject - 16.
940     int FPOffset = AFI->getCalleeSavedStackSize() - 16;
941     if (CombineSPBump)
942       FPOffset += AFI->getLocalStackSize();
943 
944     // Issue    sub fp, sp, FPOffset or
945     //          mov fp,sp          when FPOffset is zero.
946     // Note: All stores of callee-saved registers are marked as "FrameSetup".
947     // This code marks the instruction(s) that set the FP also.
948     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
949                     MachineInstr::FrameSetup, false, NeedsWinCFI);
950   }
951 
952   if (windowsRequiresStackProbe(MF, NumBytes)) {
953     uint32_t NumWords = NumBytes >> 4;
954     if (NeedsWinCFI) {
955       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
956       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
957       // This is at most two instructions, MOVZ follwed by MOVK.
958       // TODO: Fix to use multiple stack alloc unwind codes for stacks
959       // exceeding 256MB in size.
960       if (NumBytes >= (1 << 28))
961         report_fatal_error("Stack size cannot exceed 256MB for stack "
962                             "unwinding purposes");
963 
964       uint32_t LowNumWords = NumWords & 0xFFFF;
965       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
966             .addImm(LowNumWords)
967             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
968             .setMIFlag(MachineInstr::FrameSetup);
969       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
970             .setMIFlag(MachineInstr::FrameSetup);
971       if ((NumWords & 0xFFFF0000) != 0) {
972           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
973               .addReg(AArch64::X15)
974               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
975               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
976               .setMIFlag(MachineInstr::FrameSetup);
977           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
978             .setMIFlag(MachineInstr::FrameSetup);
979       }
980     } else {
981       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
982           .addImm(NumWords)
983           .setMIFlags(MachineInstr::FrameSetup);
984     }
985 
986     switch (MF.getTarget().getCodeModel()) {
987     case CodeModel::Tiny:
988     case CodeModel::Small:
989     case CodeModel::Medium:
990     case CodeModel::Kernel:
991       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
992           .addExternalSymbol("__chkstk")
993           .addReg(AArch64::X15, RegState::Implicit)
994           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
995           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
996           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
997           .setMIFlags(MachineInstr::FrameSetup);
998       if (NeedsWinCFI)
999         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1000             .setMIFlag(MachineInstr::FrameSetup);
1001       break;
1002     case CodeModel::Large:
1003       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
1004           .addReg(AArch64::X16, RegState::Define)
1005           .addExternalSymbol("__chkstk")
1006           .addExternalSymbol("__chkstk")
1007           .setMIFlags(MachineInstr::FrameSetup);
1008       if (NeedsWinCFI)
1009         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1010             .setMIFlag(MachineInstr::FrameSetup);
1011 
1012       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
1013           .addReg(AArch64::X16, RegState::Kill)
1014           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
1015           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
1016           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
1017           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
1018           .setMIFlags(MachineInstr::FrameSetup);
1019       if (NeedsWinCFI)
1020         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1021             .setMIFlag(MachineInstr::FrameSetup);
1022       break;
1023     }
1024 
1025     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1026         .addReg(AArch64::SP, RegState::Kill)
1027         .addReg(AArch64::X15, RegState::Kill)
1028         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1029         .setMIFlags(MachineInstr::FrameSetup);
1030     if (NeedsWinCFI)
1031        BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1032             .addImm(NumBytes)
1033             .setMIFlag(MachineInstr::FrameSetup);
1034     NumBytes = 0;
1035   }
1036 
1037   // Allocate space for the rest of the frame.
1038   if (NumBytes) {
1039     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
1040     unsigned scratchSPReg = AArch64::SP;
1041 
1042     if (NeedsRealignment) {
1043       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1044       assert(scratchSPReg != AArch64::NoRegister);
1045     }
1046 
1047     // If we're a leaf function, try using the red zone.
1048     if (!canUseRedZone(MF))
1049       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1050       // the correct value here, as NumBytes also includes padding bytes,
1051       // which shouldn't be counted here.
1052       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
1053                       MachineInstr::FrameSetup, false, NeedsWinCFI);
1054 
1055     if (NeedsRealignment) {
1056       const unsigned Alignment = MFI.getMaxAlignment();
1057       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
1058       assert(NrBitsToZero > 1);
1059       assert(scratchSPReg != AArch64::SP);
1060 
1061       // SUB X9, SP, NumBytes
1062       //   -- X9 is temporary register, so shouldn't contain any live data here,
1063       //   -- free to use. This is already produced by emitFrameOffset above.
1064       // AND SP, X9, 0b11111...0000
1065       // The logical immediates have a non-trivial encoding. The following
1066       // formula computes the encoded immediate with all ones but
1067       // NrBitsToZero zero bits as least significant bits.
1068       uint32_t andMaskEncoded = (1 << 12)                         // = N
1069                                 | ((64 - NrBitsToZero) << 6)      // immr
1070                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1071 
1072       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1073           .addReg(scratchSPReg, RegState::Kill)
1074           .addImm(andMaskEncoded);
1075       AFI->setStackRealigned(true);
1076       if (NeedsWinCFI)
1077         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1078             .addImm(NumBytes & andMaskEncoded)
1079             .setMIFlag(MachineInstr::FrameSetup);
1080     }
1081   }
1082 
1083   // If we need a base pointer, set it up here. It's whatever the value of the
1084   // stack pointer is at this point. Any variable size objects will be allocated
1085   // after this, so we can still use the base pointer to reference locals.
1086   //
1087   // FIXME: Clarify FrameSetup flags here.
1088   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1089   // needed.
1090   if (RegInfo->hasBasePointer(MF)) {
1091     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1092                      false);
1093     if (NeedsWinCFI)
1094       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1095           .setMIFlag(MachineInstr::FrameSetup);
1096   }
1097 
1098   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1099   // SEH opcode indicating the prologue end.
1100   if (NeedsWinCFI)
1101     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1102         .setMIFlag(MachineInstr::FrameSetup);
1103 
1104   if (needsFrameMoves) {
1105     const DataLayout &TD = MF.getDataLayout();
1106     const int StackGrowth = -TD.getPointerSize(0);
1107     unsigned FramePtr = RegInfo->getFrameRegister(MF);
1108     // An example of the prologue:
1109     //
1110     //     .globl __foo
1111     //     .align 2
1112     //  __foo:
1113     // Ltmp0:
1114     //     .cfi_startproc
1115     //     .cfi_personality 155, ___gxx_personality_v0
1116     // Leh_func_begin:
1117     //     .cfi_lsda 16, Lexception33
1118     //
1119     //     stp  xa,bx, [sp, -#offset]!
1120     //     ...
1121     //     stp  x28, x27, [sp, #offset-32]
1122     //     stp  fp, lr, [sp, #offset-16]
1123     //     add  fp, sp, #offset - 16
1124     //     sub  sp, sp, #1360
1125     //
1126     // The Stack:
1127     //       +-------------------------------------------+
1128     // 10000 | ........ | ........ | ........ | ........ |
1129     // 10004 | ........ | ........ | ........ | ........ |
1130     //       +-------------------------------------------+
1131     // 10008 | ........ | ........ | ........ | ........ |
1132     // 1000c | ........ | ........ | ........ | ........ |
1133     //       +===========================================+
1134     // 10010 |                X28 Register               |
1135     // 10014 |                X28 Register               |
1136     //       +-------------------------------------------+
1137     // 10018 |                X27 Register               |
1138     // 1001c |                X27 Register               |
1139     //       +===========================================+
1140     // 10020 |                Frame Pointer              |
1141     // 10024 |                Frame Pointer              |
1142     //       +-------------------------------------------+
1143     // 10028 |                Link Register              |
1144     // 1002c |                Link Register              |
1145     //       +===========================================+
1146     // 10030 | ........ | ........ | ........ | ........ |
1147     // 10034 | ........ | ........ | ........ | ........ |
1148     //       +-------------------------------------------+
1149     // 10038 | ........ | ........ | ........ | ........ |
1150     // 1003c | ........ | ........ | ........ | ........ |
1151     //       +-------------------------------------------+
1152     //
1153     //     [sp] = 10030        ::    >>initial value<<
1154     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1155     //     fp = sp == 10020    ::  mov fp, sp
1156     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1157     //     sp == 10010         ::    >>final value<<
1158     //
1159     // The frame pointer (w29) points to address 10020. If we use an offset of
1160     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1161     // for w27, and -32 for w28:
1162     //
1163     //  Ltmp1:
1164     //     .cfi_def_cfa w29, 16
1165     //  Ltmp2:
1166     //     .cfi_offset w30, -8
1167     //  Ltmp3:
1168     //     .cfi_offset w29, -16
1169     //  Ltmp4:
1170     //     .cfi_offset w27, -24
1171     //  Ltmp5:
1172     //     .cfi_offset w28, -32
1173 
1174     if (HasFP) {
1175       // Define the current CFA rule to use the provided FP.
1176       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1177       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
1178           nullptr, Reg, 2 * StackGrowth - FixedObject));
1179       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1180           .addCFIIndex(CFIIndex)
1181           .setMIFlags(MachineInstr::FrameSetup);
1182     } else {
1183       // Encode the stack size of the leaf function.
1184       unsigned CFIIndex = MF.addFrameInst(
1185           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
1186       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1187           .addCFIIndex(CFIIndex)
1188           .setMIFlags(MachineInstr::FrameSetup);
1189     }
1190 
1191     // Now emit the moves for whatever callee saved regs we have (including FP,
1192     // LR if those are saved).
1193     emitCalleeSavedFrameMoves(MBB, MBBI);
1194   }
1195 }
1196 
1197 static void InsertReturnAddressAuth(MachineFunction &MF,
1198                                     MachineBasicBlock &MBB) {
1199   if (!ShouldSignReturnAddress(MF))
1200     return;
1201   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1202   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1203 
1204   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1205   DebugLoc DL;
1206   if (MBBI != MBB.end())
1207     DL = MBBI->getDebugLoc();
1208 
1209   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1210   // this instruction can safely used for any v8a architecture.
1211   // From v8.3a onwards there are optimised authenticate LR and return
1212   // instructions, namely RETA{A,B}, that can be used instead.
1213   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1214       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1215     BuildMI(MBB, MBBI, DL,
1216             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1217         .copyImplicitOps(*MBBI);
1218     MBB.erase(MBBI);
1219   } else {
1220     BuildMI(
1221         MBB, MBBI, DL,
1222         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1223         .setMIFlag(MachineInstr::FrameDestroy);
1224   }
1225 }
1226 
1227 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1228   switch (MI.getOpcode()) {
1229   default:
1230     return false;
1231   case AArch64::CATCHRET:
1232   case AArch64::CLEANUPRET:
1233     return true;
1234   }
1235 }
1236 
1237 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1238                                         MachineBasicBlock &MBB) const {
1239   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1240   MachineFrameInfo &MFI = MF.getFrameInfo();
1241   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1242   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1243   DebugLoc DL;
1244   bool IsTailCallReturn = false;
1245   bool NeedsWinCFI = needsWinCFI(MF);
1246   bool IsFunclet = false;
1247 
1248   if (MBB.end() != MBBI) {
1249     DL = MBBI->getDebugLoc();
1250     unsigned RetOpcode = MBBI->getOpcode();
1251     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
1252                        RetOpcode == AArch64::TCRETURNri ||
1253                        RetOpcode == AArch64::TCRETURNriBTI;
1254     IsFunclet = isFuncletReturnInstr(*MBBI);
1255   }
1256 
1257   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
1258                            : MFI.getStackSize();
1259   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1260 
1261   // All calls are tail calls in GHC calling conv, and functions have no
1262   // prologue/epilogue.
1263   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1264     return;
1265 
1266   // Initial and residual are named for consistency with the prologue. Note that
1267   // in the epilogue, the residual adjustment is executed first.
1268   uint64_t ArgumentPopSize = 0;
1269   if (IsTailCallReturn) {
1270     MachineOperand &StackAdjust = MBBI->getOperand(1);
1271 
1272     // For a tail-call in a callee-pops-arguments environment, some or all of
1273     // the stack may actually be in use for the call's arguments, this is
1274     // calculated during LowerCall and consumed here...
1275     ArgumentPopSize = StackAdjust.getImm();
1276   } else {
1277     // ... otherwise the amount to pop is *all* of the argument space,
1278     // conveniently stored in the MachineFunctionInfo by
1279     // LowerFormalArguments. This will, of course, be zero for the C calling
1280     // convention.
1281     ArgumentPopSize = AFI->getArgumentStackToRestore();
1282   }
1283 
1284   // The stack frame should be like below,
1285   //
1286   //      ----------------------                     ---
1287   //      |                    |                      |
1288   //      | BytesInStackArgArea|              CalleeArgStackSize
1289   //      | (NumReusableBytes) |                (of tail call)
1290   //      |                    |                     ---
1291   //      |                    |                      |
1292   //      ---------------------|        ---           |
1293   //      |                    |         |            |
1294   //      |   CalleeSavedReg   |         |            |
1295   //      | (CalleeSavedStackSize)|      |            |
1296   //      |                    |         |            |
1297   //      ---------------------|         |         NumBytes
1298   //      |                    |     StackSize  (StackAdjustUp)
1299   //      |   LocalStackSize   |         |            |
1300   //      | (covering callee   |         |            |
1301   //      |       args)        |         |            |
1302   //      |                    |         |            |
1303   //      ----------------------        ---          ---
1304   //
1305   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1306   //             = StackSize + ArgumentPopSize
1307   //
1308   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1309   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1310 
1311   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1312 
1313   bool IsWin64 =
1314       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1315   // Var args are accounted for in the containing function, so don't
1316   // include them for funclets.
1317   unsigned FixedObject =
1318       (IsWin64 && !IsFunclet) ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1319 
1320   uint64_t AfterCSRPopSize = ArgumentPopSize;
1321   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1322   // We cannot rely on the local stack size set in emitPrologue if the function
1323   // has funclets, as funclets have different local stack size requirements, and
1324   // the current value set in emitPrologue may be that of the containing
1325   // function.
1326   if (MF.hasEHFunclets())
1327     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1328   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1329   // Assume we can't combine the last pop with the sp restore.
1330 
1331   if (!CombineSPBump && PrologueSaveSize != 0) {
1332     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1333     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1334       Pop = std::prev(Pop);
1335     // Converting the last ldp to a post-index ldp is valid only if the last
1336     // ldp's offset is 0.
1337     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1338     // If the offset is 0, convert it to a post-index ldp.
1339     if (OffsetOp.getImm() == 0)
1340       convertCalleeSaveRestoreToSPPrePostIncDec(
1341           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, false);
1342     else {
1343       // If not, make sure to emit an add after the last ldp.
1344       // We're doing this by transfering the size to be restored from the
1345       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1346       // pops.
1347       AfterCSRPopSize += PrologueSaveSize;
1348     }
1349   }
1350 
1351   // Move past the restores of the callee-saved registers.
1352   // If we plan on combining the sp bump of the local stack size and the callee
1353   // save stack size, we might need to adjust the CSR save and restore offsets.
1354   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1355   MachineBasicBlock::iterator Begin = MBB.begin();
1356   while (LastPopI != Begin) {
1357     --LastPopI;
1358     if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
1359       ++LastPopI;
1360       break;
1361     } else if (CombineSPBump)
1362       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1363                                         NeedsWinCFI);
1364   }
1365 
1366   if (NeedsWinCFI)
1367     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1368         .setMIFlag(MachineInstr::FrameDestroy);
1369 
1370   // If there is a single SP update, insert it before the ret and we're done.
1371   if (CombineSPBump) {
1372     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1373                     NumBytes + AfterCSRPopSize, TII, MachineInstr::FrameDestroy,
1374                     false, NeedsWinCFI);
1375     if (NeedsWinCFI)
1376       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1377               TII->get(AArch64::SEH_EpilogEnd))
1378           .setMIFlag(MachineInstr::FrameDestroy);
1379     return;
1380   }
1381 
1382   NumBytes -= PrologueSaveSize;
1383   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1384 
1385   if (!hasFP(MF)) {
1386     bool RedZone = canUseRedZone(MF);
1387     // If this was a redzone leaf function, we don't need to restore the
1388     // stack pointer (but we may need to pop stack args for fastcc).
1389     if (RedZone && AfterCSRPopSize == 0)
1390       return;
1391 
1392     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1393     int StackRestoreBytes = RedZone ? 0 : NumBytes;
1394     if (NoCalleeSaveRestore)
1395       StackRestoreBytes += AfterCSRPopSize;
1396 
1397     // If we were able to combine the local stack pop with the argument pop,
1398     // then we're done.
1399     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1400 
1401     // If we're done after this, make sure to help the load store optimizer.
1402     if (Done)
1403       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1404 
1405     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1406                     StackRestoreBytes, TII, MachineInstr::FrameDestroy, false,
1407                     NeedsWinCFI);
1408     if (Done) {
1409       if (NeedsWinCFI)
1410         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1411                 TII->get(AArch64::SEH_EpilogEnd))
1412             .setMIFlag(MachineInstr::FrameDestroy);
1413       return;
1414     }
1415 
1416     NumBytes = 0;
1417   }
1418 
1419   // Restore the original stack pointer.
1420   // FIXME: Rather than doing the math here, we should instead just use
1421   // non-post-indexed loads for the restores if we aren't actually going to
1422   // be able to save any instructions.
1423   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned()))
1424     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1425                     -AFI->getCalleeSavedStackSize() + 16, TII,
1426                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1427   else if (NumBytes)
1428     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
1429                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1430 
1431   // This must be placed after the callee-save restore code because that code
1432   // assumes the SP is at the same location as it was after the callee-save save
1433   // code in the prologue.
1434   if (AfterCSRPopSize) {
1435     // Find an insertion point for the first ldp so that it goes before the
1436     // shadow call stack epilog instruction. This ensures that the restore of
1437     // lr from x18 is placed after the restore from sp.
1438     auto FirstSPPopI = MBB.getFirstTerminator();
1439     while (FirstSPPopI != Begin) {
1440       auto Prev = std::prev(FirstSPPopI);
1441       if (Prev->getOpcode() != AArch64::LDRXpre ||
1442           Prev->getOperand(0).getReg() == AArch64::SP)
1443         break;
1444       FirstSPPopI = Prev;
1445     }
1446 
1447     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1448 
1449     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1450                     AfterCSRPopSize, TII, MachineInstr::FrameDestroy, false,
1451                     NeedsWinCFI);
1452   }
1453   if (NeedsWinCFI)
1454     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1455         .setMIFlag(MachineInstr::FrameDestroy);
1456 }
1457 
1458 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1459 /// debug info.  It's the same as what we use for resolving the code-gen
1460 /// references for now.  FIXME: This can go wrong when references are
1461 /// SP-relative and simple call frames aren't used.
1462 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1463                                                  int FI,
1464                                                  unsigned &FrameReg) const {
1465   return resolveFrameIndexReference(MF, FI, FrameReg);
1466 }
1467 
1468 int AArch64FrameLowering::getNonLocalFrameIndexReference(
1469   const MachineFunction &MF, int FI) const {
1470   return getSEHFrameIndexOffset(MF, FI);
1471 }
1472 
1473 static int getFPOffset(const MachineFunction &MF, int FI) {
1474   const auto &MFI = MF.getFrameInfo();
1475   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1476   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1477   bool IsWin64 =
1478       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1479   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1480   return MFI.getObjectOffset(FI) + FixedObject + 16;
1481 }
1482 
1483 static int getStackOffset(const MachineFunction &MF, int FI) {
1484   const auto &MFI = MF.getFrameInfo();
1485   return MFI.getObjectOffset(FI) + MFI.getStackSize();
1486 }
1487 
1488 int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
1489                                                  int FI) const {
1490   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1491       MF.getSubtarget().getRegisterInfo());
1492   return RegInfo->getLocalAddressRegister(MF) == AArch64::FP ?
1493          getFPOffset(MF, FI) : getStackOffset(MF, FI);
1494 }
1495 
1496 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
1497                                                      int FI, unsigned &FrameReg,
1498                                                      bool PreferFP) const {
1499   const auto &MFI = MF.getFrameInfo();
1500   const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
1501       MF.getSubtarget().getRegisterInfo());
1502   const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1503   const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1504   int FPOffset = getFPOffset(MF, FI);
1505   int Offset = getStackOffset(MF, FI);
1506   bool isFixed = MFI.isFixedObjectIndex(FI);
1507   bool isCSR = !isFixed && MFI.getObjectOffset(FI) >=
1508                                -((int)AFI->getCalleeSavedStackSize());
1509 
1510   // Use frame pointer to reference fixed objects. Use it for locals if
1511   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1512   // reliable as a base). Make sure useFPForScavengingIndex() does the
1513   // right thing for the emergency spill slot.
1514   bool UseFP = false;
1515   if (AFI->hasStackFrame()) {
1516     // Note: Keeping the following as multiple 'if' statements rather than
1517     // merging to a single expression for readability.
1518     //
1519     // Argument access should always use the FP.
1520     if (isFixed) {
1521       UseFP = hasFP(MF);
1522     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1523       // References to the CSR area must use FP if we're re-aligning the stack
1524       // since the dynamically-sized alignment padding is between the SP/BP and
1525       // the CSR area.
1526       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1527       UseFP = true;
1528     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1529       // If the FPOffset is negative, we have to keep in mind that the
1530       // available offset range for negative offsets is smaller than for
1531       // positive ones. If an offset is
1532       // available via the FP and the SP, use whichever is closest.
1533       bool FPOffsetFits = FPOffset >= -256;
1534       PreferFP |= Offset > -FPOffset;
1535 
1536       if (MFI.hasVarSizedObjects()) {
1537         // If we have variable sized objects, we can use either FP or BP, as the
1538         // SP offset is unknown. We can use the base pointer if we have one and
1539         // FP is not preferred. If not, we're stuck with using FP.
1540         bool CanUseBP = RegInfo->hasBasePointer(MF);
1541         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1542           UseFP = PreferFP;
1543         else if (!CanUseBP) // Can't use BP. Forced to use FP.
1544           UseFP = true;
1545         // else we can use BP and FP, but the offset from FP won't fit.
1546         // That will make us scavenge registers which we can probably avoid by
1547         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1548       } else if (FPOffset >= 0) {
1549         // Use SP or FP, whichever gives us the best chance of the offset
1550         // being in range for direct access. If the FPOffset is positive,
1551         // that'll always be best, as the SP will be even further away.
1552         UseFP = true;
1553       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1554         // Funclets access the locals contained in the parent's stack frame
1555         // via the frame pointer, so we have to use the FP in the parent
1556         // function.
1557         (void) Subtarget;
1558         assert(
1559             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1560             "Funclets should only be present on Win64");
1561         UseFP = true;
1562       } else {
1563         // We have the choice between FP and (SP or BP).
1564         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1565           UseFP = true;
1566       }
1567     }
1568   }
1569 
1570   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1571          "In the presence of dynamic stack pointer realignment, "
1572          "non-argument/CSR objects cannot be accessed through the frame pointer");
1573 
1574   if (UseFP) {
1575     FrameReg = RegInfo->getFrameRegister(MF);
1576     return FPOffset;
1577   }
1578 
1579   // Use the base pointer if we have one.
1580   if (RegInfo->hasBasePointer(MF))
1581     FrameReg = RegInfo->getBaseRegister();
1582   else {
1583     assert(!MFI.hasVarSizedObjects() &&
1584            "Can't use SP when we have var sized objects.");
1585     FrameReg = AArch64::SP;
1586     // If we're using the red zone for this function, the SP won't actually
1587     // be adjusted, so the offsets will be negative. They're also all
1588     // within range of the signed 9-bit immediate instructions.
1589     if (canUseRedZone(MF))
1590       Offset -= AFI->getLocalStackSize();
1591   }
1592 
1593   return Offset;
1594 }
1595 
1596 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1597   // Do not set a kill flag on values that are also marked as live-in. This
1598   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1599   // callee saved registers.
1600   // Omitting the kill flags is conservatively correct even if the live-in
1601   // is not used after all.
1602   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1603   return getKillRegState(!IsLiveIn);
1604 }
1605 
1606 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1607   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1608   AttributeList Attrs = MF.getFunction().getAttributes();
1609   return Subtarget.isTargetMachO() &&
1610          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1611            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1612 }
1613 
1614 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1615                                              bool NeedsWinCFI) {
1616   // If we are generating register pairs for a Windows function that requires
1617   // EH support, then pair consecutive registers only.  There are no unwind
1618   // opcodes for saves/restores of non-consectuve register pairs.
1619   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1620   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1621 
1622   // TODO: LR can be paired with any register.  We don't support this yet in
1623   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1624   if (!NeedsWinCFI)
1625     return false;
1626   if (Reg2 == Reg1 + 1)
1627     return false;
1628   return true;
1629 }
1630 
1631 namespace {
1632 
1633 struct RegPairInfo {
1634   unsigned Reg1 = AArch64::NoRegister;
1635   unsigned Reg2 = AArch64::NoRegister;
1636   int FrameIdx;
1637   int Offset;
1638   enum RegType { GPR, FPR64, FPR128 } Type;
1639 
1640   RegPairInfo() = default;
1641 
1642   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1643 };
1644 
1645 } // end anonymous namespace
1646 
1647 static void computeCalleeSaveRegisterPairs(
1648     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1649     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1650     bool &NeedShadowCallStackProlog) {
1651 
1652   if (CSI.empty())
1653     return;
1654 
1655   bool NeedsWinCFI = needsWinCFI(MF);
1656   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1657   MachineFrameInfo &MFI = MF.getFrameInfo();
1658   CallingConv::ID CC = MF.getFunction().getCallingConv();
1659   unsigned Count = CSI.size();
1660   (void)CC;
1661   // MachO's compact unwind format relies on all registers being stored in
1662   // pairs.
1663   assert((!produceCompactUnwindFrame(MF) ||
1664           CC == CallingConv::PreserveMost ||
1665           (Count & 1) == 0) &&
1666          "Odd number of callee-saved regs to spill!");
1667   int Offset = AFI->getCalleeSavedStackSize();
1668   // On Linux, we will have either one or zero non-paired register.  On Windows
1669   // with CFI, we can have multiple unpaired registers in order to utilize the
1670   // available unwind codes.  This flag assures that the alignment fixup is done
1671   // only once, as intened.
1672   bool FixupDone = false;
1673   for (unsigned i = 0; i < Count; ++i) {
1674     RegPairInfo RPI;
1675     RPI.Reg1 = CSI[i].getReg();
1676 
1677     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1678       RPI.Type = RegPairInfo::GPR;
1679     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1680       RPI.Type = RegPairInfo::FPR64;
1681     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1682       RPI.Type = RegPairInfo::FPR128;
1683     else
1684       llvm_unreachable("Unsupported register class.");
1685 
1686     // Add the next reg to the pair if it is in the same register class.
1687     if (i + 1 < Count) {
1688       unsigned NextReg = CSI[i + 1].getReg();
1689       switch (RPI.Type) {
1690       case RegPairInfo::GPR:
1691         if (AArch64::GPR64RegClass.contains(NextReg) &&
1692             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1693           RPI.Reg2 = NextReg;
1694         break;
1695       case RegPairInfo::FPR64:
1696         if (AArch64::FPR64RegClass.contains(NextReg) &&
1697             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1698           RPI.Reg2 = NextReg;
1699         break;
1700       case RegPairInfo::FPR128:
1701         if (AArch64::FPR128RegClass.contains(NextReg))
1702           RPI.Reg2 = NextReg;
1703         break;
1704       }
1705     }
1706 
1707     // If either of the registers to be saved is the lr register, it means that
1708     // we also need to save lr in the shadow call stack.
1709     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
1710         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
1711       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
1712         report_fatal_error("Must reserve x18 to use shadow call stack");
1713       NeedShadowCallStackProlog = true;
1714     }
1715 
1716     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1717     // list to come in sorted by frame index so that we can issue the store
1718     // pair instructions directly. Assert if we see anything otherwise.
1719     //
1720     // The order of the registers in the list is controlled by
1721     // getCalleeSavedRegs(), so they will always be in-order, as well.
1722     assert((!RPI.isPaired() ||
1723             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
1724            "Out of order callee saved regs!");
1725 
1726     // MachO's compact unwind format relies on all registers being stored in
1727     // adjacent register pairs.
1728     assert((!produceCompactUnwindFrame(MF) ||
1729             CC == CallingConv::PreserveMost ||
1730             (RPI.isPaired() &&
1731              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1732               RPI.Reg1 + 1 == RPI.Reg2))) &&
1733            "Callee-save registers not saved as adjacent register pair!");
1734 
1735     RPI.FrameIdx = CSI[i].getFrameIdx();
1736 
1737     int Scale = RPI.Type == RegPairInfo::FPR128 ? 16 : 8;
1738     Offset -= RPI.isPaired() ? 2 * Scale : Scale;
1739 
1740     // Round up size of non-pair to pair size if we need to pad the
1741     // callee-save area to ensure 16-byte alignment.
1742     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
1743         RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired()) {
1744       FixupDone = true;
1745       Offset -= 8;
1746       assert(Offset % 16 == 0);
1747       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1748       MFI.setObjectAlignment(RPI.FrameIdx, 16);
1749     }
1750 
1751     assert(Offset % Scale == 0);
1752     RPI.Offset = Offset / Scale;
1753     assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1754            "Offset out of bounds for LDP/STP immediate");
1755 
1756     RegPairs.push_back(RPI);
1757     if (RPI.isPaired())
1758       ++i;
1759   }
1760 }
1761 
1762 bool AArch64FrameLowering::spillCalleeSavedRegisters(
1763     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1764     const std::vector<CalleeSavedInfo> &CSI,
1765     const TargetRegisterInfo *TRI) const {
1766   MachineFunction &MF = *MBB.getParent();
1767   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1768   bool NeedsWinCFI = needsWinCFI(MF);
1769   DebugLoc DL;
1770   SmallVector<RegPairInfo, 8> RegPairs;
1771 
1772   bool NeedShadowCallStackProlog = false;
1773   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1774                                  NeedShadowCallStackProlog);
1775   const MachineRegisterInfo &MRI = MF.getRegInfo();
1776 
1777   if (NeedShadowCallStackProlog) {
1778     // Shadow call stack prolog: str x30, [x18], #8
1779     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
1780         .addReg(AArch64::X18, RegState::Define)
1781         .addReg(AArch64::LR)
1782         .addReg(AArch64::X18)
1783         .addImm(8)
1784         .setMIFlag(MachineInstr::FrameSetup);
1785 
1786     if (NeedsWinCFI)
1787       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
1788           .setMIFlag(MachineInstr::FrameSetup);
1789 
1790     if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) {
1791       // Emit a CFI instruction that causes 8 to be subtracted from the value of
1792       // x18 when unwinding past this frame.
1793       static const char CFIInst[] = {
1794           dwarf::DW_CFA_val_expression,
1795           18, // register
1796           2,  // length
1797           static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1798           static_cast<char>(-8) & 0x7f, // addend (sleb128)
1799       };
1800       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
1801           nullptr, StringRef(CFIInst, sizeof(CFIInst))));
1802       BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1803           .addCFIIndex(CFIIndex)
1804           .setMIFlag(MachineInstr::FrameSetup);
1805     }
1806 
1807     // This instruction also makes x18 live-in to the entry block.
1808     MBB.addLiveIn(AArch64::X18);
1809   }
1810 
1811   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
1812        ++RPII) {
1813     RegPairInfo RPI = *RPII;
1814     unsigned Reg1 = RPI.Reg1;
1815     unsigned Reg2 = RPI.Reg2;
1816     unsigned StrOpc;
1817 
1818     // Issue sequence of spills for cs regs.  The first spill may be converted
1819     // to a pre-decrement store later by emitPrologue if the callee-save stack
1820     // area allocation can't be combined with the local stack area allocation.
1821     // For example:
1822     //    stp     x22, x21, [sp, #0]     // addImm(+0)
1823     //    stp     x20, x19, [sp, #16]    // addImm(+2)
1824     //    stp     fp, lr, [sp, #32]      // addImm(+4)
1825     // Rationale: This sequence saves uop updates compared to a sequence of
1826     // pre-increment spills like stp xi,xj,[sp,#-16]!
1827     // Note: Similar rationale and sequence for restores in epilog.
1828     unsigned Size, Align;
1829     switch (RPI.Type) {
1830     case RegPairInfo::GPR:
1831        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1832        Size = 8;
1833        Align = 8;
1834        break;
1835     case RegPairInfo::FPR64:
1836        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1837        Size = 8;
1838        Align = 8;
1839        break;
1840     case RegPairInfo::FPR128:
1841        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
1842        Size = 16;
1843        Align = 16;
1844        break;
1845     }
1846     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
1847                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1848                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1849                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1850                dbgs() << ")\n");
1851 
1852     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
1853            "Windows unwdinding requires a consecutive (FP,LR) pair");
1854     // Windows unwind codes require consecutive registers if registers are
1855     // paired.  Make the switch here, so that the code below will save (x,x+1)
1856     // and not (x+1,x).
1857     unsigned FrameIdxReg1 = RPI.FrameIdx;
1858     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1859     if (NeedsWinCFI && RPI.isPaired()) {
1860       std::swap(Reg1, Reg2);
1861       std::swap(FrameIdxReg1, FrameIdxReg2);
1862     }
1863     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
1864     if (!MRI.isReserved(Reg1))
1865       MBB.addLiveIn(Reg1);
1866     if (RPI.isPaired()) {
1867       if (!MRI.isReserved(Reg2))
1868         MBB.addLiveIn(Reg2);
1869       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
1870       MIB.addMemOperand(MF.getMachineMemOperand(
1871           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1872           MachineMemOperand::MOStore, Size, Align));
1873     }
1874     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1875         .addReg(AArch64::SP)
1876         .addImm(RPI.Offset) // [sp, #offset*scale],
1877                             // where factor*scale is implicit
1878         .setMIFlag(MachineInstr::FrameSetup);
1879     MIB.addMemOperand(MF.getMachineMemOperand(
1880         MachinePointerInfo::getFixedStack(MF,FrameIdxReg1),
1881         MachineMemOperand::MOStore, Size, Align));
1882     if (NeedsWinCFI)
1883       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
1884 
1885   }
1886   return true;
1887 }
1888 
1889 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1890     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1891     std::vector<CalleeSavedInfo> &CSI,
1892     const TargetRegisterInfo *TRI) const {
1893   MachineFunction &MF = *MBB.getParent();
1894   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1895   DebugLoc DL;
1896   SmallVector<RegPairInfo, 8> RegPairs;
1897   bool NeedsWinCFI = needsWinCFI(MF);
1898 
1899   if (MI != MBB.end())
1900     DL = MI->getDebugLoc();
1901 
1902   bool NeedShadowCallStackProlog = false;
1903   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1904                                  NeedShadowCallStackProlog);
1905 
1906   auto EmitMI = [&](const RegPairInfo &RPI) {
1907     unsigned Reg1 = RPI.Reg1;
1908     unsigned Reg2 = RPI.Reg2;
1909 
1910     // Issue sequence of restores for cs regs. The last restore may be converted
1911     // to a post-increment load later by emitEpilogue if the callee-save stack
1912     // area allocation can't be combined with the local stack area allocation.
1913     // For example:
1914     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
1915     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
1916     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
1917     // Note: see comment in spillCalleeSavedRegisters()
1918     unsigned LdrOpc;
1919     unsigned Size, Align;
1920     switch (RPI.Type) {
1921     case RegPairInfo::GPR:
1922        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1923        Size = 8;
1924        Align = 8;
1925        break;
1926     case RegPairInfo::FPR64:
1927        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1928        Size = 8;
1929        Align = 8;
1930        break;
1931     case RegPairInfo::FPR128:
1932        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
1933        Size = 16;
1934        Align = 16;
1935        break;
1936     }
1937     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
1938                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1939                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1940                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1941                dbgs() << ")\n");
1942 
1943     // Windows unwind codes require consecutive registers if registers are
1944     // paired.  Make the switch here, so that the code below will save (x,x+1)
1945     // and not (x+1,x).
1946     unsigned FrameIdxReg1 = RPI.FrameIdx;
1947     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1948     if (NeedsWinCFI && RPI.isPaired()) {
1949       std::swap(Reg1, Reg2);
1950       std::swap(FrameIdxReg1, FrameIdxReg2);
1951     }
1952     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
1953     if (RPI.isPaired()) {
1954       MIB.addReg(Reg2, getDefRegState(true));
1955       MIB.addMemOperand(MF.getMachineMemOperand(
1956           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1957           MachineMemOperand::MOLoad, Size, Align));
1958     }
1959     MIB.addReg(Reg1, getDefRegState(true))
1960         .addReg(AArch64::SP)
1961         .addImm(RPI.Offset) // [sp, #offset*scale]
1962                             // where factor*scale is implicit
1963         .setMIFlag(MachineInstr::FrameDestroy);
1964     MIB.addMemOperand(MF.getMachineMemOperand(
1965         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
1966         MachineMemOperand::MOLoad, Size, Align));
1967     if (NeedsWinCFI)
1968       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
1969   };
1970   if (ReverseCSRRestoreSeq)
1971     for (const RegPairInfo &RPI : reverse(RegPairs))
1972       EmitMI(RPI);
1973   else
1974     for (const RegPairInfo &RPI : RegPairs)
1975       EmitMI(RPI);
1976 
1977   if (NeedShadowCallStackProlog) {
1978     // Shadow call stack epilog: ldr x30, [x18, #-8]!
1979     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
1980         .addReg(AArch64::X18, RegState::Define)
1981         .addReg(AArch64::LR, RegState::Define)
1982         .addReg(AArch64::X18)
1983         .addImm(-8)
1984         .setMIFlag(MachineInstr::FrameDestroy);
1985   }
1986 
1987   return true;
1988 }
1989 
1990 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1991                                                 BitVector &SavedRegs,
1992                                                 RegScavenger *RS) const {
1993   // All calls are tail calls in GHC calling conv, and functions have no
1994   // prologue/epilogue.
1995   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1996     return;
1997 
1998   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1999   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
2000       MF.getSubtarget().getRegisterInfo());
2001   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2002   unsigned UnspilledCSGPR = AArch64::NoRegister;
2003   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
2004 
2005   MachineFrameInfo &MFI = MF.getFrameInfo();
2006   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2007 
2008   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
2009                                 ? RegInfo->getBaseRegister()
2010                                 : (unsigned)AArch64::NoRegister;
2011 
2012   unsigned ExtraCSSpill = 0;
2013   // Figure out which callee-saved registers to save/restore.
2014   for (unsigned i = 0; CSRegs[i]; ++i) {
2015     const unsigned Reg = CSRegs[i];
2016 
2017     // Add the base pointer register to SavedRegs if it is callee-save.
2018     if (Reg == BasePointerReg)
2019       SavedRegs.set(Reg);
2020 
2021     bool RegUsed = SavedRegs.test(Reg);
2022     unsigned PairedReg = CSRegs[i ^ 1];
2023     if (!RegUsed) {
2024       if (AArch64::GPR64RegClass.contains(Reg) &&
2025           !RegInfo->isReservedReg(MF, Reg)) {
2026         UnspilledCSGPR = Reg;
2027         UnspilledCSGPRPaired = PairedReg;
2028       }
2029       continue;
2030     }
2031 
2032     // MachO's compact unwind format relies on all registers being stored in
2033     // pairs.
2034     // FIXME: the usual format is actually better if unwinding isn't needed.
2035     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
2036         !SavedRegs.test(PairedReg)) {
2037       SavedRegs.set(PairedReg);
2038       if (AArch64::GPR64RegClass.contains(PairedReg) &&
2039           !RegInfo->isReservedReg(MF, PairedReg))
2040         ExtraCSSpill = PairedReg;
2041     }
2042   }
2043 
2044   // Calculates the callee saved stack size.
2045   unsigned CSStackSize = 0;
2046   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2047   const MachineRegisterInfo &MRI = MF.getRegInfo();
2048   for (unsigned Reg : SavedRegs.set_bits())
2049     CSStackSize += TRI->getRegSizeInBits(Reg, MRI) / 8;
2050 
2051   // Save number of saved regs, so we can easily update CSStackSize later.
2052   unsigned NumSavedRegs = SavedRegs.count();
2053 
2054   // The frame record needs to be created by saving the appropriate registers
2055   unsigned EstimatedStackSize = MFI.estimateStackSize(MF);
2056   if (hasFP(MF) ||
2057       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2058     SavedRegs.set(AArch64::FP);
2059     SavedRegs.set(AArch64::LR);
2060   }
2061 
2062   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
2063              for (unsigned Reg
2064                   : SavedRegs.set_bits()) dbgs()
2065              << ' ' << printReg(Reg, RegInfo);
2066              dbgs() << "\n";);
2067 
2068   // If any callee-saved registers are used, the frame cannot be eliminated.
2069   bool CanEliminateFrame = SavedRegs.count() == 0;
2070 
2071   // The CSR spill slots have not been allocated yet, so estimateStackSize
2072   // won't include them.
2073   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2074   bool BigStack = (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2075   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2076     AFI->setHasStackFrame(true);
2077 
2078   // Estimate if we might need to scavenge a register at some point in order
2079   // to materialize a stack offset. If so, either spill one additional
2080   // callee-saved register or reserve a special spill slot to facilitate
2081   // register scavenging. If we already spilled an extra callee-saved register
2082   // above to keep the number of spills even, we don't need to do anything else
2083   // here.
2084   if (BigStack) {
2085     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2086       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2087                         << " to get a scratch register.\n");
2088       SavedRegs.set(UnspilledCSGPR);
2089       // MachO's compact unwind format relies on all registers being stored in
2090       // pairs, so if we need to spill one extra for BigStack, then we need to
2091       // store the pair.
2092       if (produceCompactUnwindFrame(MF))
2093         SavedRegs.set(UnspilledCSGPRPaired);
2094       ExtraCSSpill = UnspilledCSGPRPaired;
2095     }
2096 
2097     // If we didn't find an extra callee-saved register to spill, create
2098     // an emergency spill slot.
2099     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2100       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2101       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2102       unsigned Size = TRI->getSpillSize(RC);
2103       unsigned Align = TRI->getSpillAlignment(RC);
2104       int FI = MFI.CreateStackObject(Size, Align, false);
2105       RS->addScavengingFrameIndex(FI);
2106       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2107                         << " as the emergency spill slot.\n");
2108     }
2109   }
2110 
2111   // Adding the size of additional 64bit GPR saves.
2112   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2113   unsigned AlignedCSStackSize = alignTo(CSStackSize, 16);
2114   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2115                << EstimatedStackSize + AlignedCSStackSize
2116                << " bytes.\n");
2117 
2118   // Round up to register pair alignment to avoid additional SP adjustment
2119   // instructions.
2120   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2121   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2122 }
2123 
2124 bool AArch64FrameLowering::enableStackSlotScavenging(
2125     const MachineFunction &MF) const {
2126   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2127   return AFI->hasCalleeSaveStackFreeSpace();
2128 }
2129 
2130 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2131     MachineFunction &MF, RegScavenger *RS) const {
2132   // If this function isn't doing Win64-style C++ EH, we don't need to do
2133   // anything.
2134   if (!MF.hasEHFunclets())
2135     return;
2136   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2137   MachineFrameInfo &MFI = MF.getFrameInfo();
2138   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2139 
2140   MachineBasicBlock &MBB = MF.front();
2141   auto MBBI = MBB.begin();
2142   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2143     ++MBBI;
2144 
2145   // Create an UnwindHelp object.
2146   int UnwindHelpFI =
2147       MFI.CreateStackObject(/*size*/8, /*alignment*/16, false);
2148   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2149   // We need to store -2 into the UnwindHelp object at the start of the
2150   // function.
2151   DebugLoc DL;
2152   RS->enterBasicBlockEnd(MBB);
2153   RS->backward(std::prev(MBBI));
2154   unsigned DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
2155   assert(DstReg && "There must be a free register after frame setup");
2156   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2157   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2158       .addReg(DstReg, getKillRegState(true))
2159       .addFrameIndex(UnwindHelpFI)
2160       .addImm(0);
2161 }
2162 
2163 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before
2164 /// the update.  This is easily retrieved as it is exactly the offset that is set
2165 /// in processFunctionBeforeFrameFinalized.
2166 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
2167     const MachineFunction &MF, int FI, unsigned &FrameReg,
2168     bool IgnoreSPUpdates) const {
2169   const MachineFrameInfo &MFI = MF.getFrameInfo();
2170   LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
2171                     << MFI.getObjectOffset(FI) << "\n");
2172   FrameReg = AArch64::SP;
2173   return MFI.getObjectOffset(FI);
2174 }
2175 
2176 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
2177 /// the parent's frame pointer
2178 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
2179     const MachineFunction &MF) const {
2180   return 0;
2181 }
2182 
2183 /// Funclets only need to account for space for the callee saved registers,
2184 /// as the locals are accounted for in the parent's stack frame.
2185 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
2186     const MachineFunction &MF) const {
2187   // This is the size of the pushed CSRs.
2188   unsigned CSSize =
2189       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
2190   // This is the amount of stack a funclet needs to allocate.
2191   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
2192                  getStackAlignment());
2193 }
2194