blob: 1cdb525eaa1a619bdfd1bb4d7a4d7cd50a79b93e [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===- 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//
Kristof Beyls17cb8982015-04-09 08:49:47 +000012// On AArch64, stack frames are structured as follows:
13//
14// The stack grows downward.
15//
16// All of the individual frame areas on the frame below are optional, i.e. it's
17// possible to create a function so that the particular area isn't present
18// in the frame.
19//
20// At function entry, the "frame" looks as follows:
21//
22// | | Higher address
23// |-----------------------------------|
24// | |
25// | arguments passed on the stack |
26// | |
27// |-----------------------------------| <- sp
28// | | Lower address
29//
30//
31// After the prologue has run, the frame has the following general structure.
32// Note that this doesn't depict the case where a red-zone is used. Also,
33// technically the last frame area (VLAs) doesn't get created until in the
34// main function body, after the prologue is run. However, it's depicted here
35// for completeness.
36//
37// | | Higher address
38// |-----------------------------------|
39// | |
40// | arguments passed on the stack |
41// | |
42// |-----------------------------------|
43// | |
44// | prev_fp, prev_lr |
45// | (a.k.a. "frame record") |
46// |-----------------------------------| <- fp(=x29)
47// | |
48// | other callee-saved registers |
49// | |
50// |-----------------------------------|
51// |.empty.space.to.make.part.below....|
52// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
53// |.the.standard.16-byte.alignment....| compile time; if present)
54// |-----------------------------------|
55// | |
56// | local variables of fixed size |
57// | including spill slots |
58// |-----------------------------------| <- bp(not defined by ABI,
59// |.variable-sized.local.variables....| LLVM chooses X19)
60// |.(VLAs)............................| (size of this area is unknown at
61// |...................................| compile time)
62// |-----------------------------------| <- sp
63// | | Lower address
64//
65//
66// To access the data in a frame, at-compile time, a constant offset must be
67// computable from one of the pointers (fp, bp, sp) to access it. The size
68// of the areas with a dotted background cannot be computed at compile-time
69// if they are present, making it required to have all three of fp, bp and
70// sp to be set up to be able to access all contents in the frame areas,
71// assuming all of the frame areas are non-empty.
72//
73// For most functions, some of the frame areas are empty. For those functions,
74// it may not be necessary to set up fp or bp:
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000075// * A base pointer is definitely needed when there are both VLAs and local
Kristof Beyls17cb8982015-04-09 08:49:47 +000076// variables with more-than-default alignment requirements.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000077// * A frame pointer is definitely needed when there are local variables with
Kristof Beyls17cb8982015-04-09 08:49:47 +000078// more-than-default alignment requirements.
79//
80// In some cases when a base pointer is not strictly needed, it is generated
81// anyway when offsets from the frame pointer to access local variables become
82// so large that the offset can't be encoded in the immediate fields of loads
83// or stores.
84//
85// FIXME: also explain the redzone concept.
86// FIXME: also explain the concept of reserved call frames.
87//
Tim Northover3b0846e2014-05-24 12:50:23 +000088//===----------------------------------------------------------------------===//
89
90#include "AArch64FrameLowering.h"
91#include "AArch64InstrInfo.h"
92#include "AArch64MachineFunctionInfo.h"
93#include "AArch64Subtarget.h"
94#include "AArch64TargetMachine.h"
95#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000096#include "llvm/CodeGen/MachineFrameInfo.h"
97#include "llvm/CodeGen/MachineFunction.h"
98#include "llvm/CodeGen/MachineInstrBuilder.h"
99#include "llvm/CodeGen/MachineModuleInfo.h"
100#include "llvm/CodeGen/MachineRegisterInfo.h"
101#include "llvm/CodeGen/RegisterScavenging.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000102#include "llvm/IR/DataLayout.h"
103#include "llvm/IR/Function.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000104#include "llvm/Support/CommandLine.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000105#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000106#include "llvm/Support/raw_ostream.h"
107
108using namespace llvm;
109
110#define DEBUG_TYPE "frame-info"
111
112static cl::opt<bool> EnableRedZone("aarch64-redzone",
113 cl::desc("enable use of redzone on AArch64"),
114 cl::init(false), cl::Hidden);
115
116STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
117
Tim Northover3b0846e2014-05-24 12:50:23 +0000118bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
119 if (!EnableRedZone)
120 return false;
121 // Don't use the red zone if the function explicitly asks us not to.
122 // This is typically used for kernel code.
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +0000123 if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone))
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 return false;
125
126 const MachineFrameInfo *MFI = MF.getFrameInfo();
127 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
128 unsigned NumBytes = AFI->getLocalStackSize();
129
Eric Christopher114fa1c2016-02-29 22:50:49 +0000130 return !(MFI->hasCalls() || hasFP(MF) || NumBytes > 128);
Tim Northover3b0846e2014-05-24 12:50:23 +0000131}
132
133/// hasFP - Return true if the specified function should have a dedicated frame
134/// pointer register.
135bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
136 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000137 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000138 // Retain behavior of always omitting the FP for leaf functions when possible.
139 return (MFI->hasCalls() &&
140 MF.getTarget().Options.DisableFramePointerElim(MF)) ||
141 MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken() ||
142 MFI->hasStackMap() || MFI->hasPatchPoint() ||
143 RegInfo->needsStackRealignment(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000144}
145
146/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
147/// not required, we reserve argument space for call sites in the function
148/// immediately on entry to the current function. This eliminates the need for
149/// add/sub sp brackets around call sites. Returns true if the call frame is
150/// included as part of the stack frame.
151bool
152AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
153 return !MF.getFrameInfo()->hasVarSizedObjects();
154}
155
156void AArch64FrameLowering::eliminateCallFramePseudoInstr(
157 MachineFunction &MF, MachineBasicBlock &MBB,
158 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000159 const AArch64InstrInfo *TII =
160 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000161 DebugLoc DL = I->getDebugLoc();
Matthias Braunfa3872e2015-05-18 20:27:55 +0000162 unsigned Opc = I->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000163 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
164 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
165
Eric Christopherfc6de422014-08-05 02:39:49 +0000166 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Tim Northover3b0846e2014-05-24 12:50:23 +0000167 if (!TFI->hasReservedCallFrame(MF)) {
168 unsigned Align = getStackAlignment();
169
170 int64_t Amount = I->getOperand(0).getImm();
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000171 Amount = alignTo(Amount, Align);
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 if (!IsDestroy)
173 Amount = -Amount;
174
175 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
176 // doesn't have to pop anything), then the first operand will be zero too so
177 // this adjustment is a no-op.
178 if (CalleePopAmount == 0) {
179 // FIXME: in-function stack adjustment for calls is limited to 24-bits
180 // because there's no guaranteed temporary register available.
181 //
Sylvestre Ledru469de192014-08-11 18:04:46 +0000182 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000183 // 1) For offset <= 12-bit, we use LSL #0
184 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
185 // LSL #0, and the other uses LSL #12.
186 //
Chad Rosier401a4ab2016-01-19 16:50:45 +0000187 // Most call frames will be allocated at the start of a function so
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 // this is OK, but it is a limitation that needs dealing with.
189 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
190 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
191 }
192 } else if (CalleePopAmount != 0) {
193 // If the calling convention demands that the callee pops arguments from the
194 // stack, we want to add it back if we have a reserved call frame.
195 assert(CalleePopAmount < 0xffffff && "call frame too large");
196 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
197 TII);
198 }
199 MBB.erase(I);
200}
201
202void AArch64FrameLowering::emitCalleeSavedFrameMoves(
Geoff Berry62d47252016-02-25 16:36:08 +0000203 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000204 MachineFunction &MF = *MBB.getParent();
205 MachineFrameInfo *MFI = MF.getFrameInfo();
206 MachineModuleInfo &MMI = MF.getMMI();
207 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000208 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000209 DebugLoc DL = MBB.findDebugLoc(MBBI);
210
211 // Add callee saved registers to move list.
212 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
213 if (CSI.empty())
214 return;
215
Tim Northover3b0846e2014-05-24 12:50:23 +0000216 for (const auto &Info : CSI) {
217 unsigned Reg = Info.getReg();
Geoff Berry62d47252016-02-25 16:36:08 +0000218 int64_t Offset =
219 MFI->getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
Tim Northover3b0846e2014-05-24 12:50:23 +0000220 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Geoff Berry62d47252016-02-25 16:36:08 +0000221 unsigned CFIIndex = MMI.addFrameInst(
222 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover3b0846e2014-05-24 12:50:23 +0000223 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000224 .addCFIIndex(CFIIndex)
225 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000226 }
227}
228
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000229// Find a scratch register that we can use at the start of the prologue to
230// re-align the stack pointer. We avoid using callee-save registers since they
231// may appear to be free when this is called from canUseAsPrologue (during
232// shrink wrapping), but then no longer be free when this is called from
233// emitPrologue.
234//
235// FIXME: This is a bit conservative, since in the above case we could use one
236// of the callee-save registers as a scratch temp to re-align the stack pointer,
237// but we would then have to make sure that we were in fact saving at least one
238// callee-save register in the prologue, which is additional complexity that
239// doesn't seem worth the benefit.
240static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
241 MachineFunction *MF = MBB->getParent();
242
243 // If MBB is an entry block, use X9 as the scratch register
244 if (&MF->front() == MBB)
245 return AArch64::X9;
246
247 RegScavenger RS;
248 RS.enterBasicBlock(MBB);
249
250 // Prefer X9 since it was historically used for the prologue scratch reg.
251 if (!RS.isRegUsed(AArch64::X9))
252 return AArch64::X9;
253
254 // Find a free non callee-save reg.
255 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
256 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
257 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MF);
258 BitVector CalleeSaveRegs(RegInfo->getNumRegs());
259 for (unsigned i = 0; CSRegs[i]; ++i)
260 CalleeSaveRegs.set(CSRegs[i]);
261
262 BitVector Available = RS.getRegsAvailable(&AArch64::GPR64RegClass);
263 for (int AvailReg = Available.find_first(); AvailReg != -1;
264 AvailReg = Available.find_next(AvailReg))
265 if (!CalleeSaveRegs.test(AvailReg))
266 return AvailReg;
267
268 return AArch64::NoRegister;
269}
270
271bool AArch64FrameLowering::canUseAsPrologue(
272 const MachineBasicBlock &MBB) const {
273 const MachineFunction *MF = MBB.getParent();
274 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
275 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
276 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
277
278 // Don't need a scratch register if we're not going to re-align the stack.
279 if (!RegInfo->needsStackRealignment(*MF))
280 return true;
281 // Otherwise, we can use any block as long as it has a scratch register
282 // available.
283 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
284}
285
Quentin Colombet61b305e2015-05-05 17:38:16 +0000286void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
287 MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000288 MachineBasicBlock::iterator MBBI = MBB.begin();
289 const MachineFrameInfo *MFI = MF.getFrameInfo();
290 const Function *Fn = MF.getFunction();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000291 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
292 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
293 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000294 MachineModuleInfo &MMI = MF.getMMI();
Tim Northover775aaeb2015-11-05 21:54:58 +0000295 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
296 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
297 bool HasFP = hasFP(MF);
298
299 // Debug location must be unknown since the first debug location is used
300 // to determine the end of the prologue.
301 DebugLoc DL;
302
303 // All calls are tail calls in GHC calling conv, and functions have no
304 // prologue/epilogue.
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000305 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
306 return;
307
Tim Northover3b0846e2014-05-24 12:50:23 +0000308 int NumBytes = (int)MFI->getStackSize();
309 if (!AFI->hasStackFrame()) {
310 assert(!HasFP && "unexpected function without stack frame but with FP");
311
312 // All of the stack allocation is for locals.
313 AFI->setLocalStackSize(NumBytes);
314
315 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
Jim Grosbach6f482002015-05-18 18:43:14 +0000316 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Tim Northover3b0846e2014-05-24 12:50:23 +0000317
318 // REDZONE: If the stack size is less than 128 bytes, we don't need
319 // to actually allocate.
320 if (NumBytes && !canUseRedZone(MF)) {
321 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
322 MachineInstr::FrameSetup);
323
324 // Encode the stack size of the leaf function.
325 unsigned CFIIndex = MMI.addFrameInst(
326 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
327 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000328 .addCFIIndex(CFIIndex)
329 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000330 } else if (NumBytes) {
331 ++NumRedZoneFunctions;
332 }
333
334 return;
335 }
336
337 // Only set up FP if we actually need to.
338 int FPOffset = 0;
Manman Ren0e208222015-04-29 20:03:38 +0000339 if (HasFP)
Geoff Berry04bf91a2016-02-01 16:29:19 +0000340 // Frame pointer is fp = sp - 16.
341 FPOffset = AFI->getCalleeSavedStackSize() - 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000342
343 // Move past the saves of the callee-saved registers.
Geoff Berry04bf91a2016-02-01 16:29:19 +0000344 MachineBasicBlock::iterator End = MBB.end();
345 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup))
Tim Northover3b0846e2014-05-24 12:50:23 +0000346 ++MBBI;
Geoff Berry04bf91a2016-02-01 16:29:19 +0000347 NumBytes -= AFI->getCalleeSavedStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000348 assert(NumBytes >= 0 && "Negative stack allocation size!?");
349 if (HasFP) {
350 // Issue sub fp, sp, FPOffset or
351 // mov fp,sp when FPOffset is zero.
352 // Note: All stores of callee-saved registers are marked as "FrameSetup".
353 // This code marks the instruction(s) that set the FP also.
354 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
355 MachineInstr::FrameSetup);
356 }
357
358 // All of the remaining stack allocations are for locals.
359 AFI->setLocalStackSize(NumBytes);
360
361 // Allocate space for the rest of the frame.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000362
363 const unsigned Alignment = MFI->getMaxAlignment();
Evgeniy Stepanov00b30202015-07-10 21:24:07 +0000364 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000365 unsigned scratchSPReg = AArch64::SP;
Evgeniy Stepanov00b30202015-07-10 21:24:07 +0000366 if (NumBytes && NeedsRealignment) {
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000367 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
368 assert(scratchSPReg != AArch64::NoRegister);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000369 }
370
371 // If we're a leaf function, try using the red zone.
372 if (NumBytes && !canUseRedZone(MF))
373 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
374 // the correct value here, as NumBytes also includes padding bytes,
375 // which shouldn't be counted here.
376 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
377 MachineInstr::FrameSetup);
378
Kristof Beyls17cb8982015-04-09 08:49:47 +0000379 if (NumBytes && NeedsRealignment) {
380 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
381 assert(NrBitsToZero > 1);
382 assert(scratchSPReg != AArch64::SP);
383
384 // SUB X9, SP, NumBytes
385 // -- X9 is temporary register, so shouldn't contain any live data here,
386 // -- free to use. This is already produced by emitFrameOffset above.
387 // AND SP, X9, 0b11111...0000
388 // The logical immediates have a non-trivial encoding. The following
389 // formula computes the encoded immediate with all ones but
390 // NrBitsToZero zero bits as least significant bits.
391 uint32_t andMaskEncoded =
392 (1 <<12) // = N
393 | ((64-NrBitsToZero) << 6) // immr
394 | ((64-NrBitsToZero-1) << 0) // imms
395 ;
396 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
397 .addReg(scratchSPReg, RegState::Kill)
398 .addImm(andMaskEncoded);
Chad Rosier6d986552016-03-14 18:17:41 +0000399 AFI->setStackRealigned(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000400 }
401
402 // If we need a base pointer, set it up here. It's whatever the value of the
403 // stack pointer is at this point. Any variable size objects will be allocated
404 // after this, so we can still use the base pointer to reference locals.
405 //
406 // FIXME: Clarify FrameSetup flags here.
407 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
408 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000409 if (RegInfo->hasBasePointer(MF)) {
410 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
411 false);
412 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000413
414 if (needsFrameMoves) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000415 const DataLayout &TD = MF.getDataLayout();
416 const int StackGrowth = -TD.getPointerSize(0);
Tim Northover3b0846e2014-05-24 12:50:23 +0000417 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000418 // An example of the prologue:
419 //
420 // .globl __foo
421 // .align 2
422 // __foo:
423 // Ltmp0:
424 // .cfi_startproc
425 // .cfi_personality 155, ___gxx_personality_v0
426 // Leh_func_begin:
427 // .cfi_lsda 16, Lexception33
428 //
429 // stp xa,bx, [sp, -#offset]!
430 // ...
431 // stp x28, x27, [sp, #offset-32]
432 // stp fp, lr, [sp, #offset-16]
433 // add fp, sp, #offset - 16
434 // sub sp, sp, #1360
435 //
436 // The Stack:
437 // +-------------------------------------------+
438 // 10000 | ........ | ........ | ........ | ........ |
439 // 10004 | ........ | ........ | ........ | ........ |
440 // +-------------------------------------------+
441 // 10008 | ........ | ........ | ........ | ........ |
442 // 1000c | ........ | ........ | ........ | ........ |
443 // +===========================================+
444 // 10010 | X28 Register |
445 // 10014 | X28 Register |
446 // +-------------------------------------------+
447 // 10018 | X27 Register |
448 // 1001c | X27 Register |
449 // +===========================================+
450 // 10020 | Frame Pointer |
451 // 10024 | Frame Pointer |
452 // +-------------------------------------------+
453 // 10028 | Link Register |
454 // 1002c | Link Register |
455 // +===========================================+
456 // 10030 | ........ | ........ | ........ | ........ |
457 // 10034 | ........ | ........ | ........ | ........ |
458 // +-------------------------------------------+
459 // 10038 | ........ | ........ | ........ | ........ |
460 // 1003c | ........ | ........ | ........ | ........ |
461 // +-------------------------------------------+
462 //
463 // [sp] = 10030 :: >>initial value<<
464 // sp = 10020 :: stp fp, lr, [sp, #-16]!
465 // fp = sp == 10020 :: mov fp, sp
466 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
467 // sp == 10010 :: >>final value<<
468 //
469 // The frame pointer (w29) points to address 10020. If we use an offset of
470 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
471 // for w27, and -32 for w28:
472 //
473 // Ltmp1:
474 // .cfi_def_cfa w29, 16
475 // Ltmp2:
476 // .cfi_offset w30, -8
477 // Ltmp3:
478 // .cfi_offset w29, -16
479 // Ltmp4:
480 // .cfi_offset w27, -24
481 // Ltmp5:
482 // .cfi_offset w28, -32
483
484 if (HasFP) {
485 // Define the current CFA rule to use the provided FP.
486 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
487 unsigned CFIIndex = MMI.addFrameInst(
488 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
489 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000490 .addCFIIndex(CFIIndex)
491 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000492 } else {
493 // Encode the stack size of the leaf function.
494 unsigned CFIIndex = MMI.addFrameInst(
495 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
496 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000497 .addCFIIndex(CFIIndex)
498 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000499 }
500
Geoff Berry62d47252016-02-25 16:36:08 +0000501 // Now emit the moves for whatever callee saved regs we have (including FP,
502 // LR if those are saved).
503 emitCalleeSavedFrameMoves(MBB, MBBI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000504 }
505}
506
Tim Northover3b0846e2014-05-24 12:50:23 +0000507void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
508 MachineBasicBlock &MBB) const {
509 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Tim Northover3b0846e2014-05-24 12:50:23 +0000510 MachineFrameInfo *MFI = MF.getFrameInfo();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000511 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000512 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000513 DebugLoc DL;
514 bool IsTailCallReturn = false;
515 if (MBB.end() != MBBI) {
516 DL = MBBI->getDebugLoc();
517 unsigned RetOpcode = MBBI->getOpcode();
518 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
519 RetOpcode == AArch64::TCRETURNri;
520 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000521 int NumBytes = MFI->getStackSize();
522 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
523
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000524 // All calls are tail calls in GHC calling conv, and functions have no
525 // prologue/epilogue.
526 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
527 return;
528
Kristof Beyls17cb8982015-04-09 08:49:47 +0000529 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 // in the epilogue, the residual adjustment is executed first.
531 uint64_t ArgumentPopSize = 0;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000532 if (IsTailCallReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000533 MachineOperand &StackAdjust = MBBI->getOperand(1);
534
535 // For a tail-call in a callee-pops-arguments environment, some or all of
536 // the stack may actually be in use for the call's arguments, this is
537 // calculated during LowerCall and consumed here...
538 ArgumentPopSize = StackAdjust.getImm();
539 } else {
540 // ... otherwise the amount to pop is *all* of the argument space,
541 // conveniently stored in the MachineFunctionInfo by
542 // LowerFormalArguments. This will, of course, be zero for the C calling
543 // convention.
544 ArgumentPopSize = AFI->getArgumentStackToRestore();
545 }
546
547 // The stack frame should be like below,
548 //
549 // ---------------------- ---
550 // | | |
551 // | BytesInStackArgArea| CalleeArgStackSize
552 // | (NumReusableBytes) | (of tail call)
553 // | | ---
554 // | | |
555 // ---------------------| --- |
556 // | | | |
557 // | CalleeSavedReg | | |
Geoff Berry04bf91a2016-02-01 16:29:19 +0000558 // | (CalleeSavedStackSize)| | |
Tim Northover3b0846e2014-05-24 12:50:23 +0000559 // | | | |
560 // ---------------------| | NumBytes
561 // | | StackSize (StackAdjustUp)
562 // | LocalStackSize | | |
563 // | (covering callee | | |
564 // | args) | | |
565 // | | | |
566 // ---------------------- --- ---
567 //
568 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
569 // = StackSize + ArgumentPopSize
570 //
571 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
572 // it as the 2nd argument of AArch64ISD::TC_RETURN.
Tim Northover3b0846e2014-05-24 12:50:23 +0000573
Tim Northover3b0846e2014-05-24 12:50:23 +0000574 // Move past the restores of the callee-saved registers.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000575 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
Matthias Braun45419292015-12-17 03:18:47 +0000576 MachineBasicBlock::iterator Begin = MBB.begin();
577 while (LastPopI != Begin) {
578 --LastPopI;
Geoff Berry04bf91a2016-02-01 16:29:19 +0000579 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000580 ++LastPopI;
Matthias Braun45419292015-12-17 03:18:47 +0000581 break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000582 }
583 }
Geoff Berry04bf91a2016-02-01 16:29:19 +0000584 NumBytes -= AFI->getCalleeSavedStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000585 assert(NumBytes >= 0 && "Negative stack allocation size!?");
586
587 if (!hasFP(MF)) {
Geoff Berrya1c62692016-02-23 16:54:36 +0000588 bool RedZone = canUseRedZone(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 // If this was a redzone leaf function, we don't need to restore the
Geoff Berrya1c62692016-02-23 16:54:36 +0000590 // stack pointer (but we may need to pop stack args for fastcc).
591 if (RedZone && ArgumentPopSize == 0)
592 return;
593
594 bool NoCalleeSaveRestore = AFI->getCalleeSavedStackSize() == 0;
595 int StackRestoreBytes = RedZone ? 0 : NumBytes;
596 if (NoCalleeSaveRestore)
597 StackRestoreBytes += ArgumentPopSize;
598 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
599 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
600 // If we were able to combine the local stack pop with the argument pop,
601 // then we're done.
602 if (NoCalleeSaveRestore || ArgumentPopSize == 0)
603 return;
604 NumBytes = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000605 }
606
607 // Restore the original stack pointer.
608 // FIXME: Rather than doing the math here, we should instead just use
609 // non-post-indexed loads for the restores if we aren't actually going to
610 // be able to save any instructions.
Chad Rosier6d986552016-03-14 18:17:41 +0000611 if (MFI->hasVarSizedObjects() || AFI->isStackRealigned())
Tim Northover3b0846e2014-05-24 12:50:23 +0000612 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
Geoff Berry04bf91a2016-02-01 16:29:19 +0000613 -AFI->getCalleeSavedStackSize() + 16, TII,
614 MachineInstr::FrameDestroy);
Chad Rosier6d986552016-03-14 18:17:41 +0000615 else if (NumBytes)
616 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
617 MachineInstr::FrameDestroy);
Geoff Berrya1c62692016-02-23 16:54:36 +0000618
619 // This must be placed after the callee-save restore code because that code
620 // assumes the SP is at the same location as it was after the callee-save save
621 // code in the prologue.
622 if (ArgumentPopSize)
623 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
624 ArgumentPopSize, TII, MachineInstr::FrameDestroy);
Tim Northover3b0846e2014-05-24 12:50:23 +0000625}
626
Tim Northover3b0846e2014-05-24 12:50:23 +0000627/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
628/// debug info. It's the same as what we use for resolving the code-gen
629/// references for now. FIXME: This can go wrong when references are
630/// SP-relative and simple call frames aren't used.
631int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
632 int FI,
633 unsigned &FrameReg) const {
634 return resolveFrameIndexReference(MF, FI, FrameReg);
635}
636
637int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
638 int FI, unsigned &FrameReg,
639 bool PreferFP) const {
640 const MachineFrameInfo *MFI = MF.getFrameInfo();
641 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000642 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
644 int FPOffset = MFI->getObjectOffset(FI) + 16;
645 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
646 bool isFixed = MFI->isFixedObjectIndex(FI);
647
648 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +0000649 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
650 // reliable as a base). Make sure useFPForScavengingIndex() does the
651 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +0000652 bool UseFP = false;
653 if (AFI->hasStackFrame()) {
654 // Note: Keeping the following as multiple 'if' statements rather than
655 // merging to a single expression for readability.
656 //
657 // Argument access should always use the FP.
658 if (isFixed) {
659 UseFP = hasFP(MF);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000660 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
661 !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000662 // Use SP or FP, whichever gives us the best chance of the offset
663 // being in range for direct access. If the FPOffset is positive,
664 // that'll always be best, as the SP will be even further away.
665 // If the FPOffset is negative, we have to keep in mind that the
666 // available offset range for negative offsets is smaller than for
667 // positive ones. If we have variable sized objects, we're stuck with
668 // using the FP regardless, though, as the SP offset is unknown
669 // and we don't have a base pointer available. If an offset is
670 // available via the FP and the SP, use whichever is closest.
671 if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
672 (FPOffset >= -256 && Offset > -FPOffset))
673 UseFP = true;
674 }
675 }
676
Kristof Beyls17cb8982015-04-09 08:49:47 +0000677 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
678 "In the presence of dynamic stack pointer realignment, "
679 "non-argument objects cannot be accessed through the frame pointer");
680
Tim Northover3b0846e2014-05-24 12:50:23 +0000681 if (UseFP) {
682 FrameReg = RegInfo->getFrameRegister(MF);
683 return FPOffset;
684 }
685
686 // Use the base pointer if we have one.
687 if (RegInfo->hasBasePointer(MF))
688 FrameReg = RegInfo->getBaseRegister();
689 else {
690 FrameReg = AArch64::SP;
691 // If we're using the red zone for this function, the SP won't actually
692 // be adjusted, so the offsets will be negative. They're also all
693 // within range of the signed 9-bit immediate instructions.
694 if (canUseRedZone(MF))
695 Offset -= AFI->getLocalStackSize();
696 }
697
698 return Offset;
699}
700
701static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
702 if (Reg != AArch64::LR)
703 return getKillRegState(true);
704
705 // LR maybe referred to later by an @llvm.returnaddress intrinsic.
706 bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
707 bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
708 return getKillRegState(LRKill);
709}
710
Geoff Berry29d4a692016-02-01 19:07:06 +0000711struct RegPairInfo {
712 RegPairInfo() : Reg1(AArch64::NoRegister), Reg2(AArch64::NoRegister) {}
713 unsigned Reg1;
714 unsigned Reg2;
715 int FrameIdx;
716 int Offset;
717 bool IsGPR;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000718 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
Geoff Berry29d4a692016-02-01 19:07:06 +0000719};
720
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000721static void computeCalleeSaveRegisterPairs(
722 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
723 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) {
Geoff Berry29d4a692016-02-01 19:07:06 +0000724
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000725 if (CSI.empty())
726 return;
727
728 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
729 MachineFrameInfo *MFI = MF.getFrameInfo();
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000730 CallingConv::ID CC = MF.getFunction()->getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +0000731 unsigned Count = CSI.size();
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000732 (void)CC;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000733 // MachO's compact unwind format relies on all registers being stored in
734 // pairs.
735 assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000736 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000737 (Count & 1) == 0) &&
738 "Odd number of callee-saved regs to spill!");
739 unsigned Offset = AFI->getCalleeSavedStackSize();
Tim Northover775aaeb2015-11-05 21:54:58 +0000740
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000741 for (unsigned i = 0; i < Count; ++i) {
Geoff Berry29d4a692016-02-01 19:07:06 +0000742 RegPairInfo RPI;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000743 RPI.Reg1 = CSI[i].getReg();
744
745 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
746 AArch64::FPR64RegClass.contains(RPI.Reg1));
747 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
748
749 // Add the next reg to the pair if it is in the same register class.
750 if (i + 1 < Count) {
751 unsigned NextReg = CSI[i + 1].getReg();
752 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
753 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
754 RPI.Reg2 = NextReg;
755 }
Geoff Berry29d4a692016-02-01 19:07:06 +0000756
Tim Northover3b0846e2014-05-24 12:50:23 +0000757 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
758 // list to come in sorted by frame index so that we can issue the store
759 // pair instructions directly. Assert if we see anything otherwise.
760 //
761 // The order of the registers in the list is controlled by
762 // getCalleeSavedRegs(), so they will always be in-order, as well.
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000763 assert((!RPI.isPaired() ||
764 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
Tim Northover3b0846e2014-05-24 12:50:23 +0000765 "Out of order callee saved regs!");
Geoff Berry29d4a692016-02-01 19:07:06 +0000766
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000767 // MachO's compact unwind format relies on all registers being stored in
768 // adjacent register pairs.
769 assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000770 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000771 (RPI.isPaired() &&
772 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
773 RPI.Reg1 + 1 == RPI.Reg2))) &&
774 "Callee-save registers not saved as adjacent register pair!");
775
776 RPI.FrameIdx = CSI[i].getFrameIdx();
777
778 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
779 // Round up size of non-pair to pair size if we need to pad the
780 // callee-save area to ensure 16-byte alignment.
781 Offset -= 16;
782 assert(MFI->getObjectAlignment(RPI.FrameIdx) <= 16);
783 MFI->setObjectSize(RPI.FrameIdx, 16);
784 } else
785 Offset -= RPI.isPaired() ? 16 : 8;
786 assert(Offset % 8 == 0);
787 RPI.Offset = Offset / 8;
Geoff Berry29d4a692016-02-01 19:07:06 +0000788 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
789 "Offset out of bounds for LDP/STP immediate");
790
791 RegPairs.push_back(RPI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000792 if (RPI.isPaired())
793 ++i;
Geoff Berry29d4a692016-02-01 19:07:06 +0000794 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000795
796 // Align first offset to even 16-byte boundary to avoid additional SP
797 // adjustment instructions.
798 // Last pair offset is size of whole callee-save region for SP
799 // pre-dec/post-inc.
800 RegPairInfo &LastPair = RegPairs.back();
801 assert(AFI->getCalleeSavedStackSize() % 8 == 0);
802 LastPair.Offset = AFI->getCalleeSavedStackSize() / 8;
Geoff Berry29d4a692016-02-01 19:07:06 +0000803}
804
805bool AArch64FrameLowering::spillCalleeSavedRegisters(
806 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
807 const std::vector<CalleeSavedInfo> &CSI,
808 const TargetRegisterInfo *TRI) const {
809 MachineFunction &MF = *MBB.getParent();
810 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
811 DebugLoc DL;
812 SmallVector<RegPairInfo, 8> RegPairs;
813
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000814 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Geoff Berry29d4a692016-02-01 19:07:06 +0000815
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000816 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +0000817 ++RPII) {
818 RegPairInfo RPI = *RPII;
819 unsigned Reg1 = RPI.Reg1;
820 unsigned Reg2 = RPI.Reg2;
821 unsigned StrOpc;
822
Tim Northover3b0846e2014-05-24 12:50:23 +0000823 // Issue sequence of non-sp increment and pi sp spills for cs regs. The
824 // first spill is a pre-increment that allocates the stack.
825 // For example:
826 // stp x22, x21, [sp, #-48]! // addImm(-6)
827 // stp x20, x19, [sp, #16] // addImm(+2)
828 // stp fp, lr, [sp, #32] // addImm(+4)
829 // Rationale: This sequence saves uop updates compared to a sequence of
830 // pre-increment spills like stp xi,xj,[sp,#-16]!
Geoff Berry29d4a692016-02-01 19:07:06 +0000831 // Note: Similar rationale and sequence for restores in epilog.
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000832 bool BumpSP = RPII == RegPairs.rbegin();
Geoff Berry29d4a692016-02-01 19:07:06 +0000833 if (RPI.IsGPR) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000834 // For first spill use pre-increment store.
Geoff Berry29d4a692016-02-01 19:07:06 +0000835 if (BumpSP)
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000836 StrOpc = RPI.isPaired() ? AArch64::STPXpre : AArch64::STRXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000837 else
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000838 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
Geoff Berry29d4a692016-02-01 19:07:06 +0000839 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +0000840 // For first spill use pre-increment store.
Geoff Berry29d4a692016-02-01 19:07:06 +0000841 if (BumpSP)
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000842 StrOpc = RPI.isPaired() ? AArch64::STPDpre : AArch64::STRDpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000843 else
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000844 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
Geoff Berry29d4a692016-02-01 19:07:06 +0000845 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000846 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1);
847 if (RPI.isPaired())
848 dbgs() << ", " << TRI->getName(Reg2);
849 dbgs() << ") -> fi#(" << RPI.FrameIdx;
850 if (RPI.isPaired())
851 dbgs() << ", " << RPI.FrameIdx+1;
852 dbgs() << ")\n");
Geoff Berry29d4a692016-02-01 19:07:06 +0000853
854 const int Offset = BumpSP ? -RPI.Offset : RPI.Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000855 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
Geoff Berry29d4a692016-02-01 19:07:06 +0000856 if (BumpSP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000857 MIB.addReg(AArch64::SP, RegState::Define);
858
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000859 if (RPI.isPaired()) {
860 MBB.addLiveIn(Reg1);
861 MBB.addLiveIn(Reg2);
862 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
Tim Northover3b0846e2014-05-24 12:50:23 +0000863 .addReg(Reg1, getPrologueDeath(MF, Reg1))
864 .addReg(AArch64::SP)
865 .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
866 .setMIFlag(MachineInstr::FrameSetup);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000867 } else {
868 MBB.addLiveIn(Reg1);
869 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
870 .addReg(AArch64::SP)
871 .addImm(BumpSP ? Offset * 8 : Offset) // pre-inc version is unscaled
872 .setMIFlag(MachineInstr::FrameSetup);
873 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000874 }
875 return true;
876}
877
878bool AArch64FrameLowering::restoreCalleeSavedRegisters(
879 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
880 const std::vector<CalleeSavedInfo> &CSI,
881 const TargetRegisterInfo *TRI) const {
882 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000883 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000884 DebugLoc DL;
Geoff Berry29d4a692016-02-01 19:07:06 +0000885 SmallVector<RegPairInfo, 8> RegPairs;
Tim Northover3b0846e2014-05-24 12:50:23 +0000886
887 if (MI != MBB.end())
888 DL = MI->getDebugLoc();
889
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000890 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Geoff Berry29d4a692016-02-01 19:07:06 +0000891
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000892 for (auto RPII = RegPairs.begin(), RPIE = RegPairs.end(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +0000893 ++RPII) {
894 RegPairInfo RPI = *RPII;
895 unsigned Reg1 = RPI.Reg1;
896 unsigned Reg2 = RPI.Reg2;
897
Tim Northover3b0846e2014-05-24 12:50:23 +0000898 // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
899 // the last load is sp-pi post-increment and de-allocates the stack:
900 // For example:
901 // ldp fp, lr, [sp, #32] // addImm(+4)
902 // ldp x20, x19, [sp, #16] // addImm(+2)
903 // ldp x22, x21, [sp], #48 // addImm(+6)
904 // Note: see comment in spillCalleeSavedRegisters()
905 unsigned LdrOpc;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000906 bool BumpSP = RPII == std::prev(RegPairs.end());
Geoff Berry29d4a692016-02-01 19:07:06 +0000907 if (RPI.IsGPR) {
908 if (BumpSP)
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000909 LdrOpc = RPI.isPaired() ? AArch64::LDPXpost : AArch64::LDRXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000910 else
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000911 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
Geoff Berry29d4a692016-02-01 19:07:06 +0000912 } else {
913 if (BumpSP)
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000914 LdrOpc = RPI.isPaired() ? AArch64::LDPDpost : AArch64::LDRDpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 else
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000916 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
Geoff Berry29d4a692016-02-01 19:07:06 +0000917 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000918 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1);
919 if (RPI.isPaired())
920 dbgs() << ", " << TRI->getName(Reg2);
921 dbgs() << ") -> fi#(" << RPI.FrameIdx;
922 if (RPI.isPaired())
923 dbgs() << ", " << RPI.FrameIdx+1;
924 dbgs() << ")\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000925
Geoff Berry29d4a692016-02-01 19:07:06 +0000926 const int Offset = RPI.Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000927 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
Geoff Berry29d4a692016-02-01 19:07:06 +0000928 if (BumpSP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000929 MIB.addReg(AArch64::SP, RegState::Define);
930
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000931 if (RPI.isPaired())
932 MIB.addReg(Reg2, getDefRegState(true))
Tim Northover3b0846e2014-05-24 12:50:23 +0000933 .addReg(Reg1, getDefRegState(true))
934 .addReg(AArch64::SP)
Geoff Berry04bf91a2016-02-01 16:29:19 +0000935 .addImm(Offset) // [sp], #offset * 8 or [sp, #offset * 8]
936 // where the factor * 8 is implicit
937 .setMIFlag(MachineInstr::FrameDestroy);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000938 else
939 MIB.addReg(Reg1, getDefRegState(true))
940 .addReg(AArch64::SP)
941 .addImm(BumpSP ? Offset * 8 : Offset) // post-dec version is unscaled
942 .setMIFlag(MachineInstr::FrameDestroy);
Tim Northover3b0846e2014-05-24 12:50:23 +0000943 }
944 return true;
945}
946
Matthias Braun02564862015-07-14 17:17:13 +0000947void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
948 BitVector &SavedRegs,
949 RegScavenger *RS) const {
950 // All calls are tail calls in GHC calling conv, and functions have no
951 // prologue/epilogue.
952 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
953 return;
954
955 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Tim Northover3b0846e2014-05-24 12:50:23 +0000956 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000957 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000958 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000959 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
960 unsigned UnspilledCSGPR = AArch64::NoRegister;
961 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +0000962
963 // The frame record needs to be created by saving the appropriate registers
964 if (hasFP(MF)) {
Matthias Braun02564862015-07-14 17:17:13 +0000965 SavedRegs.set(AArch64::FP);
966 SavedRegs.set(AArch64::LR);
Tim Northover3b0846e2014-05-24 12:50:23 +0000967 }
968
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000969 unsigned BasePointerReg = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +0000970 if (RegInfo->hasBasePointer(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000971 BasePointerReg = RegInfo->getBaseRegister();
Tim Northover3b0846e2014-05-24 12:50:23 +0000972
Tim Northover3b0846e2014-05-24 12:50:23 +0000973 bool ExtraCSSpill = false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000974 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000975 // Figure out which callee-saved registers to save/restore.
976 for (unsigned i = 0; CSRegs[i]; ++i) {
977 const unsigned Reg = CSRegs[i];
Tim Northover3b0846e2014-05-24 12:50:23 +0000978
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000979 // Add the base pointer register to SavedRegs if it is callee-save.
980 if (Reg == BasePointerReg)
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000981 SavedRegs.set(Reg);
Tim Northover3b0846e2014-05-24 12:50:23 +0000982
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000983 bool RegUsed = SavedRegs.test(Reg);
984 unsigned PairedReg = CSRegs[i ^ 1];
985 if (!RegUsed) {
986 if (AArch64::GPR64RegClass.contains(Reg) &&
987 !RegInfo->isReservedReg(MF, Reg)) {
988 UnspilledCSGPR = Reg;
989 UnspilledCSGPRPaired = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +0000990 }
991 continue;
992 }
993
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000994 // MachO's compact unwind format relies on all registers being stored in
995 // pairs.
996 // FIXME: the usual format is actually better if unwinding isn't needed.
997 if (Subtarget.isTargetMachO() && !SavedRegs.test(PairedReg)) {
998 SavedRegs.set(PairedReg);
999 ExtraCSSpill = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001001 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001002
1003 DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1004 for (int Reg = SavedRegs.find_first(); Reg != -1;
1005 Reg = SavedRegs.find_next(Reg))
1006 dbgs() << ' ' << PrintReg(Reg, RegInfo);
1007 dbgs() << "\n";);
1008
1009 // If any callee-saved registers are used, the frame cannot be eliminated.
1010 unsigned NumRegsSpilled = SavedRegs.count();
1011 bool CanEliminateFrame = NumRegsSpilled == 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001012
1013 // FIXME: Set BigStack if any stack slot references may be out of range.
1014 // For now, just conservatively guestimate based on unscaled indexing
1015 // range. We'll end up allocating an unnecessary spill slot a lot, but
1016 // realistically that's not a big deal at this stage of the game.
1017 // The CSR spill slots have not been allocated yet, so estimateStackSize
1018 // won't include them.
1019 MachineFrameInfo *MFI = MF.getFrameInfo();
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001020 unsigned CFSize = MFI->estimateStackSize(MF) + 8 * NumRegsSpilled;
Tim Northover3b0846e2014-05-24 12:50:23 +00001021 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
1022 bool BigStack = (CFSize >= 256);
1023 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1024 AFI->setHasStackFrame(true);
1025
1026 // Estimate if we might need to scavenge a register at some point in order
1027 // to materialize a stack offset. If so, either spill one additional
1028 // callee-saved register or reserve a special spill slot to facilitate
1029 // register scavenging. If we already spilled an extra callee-saved register
1030 // above to keep the number of spills even, we don't need to do anything else
1031 // here.
1032 if (BigStack && !ExtraCSSpill) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001033 if (UnspilledCSGPR != AArch64::NoRegister) {
1034 DEBUG(dbgs() << "Spilling " << PrintReg(UnspilledCSGPR, RegInfo)
1035 << " to get a scratch register.\n");
1036 SavedRegs.set(UnspilledCSGPR);
1037 // MachO's compact unwind format relies on all registers being stored in
1038 // pairs, so if we need to spill one extra for BigStack, then we need to
1039 // store the pair.
1040 if (Subtarget.isTargetMachO())
1041 SavedRegs.set(UnspilledCSGPRPaired);
Tim Northover3b0846e2014-05-24 12:50:23 +00001042 ExtraCSSpill = true;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001043 NumRegsSpilled = SavedRegs.count();
Tim Northover3b0846e2014-05-24 12:50:23 +00001044 }
1045
1046 // If we didn't find an extra callee-saved register to spill, create
1047 // an emergency spill slot.
1048 if (!ExtraCSSpill) {
1049 const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
1050 int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
1051 RS->addScavengingFrameIndex(FI);
1052 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1053 << " as the emergency spill slot.\n");
1054 }
1055 }
Geoff Berry04bf91a2016-02-01 16:29:19 +00001056
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001057 // Round up to register pair alignment to avoid additional SP adjustment
1058 // instructions.
1059 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00001060}