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 
825   // All calls are tail calls in GHC calling conv, and functions have no
826   // prologue/epilogue.
827   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
828     return;
829 
830   // getStackSize() includes all the locals in its size calculation. We don't
831   // include these locals when computing the stack size of a funclet, as they
832   // are allocated in the parent's stack frame and accessed via the frame
833   // pointer from the funclet.  We only save the callee saved registers in the
834   // funclet, which are really the callee saved registers of the parent
835   // function, including the funclet.
836   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
837                            : (int)MFI.getStackSize();
838   if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
839     assert(!HasFP && "unexpected function without stack frame but with FP");
840     // All of the stack allocation is for locals.
841     AFI->setLocalStackSize(NumBytes);
842     if (!NumBytes)
843       return;
844     // REDZONE: If the stack size is less than 128 bytes, we don't need
845     // to actually allocate.
846     if (canUseRedZone(MF)) {
847       AFI->setHasRedZone(true);
848       ++NumRedZoneFunctions;
849     } else {
850       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
851                       MachineInstr::FrameSetup, false, NeedsWinCFI);
852       if (!NeedsWinCFI) {
853         // Label used to tie together the PROLOG_LABEL and the MachineMoves.
854         MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
855         // Encode the stack size of the leaf function.
856         unsigned CFIIndex = MF.addFrameInst(
857             MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
858         BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
859             .addCFIIndex(CFIIndex)
860             .setMIFlags(MachineInstr::FrameSetup);
861       }
862     }
863 
864     if (NeedsWinCFI)
865       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
866           .setMIFlag(MachineInstr::FrameSetup);
867 
868     return;
869   }
870 
871   bool IsWin64 =
872       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
873   // Var args are accounted for in the containing function, so don't
874   // include them for funclets.
875   unsigned FixedObject = (IsWin64 && !IsFunclet) ?
876                          alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
877 
878   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
879   // All of the remaining stack allocations are for locals.
880   AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
881   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
882   if (CombineSPBump) {
883     emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
884                     MachineInstr::FrameSetup, false, NeedsWinCFI);
885     NumBytes = 0;
886   } else if (PrologueSaveSize != 0) {
887     MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
888         MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI);
889     NumBytes -= PrologueSaveSize;
890   }
891   assert(NumBytes >= 0 && "Negative stack allocation size!?");
892 
893   // Move past the saves of the callee-saved registers, fixing up the offsets
894   // and pre-inc if we decided to combine the callee-save and local stack
895   // pointer bump above.
896   MachineBasicBlock::iterator End = MBB.end();
897   while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
898     if (CombineSPBump)
899       fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
900                                         NeedsWinCFI);
901     ++MBBI;
902   }
903 
904   // The code below is not applicable to funclets. We have emitted all the SEH
905   // opcodes that we needed to emit.  The FP and BP belong to the containing
906   // function.
907   if (IsFunclet) {
908     if (NeedsWinCFI)
909       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
910           .setMIFlag(MachineInstr::FrameSetup);
911     return;
912   }
913 
914   if (HasFP) {
915     // Only set up FP if we actually need to. Frame pointer is fp =
916     // sp - fixedobject - 16.
917     int FPOffset = AFI->getCalleeSavedStackSize() - 16;
918     if (CombineSPBump)
919       FPOffset += AFI->getLocalStackSize();
920 
921     // Issue    sub fp, sp, FPOffset or
922     //          mov fp,sp          when FPOffset is zero.
923     // Note: All stores of callee-saved registers are marked as "FrameSetup".
924     // This code marks the instruction(s) that set the FP also.
925     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
926                     MachineInstr::FrameSetup, false, NeedsWinCFI);
927   }
928 
929   if (windowsRequiresStackProbe(MF, NumBytes)) {
930     uint32_t NumWords = NumBytes >> 4;
931     if (NeedsWinCFI) {
932       // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
933       // exceed this amount.  We need to move at most 2^24 - 1 into x15.
934       // This is at most two instructions, MOVZ follwed by MOVK.
935       // TODO: Fix to use multiple stack alloc unwind codes for stacks
936       // exceeding 256MB in size.
937       if (NumBytes >= (1 << 28))
938         report_fatal_error("Stack size cannot exceed 256MB for stack "
939                             "unwinding purposes");
940 
941       uint32_t LowNumWords = NumWords & 0xFFFF;
942       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
943             .addImm(LowNumWords)
944             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
945             .setMIFlag(MachineInstr::FrameSetup);
946       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
947             .setMIFlag(MachineInstr::FrameSetup);
948       if ((NumWords & 0xFFFF0000) != 0) {
949           BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
950               .addReg(AArch64::X15)
951               .addImm((NumWords & 0xFFFF0000) >> 16) // High half
952               .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
953               .setMIFlag(MachineInstr::FrameSetup);
954           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
955             .setMIFlag(MachineInstr::FrameSetup);
956       }
957     } else {
958       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
959           .addImm(NumWords)
960           .setMIFlags(MachineInstr::FrameSetup);
961     }
962 
963     switch (MF.getTarget().getCodeModel()) {
964     case CodeModel::Tiny:
965     case CodeModel::Small:
966     case CodeModel::Medium:
967     case CodeModel::Kernel:
968       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
969           .addExternalSymbol("__chkstk")
970           .addReg(AArch64::X15, RegState::Implicit)
971           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
972           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
973           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
974           .setMIFlags(MachineInstr::FrameSetup);
975       if (NeedsWinCFI)
976         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
977             .setMIFlag(MachineInstr::FrameSetup);
978       break;
979     case CodeModel::Large:
980       BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
981           .addReg(AArch64::X16, RegState::Define)
982           .addExternalSymbol("__chkstk")
983           .addExternalSymbol("__chkstk")
984           .setMIFlags(MachineInstr::FrameSetup);
985       if (NeedsWinCFI)
986         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
987             .setMIFlag(MachineInstr::FrameSetup);
988 
989       BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
990           .addReg(AArch64::X16, RegState::Kill)
991           .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
992           .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
993           .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
994           .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
995           .setMIFlags(MachineInstr::FrameSetup);
996       if (NeedsWinCFI)
997         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
998             .setMIFlag(MachineInstr::FrameSetup);
999       break;
1000     }
1001 
1002     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
1003         .addReg(AArch64::SP, RegState::Kill)
1004         .addReg(AArch64::X15, RegState::Kill)
1005         .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
1006         .setMIFlags(MachineInstr::FrameSetup);
1007     if (NeedsWinCFI)
1008        BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1009             .addImm(NumBytes)
1010             .setMIFlag(MachineInstr::FrameSetup);
1011     NumBytes = 0;
1012   }
1013 
1014   // Allocate space for the rest of the frame.
1015   if (NumBytes) {
1016     const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
1017     unsigned scratchSPReg = AArch64::SP;
1018 
1019     if (NeedsRealignment) {
1020       scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
1021       assert(scratchSPReg != AArch64::NoRegister);
1022     }
1023 
1024     // If we're a leaf function, try using the red zone.
1025     if (!canUseRedZone(MF))
1026       // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
1027       // the correct value here, as NumBytes also includes padding bytes,
1028       // which shouldn't be counted here.
1029       emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
1030                       MachineInstr::FrameSetup, false, NeedsWinCFI);
1031 
1032     if (NeedsRealignment) {
1033       const unsigned Alignment = MFI.getMaxAlignment();
1034       const unsigned NrBitsToZero = countTrailingZeros(Alignment);
1035       assert(NrBitsToZero > 1);
1036       assert(scratchSPReg != AArch64::SP);
1037 
1038       // SUB X9, SP, NumBytes
1039       //   -- X9 is temporary register, so shouldn't contain any live data here,
1040       //   -- free to use. This is already produced by emitFrameOffset above.
1041       // AND SP, X9, 0b11111...0000
1042       // The logical immediates have a non-trivial encoding. The following
1043       // formula computes the encoded immediate with all ones but
1044       // NrBitsToZero zero bits as least significant bits.
1045       uint32_t andMaskEncoded = (1 << 12)                         // = N
1046                                 | ((64 - NrBitsToZero) << 6)      // immr
1047                                 | ((64 - NrBitsToZero - 1) << 0); // imms
1048 
1049       BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
1050           .addReg(scratchSPReg, RegState::Kill)
1051           .addImm(andMaskEncoded);
1052       AFI->setStackRealigned(true);
1053       if (NeedsWinCFI)
1054         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
1055             .addImm(NumBytes & andMaskEncoded)
1056             .setMIFlag(MachineInstr::FrameSetup);
1057     }
1058   }
1059 
1060   // If we need a base pointer, set it up here. It's whatever the value of the
1061   // stack pointer is at this point. Any variable size objects will be allocated
1062   // after this, so we can still use the base pointer to reference locals.
1063   //
1064   // FIXME: Clarify FrameSetup flags here.
1065   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
1066   // needed.
1067   if (RegInfo->hasBasePointer(MF)) {
1068     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
1069                      false);
1070     if (NeedsWinCFI)
1071       BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
1072           .setMIFlag(MachineInstr::FrameSetup);
1073   }
1074 
1075   // The very last FrameSetup instruction indicates the end of prologue. Emit a
1076   // SEH opcode indicating the prologue end.
1077   if (NeedsWinCFI)
1078     BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
1079         .setMIFlag(MachineInstr::FrameSetup);
1080 
1081   if (needsFrameMoves) {
1082     const DataLayout &TD = MF.getDataLayout();
1083     const int StackGrowth = -TD.getPointerSize(0);
1084     unsigned FramePtr = RegInfo->getFrameRegister(MF);
1085     // An example of the prologue:
1086     //
1087     //     .globl __foo
1088     //     .align 2
1089     //  __foo:
1090     // Ltmp0:
1091     //     .cfi_startproc
1092     //     .cfi_personality 155, ___gxx_personality_v0
1093     // Leh_func_begin:
1094     //     .cfi_lsda 16, Lexception33
1095     //
1096     //     stp  xa,bx, [sp, -#offset]!
1097     //     ...
1098     //     stp  x28, x27, [sp, #offset-32]
1099     //     stp  fp, lr, [sp, #offset-16]
1100     //     add  fp, sp, #offset - 16
1101     //     sub  sp, sp, #1360
1102     //
1103     // The Stack:
1104     //       +-------------------------------------------+
1105     // 10000 | ........ | ........ | ........ | ........ |
1106     // 10004 | ........ | ........ | ........ | ........ |
1107     //       +-------------------------------------------+
1108     // 10008 | ........ | ........ | ........ | ........ |
1109     // 1000c | ........ | ........ | ........ | ........ |
1110     //       +===========================================+
1111     // 10010 |                X28 Register               |
1112     // 10014 |                X28 Register               |
1113     //       +-------------------------------------------+
1114     // 10018 |                X27 Register               |
1115     // 1001c |                X27 Register               |
1116     //       +===========================================+
1117     // 10020 |                Frame Pointer              |
1118     // 10024 |                Frame Pointer              |
1119     //       +-------------------------------------------+
1120     // 10028 |                Link Register              |
1121     // 1002c |                Link Register              |
1122     //       +===========================================+
1123     // 10030 | ........ | ........ | ........ | ........ |
1124     // 10034 | ........ | ........ | ........ | ........ |
1125     //       +-------------------------------------------+
1126     // 10038 | ........ | ........ | ........ | ........ |
1127     // 1003c | ........ | ........ | ........ | ........ |
1128     //       +-------------------------------------------+
1129     //
1130     //     [sp] = 10030        ::    >>initial value<<
1131     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
1132     //     fp = sp == 10020    ::  mov fp, sp
1133     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
1134     //     sp == 10010         ::    >>final value<<
1135     //
1136     // The frame pointer (w29) points to address 10020. If we use an offset of
1137     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
1138     // for w27, and -32 for w28:
1139     //
1140     //  Ltmp1:
1141     //     .cfi_def_cfa w29, 16
1142     //  Ltmp2:
1143     //     .cfi_offset w30, -8
1144     //  Ltmp3:
1145     //     .cfi_offset w29, -16
1146     //  Ltmp4:
1147     //     .cfi_offset w27, -24
1148     //  Ltmp5:
1149     //     .cfi_offset w28, -32
1150 
1151     if (HasFP) {
1152       // Define the current CFA rule to use the provided FP.
1153       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
1154       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
1155           nullptr, Reg, 2 * StackGrowth - FixedObject));
1156       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1157           .addCFIIndex(CFIIndex)
1158           .setMIFlags(MachineInstr::FrameSetup);
1159     } else {
1160       // Encode the stack size of the leaf function.
1161       unsigned CFIIndex = MF.addFrameInst(
1162           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
1163       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
1164           .addCFIIndex(CFIIndex)
1165           .setMIFlags(MachineInstr::FrameSetup);
1166     }
1167 
1168     // Now emit the moves for whatever callee saved regs we have (including FP,
1169     // LR if those are saved).
1170     emitCalleeSavedFrameMoves(MBB, MBBI);
1171   }
1172 }
1173 
1174 static void InsertReturnAddressAuth(MachineFunction &MF,
1175                                     MachineBasicBlock &MBB) {
1176   if (!ShouldSignReturnAddress(MF))
1177     return;
1178   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1179   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1180 
1181   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1182   DebugLoc DL;
1183   if (MBBI != MBB.end())
1184     DL = MBBI->getDebugLoc();
1185 
1186   // The AUTIASP instruction assembles to a hint instruction before v8.3a so
1187   // this instruction can safely used for any v8a architecture.
1188   // From v8.3a onwards there are optimised authenticate LR and return
1189   // instructions, namely RETA{A,B}, that can be used instead.
1190   if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
1191       MBBI->getOpcode() == AArch64::RET_ReallyLR) {
1192     BuildMI(MBB, MBBI, DL,
1193             TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB))
1194         .copyImplicitOps(*MBBI);
1195     MBB.erase(MBBI);
1196   } else {
1197     BuildMI(
1198         MBB, MBBI, DL,
1199         TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP))
1200         .setMIFlag(MachineInstr::FrameDestroy);
1201   }
1202 }
1203 
1204 static bool isFuncletReturnInstr(const MachineInstr &MI) {
1205   switch (MI.getOpcode()) {
1206   default:
1207     return false;
1208   case AArch64::CATCHRET:
1209   case AArch64::CLEANUPRET:
1210     return true;
1211   }
1212 }
1213 
1214 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
1215                                         MachineBasicBlock &MBB) const {
1216   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1217   MachineFrameInfo &MFI = MF.getFrameInfo();
1218   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1219   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1220   DebugLoc DL;
1221   bool IsTailCallReturn = false;
1222   bool NeedsWinCFI = needsWinCFI(MF);
1223   bool IsFunclet = false;
1224 
1225   if (MBB.end() != MBBI) {
1226     DL = MBBI->getDebugLoc();
1227     unsigned RetOpcode = MBBI->getOpcode();
1228     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
1229                        RetOpcode == AArch64::TCRETURNri ||
1230                        RetOpcode == AArch64::TCRETURNriBTI;
1231     IsFunclet = isFuncletReturnInstr(*MBBI);
1232   }
1233 
1234   int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF)
1235                            : MFI.getStackSize();
1236   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1237 
1238   // All calls are tail calls in GHC calling conv, and functions have no
1239   // prologue/epilogue.
1240   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1241     return;
1242 
1243   // Initial and residual are named for consistency with the prologue. Note that
1244   // in the epilogue, the residual adjustment is executed first.
1245   uint64_t ArgumentPopSize = 0;
1246   if (IsTailCallReturn) {
1247     MachineOperand &StackAdjust = MBBI->getOperand(1);
1248 
1249     // For a tail-call in a callee-pops-arguments environment, some or all of
1250     // the stack may actually be in use for the call's arguments, this is
1251     // calculated during LowerCall and consumed here...
1252     ArgumentPopSize = StackAdjust.getImm();
1253   } else {
1254     // ... otherwise the amount to pop is *all* of the argument space,
1255     // conveniently stored in the MachineFunctionInfo by
1256     // LowerFormalArguments. This will, of course, be zero for the C calling
1257     // convention.
1258     ArgumentPopSize = AFI->getArgumentStackToRestore();
1259   }
1260 
1261   // The stack frame should be like below,
1262   //
1263   //      ----------------------                     ---
1264   //      |                    |                      |
1265   //      | BytesInStackArgArea|              CalleeArgStackSize
1266   //      | (NumReusableBytes) |                (of tail call)
1267   //      |                    |                     ---
1268   //      |                    |                      |
1269   //      ---------------------|        ---           |
1270   //      |                    |         |            |
1271   //      |   CalleeSavedReg   |         |            |
1272   //      | (CalleeSavedStackSize)|      |            |
1273   //      |                    |         |            |
1274   //      ---------------------|         |         NumBytes
1275   //      |                    |     StackSize  (StackAdjustUp)
1276   //      |   LocalStackSize   |         |            |
1277   //      | (covering callee   |         |            |
1278   //      |       args)        |         |            |
1279   //      |                    |         |            |
1280   //      ----------------------        ---          ---
1281   //
1282   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
1283   //             = StackSize + ArgumentPopSize
1284   //
1285   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
1286   // it as the 2nd argument of AArch64ISD::TC_RETURN.
1287 
1288   auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
1289 
1290   bool IsWin64 =
1291       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1292   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1293 
1294   uint64_t AfterCSRPopSize = ArgumentPopSize;
1295   auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
1296   // Var args are accounted for in the containting function, so don't
1297   // include them for funclets.
1298   if (MF.hasEHFunclets())
1299     AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
1300   bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
1301   // Assume we can't combine the last pop with the sp restore.
1302 
1303   if (!CombineSPBump && PrologueSaveSize != 0) {
1304     MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
1305     while (AArch64InstrInfo::isSEHInstruction(*Pop))
1306       Pop = std::prev(Pop);
1307     // Converting the last ldp to a post-index ldp is valid only if the last
1308     // ldp's offset is 0.
1309     const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1310     // If the offset is 0, convert it to a post-index ldp.
1311     if (OffsetOp.getImm() == 0)
1312       convertCalleeSaveRestoreToSPPrePostIncDec(
1313           MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, false);
1314     else {
1315       // If not, make sure to emit an add after the last ldp.
1316       // We're doing this by transfering the size to be restored from the
1317       // adjustment *before* the CSR pops to the adjustment *after* the CSR
1318       // pops.
1319       AfterCSRPopSize += PrologueSaveSize;
1320     }
1321   }
1322 
1323   // Move past the restores of the callee-saved registers.
1324   // If we plan on combining the sp bump of the local stack size and the callee
1325   // save stack size, we might need to adjust the CSR save and restore offsets.
1326   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
1327   MachineBasicBlock::iterator Begin = MBB.begin();
1328   while (LastPopI != Begin) {
1329     --LastPopI;
1330     if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
1331       ++LastPopI;
1332       break;
1333     } else if (CombineSPBump)
1334       fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
1335                                         NeedsWinCFI);
1336   }
1337 
1338   if (NeedsWinCFI)
1339     BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
1340         .setMIFlag(MachineInstr::FrameDestroy);
1341 
1342   // If there is a single SP update, insert it before the ret and we're done.
1343   if (CombineSPBump) {
1344     emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
1345                     NumBytes + AfterCSRPopSize, TII, MachineInstr::FrameDestroy,
1346                     false, NeedsWinCFI);
1347     if (NeedsWinCFI)
1348       BuildMI(MBB, MBB.getFirstTerminator(), DL,
1349               TII->get(AArch64::SEH_EpilogEnd))
1350           .setMIFlag(MachineInstr::FrameDestroy);
1351     return;
1352   }
1353 
1354   NumBytes -= PrologueSaveSize;
1355   assert(NumBytes >= 0 && "Negative stack allocation size!?");
1356 
1357   if (!hasFP(MF)) {
1358     bool RedZone = canUseRedZone(MF);
1359     // If this was a redzone leaf function, we don't need to restore the
1360     // stack pointer (but we may need to pop stack args for fastcc).
1361     if (RedZone && AfterCSRPopSize == 0)
1362       return;
1363 
1364     bool NoCalleeSaveRestore = PrologueSaveSize == 0;
1365     int StackRestoreBytes = RedZone ? 0 : NumBytes;
1366     if (NoCalleeSaveRestore)
1367       StackRestoreBytes += AfterCSRPopSize;
1368 
1369     // If we were able to combine the local stack pop with the argument pop,
1370     // then we're done.
1371     bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1372 
1373     // If we're done after this, make sure to help the load store optimizer.
1374     if (Done)
1375       adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1376 
1377     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1378                     StackRestoreBytes, TII, MachineInstr::FrameDestroy, false,
1379                     NeedsWinCFI);
1380     if (Done) {
1381       if (NeedsWinCFI)
1382         BuildMI(MBB, MBB.getFirstTerminator(), DL,
1383                 TII->get(AArch64::SEH_EpilogEnd))
1384             .setMIFlag(MachineInstr::FrameDestroy);
1385       return;
1386     }
1387 
1388     NumBytes = 0;
1389   }
1390 
1391   // Restore the original stack pointer.
1392   // FIXME: Rather than doing the math here, we should instead just use
1393   // non-post-indexed loads for the restores if we aren't actually going to
1394   // be able to save any instructions.
1395   if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned()))
1396     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
1397                     -AFI->getCalleeSavedStackSize() + 16, TII,
1398                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1399   else if (NumBytes)
1400     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
1401                     MachineInstr::FrameDestroy, false, NeedsWinCFI);
1402 
1403   // This must be placed after the callee-save restore code because that code
1404   // assumes the SP is at the same location as it was after the callee-save save
1405   // code in the prologue.
1406   if (AfterCSRPopSize) {
1407     // Find an insertion point for the first ldp so that it goes before the
1408     // shadow call stack epilog instruction. This ensures that the restore of
1409     // lr from x18 is placed after the restore from sp.
1410     auto FirstSPPopI = MBB.getFirstTerminator();
1411     while (FirstSPPopI != Begin) {
1412       auto Prev = std::prev(FirstSPPopI);
1413       if (Prev->getOpcode() != AArch64::LDRXpre ||
1414           Prev->getOperand(0).getReg() == AArch64::SP)
1415         break;
1416       FirstSPPopI = Prev;
1417     }
1418 
1419     adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1420 
1421     emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
1422                     AfterCSRPopSize, TII, MachineInstr::FrameDestroy, false,
1423                     NeedsWinCFI);
1424   }
1425   if (NeedsWinCFI)
1426     BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd))
1427         .setMIFlag(MachineInstr::FrameDestroy);
1428 }
1429 
1430 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1431 /// debug info.  It's the same as what we use for resolving the code-gen
1432 /// references for now.  FIXME: This can go wrong when references are
1433 /// SP-relative and simple call frames aren't used.
1434 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1435                                                  int FI,
1436                                                  unsigned &FrameReg) const {
1437   return resolveFrameIndexReference(MF, FI, FrameReg);
1438 }
1439 
1440 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
1441                                                      int FI, unsigned &FrameReg,
1442                                                      bool PreferFP) const {
1443   const MachineFrameInfo &MFI = MF.getFrameInfo();
1444   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1445       MF.getSubtarget().getRegisterInfo());
1446   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1447   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1448   bool IsWin64 =
1449       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
1450   unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1451   int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16;
1452   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1453   bool isFixed = MFI.isFixedObjectIndex(FI);
1454   bool isCSR = !isFixed && MFI.getObjectOffset(FI) >=
1455                                -((int)AFI->getCalleeSavedStackSize());
1456 
1457   // Use frame pointer to reference fixed objects. Use it for locals if
1458   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1459   // reliable as a base). Make sure useFPForScavengingIndex() does the
1460   // right thing for the emergency spill slot.
1461   bool UseFP = false;
1462   if (AFI->hasStackFrame()) {
1463     // Note: Keeping the following as multiple 'if' statements rather than
1464     // merging to a single expression for readability.
1465     //
1466     // Argument access should always use the FP.
1467     if (isFixed) {
1468       UseFP = hasFP(MF);
1469     } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1470       // References to the CSR area must use FP if we're re-aligning the stack
1471       // since the dynamically-sized alignment padding is between the SP/BP and
1472       // the CSR area.
1473       assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1474       UseFP = true;
1475     } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
1476       // If the FPOffset is negative, we have to keep in mind that the
1477       // available offset range for negative offsets is smaller than for
1478       // positive ones. If an offset is
1479       // available via the FP and the SP, use whichever is closest.
1480       bool FPOffsetFits = FPOffset >= -256;
1481       PreferFP |= Offset > -FPOffset;
1482 
1483       if (MFI.hasVarSizedObjects()) {
1484         // If we have variable sized objects, we can use either FP or BP, as the
1485         // SP offset is unknown. We can use the base pointer if we have one and
1486         // FP is not preferred. If not, we're stuck with using FP.
1487         bool CanUseBP = RegInfo->hasBasePointer(MF);
1488         if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1489           UseFP = PreferFP;
1490         else if (!CanUseBP) // Can't use BP. Forced to use FP.
1491           UseFP = true;
1492         // else we can use BP and FP, but the offset from FP won't fit.
1493         // That will make us scavenge registers which we can probably avoid by
1494         // using BP. If it won't fit for BP either, we'll scavenge anyway.
1495       } else if (FPOffset >= 0) {
1496         // Use SP or FP, whichever gives us the best chance of the offset
1497         // being in range for direct access. If the FPOffset is positive,
1498         // that'll always be best, as the SP will be even further away.
1499         UseFP = true;
1500       } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1501         // Funclets access the locals contained in the parent's stack frame
1502         // via the frame pointer, so we have to use the FP in the parent
1503         // function.
1504         assert(
1505             Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
1506             "Funclets should only be present on Win64");
1507         UseFP = true;
1508       } else {
1509         // We have the choice between FP and (SP or BP).
1510         if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1511           UseFP = true;
1512       }
1513     }
1514   }
1515 
1516   assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1517          "In the presence of dynamic stack pointer realignment, "
1518          "non-argument/CSR objects cannot be accessed through the frame pointer");
1519 
1520   if (UseFP) {
1521     FrameReg = RegInfo->getFrameRegister(MF);
1522     return FPOffset;
1523   }
1524 
1525   // Use the base pointer if we have one.
1526   if (RegInfo->hasBasePointer(MF))
1527     FrameReg = RegInfo->getBaseRegister();
1528   else {
1529     assert(!MFI.hasVarSizedObjects() &&
1530            "Can't use SP when we have var sized objects.");
1531     FrameReg = AArch64::SP;
1532     // If we're using the red zone for this function, the SP won't actually
1533     // be adjusted, so the offsets will be negative. They're also all
1534     // within range of the signed 9-bit immediate instructions.
1535     if (canUseRedZone(MF))
1536       Offset -= AFI->getLocalStackSize();
1537   }
1538 
1539   return Offset;
1540 }
1541 
1542 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
1543   // Do not set a kill flag on values that are also marked as live-in. This
1544   // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1545   // callee saved registers.
1546   // Omitting the kill flags is conservatively correct even if the live-in
1547   // is not used after all.
1548   bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1549   return getKillRegState(!IsLiveIn);
1550 }
1551 
1552 static bool produceCompactUnwindFrame(MachineFunction &MF) {
1553   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1554   AttributeList Attrs = MF.getFunction().getAttributes();
1555   return Subtarget.isTargetMachO() &&
1556          !(Subtarget.getTargetLowering()->supportSwiftError() &&
1557            Attrs.hasAttrSomewhere(Attribute::SwiftError));
1558 }
1559 
1560 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
1561                                              bool NeedsWinCFI) {
1562   // If we are generating register pairs for a Windows function that requires
1563   // EH support, then pair consecutive registers only.  There are no unwind
1564   // opcodes for saves/restores of non-consectuve register pairs.
1565   // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x.
1566   // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1567 
1568   // TODO: LR can be paired with any register.  We don't support this yet in
1569   // the MCLayer.  We need to add support for the save_lrpair unwind code.
1570   if (!NeedsWinCFI)
1571     return false;
1572   if (Reg2 == Reg1 + 1)
1573     return false;
1574   return true;
1575 }
1576 
1577 namespace {
1578 
1579 struct RegPairInfo {
1580   unsigned Reg1 = AArch64::NoRegister;
1581   unsigned Reg2 = AArch64::NoRegister;
1582   int FrameIdx;
1583   int Offset;
1584   enum RegType { GPR, FPR64, FPR128 } Type;
1585 
1586   RegPairInfo() = default;
1587 
1588   bool isPaired() const { return Reg2 != AArch64::NoRegister; }
1589 };
1590 
1591 } // end anonymous namespace
1592 
1593 static void computeCalleeSaveRegisterPairs(
1594     MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1595     const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1596     bool &NeedShadowCallStackProlog) {
1597 
1598   if (CSI.empty())
1599     return;
1600 
1601   bool NeedsWinCFI = needsWinCFI(MF);
1602   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1603   MachineFrameInfo &MFI = MF.getFrameInfo();
1604   CallingConv::ID CC = MF.getFunction().getCallingConv();
1605   unsigned Count = CSI.size();
1606   (void)CC;
1607   // MachO's compact unwind format relies on all registers being stored in
1608   // pairs.
1609   assert((!produceCompactUnwindFrame(MF) ||
1610           CC == CallingConv::PreserveMost ||
1611           (Count & 1) == 0) &&
1612          "Odd number of callee-saved regs to spill!");
1613   int Offset = AFI->getCalleeSavedStackSize();
1614   // On Linux, we will have either one or zero non-paired register.  On Windows
1615   // with CFI, we can have multiple unpaired registers in order to utilize the
1616   // available unwind codes.  This flag assures that the alignment fixup is done
1617   // only once, as intened.
1618   bool FixupDone = false;
1619   for (unsigned i = 0; i < Count; ++i) {
1620     RegPairInfo RPI;
1621     RPI.Reg1 = CSI[i].getReg();
1622 
1623     if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1624       RPI.Type = RegPairInfo::GPR;
1625     else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1626       RPI.Type = RegPairInfo::FPR64;
1627     else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1628       RPI.Type = RegPairInfo::FPR128;
1629     else
1630       llvm_unreachable("Unsupported register class.");
1631 
1632     // Add the next reg to the pair if it is in the same register class.
1633     if (i + 1 < Count) {
1634       unsigned NextReg = CSI[i + 1].getReg();
1635       switch (RPI.Type) {
1636       case RegPairInfo::GPR:
1637         if (AArch64::GPR64RegClass.contains(NextReg) &&
1638             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1639           RPI.Reg2 = NextReg;
1640         break;
1641       case RegPairInfo::FPR64:
1642         if (AArch64::FPR64RegClass.contains(NextReg) &&
1643             !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI))
1644           RPI.Reg2 = NextReg;
1645         break;
1646       case RegPairInfo::FPR128:
1647         if (AArch64::FPR128RegClass.contains(NextReg))
1648           RPI.Reg2 = NextReg;
1649         break;
1650       }
1651     }
1652 
1653     // If either of the registers to be saved is the lr register, it means that
1654     // we also need to save lr in the shadow call stack.
1655     if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
1656         MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
1657       if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
1658         report_fatal_error("Must reserve x18 to use shadow call stack");
1659       NeedShadowCallStackProlog = true;
1660     }
1661 
1662     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1663     // list to come in sorted by frame index so that we can issue the store
1664     // pair instructions directly. Assert if we see anything otherwise.
1665     //
1666     // The order of the registers in the list is controlled by
1667     // getCalleeSavedRegs(), so they will always be in-order, as well.
1668     assert((!RPI.isPaired() ||
1669             (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
1670            "Out of order callee saved regs!");
1671 
1672     // MachO's compact unwind format relies on all registers being stored in
1673     // adjacent register pairs.
1674     assert((!produceCompactUnwindFrame(MF) ||
1675             CC == CallingConv::PreserveMost ||
1676             (RPI.isPaired() &&
1677              ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1678               RPI.Reg1 + 1 == RPI.Reg2))) &&
1679            "Callee-save registers not saved as adjacent register pair!");
1680 
1681     RPI.FrameIdx = CSI[i].getFrameIdx();
1682 
1683     int Scale = RPI.Type == RegPairInfo::FPR128 ? 16 : 8;
1684     Offset -= RPI.isPaired() ? 2 * Scale : Scale;
1685 
1686     // Round up size of non-pair to pair size if we need to pad the
1687     // callee-save area to ensure 16-byte alignment.
1688     if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone &&
1689         RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired()) {
1690       FixupDone = true;
1691       Offset -= 8;
1692       assert(Offset % 16 == 0);
1693       assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1694       MFI.setObjectAlignment(RPI.FrameIdx, 16);
1695     }
1696 
1697     assert(Offset % Scale == 0);
1698     RPI.Offset = Offset / Scale;
1699     assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1700            "Offset out of bounds for LDP/STP immediate");
1701 
1702     RegPairs.push_back(RPI);
1703     if (RPI.isPaired())
1704       ++i;
1705   }
1706 }
1707 
1708 bool AArch64FrameLowering::spillCalleeSavedRegisters(
1709     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1710     const std::vector<CalleeSavedInfo> &CSI,
1711     const TargetRegisterInfo *TRI) const {
1712   MachineFunction &MF = *MBB.getParent();
1713   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1714   bool NeedsWinCFI = needsWinCFI(MF);
1715   DebugLoc DL;
1716   SmallVector<RegPairInfo, 8> RegPairs;
1717 
1718   bool NeedShadowCallStackProlog = false;
1719   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1720                                  NeedShadowCallStackProlog);
1721   const MachineRegisterInfo &MRI = MF.getRegInfo();
1722 
1723   if (NeedShadowCallStackProlog) {
1724     // Shadow call stack prolog: str x30, [x18], #8
1725     BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
1726         .addReg(AArch64::X18, RegState::Define)
1727         .addReg(AArch64::LR)
1728         .addReg(AArch64::X18)
1729         .addImm(8)
1730         .setMIFlag(MachineInstr::FrameSetup);
1731 
1732     if (NeedsWinCFI)
1733       BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop))
1734           .setMIFlag(MachineInstr::FrameSetup);
1735 
1736     // Emit a CFI instruction that causes 8 to be subtracted from the value of
1737     // x18 when unwinding past this frame.
1738     static const char CFIInst[] = {
1739         dwarf::DW_CFA_val_expression,
1740         18, // register
1741         2,  // length
1742         static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
1743         static_cast<char>(-8) & 0x7f, // addend (sleb128)
1744     };
1745     unsigned CFIIndex =
1746         MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, CFIInst));
1747     BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION))
1748         .addCFIIndex(CFIIndex)
1749         .setMIFlag(MachineInstr::FrameSetup);
1750 
1751     // This instruction also makes x18 live-in to the entry block.
1752     MBB.addLiveIn(AArch64::X18);
1753   }
1754 
1755   for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
1756        ++RPII) {
1757     RegPairInfo RPI = *RPII;
1758     unsigned Reg1 = RPI.Reg1;
1759     unsigned Reg2 = RPI.Reg2;
1760     unsigned StrOpc;
1761 
1762     // Issue sequence of spills for cs regs.  The first spill may be converted
1763     // to a pre-decrement store later by emitPrologue if the callee-save stack
1764     // area allocation can't be combined with the local stack area allocation.
1765     // For example:
1766     //    stp     x22, x21, [sp, #0]     // addImm(+0)
1767     //    stp     x20, x19, [sp, #16]    // addImm(+2)
1768     //    stp     fp, lr, [sp, #32]      // addImm(+4)
1769     // Rationale: This sequence saves uop updates compared to a sequence of
1770     // pre-increment spills like stp xi,xj,[sp,#-16]!
1771     // Note: Similar rationale and sequence for restores in epilog.
1772     unsigned Size, Align;
1773     switch (RPI.Type) {
1774     case RegPairInfo::GPR:
1775        StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1776        Size = 8;
1777        Align = 8;
1778        break;
1779     case RegPairInfo::FPR64:
1780        StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1781        Size = 8;
1782        Align = 8;
1783        break;
1784     case RegPairInfo::FPR128:
1785        StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
1786        Size = 16;
1787        Align = 16;
1788        break;
1789     }
1790     LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
1791                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1792                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1793                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1794                dbgs() << ")\n");
1795 
1796     assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
1797            "Windows unwdinding requires a consecutive (FP,LR) pair");
1798     // Windows unwind codes require consecutive registers if registers are
1799     // paired.  Make the switch here, so that the code below will save (x,x+1)
1800     // and not (x+1,x).
1801     unsigned FrameIdxReg1 = RPI.FrameIdx;
1802     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1803     if (NeedsWinCFI && RPI.isPaired()) {
1804       std::swap(Reg1, Reg2);
1805       std::swap(FrameIdxReg1, FrameIdxReg2);
1806     }
1807     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
1808     if (!MRI.isReserved(Reg1))
1809       MBB.addLiveIn(Reg1);
1810     if (RPI.isPaired()) {
1811       if (!MRI.isReserved(Reg2))
1812         MBB.addLiveIn(Reg2);
1813       MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
1814       MIB.addMemOperand(MF.getMachineMemOperand(
1815           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1816           MachineMemOperand::MOStore, Size, Align));
1817     }
1818     MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1819         .addReg(AArch64::SP)
1820         .addImm(RPI.Offset) // [sp, #offset*scale],
1821                             // where factor*scale is implicit
1822         .setMIFlag(MachineInstr::FrameSetup);
1823     MIB.addMemOperand(MF.getMachineMemOperand(
1824         MachinePointerInfo::getFixedStack(MF,FrameIdxReg1),
1825         MachineMemOperand::MOStore, Size, Align));
1826     if (NeedsWinCFI)
1827       InsertSEH(MIB, TII, MachineInstr::FrameSetup);
1828 
1829   }
1830   return true;
1831 }
1832 
1833 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1834     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1835     std::vector<CalleeSavedInfo> &CSI,
1836     const TargetRegisterInfo *TRI) const {
1837   MachineFunction &MF = *MBB.getParent();
1838   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1839   DebugLoc DL;
1840   SmallVector<RegPairInfo, 8> RegPairs;
1841   bool NeedsWinCFI = needsWinCFI(MF);
1842 
1843   if (MI != MBB.end())
1844     DL = MI->getDebugLoc();
1845 
1846   bool NeedShadowCallStackProlog = false;
1847   computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1848                                  NeedShadowCallStackProlog);
1849 
1850   auto EmitMI = [&](const RegPairInfo &RPI) {
1851     unsigned Reg1 = RPI.Reg1;
1852     unsigned Reg2 = RPI.Reg2;
1853 
1854     // Issue sequence of restores for cs regs. The last restore may be converted
1855     // to a post-increment load later by emitEpilogue if the callee-save stack
1856     // area allocation can't be combined with the local stack area allocation.
1857     // For example:
1858     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
1859     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
1860     //    ldp     x22, x21, [sp, #0]      // addImm(+0)
1861     // Note: see comment in spillCalleeSavedRegisters()
1862     unsigned LdrOpc;
1863     unsigned Size, Align;
1864     switch (RPI.Type) {
1865     case RegPairInfo::GPR:
1866        LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1867        Size = 8;
1868        Align = 8;
1869        break;
1870     case RegPairInfo::FPR64:
1871        LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1872        Size = 8;
1873        Align = 8;
1874        break;
1875     case RegPairInfo::FPR128:
1876        LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
1877        Size = 16;
1878        Align = 16;
1879        break;
1880     }
1881     LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
1882                if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1883                dbgs() << ") -> fi#(" << RPI.FrameIdx;
1884                if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1885                dbgs() << ")\n");
1886 
1887     // Windows unwind codes require consecutive registers if registers are
1888     // paired.  Make the switch here, so that the code below will save (x,x+1)
1889     // and not (x+1,x).
1890     unsigned FrameIdxReg1 = RPI.FrameIdx;
1891     unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
1892     if (NeedsWinCFI && RPI.isPaired()) {
1893       std::swap(Reg1, Reg2);
1894       std::swap(FrameIdxReg1, FrameIdxReg2);
1895     }
1896     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
1897     if (RPI.isPaired()) {
1898       MIB.addReg(Reg2, getDefRegState(true));
1899       MIB.addMemOperand(MF.getMachineMemOperand(
1900           MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
1901           MachineMemOperand::MOLoad, Size, Align));
1902     }
1903     MIB.addReg(Reg1, getDefRegState(true))
1904         .addReg(AArch64::SP)
1905         .addImm(RPI.Offset) // [sp, #offset*scale]
1906                             // where factor*scale is implicit
1907         .setMIFlag(MachineInstr::FrameDestroy);
1908     MIB.addMemOperand(MF.getMachineMemOperand(
1909         MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
1910         MachineMemOperand::MOLoad, Size, Align));
1911     if (NeedsWinCFI)
1912       InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
1913   };
1914   if (ReverseCSRRestoreSeq)
1915     for (const RegPairInfo &RPI : reverse(RegPairs))
1916       EmitMI(RPI);
1917   else
1918     for (const RegPairInfo &RPI : RegPairs)
1919       EmitMI(RPI);
1920 
1921   if (NeedShadowCallStackProlog) {
1922     // Shadow call stack epilog: ldr x30, [x18, #-8]!
1923     BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
1924         .addReg(AArch64::X18, RegState::Define)
1925         .addReg(AArch64::LR, RegState::Define)
1926         .addReg(AArch64::X18)
1927         .addImm(-8)
1928         .setMIFlag(MachineInstr::FrameDestroy);
1929   }
1930 
1931   return true;
1932 }
1933 
1934 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1935                                                 BitVector &SavedRegs,
1936                                                 RegScavenger *RS) const {
1937   // All calls are tail calls in GHC calling conv, and functions have no
1938   // prologue/epilogue.
1939   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1940     return;
1941 
1942   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1943   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1944       MF.getSubtarget().getRegisterInfo());
1945   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1946   unsigned UnspilledCSGPR = AArch64::NoRegister;
1947   unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
1948 
1949   MachineFrameInfo &MFI = MF.getFrameInfo();
1950   const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
1951 
1952   unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
1953                                 ? RegInfo->getBaseRegister()
1954                                 : (unsigned)AArch64::NoRegister;
1955 
1956   unsigned ExtraCSSpill = 0;
1957   // Figure out which callee-saved registers to save/restore.
1958   for (unsigned i = 0; CSRegs[i]; ++i) {
1959     const unsigned Reg = CSRegs[i];
1960 
1961     // Add the base pointer register to SavedRegs if it is callee-save.
1962     if (Reg == BasePointerReg)
1963       SavedRegs.set(Reg);
1964 
1965     bool RegUsed = SavedRegs.test(Reg);
1966     unsigned PairedReg = CSRegs[i ^ 1];
1967     if (!RegUsed) {
1968       if (AArch64::GPR64RegClass.contains(Reg) &&
1969           !RegInfo->isReservedReg(MF, Reg)) {
1970         UnspilledCSGPR = Reg;
1971         UnspilledCSGPRPaired = PairedReg;
1972       }
1973       continue;
1974     }
1975 
1976     // MachO's compact unwind format relies on all registers being stored in
1977     // pairs.
1978     // FIXME: the usual format is actually better if unwinding isn't needed.
1979     if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
1980         !SavedRegs.test(PairedReg)) {
1981       SavedRegs.set(PairedReg);
1982       if (AArch64::GPR64RegClass.contains(PairedReg) &&
1983           !RegInfo->isReservedReg(MF, PairedReg))
1984         ExtraCSSpill = PairedReg;
1985     }
1986   }
1987 
1988   // Calculates the callee saved stack size.
1989   unsigned CSStackSize = 0;
1990   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1991   const MachineRegisterInfo &MRI = MF.getRegInfo();
1992   for (unsigned Reg : SavedRegs.set_bits())
1993     CSStackSize += TRI->getRegSizeInBits(Reg, MRI) / 8;
1994 
1995   // Save number of saved regs, so we can easily update CSStackSize later.
1996   unsigned NumSavedRegs = SavedRegs.count();
1997 
1998   // The frame record needs to be created by saving the appropriate registers
1999   unsigned EstimatedStackSize = MFI.estimateStackSize(MF);
2000   if (hasFP(MF) ||
2001       windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2002     SavedRegs.set(AArch64::FP);
2003     SavedRegs.set(AArch64::LR);
2004   }
2005 
2006   LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
2007              for (unsigned Reg
2008                   : SavedRegs.set_bits()) dbgs()
2009              << ' ' << printReg(Reg, RegInfo);
2010              dbgs() << "\n";);
2011 
2012   // If any callee-saved registers are used, the frame cannot be eliminated.
2013   bool CanEliminateFrame = SavedRegs.count() == 0;
2014 
2015   // The CSR spill slots have not been allocated yet, so estimateStackSize
2016   // won't include them.
2017   unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2018   bool BigStack = (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
2019   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2020     AFI->setHasStackFrame(true);
2021 
2022   // Estimate if we might need to scavenge a register at some point in order
2023   // to materialize a stack offset. If so, either spill one additional
2024   // callee-saved register or reserve a special spill slot to facilitate
2025   // register scavenging. If we already spilled an extra callee-saved register
2026   // above to keep the number of spills even, we don't need to do anything else
2027   // here.
2028   if (BigStack) {
2029     if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
2030       LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2031                         << " to get a scratch register.\n");
2032       SavedRegs.set(UnspilledCSGPR);
2033       // MachO's compact unwind format relies on all registers being stored in
2034       // pairs, so if we need to spill one extra for BigStack, then we need to
2035       // store the pair.
2036       if (produceCompactUnwindFrame(MF))
2037         SavedRegs.set(UnspilledCSGPRPaired);
2038       ExtraCSSpill = UnspilledCSGPRPaired;
2039     }
2040 
2041     // If we didn't find an extra callee-saved register to spill, create
2042     // an emergency spill slot.
2043     if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2044       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2045       const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2046       unsigned Size = TRI->getSpillSize(RC);
2047       unsigned Align = TRI->getSpillAlignment(RC);
2048       int FI = MFI.CreateStackObject(Size, Align, false);
2049       RS->addScavengingFrameIndex(FI);
2050       LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2051                         << " as the emergency spill slot.\n");
2052     }
2053   }
2054 
2055   // Adding the size of additional 64bit GPR saves.
2056   CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2057   unsigned AlignedCSStackSize = alignTo(CSStackSize, 16);
2058   LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2059                << EstimatedStackSize + AlignedCSStackSize
2060                << " bytes.\n");
2061 
2062   // Round up to register pair alignment to avoid additional SP adjustment
2063   // instructions.
2064   AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2065   AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2066 }
2067 
2068 bool AArch64FrameLowering::enableStackSlotScavenging(
2069     const MachineFunction &MF) const {
2070   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2071   return AFI->hasCalleeSaveStackFreeSpace();
2072 }
2073 
2074 void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
2075     MachineFunction &MF, RegScavenger *RS) const {
2076   // If this function isn't doing Win64-style C++ EH, we don't need to do
2077   // anything.
2078   if (!MF.hasEHFunclets())
2079     return;
2080   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2081   MachineFrameInfo &MFI = MF.getFrameInfo();
2082   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
2083 
2084   MachineBasicBlock &MBB = MF.front();
2085   auto MBBI = MBB.begin();
2086   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2087     ++MBBI;
2088 
2089   if (MBBI->isTerminator())
2090     return;
2091 
2092   // Create an UnwindHelp object.
2093   int UnwindHelpFI =
2094       MFI.CreateStackObject(/*size*/8, /*alignment*/16, false);
2095   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
2096   // We need to store -2 into the UnwindHelp object at the start of the
2097   // function.
2098   DebugLoc DL;
2099   RS->enterBasicBlock(MBB);
2100   unsigned DstReg = RS->scavengeRegister(&AArch64::GPR64RegClass, MBBI, 0);
2101   BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
2102   BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
2103       .addReg(DstReg, getKillRegState(true))
2104       .addFrameIndex(UnwindHelpFI)
2105       .addImm(0);
2106 }
2107 
2108 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before
2109 /// the update.  This is easily retrieved as it is exactly the offset that is set
2110 /// in processFunctionBeforeFrameFinalized.
2111 int AArch64FrameLowering::getFrameIndexReferencePreferSP(
2112     const MachineFunction &MF, int FI, unsigned &FrameReg,
2113     bool IgnoreSPUpdates) const {
2114   const MachineFrameInfo &MFI = MF.getFrameInfo();
2115   LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
2116                     << MFI.getObjectOffset(FI) << "\n");
2117   FrameReg = AArch64::SP;
2118   return MFI.getObjectOffset(FI);
2119 }
2120 
2121 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
2122 /// the parent's frame pointer
2123 unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
2124     const MachineFunction &MF) const {
2125   return 0;
2126 }
2127 
2128 /// Funclets only need to account for space for the callee saved registers,
2129 /// as the locals are accounted for in the parent's stack frame.
2130 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
2131     const MachineFunction &MF) const {
2132   // This is the size of the pushed CSRs.
2133   unsigned CSSize =
2134       MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
2135   // This is the amount of stack a funclet needs to allocate.
2136   return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
2137                  getStackAlignment());
2138 }
2139