blob: 01716c3cca505e77ca229b096887c82c45985cca [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:
75// * A base pointer is definitly needed when there are both VLAs and local
76// variables with more-than-default alignment requirements.
77// * A frame pointer is definitly needed when there are local variables with
78// 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
130 // Note: currently hasFP() is always true for hasCalls(), but that's an
131 // implementation detail of the current code, not a strict requirement,
132 // so stay safe here and check both.
133 if (MFI->hasCalls() || hasFP(MF) || NumBytes > 128)
134 return false;
135 return true;
136}
137
138/// hasFP - Return true if the specified function should have a dedicated frame
139/// pointer register.
140bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
141 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000142 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 return (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
Juergen Ributzka99bd3cb2014-10-02 22:21:49 +0000144 MFI->isFrameAddressTaken() || MFI->hasStackMap() ||
Kristof Beyls17cb8982015-04-09 08:49:47 +0000145 MFI->hasPatchPoint() || RegInfo->needsStackRealignment(MF));
Tim Northover3b0846e2014-05-24 12:50:23 +0000146}
147
148/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
149/// not required, we reserve argument space for call sites in the function
150/// immediately on entry to the current function. This eliminates the need for
151/// add/sub sp brackets around call sites. Returns true if the call frame is
152/// included as part of the stack frame.
153bool
154AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
155 return !MF.getFrameInfo()->hasVarSizedObjects();
156}
157
158void AArch64FrameLowering::eliminateCallFramePseudoInstr(
159 MachineFunction &MF, MachineBasicBlock &MBB,
160 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000161 const AArch64InstrInfo *TII =
162 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000163 DebugLoc DL = I->getDebugLoc();
164 int Opc = I->getOpcode();
165 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
166 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
167
Eric Christopherfc6de422014-08-05 02:39:49 +0000168 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Tim Northover3b0846e2014-05-24 12:50:23 +0000169 if (!TFI->hasReservedCallFrame(MF)) {
170 unsigned Align = getStackAlignment();
171
172 int64_t Amount = I->getOperand(0).getImm();
173 Amount = RoundUpToAlignment(Amount, Align);
174 if (!IsDestroy)
175 Amount = -Amount;
176
177 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
178 // doesn't have to pop anything), then the first operand will be zero too so
179 // this adjustment is a no-op.
180 if (CalleePopAmount == 0) {
181 // FIXME: in-function stack adjustment for calls is limited to 24-bits
182 // because there's no guaranteed temporary register available.
183 //
Sylvestre Ledru469de192014-08-11 18:04:46 +0000184 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 // 1) For offset <= 12-bit, we use LSL #0
186 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
187 // LSL #0, and the other uses LSL #12.
188 //
189 // Mostly call frames will be allocated at the start of a function so
190 // this is OK, but it is a limitation that needs dealing with.
191 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
192 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
193 }
194 } else if (CalleePopAmount != 0) {
195 // If the calling convention demands that the callee pops arguments from the
196 // stack, we want to add it back if we have a reserved call frame.
197 assert(CalleePopAmount < 0xffffff && "call frame too large");
198 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
199 TII);
200 }
201 MBB.erase(I);
202}
203
204void AArch64FrameLowering::emitCalleeSavedFrameMoves(
205 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
206 unsigned FramePtr) const {
207 MachineFunction &MF = *MBB.getParent();
208 MachineFrameInfo *MFI = MF.getFrameInfo();
209 MachineModuleInfo &MMI = MF.getMMI();
210 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000211 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000212 DebugLoc DL = MBB.findDebugLoc(MBBI);
213
214 // Add callee saved registers to move list.
215 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
216 if (CSI.empty())
217 return;
218
Eric Christopher8b770652015-01-26 19:03:15 +0000219 const DataLayout *TD = MF.getTarget().getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +0000220 bool HasFP = hasFP(MF);
221
222 // Calculate amount of bytes used for return address storing.
223 int stackGrowth = -TD->getPointerSize(0);
224
225 // Calculate offsets.
226 int64_t saveAreaOffset = (HasFP ? 2 : 1) * stackGrowth;
227 unsigned TotalSkipped = 0;
228 for (const auto &Info : CSI) {
229 unsigned Reg = Info.getReg();
230 int64_t Offset = MFI->getObjectOffset(Info.getFrameIdx()) -
231 getOffsetOfLocalArea() + saveAreaOffset;
232
233 // Don't output a new CFI directive if we're re-saving the frame pointer or
234 // link register. This happens when the PrologEpilogInserter has inserted an
235 // extra "STP" of the frame pointer and link register -- the "emitPrologue"
236 // method automatically generates the directives when frame pointers are
237 // used. If we generate CFI directives for the extra "STP"s, the linker will
238 // lose track of the correct values for the frame pointer and link register.
239 if (HasFP && (FramePtr == Reg || Reg == AArch64::LR)) {
240 TotalSkipped += stackGrowth;
241 continue;
242 }
243
244 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
245 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
246 nullptr, DwarfReg, Offset - TotalSkipped));
247 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000248 .addCFIIndex(CFIIndex)
249 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000250 }
251}
252
253void AArch64FrameLowering::emitPrologue(MachineFunction &MF) const {
254 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
255 MachineBasicBlock::iterator MBBI = MBB.begin();
256 const MachineFrameInfo *MFI = MF.getFrameInfo();
257 const Function *Fn = MF.getFunction();
Eric Christopherbc76b972014-06-10 17:33:39 +0000258 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000259 MF.getSubtarget().getRegisterInfo());
260 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000261 MachineModuleInfo &MMI = MF.getMMI();
262 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
263 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
264 bool HasFP = hasFP(MF);
265 DebugLoc DL = MBB.findDebugLoc(MBBI);
266
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000267 // All calls are tail calls in GHC calling conv, and functions have no
268 // prologue/epilogue.
269 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
270 return;
271
Tim Northover3b0846e2014-05-24 12:50:23 +0000272 int NumBytes = (int)MFI->getStackSize();
273 if (!AFI->hasStackFrame()) {
274 assert(!HasFP && "unexpected function without stack frame but with FP");
275
276 // All of the stack allocation is for locals.
277 AFI->setLocalStackSize(NumBytes);
278
279 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
280 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
281
282 // REDZONE: If the stack size is less than 128 bytes, we don't need
283 // to actually allocate.
284 if (NumBytes && !canUseRedZone(MF)) {
285 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
286 MachineInstr::FrameSetup);
287
288 // Encode the stack size of the leaf function.
289 unsigned CFIIndex = MMI.addFrameInst(
290 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
291 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000292 .addCFIIndex(CFIIndex)
293 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000294 } else if (NumBytes) {
295 ++NumRedZoneFunctions;
296 }
297
298 return;
299 }
300
301 // Only set up FP if we actually need to.
302 int FPOffset = 0;
303 if (HasFP) {
304 // First instruction must a) allocate the stack and b) have an immediate
305 // that is a multiple of -2.
306 assert((MBBI->getOpcode() == AArch64::STPXpre ||
307 MBBI->getOpcode() == AArch64::STPDpre) &&
308 MBBI->getOperand(3).getReg() == AArch64::SP &&
309 MBBI->getOperand(4).getImm() < 0 &&
310 (MBBI->getOperand(4).getImm() & 1) == 0);
311
312 // Frame pointer is fp = sp - 16. Since the STPXpre subtracts the space
313 // required for the callee saved register area we get the frame pointer
314 // by addding that offset - 16 = -getImm()*8 - 2*8 = -(getImm() + 2) * 8.
315 FPOffset = -(MBBI->getOperand(4).getImm() + 2) * 8;
316 assert(FPOffset >= 0 && "Bad Framepointer Offset");
317 }
318
319 // Move past the saves of the callee-saved registers.
320 while (MBBI->getOpcode() == AArch64::STPXi ||
321 MBBI->getOpcode() == AArch64::STPDi ||
322 MBBI->getOpcode() == AArch64::STPXpre ||
323 MBBI->getOpcode() == AArch64::STPDpre) {
324 ++MBBI;
325 NumBytes -= 16;
326 }
327 assert(NumBytes >= 0 && "Negative stack allocation size!?");
328 if (HasFP) {
329 // Issue sub fp, sp, FPOffset or
330 // mov fp,sp when FPOffset is zero.
331 // Note: All stores of callee-saved registers are marked as "FrameSetup".
332 // This code marks the instruction(s) that set the FP also.
333 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
334 MachineInstr::FrameSetup);
335 }
336
337 // All of the remaining stack allocations are for locals.
338 AFI->setLocalStackSize(NumBytes);
339
340 // Allocate space for the rest of the frame.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000341
342 const unsigned Alignment = MFI->getMaxAlignment();
343 const bool NeedsRealignment = (Alignment > 16);
344 unsigned scratchSPReg = AArch64::SP;
345 if (NeedsRealignment) {
346 // Use the first callee-saved register as a scratch register
347 assert(MF.getRegInfo().isPhysRegUsed(AArch64::X9) &&
348 "No scratch register to align SP!");
349 scratchSPReg = AArch64::X9;
350 }
351
352 // If we're a leaf function, try using the red zone.
353 if (NumBytes && !canUseRedZone(MF))
354 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
355 // the correct value here, as NumBytes also includes padding bytes,
356 // which shouldn't be counted here.
357 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
358 MachineInstr::FrameSetup);
359
360 assert(!(NeedsRealignment && NumBytes==0) &&
361 "NumBytes should never be 0 when realignment is needed");
362
363 if (NumBytes && NeedsRealignment) {
364 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
365 assert(NrBitsToZero > 1);
366 assert(scratchSPReg != AArch64::SP);
367
368 // SUB X9, SP, NumBytes
369 // -- X9 is temporary register, so shouldn't contain any live data here,
370 // -- free to use. This is already produced by emitFrameOffset above.
371 // AND SP, X9, 0b11111...0000
372 // The logical immediates have a non-trivial encoding. The following
373 // formula computes the encoded immediate with all ones but
374 // NrBitsToZero zero bits as least significant bits.
375 uint32_t andMaskEncoded =
376 (1 <<12) // = N
377 | ((64-NrBitsToZero) << 6) // immr
378 | ((64-NrBitsToZero-1) << 0) // imms
379 ;
380 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
381 .addReg(scratchSPReg, RegState::Kill)
382 .addImm(andMaskEncoded);
Tim Northover3b0846e2014-05-24 12:50:23 +0000383 }
384
385 // If we need a base pointer, set it up here. It's whatever the value of the
386 // stack pointer is at this point. Any variable size objects will be allocated
387 // after this, so we can still use the base pointer to reference locals.
388 //
389 // FIXME: Clarify FrameSetup flags here.
390 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
391 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000392 if (RegInfo->hasBasePointer(MF)) {
393 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
394 false);
395 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000396
397 if (needsFrameMoves) {
Eric Christopher8b770652015-01-26 19:03:15 +0000398 const DataLayout *TD = MF.getTarget().getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 const int StackGrowth = -TD->getPointerSize(0);
400 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 // An example of the prologue:
402 //
403 // .globl __foo
404 // .align 2
405 // __foo:
406 // Ltmp0:
407 // .cfi_startproc
408 // .cfi_personality 155, ___gxx_personality_v0
409 // Leh_func_begin:
410 // .cfi_lsda 16, Lexception33
411 //
412 // stp xa,bx, [sp, -#offset]!
413 // ...
414 // stp x28, x27, [sp, #offset-32]
415 // stp fp, lr, [sp, #offset-16]
416 // add fp, sp, #offset - 16
417 // sub sp, sp, #1360
418 //
419 // The Stack:
420 // +-------------------------------------------+
421 // 10000 | ........ | ........ | ........ | ........ |
422 // 10004 | ........ | ........ | ........ | ........ |
423 // +-------------------------------------------+
424 // 10008 | ........ | ........ | ........ | ........ |
425 // 1000c | ........ | ........ | ........ | ........ |
426 // +===========================================+
427 // 10010 | X28 Register |
428 // 10014 | X28 Register |
429 // +-------------------------------------------+
430 // 10018 | X27 Register |
431 // 1001c | X27 Register |
432 // +===========================================+
433 // 10020 | Frame Pointer |
434 // 10024 | Frame Pointer |
435 // +-------------------------------------------+
436 // 10028 | Link Register |
437 // 1002c | Link Register |
438 // +===========================================+
439 // 10030 | ........ | ........ | ........ | ........ |
440 // 10034 | ........ | ........ | ........ | ........ |
441 // +-------------------------------------------+
442 // 10038 | ........ | ........ | ........ | ........ |
443 // 1003c | ........ | ........ | ........ | ........ |
444 // +-------------------------------------------+
445 //
446 // [sp] = 10030 :: >>initial value<<
447 // sp = 10020 :: stp fp, lr, [sp, #-16]!
448 // fp = sp == 10020 :: mov fp, sp
449 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
450 // sp == 10010 :: >>final value<<
451 //
452 // The frame pointer (w29) points to address 10020. If we use an offset of
453 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
454 // for w27, and -32 for w28:
455 //
456 // Ltmp1:
457 // .cfi_def_cfa w29, 16
458 // Ltmp2:
459 // .cfi_offset w30, -8
460 // Ltmp3:
461 // .cfi_offset w29, -16
462 // Ltmp4:
463 // .cfi_offset w27, -24
464 // Ltmp5:
465 // .cfi_offset w28, -32
466
467 if (HasFP) {
468 // Define the current CFA rule to use the provided FP.
469 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
470 unsigned CFIIndex = MMI.addFrameInst(
471 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
472 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000473 .addCFIIndex(CFIIndex)
474 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000475
476 // Record the location of the stored LR
477 unsigned LR = RegInfo->getDwarfRegNum(AArch64::LR, true);
478 CFIIndex = MMI.addFrameInst(
479 MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
480 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000481 .addCFIIndex(CFIIndex)
482 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000483
484 // Record the location of the stored FP
485 CFIIndex = MMI.addFrameInst(
486 MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
487 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000488 .addCFIIndex(CFIIndex)
489 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000490 } else {
491 // Encode the stack size of the leaf function.
492 unsigned CFIIndex = MMI.addFrameInst(
493 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
494 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000495 .addCFIIndex(CFIIndex)
496 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000497 }
498
499 // Now emit the moves for whatever callee saved regs we have.
500 emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
501 }
502}
503
504static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
505 for (unsigned i = 0; CSRegs[i]; ++i)
506 if (Reg == CSRegs[i])
507 return true;
508 return false;
509}
510
511static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
512 unsigned RtIdx = 0;
513 if (MI->getOpcode() == AArch64::LDPXpost ||
514 MI->getOpcode() == AArch64::LDPDpost)
515 RtIdx = 1;
516
517 if (MI->getOpcode() == AArch64::LDPXpost ||
518 MI->getOpcode() == AArch64::LDPDpost ||
519 MI->getOpcode() == AArch64::LDPXi || MI->getOpcode() == AArch64::LDPDi) {
520 if (!isCalleeSavedRegister(MI->getOperand(RtIdx).getReg(), CSRegs) ||
521 !isCalleeSavedRegister(MI->getOperand(RtIdx + 1).getReg(), CSRegs) ||
522 MI->getOperand(RtIdx + 2).getReg() != AArch64::SP)
523 return false;
524 return true;
525 }
526
527 return false;
528}
529
530void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
531 MachineBasicBlock &MBB) const {
532 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
533 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
534 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000535 const AArch64InstrInfo *TII =
536 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000538 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000539 DebugLoc DL = MBBI->getDebugLoc();
540 unsigned RetOpcode = MBBI->getOpcode();
541
542 int NumBytes = MFI->getStackSize();
543 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
544
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000545 // All calls are tail calls in GHC calling conv, and functions have no
546 // prologue/epilogue.
547 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
548 return;
549
Kristof Beyls17cb8982015-04-09 08:49:47 +0000550 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000551 // in the epilogue, the residual adjustment is executed first.
552 uint64_t ArgumentPopSize = 0;
553 if (RetOpcode == AArch64::TCRETURNdi || RetOpcode == AArch64::TCRETURNri) {
554 MachineOperand &StackAdjust = MBBI->getOperand(1);
555
556 // For a tail-call in a callee-pops-arguments environment, some or all of
557 // the stack may actually be in use for the call's arguments, this is
558 // calculated during LowerCall and consumed here...
559 ArgumentPopSize = StackAdjust.getImm();
560 } else {
561 // ... otherwise the amount to pop is *all* of the argument space,
562 // conveniently stored in the MachineFunctionInfo by
563 // LowerFormalArguments. This will, of course, be zero for the C calling
564 // convention.
565 ArgumentPopSize = AFI->getArgumentStackToRestore();
566 }
567
568 // The stack frame should be like below,
569 //
570 // ---------------------- ---
571 // | | |
572 // | BytesInStackArgArea| CalleeArgStackSize
573 // | (NumReusableBytes) | (of tail call)
574 // | | ---
575 // | | |
576 // ---------------------| --- |
577 // | | | |
578 // | CalleeSavedReg | | |
579 // | (NumRestores * 16) | | |
580 // | | | |
581 // ---------------------| | NumBytes
582 // | | StackSize (StackAdjustUp)
583 // | LocalStackSize | | |
584 // | (covering callee | | |
585 // | args) | | |
586 // | | | |
587 // ---------------------- --- ---
588 //
589 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
590 // = StackSize + ArgumentPopSize
591 //
592 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
593 // it as the 2nd argument of AArch64ISD::TC_RETURN.
594 NumBytes += ArgumentPopSize;
595
596 unsigned NumRestores = 0;
597 // Move past the restores of the callee-saved registers.
598 MachineBasicBlock::iterator LastPopI = MBBI;
599 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
600 if (LastPopI != MBB.begin()) {
601 do {
602 ++NumRestores;
603 --LastPopI;
604 } while (LastPopI != MBB.begin() && isCSRestore(LastPopI, CSRegs));
605 if (!isCSRestore(LastPopI, CSRegs)) {
606 ++LastPopI;
607 --NumRestores;
608 }
609 }
610 NumBytes -= NumRestores * 16;
611 assert(NumBytes >= 0 && "Negative stack allocation size!?");
612
613 if (!hasFP(MF)) {
614 // If this was a redzone leaf function, we don't need to restore the
615 // stack pointer.
616 if (!canUseRedZone(MF))
617 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes,
618 TII);
619 return;
620 }
621
622 // Restore the original stack pointer.
623 // FIXME: Rather than doing the math here, we should instead just use
624 // non-post-indexed loads for the restores if we aren't actually going to
625 // be able to save any instructions.
626 if (NumBytes || MFI->hasVarSizedObjects())
627 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
628 -(NumRestores - 1) * 16, TII, MachineInstr::NoFlags);
629}
630
631/// getFrameIndexOffset - Returns the displacement from the frame register to
632/// the stack frame of the specified index.
633int AArch64FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
634 int FI) const {
635 unsigned FrameReg;
636 return getFrameIndexReference(MF, FI, FrameReg);
637}
638
639/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
640/// debug info. It's the same as what we use for resolving the code-gen
641/// references for now. FIXME: This can go wrong when references are
642/// SP-relative and simple call frames aren't used.
643int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
644 int FI,
645 unsigned &FrameReg) const {
646 return resolveFrameIndexReference(MF, FI, FrameReg);
647}
648
649int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
650 int FI, unsigned &FrameReg,
651 bool PreferFP) const {
652 const MachineFrameInfo *MFI = MF.getFrameInfo();
653 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000654 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000655 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
656 int FPOffset = MFI->getObjectOffset(FI) + 16;
657 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
658 bool isFixed = MFI->isFixedObjectIndex(FI);
659
660 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +0000661 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
662 // reliable as a base). Make sure useFPForScavengingIndex() does the
663 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +0000664 bool UseFP = false;
665 if (AFI->hasStackFrame()) {
666 // Note: Keeping the following as multiple 'if' statements rather than
667 // merging to a single expression for readability.
668 //
669 // Argument access should always use the FP.
670 if (isFixed) {
671 UseFP = hasFP(MF);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000672 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
673 !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 // Use SP or FP, whichever gives us the best chance of the offset
675 // being in range for direct access. If the FPOffset is positive,
676 // that'll always be best, as the SP will be even further away.
677 // If the FPOffset is negative, we have to keep in mind that the
678 // available offset range for negative offsets is smaller than for
679 // positive ones. If we have variable sized objects, we're stuck with
680 // using the FP regardless, though, as the SP offset is unknown
681 // and we don't have a base pointer available. If an offset is
682 // available via the FP and the SP, use whichever is closest.
683 if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
684 (FPOffset >= -256 && Offset > -FPOffset))
685 UseFP = true;
686 }
687 }
688
Kristof Beyls17cb8982015-04-09 08:49:47 +0000689 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
690 "In the presence of dynamic stack pointer realignment, "
691 "non-argument objects cannot be accessed through the frame pointer");
692
Tim Northover3b0846e2014-05-24 12:50:23 +0000693 if (UseFP) {
694 FrameReg = RegInfo->getFrameRegister(MF);
695 return FPOffset;
696 }
697
698 // Use the base pointer if we have one.
699 if (RegInfo->hasBasePointer(MF))
700 FrameReg = RegInfo->getBaseRegister();
701 else {
702 FrameReg = AArch64::SP;
703 // If we're using the red zone for this function, the SP won't actually
704 // be adjusted, so the offsets will be negative. They're also all
705 // within range of the signed 9-bit immediate instructions.
706 if (canUseRedZone(MF))
707 Offset -= AFI->getLocalStackSize();
708 }
709
710 return Offset;
711}
712
713static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
714 if (Reg != AArch64::LR)
715 return getKillRegState(true);
716
717 // LR maybe referred to later by an @llvm.returnaddress intrinsic.
718 bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
719 bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
720 return getKillRegState(LRKill);
721}
722
723bool AArch64FrameLowering::spillCalleeSavedRegisters(
724 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
725 const std::vector<CalleeSavedInfo> &CSI,
726 const TargetRegisterInfo *TRI) const {
727 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000728 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000729 unsigned Count = CSI.size();
730 DebugLoc DL;
731 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
732
733 if (MI != MBB.end())
734 DL = MI->getDebugLoc();
735
736 for (unsigned i = 0; i < Count; i += 2) {
737 unsigned idx = Count - i - 2;
738 unsigned Reg1 = CSI[idx].getReg();
739 unsigned Reg2 = CSI[idx + 1].getReg();
740 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
741 // list to come in sorted by frame index so that we can issue the store
742 // pair instructions directly. Assert if we see anything otherwise.
743 //
744 // The order of the registers in the list is controlled by
745 // getCalleeSavedRegs(), so they will always be in-order, as well.
746 assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
747 "Out of order callee saved regs!");
748 unsigned StrOpc;
749 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
750 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
751 // Issue sequence of non-sp increment and pi sp spills for cs regs. The
752 // first spill is a pre-increment that allocates the stack.
753 // For example:
754 // stp x22, x21, [sp, #-48]! // addImm(-6)
755 // stp x20, x19, [sp, #16] // addImm(+2)
756 // stp fp, lr, [sp, #32] // addImm(+4)
757 // Rationale: This sequence saves uop updates compared to a sequence of
758 // pre-increment spills like stp xi,xj,[sp,#-16]!
759 // Note: Similar rational and sequence for restores in epilog.
760 if (AArch64::GPR64RegClass.contains(Reg1)) {
761 assert(AArch64::GPR64RegClass.contains(Reg2) &&
762 "Expected GPR64 callee-saved register pair!");
763 // For first spill use pre-increment store.
764 if (i == 0)
765 StrOpc = AArch64::STPXpre;
766 else
767 StrOpc = AArch64::STPXi;
768 } else if (AArch64::FPR64RegClass.contains(Reg1)) {
769 assert(AArch64::FPR64RegClass.contains(Reg2) &&
770 "Expected FPR64 callee-saved register pair!");
771 // For first spill use pre-increment store.
772 if (i == 0)
773 StrOpc = AArch64::STPDpre;
774 else
775 StrOpc = AArch64::STPDi;
776 } else
777 llvm_unreachable("Unexpected callee saved register!");
778 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
779 << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
780 << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
781 // Compute offset: i = 0 => offset = -Count;
782 // i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
783 const int Offset = (i == 0) ? -Count : i;
784 assert((Offset >= -64 && Offset <= 63) &&
785 "Offset out of bounds for STP immediate");
786 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
787 if (StrOpc == AArch64::STPDpre || StrOpc == AArch64::STPXpre)
788 MIB.addReg(AArch64::SP, RegState::Define);
789
790 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
791 .addReg(Reg1, getPrologueDeath(MF, Reg1))
792 .addReg(AArch64::SP)
793 .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
794 .setMIFlag(MachineInstr::FrameSetup);
795 }
796 return true;
797}
798
799bool AArch64FrameLowering::restoreCalleeSavedRegisters(
800 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
801 const std::vector<CalleeSavedInfo> &CSI,
802 const TargetRegisterInfo *TRI) const {
803 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000804 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000805 unsigned Count = CSI.size();
806 DebugLoc DL;
807 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
808
809 if (MI != MBB.end())
810 DL = MI->getDebugLoc();
811
812 for (unsigned i = 0; i < Count; i += 2) {
813 unsigned Reg1 = CSI[i].getReg();
814 unsigned Reg2 = CSI[i + 1].getReg();
815 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
816 // list to come in sorted by frame index so that we can issue the store
817 // pair instructions directly. Assert if we see anything otherwise.
818 assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
819 "Out of order callee saved regs!");
820 // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
821 // the last load is sp-pi post-increment and de-allocates the stack:
822 // For example:
823 // ldp fp, lr, [sp, #32] // addImm(+4)
824 // ldp x20, x19, [sp, #16] // addImm(+2)
825 // ldp x22, x21, [sp], #48 // addImm(+6)
826 // Note: see comment in spillCalleeSavedRegisters()
827 unsigned LdrOpc;
828
829 assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
830 assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
831 if (AArch64::GPR64RegClass.contains(Reg1)) {
832 assert(AArch64::GPR64RegClass.contains(Reg2) &&
833 "Expected GPR64 callee-saved register pair!");
834 if (i == Count - 2)
835 LdrOpc = AArch64::LDPXpost;
836 else
837 LdrOpc = AArch64::LDPXi;
838 } else if (AArch64::FPR64RegClass.contains(Reg1)) {
839 assert(AArch64::FPR64RegClass.contains(Reg2) &&
840 "Expected FPR64 callee-saved register pair!");
841 if (i == Count - 2)
842 LdrOpc = AArch64::LDPDpost;
843 else
844 LdrOpc = AArch64::LDPDi;
845 } else
846 llvm_unreachable("Unexpected callee saved register!");
847 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
848 << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
849 << ", " << CSI[i + 1].getFrameIdx() << ")\n");
850
851 // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
852 // etc.
853 const int Offset = (i == Count - 2) ? Count : Count - i - 2;
854 assert((Offset >= -64 && Offset <= 63) &&
855 "Offset out of bounds for LDP immediate");
856 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
857 if (LdrOpc == AArch64::LDPXpost || LdrOpc == AArch64::LDPDpost)
858 MIB.addReg(AArch64::SP, RegState::Define);
859
860 MIB.addReg(Reg2, getDefRegState(true))
861 .addReg(Reg1, getDefRegState(true))
862 .addReg(AArch64::SP)
863 .addImm(Offset); // [sp], #offset * 8 or [sp, #offset * 8]
864 // where the factor * 8 is implicit
865 }
866 return true;
867}
868
869void AArch64FrameLowering::processFunctionBeforeCalleeSavedScan(
870 MachineFunction &MF, RegScavenger *RS) const {
871 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000872 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000873 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
874 MachineRegisterInfo *MRI = &MF.getRegInfo();
875 SmallVector<unsigned, 4> UnspilledCSGPRs;
876 SmallVector<unsigned, 4> UnspilledCSFPRs;
877
878 // The frame record needs to be created by saving the appropriate registers
879 if (hasFP(MF)) {
880 MRI->setPhysRegUsed(AArch64::FP);
881 MRI->setPhysRegUsed(AArch64::LR);
882 }
883
884 // Spill the BasePtr if it's used. Do this first thing so that the
885 // getCalleeSavedRegs() below will get the right answer.
886 if (RegInfo->hasBasePointer(MF))
887 MRI->setPhysRegUsed(RegInfo->getBaseRegister());
888
Kristof Beyls17cb8982015-04-09 08:49:47 +0000889 if (RegInfo->needsStackRealignment(MF) && !RegInfo->hasBasePointer(MF))
890 MRI->setPhysRegUsed(AArch64::X9);
891
Tim Northover3b0846e2014-05-24 12:50:23 +0000892 // If any callee-saved registers are used, the frame cannot be eliminated.
893 unsigned NumGPRSpilled = 0;
894 unsigned NumFPRSpilled = 0;
895 bool ExtraCSSpill = false;
896 bool CanEliminateFrame = true;
897 DEBUG(dbgs() << "*** processFunctionBeforeCalleeSavedScan\nUsed CSRs:");
898 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
899
900 // Check pairs of consecutive callee-saved registers.
901 for (unsigned i = 0; CSRegs[i]; i += 2) {
902 assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
903
904 const unsigned OddReg = CSRegs[i];
905 const unsigned EvenReg = CSRegs[i + 1];
906 assert((AArch64::GPR64RegClass.contains(OddReg) &&
907 AArch64::GPR64RegClass.contains(EvenReg)) ^
908 (AArch64::FPR64RegClass.contains(OddReg) &&
909 AArch64::FPR64RegClass.contains(EvenReg)) &&
910 "Register class mismatch!");
911
912 const bool OddRegUsed = MRI->isPhysRegUsed(OddReg);
913 const bool EvenRegUsed = MRI->isPhysRegUsed(EvenReg);
914
915 // Early exit if none of the registers in the register pair is actually
916 // used.
917 if (!OddRegUsed && !EvenRegUsed) {
918 if (AArch64::GPR64RegClass.contains(OddReg)) {
919 UnspilledCSGPRs.push_back(OddReg);
920 UnspilledCSGPRs.push_back(EvenReg);
921 } else {
922 UnspilledCSFPRs.push_back(OddReg);
923 UnspilledCSFPRs.push_back(EvenReg);
924 }
925 continue;
926 }
927
928 unsigned Reg = AArch64::NoRegister;
929 // If only one of the registers of the register pair is used, make sure to
930 // mark the other one as used as well.
931 if (OddRegUsed ^ EvenRegUsed) {
932 // Find out which register is the additional spill.
933 Reg = OddRegUsed ? EvenReg : OddReg;
934 MRI->setPhysRegUsed(Reg);
935 }
936
937 DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
938 DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
939
940 assert(((OddReg == AArch64::LR && EvenReg == AArch64::FP) ||
941 (RegInfo->getEncodingValue(OddReg) + 1 ==
942 RegInfo->getEncodingValue(EvenReg))) &&
943 "Register pair of non-adjacent registers!");
944 if (AArch64::GPR64RegClass.contains(OddReg)) {
945 NumGPRSpilled += 2;
946 // If it's not a reserved register, we can use it in lieu of an
947 // emergency spill slot for the register scavenger.
948 // FIXME: It would be better to instead keep looking and choose another
949 // unspilled register that isn't reserved, if there is one.
950 if (Reg != AArch64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
951 ExtraCSSpill = true;
952 } else
953 NumFPRSpilled += 2;
954
955 CanEliminateFrame = false;
956 }
957
958 // FIXME: Set BigStack if any stack slot references may be out of range.
959 // For now, just conservatively guestimate based on unscaled indexing
960 // range. We'll end up allocating an unnecessary spill slot a lot, but
961 // realistically that's not a big deal at this stage of the game.
962 // The CSR spill slots have not been allocated yet, so estimateStackSize
963 // won't include them.
964 MachineFrameInfo *MFI = MF.getFrameInfo();
Kristof Beyls17cb8982015-04-09 08:49:47 +0000965 unsigned CFSize =
966 MFI->estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
Tim Northover3b0846e2014-05-24 12:50:23 +0000967 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
968 bool BigStack = (CFSize >= 256);
969 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
970 AFI->setHasStackFrame(true);
971
972 // Estimate if we might need to scavenge a register at some point in order
973 // to materialize a stack offset. If so, either spill one additional
974 // callee-saved register or reserve a special spill slot to facilitate
975 // register scavenging. If we already spilled an extra callee-saved register
976 // above to keep the number of spills even, we don't need to do anything else
977 // here.
978 if (BigStack && !ExtraCSSpill) {
979
980 // If we're adding a register to spill here, we have to add two of them
981 // to keep the number of regs to spill even.
982 assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
983 unsigned Count = 0;
984 while (!UnspilledCSGPRs.empty() && Count < 2) {
985 unsigned Reg = UnspilledCSGPRs.back();
986 UnspilledCSGPRs.pop_back();
987 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
988 << " to get a scratch register.\n");
989 MRI->setPhysRegUsed(Reg);
990 ExtraCSSpill = true;
991 ++Count;
992 }
993
994 // If we didn't find an extra callee-saved register to spill, create
995 // an emergency spill slot.
996 if (!ExtraCSSpill) {
997 const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
998 int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
999 RS->addScavengingFrameIndex(FI);
1000 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1001 << " as the emergency spill slot.\n");
1002 }
1003 }
1004}