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