[Stackmaps] Make ithe frame-pointer required for stackmaps.
[oota-llvm.git] / lib / Target / AArch64 / AArch64FrameLowering.cpp
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 //===----------------------------------------------------------------------===//
13
14 #include "AArch64FrameLowering.h"
15 #include "AArch64InstrInfo.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31
32 using namespace llvm;
33
34 #define DEBUG_TYPE "frame-info"
35
36 static cl::opt<bool> EnableRedZone("aarch64-redzone",
37                                    cl::desc("enable use of redzone on AArch64"),
38                                    cl::init(false), cl::Hidden);
39
40 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
41
42 static unsigned estimateStackSize(MachineFunction &MF) {
43   const MachineFrameInfo *FFI = MF.getFrameInfo();
44   int Offset = 0;
45   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
46     int FixedOff = -FFI->getObjectOffset(i);
47     if (FixedOff > Offset)
48       Offset = FixedOff;
49   }
50   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
51     if (FFI->isDeadObjectIndex(i))
52       continue;
53     Offset += FFI->getObjectSize(i);
54     unsigned Align = FFI->getObjectAlignment(i);
55     // Adjust to alignment boundary
56     Offset = (Offset + Align - 1) / Align * Align;
57   }
58   // This does not include the 16 bytes used for fp and lr.
59   return (unsigned)Offset;
60 }
61
62 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
63   if (!EnableRedZone)
64     return false;
65   // Don't use the red zone if the function explicitly asks us not to.
66   // This is typically used for kernel code.
67   if (MF.getFunction()->getAttributes().hasAttribute(
68           AttributeSet::FunctionIndex, Attribute::NoRedZone))
69     return false;
70
71   const MachineFrameInfo *MFI = MF.getFrameInfo();
72   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
73   unsigned NumBytes = AFI->getLocalStackSize();
74
75   // Note: currently hasFP() is always true for hasCalls(), but that's an
76   // implementation detail of the current code, not a strict requirement,
77   // so stay safe here and check both.
78   if (MFI->hasCalls() || hasFP(MF) || NumBytes > 128)
79     return false;
80   return true;
81 }
82
83 /// hasFP - Return true if the specified function should have a dedicated frame
84 /// pointer register.
85 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
86   const MachineFrameInfo *MFI = MF.getFrameInfo();
87
88 #ifndef NDEBUG
89   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
90   assert(!RegInfo->needsStackRealignment(MF) &&
91          "No stack realignment on AArch64!");
92 #endif
93
94   return (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
95           MFI->isFrameAddressTaken() || MFI->hasStackMap() ||
96           MFI->hasPatchPoint());
97 }
98
99 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
100 /// not required, we reserve argument space for call sites in the function
101 /// immediately on entry to the current function.  This eliminates the need for
102 /// add/sub sp brackets around call sites.  Returns true if the call frame is
103 /// included as part of the stack frame.
104 bool
105 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
106   return !MF.getFrameInfo()->hasVarSizedObjects();
107 }
108
109 void AArch64FrameLowering::eliminateCallFramePseudoInstr(
110     MachineFunction &MF, MachineBasicBlock &MBB,
111     MachineBasicBlock::iterator I) const {
112   const AArch64InstrInfo *TII =
113       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
114   DebugLoc DL = I->getDebugLoc();
115   int Opc = I->getOpcode();
116   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
117   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
118
119   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
120   if (!TFI->hasReservedCallFrame(MF)) {
121     unsigned Align = getStackAlignment();
122
123     int64_t Amount = I->getOperand(0).getImm();
124     Amount = RoundUpToAlignment(Amount, Align);
125     if (!IsDestroy)
126       Amount = -Amount;
127
128     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
129     // doesn't have to pop anything), then the first operand will be zero too so
130     // this adjustment is a no-op.
131     if (CalleePopAmount == 0) {
132       // FIXME: in-function stack adjustment for calls is limited to 24-bits
133       // because there's no guaranteed temporary register available.
134       //
135       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
136       // 1) For offset <= 12-bit, we use LSL #0
137       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
138       // LSL #0, and the other uses LSL #12.
139       //
140       // Mostly call frames will be allocated at the start of a function so
141       // this is OK, but it is a limitation that needs dealing with.
142       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
143       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
144     }
145   } else if (CalleePopAmount != 0) {
146     // If the calling convention demands that the callee pops arguments from the
147     // stack, we want to add it back if we have a reserved call frame.
148     assert(CalleePopAmount < 0xffffff && "call frame too large");
149     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
150                     TII);
151   }
152   MBB.erase(I);
153 }
154
155 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
156     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
157     unsigned FramePtr) const {
158   MachineFunction &MF = *MBB.getParent();
159   MachineFrameInfo *MFI = MF.getFrameInfo();
160   MachineModuleInfo &MMI = MF.getMMI();
161   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
162   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
163   DebugLoc DL = MBB.findDebugLoc(MBBI);
164
165   // Add callee saved registers to move list.
166   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
167   if (CSI.empty())
168     return;
169
170   const DataLayout *TD = MF.getSubtarget().getDataLayout();
171   bool HasFP = hasFP(MF);
172
173   // Calculate amount of bytes used for return address storing.
174   int stackGrowth = -TD->getPointerSize(0);
175
176   // Calculate offsets.
177   int64_t saveAreaOffset = (HasFP ? 2 : 1) * stackGrowth;
178   unsigned TotalSkipped = 0;
179   for (const auto &Info : CSI) {
180     unsigned Reg = Info.getReg();
181     int64_t Offset = MFI->getObjectOffset(Info.getFrameIdx()) -
182                      getOffsetOfLocalArea() + saveAreaOffset;
183
184     // Don't output a new CFI directive if we're re-saving the frame pointer or
185     // link register. This happens when the PrologEpilogInserter has inserted an
186     // extra "STP" of the frame pointer and link register -- the "emitPrologue"
187     // method automatically generates the directives when frame pointers are
188     // used. If we generate CFI directives for the extra "STP"s, the linker will
189     // lose track of the correct values for the frame pointer and link register.
190     if (HasFP && (FramePtr == Reg || Reg == AArch64::LR)) {
191       TotalSkipped += stackGrowth;
192       continue;
193     }
194
195     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
196     unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
197         nullptr, DwarfReg, Offset - TotalSkipped));
198     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
199         .addCFIIndex(CFIIndex);
200   }
201 }
202
203 void AArch64FrameLowering::emitPrologue(MachineFunction &MF) const {
204   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
205   MachineBasicBlock::iterator MBBI = MBB.begin();
206   const MachineFrameInfo *MFI = MF.getFrameInfo();
207   const Function *Fn = MF.getFunction();
208   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
209       MF.getSubtarget().getRegisterInfo());
210   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
211   MachineModuleInfo &MMI = MF.getMMI();
212   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
213   bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
214   bool HasFP = hasFP(MF);
215   DebugLoc DL = MBB.findDebugLoc(MBBI);
216
217   int NumBytes = (int)MFI->getStackSize();
218   if (!AFI->hasStackFrame()) {
219     assert(!HasFP && "unexpected function without stack frame but with FP");
220
221     // All of the stack allocation is for locals.
222     AFI->setLocalStackSize(NumBytes);
223
224     // Label used to tie together the PROLOG_LABEL and the MachineMoves.
225     MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
226
227     // REDZONE: If the stack size is less than 128 bytes, we don't need
228     // to actually allocate.
229     if (NumBytes && !canUseRedZone(MF)) {
230       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
231                       MachineInstr::FrameSetup);
232
233       // Encode the stack size of the leaf function.
234       unsigned CFIIndex = MMI.addFrameInst(
235           MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
236       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
237           .addCFIIndex(CFIIndex);
238     } else if (NumBytes) {
239       ++NumRedZoneFunctions;
240     }
241
242     return;
243   }
244
245   // Only set up FP if we actually need to.
246   int FPOffset = 0;
247   if (HasFP) {
248     // First instruction must a) allocate the stack  and b) have an immediate
249     // that is a multiple of -2.
250     assert((MBBI->getOpcode() == AArch64::STPXpre ||
251             MBBI->getOpcode() == AArch64::STPDpre) &&
252            MBBI->getOperand(3).getReg() == AArch64::SP &&
253            MBBI->getOperand(4).getImm() < 0 &&
254            (MBBI->getOperand(4).getImm() & 1) == 0);
255
256     // Frame pointer is fp = sp - 16. Since the  STPXpre subtracts the space
257     // required for the callee saved register area we get the frame pointer
258     // by addding that offset - 16 = -getImm()*8 - 2*8 = -(getImm() + 2) * 8.
259     FPOffset = -(MBBI->getOperand(4).getImm() + 2) * 8;
260     assert(FPOffset >= 0 && "Bad Framepointer Offset");
261   }
262
263   // Move past the saves of the callee-saved registers.
264   while (MBBI->getOpcode() == AArch64::STPXi ||
265          MBBI->getOpcode() == AArch64::STPDi ||
266          MBBI->getOpcode() == AArch64::STPXpre ||
267          MBBI->getOpcode() == AArch64::STPDpre) {
268     ++MBBI;
269     NumBytes -= 16;
270   }
271   assert(NumBytes >= 0 && "Negative stack allocation size!?");
272   if (HasFP) {
273     // Issue    sub fp, sp, FPOffset or
274     //          mov fp,sp          when FPOffset is zero.
275     // Note: All stores of callee-saved registers are marked as "FrameSetup".
276     // This code marks the instruction(s) that set the FP also.
277     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
278                     MachineInstr::FrameSetup);
279   }
280
281   // All of the remaining stack allocations are for locals.
282   AFI->setLocalStackSize(NumBytes);
283
284   // Allocate space for the rest of the frame.
285   if (NumBytes) {
286     // If we're a leaf function, try using the red zone.
287     if (!canUseRedZone(MF))
288       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
289                       MachineInstr::FrameSetup);
290   }
291
292   // If we need a base pointer, set it up here. It's whatever the value of the
293   // stack pointer is at this point. Any variable size objects will be allocated
294   // after this, so we can still use the base pointer to reference locals.
295   //
296   // FIXME: Clarify FrameSetup flags here.
297   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
298   // needed.
299   //
300   if (RegInfo->hasBasePointer(MF))
301     TII->copyPhysReg(MBB, MBBI, DL, AArch64::X19, AArch64::SP, false);
302
303   if (needsFrameMoves) {
304     const DataLayout *TD = MF.getSubtarget().getDataLayout();
305     const int StackGrowth = -TD->getPointerSize(0);
306     unsigned FramePtr = RegInfo->getFrameRegister(MF);
307
308     // An example of the prologue:
309     //
310     //     .globl __foo
311     //     .align 2
312     //  __foo:
313     // Ltmp0:
314     //     .cfi_startproc
315     //     .cfi_personality 155, ___gxx_personality_v0
316     // Leh_func_begin:
317     //     .cfi_lsda 16, Lexception33
318     //
319     //     stp  xa,bx, [sp, -#offset]!
320     //     ...
321     //     stp  x28, x27, [sp, #offset-32]
322     //     stp  fp, lr, [sp, #offset-16]
323     //     add  fp, sp, #offset - 16
324     //     sub  sp, sp, #1360
325     //
326     // The Stack:
327     //       +-------------------------------------------+
328     // 10000 | ........ | ........ | ........ | ........ |
329     // 10004 | ........ | ........ | ........ | ........ |
330     //       +-------------------------------------------+
331     // 10008 | ........ | ........ | ........ | ........ |
332     // 1000c | ........ | ........ | ........ | ........ |
333     //       +===========================================+
334     // 10010 |                X28 Register               |
335     // 10014 |                X28 Register               |
336     //       +-------------------------------------------+
337     // 10018 |                X27 Register               |
338     // 1001c |                X27 Register               |
339     //       +===========================================+
340     // 10020 |                Frame Pointer              |
341     // 10024 |                Frame Pointer              |
342     //       +-------------------------------------------+
343     // 10028 |                Link Register              |
344     // 1002c |                Link Register              |
345     //       +===========================================+
346     // 10030 | ........ | ........ | ........ | ........ |
347     // 10034 | ........ | ........ | ........ | ........ |
348     //       +-------------------------------------------+
349     // 10038 | ........ | ........ | ........ | ........ |
350     // 1003c | ........ | ........ | ........ | ........ |
351     //       +-------------------------------------------+
352     //
353     //     [sp] = 10030        ::    >>initial value<<
354     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
355     //     fp = sp == 10020    ::  mov fp, sp
356     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
357     //     sp == 10010         ::    >>final value<<
358     //
359     // The frame pointer (w29) points to address 10020. If we use an offset of
360     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
361     // for w27, and -32 for w28:
362     //
363     //  Ltmp1:
364     //     .cfi_def_cfa w29, 16
365     //  Ltmp2:
366     //     .cfi_offset w30, -8
367     //  Ltmp3:
368     //     .cfi_offset w29, -16
369     //  Ltmp4:
370     //     .cfi_offset w27, -24
371     //  Ltmp5:
372     //     .cfi_offset w28, -32
373
374     if (HasFP) {
375       // Define the current CFA rule to use the provided FP.
376       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
377       unsigned CFIIndex = MMI.addFrameInst(
378           MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
379       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
380           .addCFIIndex(CFIIndex);
381
382       // Record the location of the stored LR
383       unsigned LR = RegInfo->getDwarfRegNum(AArch64::LR, true);
384       CFIIndex = MMI.addFrameInst(
385           MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
386       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
387           .addCFIIndex(CFIIndex);
388
389       // Record the location of the stored FP
390       CFIIndex = MMI.addFrameInst(
391           MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
392       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
393           .addCFIIndex(CFIIndex);
394     } else {
395       // Encode the stack size of the leaf function.
396       unsigned CFIIndex = MMI.addFrameInst(
397           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
398       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
399           .addCFIIndex(CFIIndex);
400     }
401
402     // Now emit the moves for whatever callee saved regs we have.
403     emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
404   }
405 }
406
407 static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
408   for (unsigned i = 0; CSRegs[i]; ++i)
409     if (Reg == CSRegs[i])
410       return true;
411   return false;
412 }
413
414 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
415   unsigned RtIdx = 0;
416   if (MI->getOpcode() == AArch64::LDPXpost ||
417       MI->getOpcode() == AArch64::LDPDpost)
418     RtIdx = 1;
419
420   if (MI->getOpcode() == AArch64::LDPXpost ||
421       MI->getOpcode() == AArch64::LDPDpost ||
422       MI->getOpcode() == AArch64::LDPXi || MI->getOpcode() == AArch64::LDPDi) {
423     if (!isCalleeSavedRegister(MI->getOperand(RtIdx).getReg(), CSRegs) ||
424         !isCalleeSavedRegister(MI->getOperand(RtIdx + 1).getReg(), CSRegs) ||
425         MI->getOperand(RtIdx + 2).getReg() != AArch64::SP)
426       return false;
427     return true;
428   }
429
430   return false;
431 }
432
433 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
434                                         MachineBasicBlock &MBB) const {
435   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
436   assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
437   MachineFrameInfo *MFI = MF.getFrameInfo();
438   const AArch64InstrInfo *TII =
439       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
440   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
441       MF.getSubtarget().getRegisterInfo());
442   DebugLoc DL = MBBI->getDebugLoc();
443   unsigned RetOpcode = MBBI->getOpcode();
444
445   int NumBytes = MFI->getStackSize();
446   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
447
448   // Initial and residual are named for consitency with the prologue. Note that
449   // in the epilogue, the residual adjustment is executed first.
450   uint64_t ArgumentPopSize = 0;
451   if (RetOpcode == AArch64::TCRETURNdi || RetOpcode == AArch64::TCRETURNri) {
452     MachineOperand &StackAdjust = MBBI->getOperand(1);
453
454     // For a tail-call in a callee-pops-arguments environment, some or all of
455     // the stack may actually be in use for the call's arguments, this is
456     // calculated during LowerCall and consumed here...
457     ArgumentPopSize = StackAdjust.getImm();
458   } else {
459     // ... otherwise the amount to pop is *all* of the argument space,
460     // conveniently stored in the MachineFunctionInfo by
461     // LowerFormalArguments. This will, of course, be zero for the C calling
462     // convention.
463     ArgumentPopSize = AFI->getArgumentStackToRestore();
464   }
465
466   // The stack frame should be like below,
467   //
468   //      ----------------------                     ---
469   //      |                    |                      |
470   //      | BytesInStackArgArea|              CalleeArgStackSize
471   //      | (NumReusableBytes) |                (of tail call)
472   //      |                    |                     ---
473   //      |                    |                      |
474   //      ---------------------|        ---           |
475   //      |                    |         |            |
476   //      |   CalleeSavedReg   |         |            |
477   //      | (NumRestores * 16) |         |            |
478   //      |                    |         |            |
479   //      ---------------------|         |         NumBytes
480   //      |                    |     StackSize  (StackAdjustUp)
481   //      |   LocalStackSize   |         |            |
482   //      | (covering callee   |         |            |
483   //      |       args)        |         |            |
484   //      |                    |         |            |
485   //      ----------------------        ---          ---
486   //
487   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
488   //             = StackSize + ArgumentPopSize
489   //
490   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
491   // it as the 2nd argument of AArch64ISD::TC_RETURN.
492   NumBytes += ArgumentPopSize;
493
494   unsigned NumRestores = 0;
495   // Move past the restores of the callee-saved registers.
496   MachineBasicBlock::iterator LastPopI = MBBI;
497   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
498   if (LastPopI != MBB.begin()) {
499     do {
500       ++NumRestores;
501       --LastPopI;
502     } while (LastPopI != MBB.begin() && isCSRestore(LastPopI, CSRegs));
503     if (!isCSRestore(LastPopI, CSRegs)) {
504       ++LastPopI;
505       --NumRestores;
506     }
507   }
508   NumBytes -= NumRestores * 16;
509   assert(NumBytes >= 0 && "Negative stack allocation size!?");
510
511   if (!hasFP(MF)) {
512     // If this was a redzone leaf function, we don't need to restore the
513     // stack pointer.
514     if (!canUseRedZone(MF))
515       emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes,
516                       TII);
517     return;
518   }
519
520   // Restore the original stack pointer.
521   // FIXME: Rather than doing the math here, we should instead just use
522   // non-post-indexed loads for the restores if we aren't actually going to
523   // be able to save any instructions.
524   if (NumBytes || MFI->hasVarSizedObjects())
525     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
526                     -(NumRestores - 1) * 16, TII, MachineInstr::NoFlags);
527 }
528
529 /// getFrameIndexOffset - Returns the displacement from the frame register to
530 /// the stack frame of the specified index.
531 int AArch64FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
532                                               int FI) const {
533   unsigned FrameReg;
534   return getFrameIndexReference(MF, FI, FrameReg);
535 }
536
537 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
538 /// debug info.  It's the same as what we use for resolving the code-gen
539 /// references for now.  FIXME: This can go wrong when references are
540 /// SP-relative and simple call frames aren't used.
541 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
542                                                  int FI,
543                                                  unsigned &FrameReg) const {
544   return resolveFrameIndexReference(MF, FI, FrameReg);
545 }
546
547 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
548                                                      int FI, unsigned &FrameReg,
549                                                      bool PreferFP) const {
550   const MachineFrameInfo *MFI = MF.getFrameInfo();
551   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
552       MF.getSubtarget().getRegisterInfo());
553   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
554   int FPOffset = MFI->getObjectOffset(FI) + 16;
555   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
556   bool isFixed = MFI->isFixedObjectIndex(FI);
557
558   // Use frame pointer to reference fixed objects. Use it for locals if
559   // there are VLAs (and thus the SP isn't reliable as a base).
560   // Make sure useFPForScavengingIndex() does the right thing for the emergency
561   // spill slot.
562   bool UseFP = false;
563   if (AFI->hasStackFrame()) {
564     // Note: Keeping the following as multiple 'if' statements rather than
565     // merging to a single expression for readability.
566     //
567     // Argument access should always use the FP.
568     if (isFixed) {
569       UseFP = hasFP(MF);
570     } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF)) {
571       // Use SP or FP, whichever gives us the best chance of the offset
572       // being in range for direct access. If the FPOffset is positive,
573       // that'll always be best, as the SP will be even further away.
574       // If the FPOffset is negative, we have to keep in mind that the
575       // available offset range for negative offsets is smaller than for
576       // positive ones. If we have variable sized objects, we're stuck with
577       // using the FP regardless, though, as the SP offset is unknown
578       // and we don't have a base pointer available. If an offset is
579       // available via the FP and the SP, use whichever is closest.
580       if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
581           (FPOffset >= -256 && Offset > -FPOffset))
582         UseFP = true;
583     }
584   }
585
586   if (UseFP) {
587     FrameReg = RegInfo->getFrameRegister(MF);
588     return FPOffset;
589   }
590
591   // Use the base pointer if we have one.
592   if (RegInfo->hasBasePointer(MF))
593     FrameReg = RegInfo->getBaseRegister();
594   else {
595     FrameReg = AArch64::SP;
596     // If we're using the red zone for this function, the SP won't actually
597     // be adjusted, so the offsets will be negative. They're also all
598     // within range of the signed 9-bit immediate instructions.
599     if (canUseRedZone(MF))
600       Offset -= AFI->getLocalStackSize();
601   }
602
603   return Offset;
604 }
605
606 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
607   if (Reg != AArch64::LR)
608     return getKillRegState(true);
609
610   // LR maybe referred to later by an @llvm.returnaddress intrinsic.
611   bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
612   bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
613   return getKillRegState(LRKill);
614 }
615
616 bool AArch64FrameLowering::spillCalleeSavedRegisters(
617     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
618     const std::vector<CalleeSavedInfo> &CSI,
619     const TargetRegisterInfo *TRI) const {
620   MachineFunction &MF = *MBB.getParent();
621   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
622   unsigned Count = CSI.size();
623   DebugLoc DL;
624   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
625
626   if (MI != MBB.end())
627     DL = MI->getDebugLoc();
628
629   for (unsigned i = 0; i < Count; i += 2) {
630     unsigned idx = Count - i - 2;
631     unsigned Reg1 = CSI[idx].getReg();
632     unsigned Reg2 = CSI[idx + 1].getReg();
633     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
634     // list to come in sorted by frame index so that we can issue the store
635     // pair instructions directly. Assert if we see anything otherwise.
636     //
637     // The order of the registers in the list is controlled by
638     // getCalleeSavedRegs(), so they will always be in-order, as well.
639     assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
640            "Out of order callee saved regs!");
641     unsigned StrOpc;
642     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
643     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
644     // Issue sequence of non-sp increment and pi sp spills for cs regs. The
645     // first spill is a pre-increment that allocates the stack.
646     // For example:
647     //    stp     x22, x21, [sp, #-48]!   // addImm(-6)
648     //    stp     x20, x19, [sp, #16]    // addImm(+2)
649     //    stp     fp, lr, [sp, #32]      // addImm(+4)
650     // Rationale: This sequence saves uop updates compared to a sequence of
651     // pre-increment spills like stp xi,xj,[sp,#-16]!
652     // Note: Similar rational and sequence for restores in epilog.
653     if (AArch64::GPR64RegClass.contains(Reg1)) {
654       assert(AArch64::GPR64RegClass.contains(Reg2) &&
655              "Expected GPR64 callee-saved register pair!");
656       // For first spill use pre-increment store.
657       if (i == 0)
658         StrOpc = AArch64::STPXpre;
659       else
660         StrOpc = AArch64::STPXi;
661     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
662       assert(AArch64::FPR64RegClass.contains(Reg2) &&
663              "Expected FPR64 callee-saved register pair!");
664       // For first spill use pre-increment store.
665       if (i == 0)
666         StrOpc = AArch64::STPDpre;
667       else
668         StrOpc = AArch64::STPDi;
669     } else
670       llvm_unreachable("Unexpected callee saved register!");
671     DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
672                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
673                  << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
674     // Compute offset: i = 0 => offset = -Count;
675     //                 i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
676     const int Offset = (i == 0) ? -Count : i;
677     assert((Offset >= -64 && Offset <= 63) &&
678            "Offset out of bounds for STP immediate");
679     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
680     if (StrOpc == AArch64::STPDpre || StrOpc == AArch64::STPXpre)
681       MIB.addReg(AArch64::SP, RegState::Define);
682
683     MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
684         .addReg(Reg1, getPrologueDeath(MF, Reg1))
685         .addReg(AArch64::SP)
686         .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
687         .setMIFlag(MachineInstr::FrameSetup);
688   }
689   return true;
690 }
691
692 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
693     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
694     const std::vector<CalleeSavedInfo> &CSI,
695     const TargetRegisterInfo *TRI) const {
696   MachineFunction &MF = *MBB.getParent();
697   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
698   unsigned Count = CSI.size();
699   DebugLoc DL;
700   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
701
702   if (MI != MBB.end())
703     DL = MI->getDebugLoc();
704
705   for (unsigned i = 0; i < Count; i += 2) {
706     unsigned Reg1 = CSI[i].getReg();
707     unsigned Reg2 = CSI[i + 1].getReg();
708     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
709     // list to come in sorted by frame index so that we can issue the store
710     // pair instructions directly. Assert if we see anything otherwise.
711     assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
712            "Out of order callee saved regs!");
713     // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
714     // the last load is sp-pi post-increment and de-allocates the stack:
715     // For example:
716     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
717     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
718     //    ldp     x22, x21, [sp], #48     // addImm(+6)
719     // Note: see comment in spillCalleeSavedRegisters()
720     unsigned LdrOpc;
721
722     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
723     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
724     if (AArch64::GPR64RegClass.contains(Reg1)) {
725       assert(AArch64::GPR64RegClass.contains(Reg2) &&
726              "Expected GPR64 callee-saved register pair!");
727       if (i == Count - 2)
728         LdrOpc = AArch64::LDPXpost;
729       else
730         LdrOpc = AArch64::LDPXi;
731     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
732       assert(AArch64::FPR64RegClass.contains(Reg2) &&
733              "Expected FPR64 callee-saved register pair!");
734       if (i == Count - 2)
735         LdrOpc = AArch64::LDPDpost;
736       else
737         LdrOpc = AArch64::LDPDi;
738     } else
739       llvm_unreachable("Unexpected callee saved register!");
740     DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
741                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
742                  << ", " << CSI[i + 1].getFrameIdx() << ")\n");
743
744     // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
745     // etc.
746     const int Offset = (i == Count - 2) ? Count : Count - i - 2;
747     assert((Offset >= -64 && Offset <= 63) &&
748            "Offset out of bounds for LDP immediate");
749     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
750     if (LdrOpc == AArch64::LDPXpost || LdrOpc == AArch64::LDPDpost)
751       MIB.addReg(AArch64::SP, RegState::Define);
752
753     MIB.addReg(Reg2, getDefRegState(true))
754         .addReg(Reg1, getDefRegState(true))
755         .addReg(AArch64::SP)
756         .addImm(Offset); // [sp], #offset * 8  or [sp, #offset * 8]
757                          // where the factor * 8 is implicit
758   }
759   return true;
760 }
761
762 void AArch64FrameLowering::processFunctionBeforeCalleeSavedScan(
763     MachineFunction &MF, RegScavenger *RS) const {
764   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
765       MF.getSubtarget().getRegisterInfo());
766   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
767   MachineRegisterInfo *MRI = &MF.getRegInfo();
768   SmallVector<unsigned, 4> UnspilledCSGPRs;
769   SmallVector<unsigned, 4> UnspilledCSFPRs;
770
771   // The frame record needs to be created by saving the appropriate registers
772   if (hasFP(MF)) {
773     MRI->setPhysRegUsed(AArch64::FP);
774     MRI->setPhysRegUsed(AArch64::LR);
775   }
776
777   // Spill the BasePtr if it's used. Do this first thing so that the
778   // getCalleeSavedRegs() below will get the right answer.
779   if (RegInfo->hasBasePointer(MF))
780     MRI->setPhysRegUsed(RegInfo->getBaseRegister());
781
782   // If any callee-saved registers are used, the frame cannot be eliminated.
783   unsigned NumGPRSpilled = 0;
784   unsigned NumFPRSpilled = 0;
785   bool ExtraCSSpill = false;
786   bool CanEliminateFrame = true;
787   DEBUG(dbgs() << "*** processFunctionBeforeCalleeSavedScan\nUsed CSRs:");
788   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
789
790   // Check pairs of consecutive callee-saved registers.
791   for (unsigned i = 0; CSRegs[i]; i += 2) {
792     assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
793
794     const unsigned OddReg = CSRegs[i];
795     const unsigned EvenReg = CSRegs[i + 1];
796     assert((AArch64::GPR64RegClass.contains(OddReg) &&
797             AArch64::GPR64RegClass.contains(EvenReg)) ^
798                (AArch64::FPR64RegClass.contains(OddReg) &&
799                 AArch64::FPR64RegClass.contains(EvenReg)) &&
800            "Register class mismatch!");
801
802     const bool OddRegUsed = MRI->isPhysRegUsed(OddReg);
803     const bool EvenRegUsed = MRI->isPhysRegUsed(EvenReg);
804
805     // Early exit if none of the registers in the register pair is actually
806     // used.
807     if (!OddRegUsed && !EvenRegUsed) {
808       if (AArch64::GPR64RegClass.contains(OddReg)) {
809         UnspilledCSGPRs.push_back(OddReg);
810         UnspilledCSGPRs.push_back(EvenReg);
811       } else {
812         UnspilledCSFPRs.push_back(OddReg);
813         UnspilledCSFPRs.push_back(EvenReg);
814       }
815       continue;
816     }
817
818     unsigned Reg = AArch64::NoRegister;
819     // If only one of the registers of the register pair is used, make sure to
820     // mark the other one as used as well.
821     if (OddRegUsed ^ EvenRegUsed) {
822       // Find out which register is the additional spill.
823       Reg = OddRegUsed ? EvenReg : OddReg;
824       MRI->setPhysRegUsed(Reg);
825     }
826
827     DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
828     DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
829
830     assert(((OddReg == AArch64::LR && EvenReg == AArch64::FP) ||
831             (RegInfo->getEncodingValue(OddReg) + 1 ==
832              RegInfo->getEncodingValue(EvenReg))) &&
833            "Register pair of non-adjacent registers!");
834     if (AArch64::GPR64RegClass.contains(OddReg)) {
835       NumGPRSpilled += 2;
836       // If it's not a reserved register, we can use it in lieu of an
837       // emergency spill slot for the register scavenger.
838       // FIXME: It would be better to instead keep looking and choose another
839       // unspilled register that isn't reserved, if there is one.
840       if (Reg != AArch64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
841         ExtraCSSpill = true;
842     } else
843       NumFPRSpilled += 2;
844
845     CanEliminateFrame = false;
846   }
847
848   // FIXME: Set BigStack if any stack slot references may be out of range.
849   // For now, just conservatively guestimate based on unscaled indexing
850   // range. We'll end up allocating an unnecessary spill slot a lot, but
851   // realistically that's not a big deal at this stage of the game.
852   // The CSR spill slots have not been allocated yet, so estimateStackSize
853   // won't include them.
854   MachineFrameInfo *MFI = MF.getFrameInfo();
855   unsigned CFSize = estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
856   DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
857   bool BigStack = (CFSize >= 256);
858   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
859     AFI->setHasStackFrame(true);
860
861   // Estimate if we might need to scavenge a register at some point in order
862   // to materialize a stack offset. If so, either spill one additional
863   // callee-saved register or reserve a special spill slot to facilitate
864   // register scavenging. If we already spilled an extra callee-saved register
865   // above to keep the number of spills even, we don't need to do anything else
866   // here.
867   if (BigStack && !ExtraCSSpill) {
868
869     // If we're adding a register to spill here, we have to add two of them
870     // to keep the number of regs to spill even.
871     assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
872     unsigned Count = 0;
873     while (!UnspilledCSGPRs.empty() && Count < 2) {
874       unsigned Reg = UnspilledCSGPRs.back();
875       UnspilledCSGPRs.pop_back();
876       DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
877                    << " to get a scratch register.\n");
878       MRI->setPhysRegUsed(Reg);
879       ExtraCSSpill = true;
880       ++Count;
881     }
882
883     // If we didn't find an extra callee-saved register to spill, create
884     // an emergency spill slot.
885     if (!ExtraCSSpill) {
886       const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
887       int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
888       RS->addScavengingFrameIndex(FI);
889       DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
890                    << " as the emergency spill slot.\n");
891     }
892   }
893 }