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