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