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