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