blob: 65e94699ca318c1d4d6b07ad378643aaa4e9222d [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"
Matthias Braun332bb5c2016-07-06 21:31:27 +000096#include "llvm/CodeGen/LivePhysRegs.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000097#include "llvm/CodeGen/MachineFrameInfo.h"
98#include "llvm/CodeGen/MachineFunction.h"
99#include "llvm/CodeGen/MachineInstrBuilder.h"
100#include "llvm/CodeGen/MachineModuleInfo.h"
101#include "llvm/CodeGen/MachineRegisterInfo.h"
102#include "llvm/CodeGen/RegisterScavenging.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000103#include "llvm/IR/DataLayout.h"
104#include "llvm/IR/Function.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000105#include "llvm/Support/CommandLine.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000106#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000107#include "llvm/Support/raw_ostream.h"
108
109using namespace llvm;
110
111#define DEBUG_TYPE "frame-info"
112
113static cl::opt<bool> EnableRedZone("aarch64-redzone",
114 cl::desc("enable use of redzone on AArch64"),
115 cl::init(false), cl::Hidden);
116
117STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
118
Tim Northover3b0846e2014-05-24 12:50:23 +0000119bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
120 if (!EnableRedZone)
121 return false;
122 // Don't use the red zone if the function explicitly asks us not to.
123 // This is typically used for kernel code.
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +0000124 if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone))
Tim Northover3b0846e2014-05-24 12:50:23 +0000125 return false;
126
Matthias Braun941a7052016-07-28 18:40:00 +0000127 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000128 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
129 unsigned NumBytes = AFI->getLocalStackSize();
130
Matthias Braun941a7052016-07-28 18:40:00 +0000131 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
Tim Northover3b0846e2014-05-24 12:50:23 +0000132}
133
134/// hasFP - Return true if the specified function should have a dedicated frame
135/// pointer register.
136bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000137 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000138 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000139 // Retain behavior of always omitting the FP for leaf functions when possible.
Matthias Braun941a7052016-07-28 18:40:00 +0000140 return (MFI.hasCalls() &&
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000141 MF.getTarget().Options.DisableFramePointerElim(MF)) ||
Matthias Braun941a7052016-07-28 18:40:00 +0000142 MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
143 MFI.hasStackMap() || MFI.hasPatchPoint() ||
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000144 RegInfo->needsStackRealignment(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000145}
146
147/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
148/// not required, we reserve argument space for call sites in the function
149/// immediately on entry to the current function. This eliminates the need for
150/// add/sub sp brackets around call sites. Returns true if the call frame is
151/// included as part of the stack frame.
152bool
153AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000154 return !MF.getFrameInfo().hasVarSizedObjects();
Tim Northover3b0846e2014-05-24 12:50:23 +0000155}
156
Hans Wennborge1a2e902016-03-31 18:33:38 +0000157MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 MachineFunction &MF, MachineBasicBlock &MBB,
159 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000160 const AArch64InstrInfo *TII =
161 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000162 DebugLoc DL = I->getDebugLoc();
Matthias Braunfa3872e2015-05-18 20:27:55 +0000163 unsigned Opc = I->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000164 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
165 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
166
Eric Christopherfc6de422014-08-05 02:39:49 +0000167 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Tim Northover3b0846e2014-05-24 12:50:23 +0000168 if (!TFI->hasReservedCallFrame(MF)) {
169 unsigned Align = getStackAlignment();
170
171 int64_t Amount = I->getOperand(0).getImm();
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000172 Amount = alignTo(Amount, Align);
Tim Northover3b0846e2014-05-24 12:50:23 +0000173 if (!IsDestroy)
174 Amount = -Amount;
175
176 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
177 // doesn't have to pop anything), then the first operand will be zero too so
178 // this adjustment is a no-op.
179 if (CalleePopAmount == 0) {
180 // FIXME: in-function stack adjustment for calls is limited to 24-bits
181 // because there's no guaranteed temporary register available.
182 //
Sylvestre Ledru469de192014-08-11 18:04:46 +0000183 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000184 // 1) For offset <= 12-bit, we use LSL #0
185 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
186 // LSL #0, and the other uses LSL #12.
187 //
Chad Rosier401a4ab2016-01-19 16:50:45 +0000188 // Most call frames will be allocated at the start of a function so
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 // this is OK, but it is a limitation that needs dealing with.
190 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
191 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
192 }
193 } else if (CalleePopAmount != 0) {
194 // If the calling convention demands that the callee pops arguments from the
195 // stack, we want to add it back if we have a reserved call frame.
196 assert(CalleePopAmount < 0xffffff && "call frame too large");
197 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
198 TII);
199 }
Hans Wennborge1a2e902016-03-31 18:33:38 +0000200 return MBB.erase(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000201}
202
203void AArch64FrameLowering::emitCalleeSavedFrameMoves(
Geoff Berry62d47252016-02-25 16:36:08 +0000204 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000205 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000206 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf23ef432016-11-30 23:48:42 +0000207 const TargetSubtargetInfo &STI = MF.getSubtarget();
208 const MCRegisterInfo *MRI = STI.getRegisterInfo();
209 const TargetInstrInfo *TII = STI.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000210 DebugLoc DL = MBB.findDebugLoc(MBBI);
211
212 // Add callee saved registers to move list.
Matthias Braun941a7052016-07-28 18:40:00 +0000213 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000214 if (CSI.empty())
215 return;
216
Tim Northover3b0846e2014-05-24 12:50:23 +0000217 for (const auto &Info : CSI) {
218 unsigned Reg = Info.getReg();
Geoff Berry62d47252016-02-25 16:36:08 +0000219 int64_t Offset =
Matthias Braun941a7052016-07-28 18:40:00 +0000220 MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
Tim Northover3b0846e2014-05-24 12:50:23 +0000221 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braunf23ef432016-11-30 23:48:42 +0000222 unsigned CFIIndex = MF.addFrameInst(
Geoff Berry62d47252016-02-25 16:36:08 +0000223 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover3b0846e2014-05-24 12:50:23 +0000224 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000225 .addCFIIndex(CFIIndex)
226 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000227 }
228}
229
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000230// Find a scratch register that we can use at the start of the prologue to
231// re-align the stack pointer. We avoid using callee-save registers since they
232// may appear to be free when this is called from canUseAsPrologue (during
233// shrink wrapping), but then no longer be free when this is called from
234// emitPrologue.
235//
236// FIXME: This is a bit conservative, since in the above case we could use one
237// of the callee-save registers as a scratch temp to re-align the stack pointer,
238// but we would then have to make sure that we were in fact saving at least one
239// callee-save register in the prologue, which is additional complexity that
240// doesn't seem worth the benefit.
241static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
242 MachineFunction *MF = MBB->getParent();
243
244 // If MBB is an entry block, use X9 as the scratch register
245 if (&MF->front() == MBB)
246 return AArch64::X9;
247
Matthias Braun332bb5c2016-07-06 21:31:27 +0000248 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
249 LivePhysRegs LiveRegs(&TRI);
250 LiveRegs.addLiveIns(*MBB);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000251
Matthias Braun332bb5c2016-07-06 21:31:27 +0000252 // Mark callee saved registers as used so we will not choose them.
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000253 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
254 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
255 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MF);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000256 for (unsigned i = 0; CSRegs[i]; ++i)
Matthias Braun332bb5c2016-07-06 21:31:27 +0000257 LiveRegs.addReg(CSRegs[i]);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000258
Matthias Braun332bb5c2016-07-06 21:31:27 +0000259 // Prefer X9 since it was historically used for the prologue scratch reg.
260 const MachineRegisterInfo &MRI = MF->getRegInfo();
261 if (LiveRegs.available(MRI, AArch64::X9))
262 return AArch64::X9;
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000263
Matthias Braun332bb5c2016-07-06 21:31:27 +0000264 for (unsigned Reg : AArch64::GPR64RegClass) {
265 if (LiveRegs.available(MRI, Reg))
266 return Reg;
267 }
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000268 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
Geoff Berrya5335642016-05-06 16:34:59 +0000286bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
287 MachineFunction &MF, unsigned StackBumpBytes) const {
288 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000289 const MachineFrameInfo &MFI = MF.getFrameInfo();
Geoff Berrya5335642016-05-06 16:34:59 +0000290 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
291 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
292
293 if (AFI->getLocalStackSize() == 0)
294 return false;
295
296 // 512 is the maximum immediate for stp/ldp that will be used for
297 // callee-save save/restores
298 if (StackBumpBytes >= 512)
299 return false;
300
Matthias Braun941a7052016-07-28 18:40:00 +0000301 if (MFI.hasVarSizedObjects())
Geoff Berrya5335642016-05-06 16:34:59 +0000302 return false;
303
304 if (RegInfo->needsStackRealignment(MF))
305 return false;
306
307 // This isn't strictly necessary, but it simplifies things a bit since the
308 // current RedZone handling code assumes the SP is adjusted by the
309 // callee-save save/restore code.
310 if (canUseRedZone(MF))
311 return false;
312
313 return true;
314}
315
316// Convert callee-save register save/restore instruction to do stack pointer
317// decrement/increment to allocate/deallocate the callee-save stack area by
318// converting store/load to use pre/post increment version.
319static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000320 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
321 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc) {
Geoff Berrya5335642016-05-06 16:34:59 +0000322
323 unsigned NewOpc;
324 bool NewIsUnscaled = false;
325 switch (MBBI->getOpcode()) {
326 default:
327 llvm_unreachable("Unexpected callee-save save/restore opcode!");
328 case AArch64::STPXi:
329 NewOpc = AArch64::STPXpre;
330 break;
331 case AArch64::STPDi:
332 NewOpc = AArch64::STPDpre;
333 break;
334 case AArch64::STRXui:
335 NewOpc = AArch64::STRXpre;
336 NewIsUnscaled = true;
337 break;
338 case AArch64::STRDui:
339 NewOpc = AArch64::STRDpre;
340 NewIsUnscaled = true;
341 break;
342 case AArch64::LDPXi:
343 NewOpc = AArch64::LDPXpost;
344 break;
345 case AArch64::LDPDi:
346 NewOpc = AArch64::LDPDpost;
347 break;
348 case AArch64::LDRXui:
349 NewOpc = AArch64::LDRXpost;
350 NewIsUnscaled = true;
351 break;
352 case AArch64::LDRDui:
353 NewOpc = AArch64::LDRDpost;
354 NewIsUnscaled = true;
355 break;
356 }
357
358 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
359 MIB.addReg(AArch64::SP, RegState::Define);
360
361 // Copy all operands other than the immediate offset.
362 unsigned OpndIdx = 0;
363 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
364 ++OpndIdx)
Diana Picus116bbab2017-01-13 09:58:52 +0000365 MIB.add(MBBI->getOperand(OpndIdx));
Geoff Berrya5335642016-05-06 16:34:59 +0000366
367 assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
368 "Unexpected immediate offset in first/last callee-save save/restore "
369 "instruction!");
370 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
371 "Unexpected base register in callee-save save/restore instruction!");
372 // Last operand is immediate offset that needs fixing.
373 assert(CSStackSizeInc % 8 == 0);
374 int64_t CSStackSizeIncImm = CSStackSizeInc;
375 if (!NewIsUnscaled)
376 CSStackSizeIncImm /= 8;
377 MIB.addImm(CSStackSizeIncImm);
378
379 MIB.setMIFlags(MBBI->getFlags());
380 MIB.setMemRefs(MBBI->memoperands_begin(), MBBI->memoperands_end());
381
382 return std::prev(MBB.erase(MBBI));
383}
384
385// Fixup callee-save register save/restore instructions to take into account
386// combined SP bump by adding the local stack size to the stack offsets.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000387static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
Geoff Berrya5335642016-05-06 16:34:59 +0000388 unsigned LocalStackSize) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000389 unsigned Opc = MI.getOpcode();
Geoff Berrya5335642016-05-06 16:34:59 +0000390 (void)Opc;
391 assert((Opc == AArch64::STPXi || Opc == AArch64::STPDi ||
392 Opc == AArch64::STRXui || Opc == AArch64::STRDui ||
393 Opc == AArch64::LDPXi || Opc == AArch64::LDPDi ||
394 Opc == AArch64::LDRXui || Opc == AArch64::LDRDui) &&
395 "Unexpected callee-save save/restore opcode!");
396
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000397 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
398 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
Geoff Berrya5335642016-05-06 16:34:59 +0000399 "Unexpected base register in callee-save save/restore instruction!");
400 // Last operand is immediate offset that needs fixing.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000401 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
Geoff Berrya5335642016-05-06 16:34:59 +0000402 // All generated opcodes have scaled offsets.
403 assert(LocalStackSize % 8 == 0);
404 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / 8);
405}
406
Quentin Colombet61b305e2015-05-05 17:38:16 +0000407void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
408 MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000409 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000410 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000411 const Function *Fn = MF.getFunction();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000412 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
413 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
414 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000415 MachineModuleInfo &MMI = MF.getMMI();
Tim Northover775aaeb2015-11-05 21:54:58 +0000416 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
417 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
418 bool HasFP = hasFP(MF);
419
420 // Debug location must be unknown since the first debug location is used
421 // to determine the end of the prologue.
422 DebugLoc DL;
423
424 // All calls are tail calls in GHC calling conv, and functions have no
425 // prologue/epilogue.
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000426 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
427 return;
428
Matthias Braun941a7052016-07-28 18:40:00 +0000429 int NumBytes = (int)MFI.getStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000430 if (!AFI->hasStackFrame()) {
431 assert(!HasFP && "unexpected function without stack frame but with FP");
432
433 // All of the stack allocation is for locals.
434 AFI->setLocalStackSize(NumBytes);
435
Chad Rosier27c352d2016-03-14 18:24:34 +0000436 if (!NumBytes)
437 return;
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 // REDZONE: If the stack size is less than 128 bytes, we don't need
439 // to actually allocate.
Chad Rosier27c352d2016-03-14 18:24:34 +0000440 if (canUseRedZone(MF))
441 ++NumRedZoneFunctions;
442 else {
Tim Northover3b0846e2014-05-24 12:50:23 +0000443 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
444 MachineInstr::FrameSetup);
445
Chad Rosier27c352d2016-03-14 18:24:34 +0000446 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
447 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Tim Northover3b0846e2014-05-24 12:50:23 +0000448 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000449 unsigned CFIIndex = MF.addFrameInst(
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
451 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000452 .addCFIIndex(CFIIndex)
453 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000454 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000455 return;
456 }
457
Geoff Berrya5335642016-05-06 16:34:59 +0000458 auto CSStackSize = AFI->getCalleeSavedStackSize();
Chad Rosier27c352d2016-03-14 18:24:34 +0000459 // All of the remaining stack allocations are for locals.
Geoff Berrya5335642016-05-06 16:34:59 +0000460 AFI->setLocalStackSize(NumBytes - CSStackSize);
Tim Northover3b0846e2014-05-24 12:50:23 +0000461
Geoff Berrya5335642016-05-06 16:34:59 +0000462 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
463 if (CombineSPBump) {
464 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
465 MachineInstr::FrameSetup);
466 NumBytes = 0;
467 } else if (CSStackSize != 0) {
468 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
469 -CSStackSize);
470 NumBytes -= CSStackSize;
471 }
472 assert(NumBytes >= 0 && "Negative stack allocation size!?");
473
474 // Move past the saves of the callee-saved registers, fixing up the offsets
475 // and pre-inc if we decided to combine the callee-save and local stack
476 // pointer bump above.
Geoff Berry04bf91a2016-02-01 16:29:19 +0000477 MachineBasicBlock::iterator End = MBB.end();
Geoff Berrya5335642016-05-06 16:34:59 +0000478 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
479 if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000480 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000481 ++MBBI;
Geoff Berrya5335642016-05-06 16:34:59 +0000482 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000483 if (HasFP) {
Chad Rosier27c352d2016-03-14 18:24:34 +0000484 // Only set up FP if we actually need to. Frame pointer is fp = sp - 16.
Geoff Berrya5335642016-05-06 16:34:59 +0000485 int FPOffset = CSStackSize - 16;
486 if (CombineSPBump)
487 FPOffset += AFI->getLocalStackSize();
Chad Rosier27c352d2016-03-14 18:24:34 +0000488
Tim Northover3b0846e2014-05-24 12:50:23 +0000489 // Issue sub fp, sp, FPOffset or
490 // mov fp,sp when FPOffset is zero.
491 // Note: All stores of callee-saved registers are marked as "FrameSetup".
492 // This code marks the instruction(s) that set the FP also.
493 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
494 MachineInstr::FrameSetup);
495 }
496
Tim Northover3b0846e2014-05-24 12:50:23 +0000497 // Allocate space for the rest of the frame.
Chad Rosier27c352d2016-03-14 18:24:34 +0000498 if (NumBytes) {
499 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
500 unsigned scratchSPReg = AArch64::SP;
Kristof Beyls17cb8982015-04-09 08:49:47 +0000501
Chad Rosier27c352d2016-03-14 18:24:34 +0000502 if (NeedsRealignment) {
503 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
504 assert(scratchSPReg != AArch64::NoRegister);
505 }
Kristof Beyls17cb8982015-04-09 08:49:47 +0000506
Chad Rosier27c352d2016-03-14 18:24:34 +0000507 // If we're a leaf function, try using the red zone.
508 if (!canUseRedZone(MF))
509 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
510 // the correct value here, as NumBytes also includes padding bytes,
511 // which shouldn't be counted here.
512 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
513 MachineInstr::FrameSetup);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000514
Chad Rosier27c352d2016-03-14 18:24:34 +0000515 if (NeedsRealignment) {
Matthias Braun941a7052016-07-28 18:40:00 +0000516 const unsigned Alignment = MFI.getMaxAlignment();
Chad Rosier27c352d2016-03-14 18:24:34 +0000517 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
518 assert(NrBitsToZero > 1);
519 assert(scratchSPReg != AArch64::SP);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000520
Chad Rosier27c352d2016-03-14 18:24:34 +0000521 // SUB X9, SP, NumBytes
522 // -- X9 is temporary register, so shouldn't contain any live data here,
523 // -- free to use. This is already produced by emitFrameOffset above.
524 // AND SP, X9, 0b11111...0000
525 // The logical immediates have a non-trivial encoding. The following
526 // formula computes the encoded immediate with all ones but
527 // NrBitsToZero zero bits as least significant bits.
528 uint32_t andMaskEncoded = (1 << 12) // = N
529 | ((64 - NrBitsToZero) << 6) // immr
530 | ((64 - NrBitsToZero - 1) << 0); // imms
531
532 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
533 .addReg(scratchSPReg, RegState::Kill)
534 .addImm(andMaskEncoded);
535 AFI->setStackRealigned(true);
536 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 }
538
539 // If we need a base pointer, set it up here. It's whatever the value of the
540 // stack pointer is at this point. Any variable size objects will be allocated
541 // after this, so we can still use the base pointer to reference locals.
542 //
543 // FIXME: Clarify FrameSetup flags here.
544 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
545 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000546 if (RegInfo->hasBasePointer(MF)) {
547 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
548 false);
549 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000550
551 if (needsFrameMoves) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000552 const DataLayout &TD = MF.getDataLayout();
553 const int StackGrowth = -TD.getPointerSize(0);
Tim Northover3b0846e2014-05-24 12:50:23 +0000554 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000555 // An example of the prologue:
556 //
557 // .globl __foo
558 // .align 2
559 // __foo:
560 // Ltmp0:
561 // .cfi_startproc
562 // .cfi_personality 155, ___gxx_personality_v0
563 // Leh_func_begin:
564 // .cfi_lsda 16, Lexception33
565 //
566 // stp xa,bx, [sp, -#offset]!
567 // ...
568 // stp x28, x27, [sp, #offset-32]
569 // stp fp, lr, [sp, #offset-16]
570 // add fp, sp, #offset - 16
571 // sub sp, sp, #1360
572 //
573 // The Stack:
574 // +-------------------------------------------+
575 // 10000 | ........ | ........ | ........ | ........ |
576 // 10004 | ........ | ........ | ........ | ........ |
577 // +-------------------------------------------+
578 // 10008 | ........ | ........ | ........ | ........ |
579 // 1000c | ........ | ........ | ........ | ........ |
580 // +===========================================+
581 // 10010 | X28 Register |
582 // 10014 | X28 Register |
583 // +-------------------------------------------+
584 // 10018 | X27 Register |
585 // 1001c | X27 Register |
586 // +===========================================+
587 // 10020 | Frame Pointer |
588 // 10024 | Frame Pointer |
589 // +-------------------------------------------+
590 // 10028 | Link Register |
591 // 1002c | Link Register |
592 // +===========================================+
593 // 10030 | ........ | ........ | ........ | ........ |
594 // 10034 | ........ | ........ | ........ | ........ |
595 // +-------------------------------------------+
596 // 10038 | ........ | ........ | ........ | ........ |
597 // 1003c | ........ | ........ | ........ | ........ |
598 // +-------------------------------------------+
599 //
600 // [sp] = 10030 :: >>initial value<<
601 // sp = 10020 :: stp fp, lr, [sp, #-16]!
602 // fp = sp == 10020 :: mov fp, sp
603 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
604 // sp == 10010 :: >>final value<<
605 //
606 // The frame pointer (w29) points to address 10020. If we use an offset of
607 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
608 // for w27, and -32 for w28:
609 //
610 // Ltmp1:
611 // .cfi_def_cfa w29, 16
612 // Ltmp2:
613 // .cfi_offset w30, -8
614 // Ltmp3:
615 // .cfi_offset w29, -16
616 // Ltmp4:
617 // .cfi_offset w27, -24
618 // Ltmp5:
619 // .cfi_offset w28, -32
620
621 if (HasFP) {
622 // Define the current CFA rule to use the provided FP.
623 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
Matthias Braunf23ef432016-11-30 23:48:42 +0000624 unsigned CFIIndex = MF.addFrameInst(
Tim Northover3b0846e2014-05-24 12:50:23 +0000625 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
626 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000627 .addCFIIndex(CFIIndex)
628 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000629 } else {
630 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000631 unsigned CFIIndex = MF.addFrameInst(
Matthias Braun941a7052016-07-28 18:40:00 +0000632 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000634 .addCFIIndex(CFIIndex)
635 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000636 }
637
Geoff Berry62d47252016-02-25 16:36:08 +0000638 // Now emit the moves for whatever callee saved regs we have (including FP,
639 // LR if those are saved).
640 emitCalleeSavedFrameMoves(MBB, MBBI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000641 }
642}
643
Tim Northover3b0846e2014-05-24 12:50:23 +0000644void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
645 MachineBasicBlock &MBB) const {
646 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Matthias Braun941a7052016-07-28 18:40:00 +0000647 MachineFrameInfo &MFI = MF.getFrameInfo();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000648 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000649 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000650 DebugLoc DL;
651 bool IsTailCallReturn = false;
652 if (MBB.end() != MBBI) {
653 DL = MBBI->getDebugLoc();
654 unsigned RetOpcode = MBBI->getOpcode();
655 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
656 RetOpcode == AArch64::TCRETURNri;
657 }
Matthias Braun941a7052016-07-28 18:40:00 +0000658 int NumBytes = MFI.getStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000659 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
660
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000661 // All calls are tail calls in GHC calling conv, and functions have no
662 // prologue/epilogue.
663 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
664 return;
665
Kristof Beyls17cb8982015-04-09 08:49:47 +0000666 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000667 // in the epilogue, the residual adjustment is executed first.
668 uint64_t ArgumentPopSize = 0;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000669 if (IsTailCallReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 MachineOperand &StackAdjust = MBBI->getOperand(1);
671
672 // For a tail-call in a callee-pops-arguments environment, some or all of
673 // the stack may actually be in use for the call's arguments, this is
674 // calculated during LowerCall and consumed here...
675 ArgumentPopSize = StackAdjust.getImm();
676 } else {
677 // ... otherwise the amount to pop is *all* of the argument space,
678 // conveniently stored in the MachineFunctionInfo by
679 // LowerFormalArguments. This will, of course, be zero for the C calling
680 // convention.
681 ArgumentPopSize = AFI->getArgumentStackToRestore();
682 }
683
684 // The stack frame should be like below,
685 //
686 // ---------------------- ---
687 // | | |
688 // | BytesInStackArgArea| CalleeArgStackSize
689 // | (NumReusableBytes) | (of tail call)
690 // | | ---
691 // | | |
692 // ---------------------| --- |
693 // | | | |
694 // | CalleeSavedReg | | |
Geoff Berry04bf91a2016-02-01 16:29:19 +0000695 // | (CalleeSavedStackSize)| | |
Tim Northover3b0846e2014-05-24 12:50:23 +0000696 // | | | |
697 // ---------------------| | NumBytes
698 // | | StackSize (StackAdjustUp)
699 // | LocalStackSize | | |
700 // | (covering callee | | |
701 // | args) | | |
702 // | | | |
703 // ---------------------- --- ---
704 //
705 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
706 // = StackSize + ArgumentPopSize
707 //
708 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
709 // it as the 2nd argument of AArch64ISD::TC_RETURN.
Tim Northover3b0846e2014-05-24 12:50:23 +0000710
Geoff Berrya5335642016-05-06 16:34:59 +0000711 auto CSStackSize = AFI->getCalleeSavedStackSize();
712 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
713
714 if (!CombineSPBump && CSStackSize != 0)
715 convertCalleeSaveRestoreToSPPrePostIncDec(
716 MBB, std::prev(MBB.getFirstTerminator()), DL, TII, CSStackSize);
717
Tim Northover3b0846e2014-05-24 12:50:23 +0000718 // Move past the restores of the callee-saved registers.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000719 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
Matthias Braun45419292015-12-17 03:18:47 +0000720 MachineBasicBlock::iterator Begin = MBB.begin();
721 while (LastPopI != Begin) {
722 --LastPopI;
Geoff Berry04bf91a2016-02-01 16:29:19 +0000723 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000724 ++LastPopI;
Matthias Braun45419292015-12-17 03:18:47 +0000725 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000726 } else if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000727 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000728 }
Geoff Berrya5335642016-05-06 16:34:59 +0000729
730 // If there is a single SP update, insert it before the ret and we're done.
731 if (CombineSPBump) {
732 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
733 NumBytes + ArgumentPopSize, TII,
734 MachineInstr::FrameDestroy);
735 return;
736 }
737
738 NumBytes -= CSStackSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000739 assert(NumBytes >= 0 && "Negative stack allocation size!?");
740
741 if (!hasFP(MF)) {
Geoff Berrya1c62692016-02-23 16:54:36 +0000742 bool RedZone = canUseRedZone(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000743 // If this was a redzone leaf function, we don't need to restore the
Geoff Berrya1c62692016-02-23 16:54:36 +0000744 // stack pointer (but we may need to pop stack args for fastcc).
745 if (RedZone && ArgumentPopSize == 0)
746 return;
747
Geoff Berrya5335642016-05-06 16:34:59 +0000748 bool NoCalleeSaveRestore = CSStackSize == 0;
Geoff Berrya1c62692016-02-23 16:54:36 +0000749 int StackRestoreBytes = RedZone ? 0 : NumBytes;
750 if (NoCalleeSaveRestore)
751 StackRestoreBytes += ArgumentPopSize;
752 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
753 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
754 // If we were able to combine the local stack pop with the argument pop,
755 // then we're done.
756 if (NoCalleeSaveRestore || ArgumentPopSize == 0)
757 return;
758 NumBytes = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 }
760
761 // Restore the original stack pointer.
762 // FIXME: Rather than doing the math here, we should instead just use
763 // non-post-indexed loads for the restores if we aren't actually going to
764 // be able to save any instructions.
Matthias Braun941a7052016-07-28 18:40:00 +0000765 if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
Tim Northover3b0846e2014-05-24 12:50:23 +0000766 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
Geoff Berrya5335642016-05-06 16:34:59 +0000767 -CSStackSize + 16, TII, MachineInstr::FrameDestroy);
Chad Rosier6d986552016-03-14 18:17:41 +0000768 else if (NumBytes)
769 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
770 MachineInstr::FrameDestroy);
Geoff Berrya1c62692016-02-23 16:54:36 +0000771
772 // This must be placed after the callee-save restore code because that code
773 // assumes the SP is at the same location as it was after the callee-save save
774 // code in the prologue.
775 if (ArgumentPopSize)
776 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
777 ArgumentPopSize, TII, MachineInstr::FrameDestroy);
Tim Northover3b0846e2014-05-24 12:50:23 +0000778}
779
Tim Northover3b0846e2014-05-24 12:50:23 +0000780/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
781/// debug info. It's the same as what we use for resolving the code-gen
782/// references for now. FIXME: This can go wrong when references are
783/// SP-relative and simple call frames aren't used.
784int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
785 int FI,
786 unsigned &FrameReg) const {
787 return resolveFrameIndexReference(MF, FI, FrameReg);
788}
789
790int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
791 int FI, unsigned &FrameReg,
792 bool PreferFP) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000793 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000794 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000795 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000796 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000797 int FPOffset = MFI.getObjectOffset(FI) + 16;
798 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
799 bool isFixed = MFI.isFixedObjectIndex(FI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000800
801 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +0000802 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
803 // reliable as a base). Make sure useFPForScavengingIndex() does the
804 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +0000805 bool UseFP = false;
806 if (AFI->hasStackFrame()) {
807 // Note: Keeping the following as multiple 'if' statements rather than
808 // merging to a single expression for readability.
809 //
810 // Argument access should always use the FP.
811 if (isFixed) {
812 UseFP = hasFP(MF);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000813 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
814 !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000815 // Use SP or FP, whichever gives us the best chance of the offset
816 // being in range for direct access. If the FPOffset is positive,
817 // that'll always be best, as the SP will be even further away.
818 // If the FPOffset is negative, we have to keep in mind that the
819 // available offset range for negative offsets is smaller than for
820 // positive ones. If we have variable sized objects, we're stuck with
821 // using the FP regardless, though, as the SP offset is unknown
822 // and we don't have a base pointer available. If an offset is
823 // available via the FP and the SP, use whichever is closest.
Matthias Braun941a7052016-07-28 18:40:00 +0000824 if (PreferFP || MFI.hasVarSizedObjects() || FPOffset >= 0 ||
Tim Northover3b0846e2014-05-24 12:50:23 +0000825 (FPOffset >= -256 && Offset > -FPOffset))
826 UseFP = true;
827 }
828 }
829
Kristof Beyls17cb8982015-04-09 08:49:47 +0000830 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
831 "In the presence of dynamic stack pointer realignment, "
832 "non-argument objects cannot be accessed through the frame pointer");
833
Tim Northover3b0846e2014-05-24 12:50:23 +0000834 if (UseFP) {
835 FrameReg = RegInfo->getFrameRegister(MF);
836 return FPOffset;
837 }
838
839 // Use the base pointer if we have one.
840 if (RegInfo->hasBasePointer(MF))
841 FrameReg = RegInfo->getBaseRegister();
842 else {
843 FrameReg = AArch64::SP;
844 // If we're using the red zone for this function, the SP won't actually
845 // be adjusted, so the offsets will be negative. They're also all
846 // within range of the signed 9-bit immediate instructions.
847 if (canUseRedZone(MF))
848 Offset -= AFI->getLocalStackSize();
849 }
850
851 return Offset;
852}
853
854static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
Matthias Braun74a0bd32016-04-13 21:43:16 +0000855 // Do not set a kill flag on values that are also marked as live-in. This
856 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
857 // callee saved registers.
858 // Omitting the kill flags is conservatively correct even if the live-in
859 // is not used after all.
860 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
861 return getKillRegState(!IsLiveIn);
Tim Northover3b0846e2014-05-24 12:50:23 +0000862}
863
Manman Ren57518142016-04-11 21:08:06 +0000864static bool produceCompactUnwindFrame(MachineFunction &MF) {
865 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
866 AttributeSet Attrs = MF.getFunction()->getAttributes();
867 return Subtarget.isTargetMachO() &&
868 !(Subtarget.getTargetLowering()->supportSwiftError() &&
869 Attrs.hasAttrSomewhere(Attribute::SwiftError));
870}
871
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000872namespace {
Geoff Berry29d4a692016-02-01 19:07:06 +0000873struct RegPairInfo {
874 RegPairInfo() : Reg1(AArch64::NoRegister), Reg2(AArch64::NoRegister) {}
875 unsigned Reg1;
876 unsigned Reg2;
877 int FrameIdx;
878 int Offset;
879 bool IsGPR;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000880 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
Geoff Berry29d4a692016-02-01 19:07:06 +0000881};
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000882} // end anonymous namespace
Geoff Berry29d4a692016-02-01 19:07:06 +0000883
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000884static void computeCalleeSaveRegisterPairs(
885 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
886 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) {
Geoff Berry29d4a692016-02-01 19:07:06 +0000887
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000888 if (CSI.empty())
889 return;
890
891 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000892 MachineFrameInfo &MFI = MF.getFrameInfo();
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000893 CallingConv::ID CC = MF.getFunction()->getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +0000894 unsigned Count = CSI.size();
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000895 (void)CC;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000896 // MachO's compact unwind format relies on all registers being stored in
897 // pairs.
Manman Ren57518142016-04-11 21:08:06 +0000898 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000899 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000900 (Count & 1) == 0) &&
901 "Odd number of callee-saved regs to spill!");
902 unsigned Offset = AFI->getCalleeSavedStackSize();
Tim Northover775aaeb2015-11-05 21:54:58 +0000903
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000904 for (unsigned i = 0; i < Count; ++i) {
Geoff Berry29d4a692016-02-01 19:07:06 +0000905 RegPairInfo RPI;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000906 RPI.Reg1 = CSI[i].getReg();
907
908 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
909 AArch64::FPR64RegClass.contains(RPI.Reg1));
910 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
911
912 // Add the next reg to the pair if it is in the same register class.
913 if (i + 1 < Count) {
914 unsigned NextReg = CSI[i + 1].getReg();
915 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
916 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
917 RPI.Reg2 = NextReg;
918 }
Geoff Berry29d4a692016-02-01 19:07:06 +0000919
Tim Northover3b0846e2014-05-24 12:50:23 +0000920 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
921 // list to come in sorted by frame index so that we can issue the store
922 // pair instructions directly. Assert if we see anything otherwise.
923 //
924 // The order of the registers in the list is controlled by
925 // getCalleeSavedRegs(), so they will always be in-order, as well.
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000926 assert((!RPI.isPaired() ||
927 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
Tim Northover3b0846e2014-05-24 12:50:23 +0000928 "Out of order callee saved regs!");
Geoff Berry29d4a692016-02-01 19:07:06 +0000929
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000930 // MachO's compact unwind format relies on all registers being stored in
931 // adjacent register pairs.
Manman Ren57518142016-04-11 21:08:06 +0000932 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +0000933 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000934 (RPI.isPaired() &&
935 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
936 RPI.Reg1 + 1 == RPI.Reg2))) &&
937 "Callee-save registers not saved as adjacent register pair!");
938
939 RPI.FrameIdx = CSI[i].getFrameIdx();
940
941 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
942 // Round up size of non-pair to pair size if we need to pad the
943 // callee-save area to ensure 16-byte alignment.
944 Offset -= 16;
Matthias Braun941a7052016-07-28 18:40:00 +0000945 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
946 MFI.setObjectAlignment(RPI.FrameIdx, 16);
Geoff Berry66f6b652016-06-02 16:22:07 +0000947 AFI->setCalleeSaveStackHasFreeSpace(true);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000948 } else
949 Offset -= RPI.isPaired() ? 16 : 8;
950 assert(Offset % 8 == 0);
951 RPI.Offset = Offset / 8;
Geoff Berry29d4a692016-02-01 19:07:06 +0000952 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
953 "Offset out of bounds for LDP/STP immediate");
954
955 RegPairs.push_back(RPI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000956 if (RPI.isPaired())
957 ++i;
Geoff Berry29d4a692016-02-01 19:07:06 +0000958 }
959}
960
961bool AArch64FrameLowering::spillCalleeSavedRegisters(
962 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
963 const std::vector<CalleeSavedInfo> &CSI,
964 const TargetRegisterInfo *TRI) const {
965 MachineFunction &MF = *MBB.getParent();
966 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
967 DebugLoc DL;
968 SmallVector<RegPairInfo, 8> RegPairs;
969
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000970 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Geoff Berry29d4a692016-02-01 19:07:06 +0000971
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000972 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +0000973 ++RPII) {
974 RegPairInfo RPI = *RPII;
975 unsigned Reg1 = RPI.Reg1;
976 unsigned Reg2 = RPI.Reg2;
977 unsigned StrOpc;
978
Geoff Berrya5335642016-05-06 16:34:59 +0000979 // Issue sequence of spills for cs regs. The first spill may be converted
980 // to a pre-decrement store later by emitPrologue if the callee-save stack
981 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +0000982 // For example:
Geoff Berrya5335642016-05-06 16:34:59 +0000983 // stp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +0000984 // stp x20, x19, [sp, #16] // addImm(+2)
985 // stp fp, lr, [sp, #32] // addImm(+4)
986 // Rationale: This sequence saves uop updates compared to a sequence of
987 // pre-increment spills like stp xi,xj,[sp,#-16]!
Geoff Berry29d4a692016-02-01 19:07:06 +0000988 // Note: Similar rationale and sequence for restores in epilog.
Geoff Berrya5335642016-05-06 16:34:59 +0000989 if (RPI.IsGPR)
990 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
991 else
992 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
Geoff Berryc25d3bd2016-02-12 16:31:41 +0000993 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1);
994 if (RPI.isPaired())
995 dbgs() << ", " << TRI->getName(Reg2);
996 dbgs() << ") -> fi#(" << RPI.FrameIdx;
997 if (RPI.isPaired())
998 dbgs() << ", " << RPI.FrameIdx+1;
999 dbgs() << ")\n");
Geoff Berry29d4a692016-02-01 19:07:06 +00001000
Tim Northover3b0846e2014-05-24 12:50:23 +00001001 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
Geoff Berrya5335642016-05-06 16:34:59 +00001002 MBB.addLiveIn(Reg1);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001003 if (RPI.isPaired()) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001004 MBB.addLiveIn(Reg2);
Geoff Berrya5335642016-05-06 16:34:59 +00001005 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
Geoff Berryc3764062016-04-15 15:16:19 +00001006 MIB.addMemOperand(MF.getMachineMemOperand(
1007 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1008 MachineMemOperand::MOStore, 8, 8));
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001009 }
Geoff Berrya5335642016-05-06 16:34:59 +00001010 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1011 .addReg(AArch64::SP)
1012 .addImm(RPI.Offset) // [sp, #offset*8], where factor*8 is implicit
1013 .setMIFlag(MachineInstr::FrameSetup);
Geoff Berryc3764062016-04-15 15:16:19 +00001014 MIB.addMemOperand(MF.getMachineMemOperand(
1015 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1016 MachineMemOperand::MOStore, 8, 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 }
1018 return true;
1019}
1020
1021bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1022 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1023 const std::vector<CalleeSavedInfo> &CSI,
1024 const TargetRegisterInfo *TRI) const {
1025 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001026 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001027 DebugLoc DL;
Geoff Berry29d4a692016-02-01 19:07:06 +00001028 SmallVector<RegPairInfo, 8> RegPairs;
Tim Northover3b0846e2014-05-24 12:50:23 +00001029
1030 if (MI != MBB.end())
1031 DL = MI->getDebugLoc();
1032
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001033 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Geoff Berry29d4a692016-02-01 19:07:06 +00001034
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001035 for (auto RPII = RegPairs.begin(), RPIE = RegPairs.end(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +00001036 ++RPII) {
1037 RegPairInfo RPI = *RPII;
1038 unsigned Reg1 = RPI.Reg1;
1039 unsigned Reg2 = RPI.Reg2;
1040
Geoff Berrya5335642016-05-06 16:34:59 +00001041 // Issue sequence of restores for cs regs. The last restore may be converted
1042 // to a post-increment load later by emitEpilogue if the callee-save stack
1043 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001044 // For example:
1045 // ldp fp, lr, [sp, #32] // addImm(+4)
1046 // ldp x20, x19, [sp, #16] // addImm(+2)
Geoff Berrya5335642016-05-06 16:34:59 +00001047 // ldp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001048 // Note: see comment in spillCalleeSavedRegisters()
1049 unsigned LdrOpc;
Geoff Berrya5335642016-05-06 16:34:59 +00001050 if (RPI.IsGPR)
1051 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1052 else
1053 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001054 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1);
1055 if (RPI.isPaired())
1056 dbgs() << ", " << TRI->getName(Reg2);
1057 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1058 if (RPI.isPaired())
1059 dbgs() << ", " << RPI.FrameIdx+1;
1060 dbgs() << ")\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001061
Tim Northover3b0846e2014-05-24 12:50:23 +00001062 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
Geoff Berryc3764062016-04-15 15:16:19 +00001063 if (RPI.isPaired()) {
Geoff Berrya5335642016-05-06 16:34:59 +00001064 MIB.addReg(Reg2, getDefRegState(true));
Geoff Berryc3764062016-04-15 15:16:19 +00001065 MIB.addMemOperand(MF.getMachineMemOperand(
1066 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1067 MachineMemOperand::MOLoad, 8, 8));
Geoff Berryc3764062016-04-15 15:16:19 +00001068 }
Geoff Berrya5335642016-05-06 16:34:59 +00001069 MIB.addReg(Reg1, getDefRegState(true))
1070 .addReg(AArch64::SP)
1071 .addImm(RPI.Offset) // [sp, #offset*8] where the factor*8 is implicit
1072 .setMIFlag(MachineInstr::FrameDestroy);
Geoff Berryc3764062016-04-15 15:16:19 +00001073 MIB.addMemOperand(MF.getMachineMemOperand(
1074 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1075 MachineMemOperand::MOLoad, 8, 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00001076 }
1077 return true;
1078}
1079
Matthias Braun02564862015-07-14 17:17:13 +00001080void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1081 BitVector &SavedRegs,
1082 RegScavenger *RS) const {
1083 // All calls are tail calls in GHC calling conv, and functions have no
1084 // prologue/epilogue.
1085 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
1086 return;
1087
1088 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Tim Northover3b0846e2014-05-24 12:50:23 +00001089 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001090 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001091 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001092 unsigned UnspilledCSGPR = AArch64::NoRegister;
1093 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +00001094
1095 // The frame record needs to be created by saving the appropriate registers
1096 if (hasFP(MF)) {
Matthias Braun02564862015-07-14 17:17:13 +00001097 SavedRegs.set(AArch64::FP);
1098 SavedRegs.set(AArch64::LR);
Tim Northover3b0846e2014-05-24 12:50:23 +00001099 }
1100
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001101 unsigned BasePointerReg = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +00001102 if (RegInfo->hasBasePointer(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001103 BasePointerReg = RegInfo->getBaseRegister();
Tim Northover3b0846e2014-05-24 12:50:23 +00001104
Tim Northover3b0846e2014-05-24 12:50:23 +00001105 bool ExtraCSSpill = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00001106 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001107 // Figure out which callee-saved registers to save/restore.
1108 for (unsigned i = 0; CSRegs[i]; ++i) {
1109 const unsigned Reg = CSRegs[i];
Tim Northover3b0846e2014-05-24 12:50:23 +00001110
Geoff Berry7e4ba3d2016-02-19 18:27:32 +00001111 // Add the base pointer register to SavedRegs if it is callee-save.
1112 if (Reg == BasePointerReg)
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001113 SavedRegs.set(Reg);
Tim Northover3b0846e2014-05-24 12:50:23 +00001114
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001115 bool RegUsed = SavedRegs.test(Reg);
1116 unsigned PairedReg = CSRegs[i ^ 1];
1117 if (!RegUsed) {
1118 if (AArch64::GPR64RegClass.contains(Reg) &&
1119 !RegInfo->isReservedReg(MF, Reg)) {
1120 UnspilledCSGPR = Reg;
1121 UnspilledCSGPRPaired = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001122 }
1123 continue;
1124 }
1125
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001126 // MachO's compact unwind format relies on all registers being stored in
1127 // pairs.
1128 // FIXME: the usual format is actually better if unwinding isn't needed.
Manman Ren57518142016-04-11 21:08:06 +00001129 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg)) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001130 SavedRegs.set(PairedReg);
Geoff Berry74cb7182016-05-16 20:52:28 +00001131 if (AArch64::GPR64RegClass.contains(PairedReg) &&
1132 !RegInfo->isReservedReg(MF, PairedReg))
1133 ExtraCSSpill = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001134 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001135 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001136
1137 DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1138 for (int Reg = SavedRegs.find_first(); Reg != -1;
1139 Reg = SavedRegs.find_next(Reg))
1140 dbgs() << ' ' << PrintReg(Reg, RegInfo);
1141 dbgs() << "\n";);
1142
1143 // If any callee-saved registers are used, the frame cannot be eliminated.
1144 unsigned NumRegsSpilled = SavedRegs.count();
1145 bool CanEliminateFrame = NumRegsSpilled == 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001146
1147 // FIXME: Set BigStack if any stack slot references may be out of range.
1148 // For now, just conservatively guestimate based on unscaled indexing
1149 // range. We'll end up allocating an unnecessary spill slot a lot, but
1150 // realistically that's not a big deal at this stage of the game.
1151 // The CSR spill slots have not been allocated yet, so estimateStackSize
1152 // won't include them.
Matthias Braun941a7052016-07-28 18:40:00 +00001153 MachineFrameInfo &MFI = MF.getFrameInfo();
1154 unsigned CFSize = MFI.estimateStackSize(MF) + 8 * NumRegsSpilled;
Tim Northover3b0846e2014-05-24 12:50:23 +00001155 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
1156 bool BigStack = (CFSize >= 256);
1157 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1158 AFI->setHasStackFrame(true);
1159
1160 // Estimate if we might need to scavenge a register at some point in order
1161 // to materialize a stack offset. If so, either spill one additional
1162 // callee-saved register or reserve a special spill slot to facilitate
1163 // register scavenging. If we already spilled an extra callee-saved register
1164 // above to keep the number of spills even, we don't need to do anything else
1165 // here.
1166 if (BigStack && !ExtraCSSpill) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001167 if (UnspilledCSGPR != AArch64::NoRegister) {
1168 DEBUG(dbgs() << "Spilling " << PrintReg(UnspilledCSGPR, RegInfo)
1169 << " to get a scratch register.\n");
1170 SavedRegs.set(UnspilledCSGPR);
1171 // MachO's compact unwind format relies on all registers being stored in
1172 // pairs, so if we need to spill one extra for BigStack, then we need to
1173 // store the pair.
Manman Ren57518142016-04-11 21:08:06 +00001174 if (produceCompactUnwindFrame(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001175 SavedRegs.set(UnspilledCSGPRPaired);
Tim Northover3b0846e2014-05-24 12:50:23 +00001176 ExtraCSSpill = true;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001177 NumRegsSpilled = SavedRegs.count();
Tim Northover3b0846e2014-05-24 12:50:23 +00001178 }
1179
1180 // If we didn't find an extra callee-saved register to spill, create
1181 // an emergency spill slot.
1182 if (!ExtraCSSpill) {
1183 const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
Matthias Braun941a7052016-07-28 18:40:00 +00001184 int FI = MFI.CreateStackObject(RC->getSize(), RC->getAlignment(), false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001185 RS->addScavengingFrameIndex(FI);
1186 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1187 << " as the emergency spill slot.\n");
1188 }
1189 }
Geoff Berry04bf91a2016-02-01 16:29:19 +00001190
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001191 // Round up to register pair alignment to avoid additional SP adjustment
1192 // instructions.
1193 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00001194}
Geoff Berry66f6b652016-06-02 16:22:07 +00001195
1196bool AArch64FrameLowering::enableStackSlotScavenging(
1197 const MachineFunction &MF) const {
1198 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1199 return AFI->hasCalleeSaveStackFreeSpace();
1200}