blob: e81eb5ea85250b63fbac82cd54a4bb759943d1e1 [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// | |
Martin Storsjo68266fa2017-07-13 17:03:12 +000044// | (Win64 only) varargs from reg |
45// | |
46// |-----------------------------------|
47// | |
Kristof Beyls17cb8982015-04-09 08:49:47 +000048// | prev_fp, prev_lr |
49// | (a.k.a. "frame record") |
50// |-----------------------------------| <- fp(=x29)
51// | |
52// | other callee-saved registers |
53// | |
54// |-----------------------------------|
55// |.empty.space.to.make.part.below....|
56// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
57// |.the.standard.16-byte.alignment....| compile time; if present)
58// |-----------------------------------|
59// | |
60// | local variables of fixed size |
61// | including spill slots |
62// |-----------------------------------| <- bp(not defined by ABI,
63// |.variable-sized.local.variables....| LLVM chooses X19)
64// |.(VLAs)............................| (size of this area is unknown at
65// |...................................| compile time)
66// |-----------------------------------| <- sp
67// | | Lower address
68//
69//
70// To access the data in a frame, at-compile time, a constant offset must be
71// computable from one of the pointers (fp, bp, sp) to access it. The size
72// of the areas with a dotted background cannot be computed at compile-time
73// if they are present, making it required to have all three of fp, bp and
74// sp to be set up to be able to access all contents in the frame areas,
75// assuming all of the frame areas are non-empty.
76//
77// For most functions, some of the frame areas are empty. For those functions,
78// it may not be necessary to set up fp or bp:
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000079// * A base pointer is definitely needed when there are both VLAs and local
Kristof Beyls17cb8982015-04-09 08:49:47 +000080// variables with more-than-default alignment requirements.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000081// * A frame pointer is definitely needed when there are local variables with
Kristof Beyls17cb8982015-04-09 08:49:47 +000082// more-than-default alignment requirements.
83//
84// In some cases when a base pointer is not strictly needed, it is generated
85// anyway when offsets from the frame pointer to access local variables become
86// so large that the offset can't be encoded in the immediate fields of loads
87// or stores.
88//
89// FIXME: also explain the redzone concept.
90// FIXME: also explain the concept of reserved call frames.
91//
Tim Northover3b0846e2014-05-24 12:50:23 +000092//===----------------------------------------------------------------------===//
93
94#include "AArch64FrameLowering.h"
95#include "AArch64InstrInfo.h"
96#include "AArch64MachineFunctionInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000097#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000098#include "AArch64Subtarget.h"
99#include "AArch64TargetMachine.h"
Martin Storsjo2778fd02017-12-20 06:51:45 +0000100#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000101#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000102#include "llvm/ADT/Statistic.h"
Matthias Braun332bb5c2016-07-06 21:31:27 +0000103#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000104#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000105#include "llvm/CodeGen/MachineFrameInfo.h"
106#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000107#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000108#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000109#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000110#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000111#include "llvm/CodeGen/MachineOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000112#include "llvm/CodeGen/MachineRegisterInfo.h"
113#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +0000114#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +0000115#include "llvm/CodeGen/TargetRegisterInfo.h"
116#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000117#include "llvm/IR/Attributes.h"
118#include "llvm/IR/CallingConv.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000119#include "llvm/IR/DataLayout.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000120#include "llvm/IR/DebugLoc.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000121#include "llvm/IR/Function.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000122#include "llvm/MC/MCDwarf.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000123#include "llvm/Support/CommandLine.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000124#include "llvm/Support/Debug.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000125#include "llvm/Support/ErrorHandling.h"
126#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000127#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000128#include "llvm/Target/TargetMachine.h"
129#include "llvm/Target/TargetOptions.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000130#include <cassert>
131#include <cstdint>
132#include <iterator>
133#include <vector>
Tim Northover3b0846e2014-05-24 12:50:23 +0000134
135using namespace llvm;
136
137#define DEBUG_TYPE "frame-info"
138
139static cl::opt<bool> EnableRedZone("aarch64-redzone",
140 cl::desc("enable use of redzone on AArch64"),
141 cl::init(false), cl::Hidden);
142
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000143static cl::opt<bool>
144 ReverseCSRRestoreSeq("reverse-csr-restore-seq",
145 cl::desc("reverse the CSR restore sequence"),
146 cl::init(false), cl::Hidden);
147
Tim Northover3b0846e2014-05-24 12:50:23 +0000148STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
149
Matthias Braun5c290dc2018-01-19 03:16:36 +0000150/// This is the biggest offset to the stack pointer we can encode in aarch64
151/// instructions (without using a separate calculation and a temp register).
152/// Note that the exception here are vector stores/loads which cannot encode any
153/// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
154static const unsigned DefaultSafeSPDisplacement = 255;
155
Kristof Beyls2af1e902017-05-30 06:58:41 +0000156/// Look at each instruction that references stack frames and return the stack
157/// size limit beyond which some of these instructions will require a scratch
158/// register during their expansion later.
159static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
160 // FIXME: For now, just conservatively guestimate based on unscaled indexing
161 // range. We'll end up allocating an unnecessary spill slot a lot, but
162 // realistically that's not a big deal at this stage of the game.
163 for (MachineBasicBlock &MBB : MF) {
164 for (MachineInstr &MI : MBB) {
165 if (MI.isDebugValue() || MI.isPseudo() ||
166 MI.getOpcode() == AArch64::ADDXri ||
167 MI.getOpcode() == AArch64::ADDSXri)
168 continue;
169
Javed Absard13d4192017-10-30 22:00:06 +0000170 for (const MachineOperand &MO : MI.operands()) {
171 if (!MO.isFI())
Kristof Beyls2af1e902017-05-30 06:58:41 +0000172 continue;
173
174 int Offset = 0;
175 if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
176 AArch64FrameOffsetCannotUpdate)
177 return 0;
178 }
179 }
180 }
Matthias Braun5c290dc2018-01-19 03:16:36 +0000181 return DefaultSafeSPDisplacement;
Kristof Beyls2af1e902017-05-30 06:58:41 +0000182}
183
Tim Northover3b0846e2014-05-24 12:50:23 +0000184bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
185 if (!EnableRedZone)
186 return false;
187 // Don't use the red zone if the function explicitly asks us not to.
188 // This is typically used for kernel code.
Matthias Braunf1caa282017-12-15 22:22:58 +0000189 if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 return false;
191
Matthias Braun941a7052016-07-28 18:40:00 +0000192 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
194 unsigned NumBytes = AFI->getLocalStackSize();
195
Matthias Braun941a7052016-07-28 18:40:00 +0000196 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
Tim Northover3b0846e2014-05-24 12:50:23 +0000197}
198
199/// hasFP - Return true if the specified function should have a dedicated frame
200/// pointer register.
201bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000202 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000203 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000204 // Retain behavior of always omitting the FP for leaf functions when possible.
Matthias Braun5c290dc2018-01-19 03:16:36 +0000205 if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
206 return true;
207 if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
208 MFI.hasStackMap() || MFI.hasPatchPoint() ||
209 RegInfo->needsStackRealignment(MF))
210 return true;
211 // With large callframes around we may need to use FP to access the scavenging
212 // emergency spillslot.
213 //
214 // Unfortunately some calls to hasFP() like machine verifier ->
215 // getReservedReg() -> hasFP in the middle of global isel are too early
216 // to know the max call frame size. Hopefully conservatively returning "true"
217 // in those cases is fine.
218 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
219 if (!MFI.isMaxCallFrameSizeComputed() ||
220 MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
221 return true;
222
223 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000224}
225
226/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
227/// not required, we reserve argument space for call sites in the function
228/// immediately on entry to the current function. This eliminates the need for
229/// add/sub sp brackets around call sites. Returns true if the call frame is
230/// included as part of the stack frame.
231bool
232AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000233 return !MF.getFrameInfo().hasVarSizedObjects();
Tim Northover3b0846e2014-05-24 12:50:23 +0000234}
235
Hans Wennborge1a2e902016-03-31 18:33:38 +0000236MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
Tim Northover3b0846e2014-05-24 12:50:23 +0000237 MachineFunction &MF, MachineBasicBlock &MBB,
238 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000239 const AArch64InstrInfo *TII =
240 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000241 DebugLoc DL = I->getDebugLoc();
Matthias Braunfa3872e2015-05-18 20:27:55 +0000242 unsigned Opc = I->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000243 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
244 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
245
Eric Christopherfc6de422014-08-05 02:39:49 +0000246 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Tim Northover3b0846e2014-05-24 12:50:23 +0000247 if (!TFI->hasReservedCallFrame(MF)) {
248 unsigned Align = getStackAlignment();
249
250 int64_t Amount = I->getOperand(0).getImm();
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000251 Amount = alignTo(Amount, Align);
Tim Northover3b0846e2014-05-24 12:50:23 +0000252 if (!IsDestroy)
253 Amount = -Amount;
254
255 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
256 // doesn't have to pop anything), then the first operand will be zero too so
257 // this adjustment is a no-op.
258 if (CalleePopAmount == 0) {
259 // FIXME: in-function stack adjustment for calls is limited to 24-bits
260 // because there's no guaranteed temporary register available.
261 //
Sylvestre Ledru469de192014-08-11 18:04:46 +0000262 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000263 // 1) For offset <= 12-bit, we use LSL #0
264 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
265 // LSL #0, and the other uses LSL #12.
266 //
Chad Rosier401a4ab2016-01-19 16:50:45 +0000267 // Most call frames will be allocated at the start of a function so
Tim Northover3b0846e2014-05-24 12:50:23 +0000268 // this is OK, but it is a limitation that needs dealing with.
269 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
270 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
271 }
272 } else if (CalleePopAmount != 0) {
273 // If the calling convention demands that the callee pops arguments from the
274 // stack, we want to add it back if we have a reserved call frame.
275 assert(CalleePopAmount < 0xffffff && "call frame too large");
276 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
277 TII);
278 }
Hans Wennborge1a2e902016-03-31 18:33:38 +0000279 return MBB.erase(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000280}
281
282void AArch64FrameLowering::emitCalleeSavedFrameMoves(
Geoff Berry62d47252016-02-25 16:36:08 +0000283 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000284 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000285 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf23ef432016-11-30 23:48:42 +0000286 const TargetSubtargetInfo &STI = MF.getSubtarget();
287 const MCRegisterInfo *MRI = STI.getRegisterInfo();
288 const TargetInstrInfo *TII = STI.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000289 DebugLoc DL = MBB.findDebugLoc(MBBI);
290
291 // Add callee saved registers to move list.
Matthias Braun941a7052016-07-28 18:40:00 +0000292 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000293 if (CSI.empty())
294 return;
295
Tim Northover3b0846e2014-05-24 12:50:23 +0000296 for (const auto &Info : CSI) {
297 unsigned Reg = Info.getReg();
Geoff Berry62d47252016-02-25 16:36:08 +0000298 int64_t Offset =
Matthias Braun941a7052016-07-28 18:40:00 +0000299 MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
Tim Northover3b0846e2014-05-24 12:50:23 +0000300 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braunf23ef432016-11-30 23:48:42 +0000301 unsigned CFIIndex = MF.addFrameInst(
Geoff Berry62d47252016-02-25 16:36:08 +0000302 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover3b0846e2014-05-24 12:50:23 +0000303 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000304 .addCFIIndex(CFIIndex)
305 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000306 }
307}
308
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000309// Find a scratch register that we can use at the start of the prologue to
310// re-align the stack pointer. We avoid using callee-save registers since they
311// may appear to be free when this is called from canUseAsPrologue (during
312// shrink wrapping), but then no longer be free when this is called from
313// emitPrologue.
314//
315// FIXME: This is a bit conservative, since in the above case we could use one
316// of the callee-save registers as a scratch temp to re-align the stack pointer,
317// but we would then have to make sure that we were in fact saving at least one
318// callee-save register in the prologue, which is additional complexity that
319// doesn't seem worth the benefit.
320static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
321 MachineFunction *MF = MBB->getParent();
322
323 // If MBB is an entry block, use X9 as the scratch register
324 if (&MF->front() == MBB)
325 return AArch64::X9;
326
Eric Christopher60a245e2017-03-31 23:12:27 +0000327 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
Matthias Braunac4307c2017-05-26 21:51:00 +0000328 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
Eric Christopher60a245e2017-03-31 23:12:27 +0000329 LivePhysRegs LiveRegs(TRI);
Matthias Braun332bb5c2016-07-06 21:31:27 +0000330 LiveRegs.addLiveIns(*MBB);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000331
Matthias Braun332bb5c2016-07-06 21:31:27 +0000332 // Mark callee saved registers as used so we will not choose them.
Matthias Braunac4307c2017-05-26 21:51:00 +0000333 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(MF);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000334 for (unsigned i = 0; CSRegs[i]; ++i)
Matthias Braun332bb5c2016-07-06 21:31:27 +0000335 LiveRegs.addReg(CSRegs[i]);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000336
Matthias Braun332bb5c2016-07-06 21:31:27 +0000337 // Prefer X9 since it was historically used for the prologue scratch reg.
338 const MachineRegisterInfo &MRI = MF->getRegInfo();
339 if (LiveRegs.available(MRI, AArch64::X9))
340 return AArch64::X9;
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000341
Matthias Braun332bb5c2016-07-06 21:31:27 +0000342 for (unsigned Reg : AArch64::GPR64RegClass) {
343 if (LiveRegs.available(MRI, Reg))
344 return Reg;
345 }
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000346 return AArch64::NoRegister;
347}
348
349bool AArch64FrameLowering::canUseAsPrologue(
350 const MachineBasicBlock &MBB) const {
351 const MachineFunction *MF = MBB.getParent();
352 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
353 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
354 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
355
356 // Don't need a scratch register if we're not going to re-align the stack.
357 if (!RegInfo->needsStackRealignment(*MF))
358 return true;
359 // Otherwise, we can use any block as long as it has a scratch register
360 // available.
361 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
362}
363
Martin Storsjo2778fd02017-12-20 06:51:45 +0000364static bool windowsRequiresStackProbe(MachineFunction &MF,
365 unsigned StackSizeInBytes) {
366 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
367 if (!Subtarget.isTargetWindows())
368 return false;
369 const Function &F = MF.getFunction();
370 // TODO: When implementing stack protectors, take that into account
371 // for the probe threshold.
372 unsigned StackProbeSize = 4096;
373 if (F.hasFnAttribute("stack-probe-size"))
374 F.getFnAttribute("stack-probe-size")
375 .getValueAsString()
376 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000377 return (StackSizeInBytes >= StackProbeSize) &&
378 !F.hasFnAttribute("no-stack-arg-probe");
Martin Storsjo2778fd02017-12-20 06:51:45 +0000379}
380
Geoff Berrya5335642016-05-06 16:34:59 +0000381bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
382 MachineFunction &MF, unsigned StackBumpBytes) const {
383 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000384 const MachineFrameInfo &MFI = MF.getFrameInfo();
Geoff Berrya5335642016-05-06 16:34:59 +0000385 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
386 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
387
388 if (AFI->getLocalStackSize() == 0)
389 return false;
390
391 // 512 is the maximum immediate for stp/ldp that will be used for
392 // callee-save save/restores
Martin Storsjo2778fd02017-12-20 06:51:45 +0000393 if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
Geoff Berrya5335642016-05-06 16:34:59 +0000394 return false;
395
Matthias Braun941a7052016-07-28 18:40:00 +0000396 if (MFI.hasVarSizedObjects())
Geoff Berrya5335642016-05-06 16:34:59 +0000397 return false;
398
399 if (RegInfo->needsStackRealignment(MF))
400 return false;
401
402 // This isn't strictly necessary, but it simplifies things a bit since the
403 // current RedZone handling code assumes the SP is adjusted by the
404 // callee-save save/restore code.
405 if (canUseRedZone(MF))
406 return false;
407
408 return true;
409}
410
411// Convert callee-save register save/restore instruction to do stack pointer
412// decrement/increment to allocate/deallocate the callee-save stack area by
413// converting store/load to use pre/post increment version.
414static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000415 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
416 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc) {
Geoff Berrya5335642016-05-06 16:34:59 +0000417 unsigned NewOpc;
418 bool NewIsUnscaled = false;
419 switch (MBBI->getOpcode()) {
420 default:
421 llvm_unreachable("Unexpected callee-save save/restore opcode!");
422 case AArch64::STPXi:
423 NewOpc = AArch64::STPXpre;
424 break;
425 case AArch64::STPDi:
426 NewOpc = AArch64::STPDpre;
427 break;
428 case AArch64::STRXui:
429 NewOpc = AArch64::STRXpre;
430 NewIsUnscaled = true;
431 break;
432 case AArch64::STRDui:
433 NewOpc = AArch64::STRDpre;
434 NewIsUnscaled = true;
435 break;
436 case AArch64::LDPXi:
437 NewOpc = AArch64::LDPXpost;
438 break;
439 case AArch64::LDPDi:
440 NewOpc = AArch64::LDPDpost;
441 break;
442 case AArch64::LDRXui:
443 NewOpc = AArch64::LDRXpost;
444 NewIsUnscaled = true;
445 break;
446 case AArch64::LDRDui:
447 NewOpc = AArch64::LDRDpost;
448 NewIsUnscaled = true;
449 break;
450 }
451
452 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
453 MIB.addReg(AArch64::SP, RegState::Define);
454
455 // Copy all operands other than the immediate offset.
456 unsigned OpndIdx = 0;
457 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
458 ++OpndIdx)
Diana Picus116bbab2017-01-13 09:58:52 +0000459 MIB.add(MBBI->getOperand(OpndIdx));
Geoff Berrya5335642016-05-06 16:34:59 +0000460
461 assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
462 "Unexpected immediate offset in first/last callee-save save/restore "
463 "instruction!");
464 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
465 "Unexpected base register in callee-save save/restore instruction!");
466 // Last operand is immediate offset that needs fixing.
467 assert(CSStackSizeInc % 8 == 0);
468 int64_t CSStackSizeIncImm = CSStackSizeInc;
469 if (!NewIsUnscaled)
470 CSStackSizeIncImm /= 8;
471 MIB.addImm(CSStackSizeIncImm);
472
473 MIB.setMIFlags(MBBI->getFlags());
474 MIB.setMemRefs(MBBI->memoperands_begin(), MBBI->memoperands_end());
475
476 return std::prev(MBB.erase(MBBI));
477}
478
479// Fixup callee-save register save/restore instructions to take into account
480// combined SP bump by adding the local stack size to the stack offsets.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000481static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
Geoff Berrya5335642016-05-06 16:34:59 +0000482 unsigned LocalStackSize) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000483 unsigned Opc = MI.getOpcode();
Geoff Berrya5335642016-05-06 16:34:59 +0000484 (void)Opc;
485 assert((Opc == AArch64::STPXi || Opc == AArch64::STPDi ||
486 Opc == AArch64::STRXui || Opc == AArch64::STRDui ||
487 Opc == AArch64::LDPXi || Opc == AArch64::LDPDi ||
488 Opc == AArch64::LDRXui || Opc == AArch64::LDRDui) &&
489 "Unexpected callee-save save/restore opcode!");
490
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000491 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
492 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
Geoff Berrya5335642016-05-06 16:34:59 +0000493 "Unexpected base register in callee-save save/restore instruction!");
494 // Last operand is immediate offset that needs fixing.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000495 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
Geoff Berrya5335642016-05-06 16:34:59 +0000496 // All generated opcodes have scaled offsets.
497 assert(LocalStackSize % 8 == 0);
498 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / 8);
499}
500
Quentin Colombet61b305e2015-05-05 17:38:16 +0000501void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
502 MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000503 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000504 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000505 const Function &F = MF.getFunction();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000506 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
507 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
508 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000509 MachineModuleInfo &MMI = MF.getMMI();
Tim Northover775aaeb2015-11-05 21:54:58 +0000510 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braunf1caa282017-12-15 22:22:58 +0000511 bool needsFrameMoves = MMI.hasDebugInfo() || F.needsUnwindTableEntry();
Tim Northover775aaeb2015-11-05 21:54:58 +0000512 bool HasFP = hasFP(MF);
513
514 // Debug location must be unknown since the first debug location is used
515 // to determine the end of the prologue.
516 DebugLoc DL;
517
518 // All calls are tail calls in GHC calling conv, and functions have no
519 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000520 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000521 return;
522
Matthias Braun941a7052016-07-28 18:40:00 +0000523 int NumBytes = (int)MFI.getStackSize();
Martin Storsjo2778fd02017-12-20 06:51:45 +0000524 if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000525 assert(!HasFP && "unexpected function without stack frame but with FP");
526
527 // All of the stack allocation is for locals.
528 AFI->setLocalStackSize(NumBytes);
529
Chad Rosier27c352d2016-03-14 18:24:34 +0000530 if (!NumBytes)
531 return;
Tim Northover3b0846e2014-05-24 12:50:23 +0000532 // REDZONE: If the stack size is less than 128 bytes, we don't need
533 // to actually allocate.
Chad Rosier27c352d2016-03-14 18:24:34 +0000534 if (canUseRedZone(MF))
535 ++NumRedZoneFunctions;
536 else {
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
538 MachineInstr::FrameSetup);
539
Chad Rosier27c352d2016-03-14 18:24:34 +0000540 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
541 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Tim Northover3b0846e2014-05-24 12:50:23 +0000542 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000543 unsigned CFIIndex = MF.addFrameInst(
Tim Northover3b0846e2014-05-24 12:50:23 +0000544 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
545 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000546 .addCFIIndex(CFIIndex)
547 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000548 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000549 return;
550 }
551
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000552 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000553 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000554 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
555
556 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Chad Rosier27c352d2016-03-14 18:24:34 +0000557 // All of the remaining stack allocations are for locals.
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000558 AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
Tim Northover3b0846e2014-05-24 12:50:23 +0000559
Geoff Berrya5335642016-05-06 16:34:59 +0000560 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
561 if (CombineSPBump) {
562 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
563 MachineInstr::FrameSetup);
564 NumBytes = 0;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000565 } else if (PrologueSaveSize != 0) {
Geoff Berrya5335642016-05-06 16:34:59 +0000566 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000567 -PrologueSaveSize);
568 NumBytes -= PrologueSaveSize;
Geoff Berrya5335642016-05-06 16:34:59 +0000569 }
570 assert(NumBytes >= 0 && "Negative stack allocation size!?");
571
572 // Move past the saves of the callee-saved registers, fixing up the offsets
573 // and pre-inc if we decided to combine the callee-save and local stack
574 // pointer bump above.
Geoff Berry04bf91a2016-02-01 16:29:19 +0000575 MachineBasicBlock::iterator End = MBB.end();
Geoff Berrya5335642016-05-06 16:34:59 +0000576 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
577 if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000578 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000579 ++MBBI;
Geoff Berrya5335642016-05-06 16:34:59 +0000580 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000581 if (HasFP) {
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000582 // Only set up FP if we actually need to. Frame pointer is fp =
583 // sp - fixedobject - 16.
584 int FPOffset = AFI->getCalleeSavedStackSize() - 16;
Geoff Berrya5335642016-05-06 16:34:59 +0000585 if (CombineSPBump)
586 FPOffset += AFI->getLocalStackSize();
Chad Rosier27c352d2016-03-14 18:24:34 +0000587
Tim Northover3b0846e2014-05-24 12:50:23 +0000588 // Issue sub fp, sp, FPOffset or
589 // mov fp,sp when FPOffset is zero.
590 // Note: All stores of callee-saved registers are marked as "FrameSetup".
591 // This code marks the instruction(s) that set the FP also.
592 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
593 MachineInstr::FrameSetup);
594 }
595
Martin Storsjo2778fd02017-12-20 06:51:45 +0000596 if (windowsRequiresStackProbe(MF, NumBytes)) {
597 uint32_t NumWords = NumBytes >> 4;
598
599 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
600 .addImm(NumWords)
601 .setMIFlags(MachineInstr::FrameSetup);
602
603 switch (MF.getTarget().getCodeModel()) {
604 case CodeModel::Small:
605 case CodeModel::Medium:
606 case CodeModel::Kernel:
607 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
608 .addExternalSymbol("__chkstk")
609 .addReg(AArch64::X15, RegState::Implicit)
610 .setMIFlags(MachineInstr::FrameSetup);
611 break;
612 case CodeModel::Large:
613 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
614 .addReg(AArch64::X16, RegState::Define)
615 .addExternalSymbol("__chkstk")
616 .addExternalSymbol("__chkstk")
617 .setMIFlags(MachineInstr::FrameSetup);
618
619 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
620 .addReg(AArch64::X16, RegState::Kill)
621 .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
622 .setMIFlags(MachineInstr::FrameSetup);
623 break;
624 }
625
626 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
627 .addReg(AArch64::SP, RegState::Kill)
628 .addReg(AArch64::X15, RegState::Kill)
629 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
630 .setMIFlags(MachineInstr::FrameSetup);
631 NumBytes = 0;
632 }
633
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 // Allocate space for the rest of the frame.
Chad Rosier27c352d2016-03-14 18:24:34 +0000635 if (NumBytes) {
636 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
637 unsigned scratchSPReg = AArch64::SP;
Kristof Beyls17cb8982015-04-09 08:49:47 +0000638
Chad Rosier27c352d2016-03-14 18:24:34 +0000639 if (NeedsRealignment) {
640 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
641 assert(scratchSPReg != AArch64::NoRegister);
642 }
Kristof Beyls17cb8982015-04-09 08:49:47 +0000643
Chad Rosier27c352d2016-03-14 18:24:34 +0000644 // If we're a leaf function, try using the red zone.
645 if (!canUseRedZone(MF))
646 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
647 // the correct value here, as NumBytes also includes padding bytes,
648 // which shouldn't be counted here.
649 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
650 MachineInstr::FrameSetup);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000651
Chad Rosier27c352d2016-03-14 18:24:34 +0000652 if (NeedsRealignment) {
Matthias Braun941a7052016-07-28 18:40:00 +0000653 const unsigned Alignment = MFI.getMaxAlignment();
Chad Rosier27c352d2016-03-14 18:24:34 +0000654 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
655 assert(NrBitsToZero > 1);
656 assert(scratchSPReg != AArch64::SP);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000657
Chad Rosier27c352d2016-03-14 18:24:34 +0000658 // SUB X9, SP, NumBytes
659 // -- X9 is temporary register, so shouldn't contain any live data here,
660 // -- free to use. This is already produced by emitFrameOffset above.
661 // AND SP, X9, 0b11111...0000
662 // The logical immediates have a non-trivial encoding. The following
663 // formula computes the encoded immediate with all ones but
664 // NrBitsToZero zero bits as least significant bits.
665 uint32_t andMaskEncoded = (1 << 12) // = N
666 | ((64 - NrBitsToZero) << 6) // immr
667 | ((64 - NrBitsToZero - 1) << 0); // imms
668
669 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
670 .addReg(scratchSPReg, RegState::Kill)
671 .addImm(andMaskEncoded);
672 AFI->setStackRealigned(true);
673 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 }
675
676 // If we need a base pointer, set it up here. It's whatever the value of the
677 // stack pointer is at this point. Any variable size objects will be allocated
678 // after this, so we can still use the base pointer to reference locals.
679 //
680 // FIXME: Clarify FrameSetup flags here.
681 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
682 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000683 if (RegInfo->hasBasePointer(MF)) {
684 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
685 false);
686 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000687
688 if (needsFrameMoves) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000689 const DataLayout &TD = MF.getDataLayout();
690 const int StackGrowth = -TD.getPointerSize(0);
Tim Northover3b0846e2014-05-24 12:50:23 +0000691 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000692 // An example of the prologue:
693 //
694 // .globl __foo
695 // .align 2
696 // __foo:
697 // Ltmp0:
698 // .cfi_startproc
699 // .cfi_personality 155, ___gxx_personality_v0
700 // Leh_func_begin:
701 // .cfi_lsda 16, Lexception33
702 //
703 // stp xa,bx, [sp, -#offset]!
704 // ...
705 // stp x28, x27, [sp, #offset-32]
706 // stp fp, lr, [sp, #offset-16]
707 // add fp, sp, #offset - 16
708 // sub sp, sp, #1360
709 //
710 // The Stack:
711 // +-------------------------------------------+
712 // 10000 | ........ | ........ | ........ | ........ |
713 // 10004 | ........ | ........ | ........ | ........ |
714 // +-------------------------------------------+
715 // 10008 | ........ | ........ | ........ | ........ |
716 // 1000c | ........ | ........ | ........ | ........ |
717 // +===========================================+
718 // 10010 | X28 Register |
719 // 10014 | X28 Register |
720 // +-------------------------------------------+
721 // 10018 | X27 Register |
722 // 1001c | X27 Register |
723 // +===========================================+
724 // 10020 | Frame Pointer |
725 // 10024 | Frame Pointer |
726 // +-------------------------------------------+
727 // 10028 | Link Register |
728 // 1002c | Link Register |
729 // +===========================================+
730 // 10030 | ........ | ........ | ........ | ........ |
731 // 10034 | ........ | ........ | ........ | ........ |
732 // +-------------------------------------------+
733 // 10038 | ........ | ........ | ........ | ........ |
734 // 1003c | ........ | ........ | ........ | ........ |
735 // +-------------------------------------------+
736 //
737 // [sp] = 10030 :: >>initial value<<
738 // sp = 10020 :: stp fp, lr, [sp, #-16]!
739 // fp = sp == 10020 :: mov fp, sp
740 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
741 // sp == 10010 :: >>final value<<
742 //
743 // The frame pointer (w29) points to address 10020. If we use an offset of
744 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
745 // for w27, and -32 for w28:
746 //
747 // Ltmp1:
748 // .cfi_def_cfa w29, 16
749 // Ltmp2:
750 // .cfi_offset w30, -8
751 // Ltmp3:
752 // .cfi_offset w29, -16
753 // Ltmp4:
754 // .cfi_offset w27, -24
755 // Ltmp5:
756 // .cfi_offset w28, -32
757
758 if (HasFP) {
759 // Define the current CFA rule to use the provided FP.
760 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000761 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
762 nullptr, Reg, 2 * StackGrowth - FixedObject));
Tim Northover3b0846e2014-05-24 12:50:23 +0000763 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000764 .addCFIIndex(CFIIndex)
765 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000766 } else {
767 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000768 unsigned CFIIndex = MF.addFrameInst(
Matthias Braun941a7052016-07-28 18:40:00 +0000769 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000770 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000771 .addCFIIndex(CFIIndex)
772 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000773 }
774
Geoff Berry62d47252016-02-25 16:36:08 +0000775 // Now emit the moves for whatever callee saved regs we have (including FP,
776 // LR if those are saved).
777 emitCalleeSavedFrameMoves(MBB, MBBI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000778 }
779}
780
Tim Northover3b0846e2014-05-24 12:50:23 +0000781void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
782 MachineBasicBlock &MBB) const {
783 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Matthias Braun941a7052016-07-28 18:40:00 +0000784 MachineFrameInfo &MFI = MF.getFrameInfo();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000785 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000786 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000787 DebugLoc DL;
788 bool IsTailCallReturn = false;
789 if (MBB.end() != MBBI) {
790 DL = MBBI->getDebugLoc();
791 unsigned RetOpcode = MBBI->getOpcode();
792 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
793 RetOpcode == AArch64::TCRETURNri;
794 }
Matthias Braun941a7052016-07-28 18:40:00 +0000795 int NumBytes = MFI.getStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000796 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
797
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000798 // All calls are tail calls in GHC calling conv, and functions have no
799 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000800 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000801 return;
802
Kristof Beyls17cb8982015-04-09 08:49:47 +0000803 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000804 // in the epilogue, the residual adjustment is executed first.
805 uint64_t ArgumentPopSize = 0;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000806 if (IsTailCallReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000807 MachineOperand &StackAdjust = MBBI->getOperand(1);
808
809 // For a tail-call in a callee-pops-arguments environment, some or all of
810 // the stack may actually be in use for the call's arguments, this is
811 // calculated during LowerCall and consumed here...
812 ArgumentPopSize = StackAdjust.getImm();
813 } else {
814 // ... otherwise the amount to pop is *all* of the argument space,
815 // conveniently stored in the MachineFunctionInfo by
816 // LowerFormalArguments. This will, of course, be zero for the C calling
817 // convention.
818 ArgumentPopSize = AFI->getArgumentStackToRestore();
819 }
820
821 // The stack frame should be like below,
822 //
823 // ---------------------- ---
824 // | | |
825 // | BytesInStackArgArea| CalleeArgStackSize
826 // | (NumReusableBytes) | (of tail call)
827 // | | ---
828 // | | |
829 // ---------------------| --- |
830 // | | | |
831 // | CalleeSavedReg | | |
Geoff Berry04bf91a2016-02-01 16:29:19 +0000832 // | (CalleeSavedStackSize)| | |
Tim Northover3b0846e2014-05-24 12:50:23 +0000833 // | | | |
834 // ---------------------| | NumBytes
835 // | | StackSize (StackAdjustUp)
836 // | LocalStackSize | | |
837 // | (covering callee | | |
838 // | args) | | |
839 // | | | |
840 // ---------------------- --- ---
841 //
842 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
843 // = StackSize + ArgumentPopSize
844 //
845 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
846 // it as the 2nd argument of AArch64ISD::TC_RETURN.
Tim Northover3b0846e2014-05-24 12:50:23 +0000847
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000848 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000849 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000850 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
851
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000852 uint64_t AfterCSRPopSize = ArgumentPopSize;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000853 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Geoff Berrya5335642016-05-06 16:34:59 +0000854 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000855 // Assume we can't combine the last pop with the sp restore.
Geoff Berrya5335642016-05-06 16:34:59 +0000856
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000857 if (!CombineSPBump && PrologueSaveSize != 0) {
858 MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
859 // Converting the last ldp to a post-index ldp is valid only if the last
860 // ldp's offset is 0.
861 const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
862 // If the offset is 0, convert it to a post-index ldp.
863 if (OffsetOp.getImm() == 0) {
864 convertCalleeSaveRestoreToSPPrePostIncDec(MBB, Pop, DL, TII,
865 PrologueSaveSize);
866 } else {
867 // If not, make sure to emit an add after the last ldp.
868 // We're doing this by transfering the size to be restored from the
869 // adjustment *before* the CSR pops to the adjustment *after* the CSR
870 // pops.
871 AfterCSRPopSize += PrologueSaveSize;
872 }
873 }
Geoff Berrya5335642016-05-06 16:34:59 +0000874
Tim Northover3b0846e2014-05-24 12:50:23 +0000875 // Move past the restores of the callee-saved registers.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000876 // If we plan on combining the sp bump of the local stack size and the callee
877 // save stack size, we might need to adjust the CSR save and restore offsets.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000878 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
Matthias Braun45419292015-12-17 03:18:47 +0000879 MachineBasicBlock::iterator Begin = MBB.begin();
880 while (LastPopI != Begin) {
881 --LastPopI;
Geoff Berry04bf91a2016-02-01 16:29:19 +0000882 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000883 ++LastPopI;
Matthias Braun45419292015-12-17 03:18:47 +0000884 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000885 } else if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000886 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000887 }
Geoff Berrya5335642016-05-06 16:34:59 +0000888
889 // If there is a single SP update, insert it before the ret and we're done.
890 if (CombineSPBump) {
891 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000892 NumBytes + AfterCSRPopSize, TII,
Geoff Berrya5335642016-05-06 16:34:59 +0000893 MachineInstr::FrameDestroy);
894 return;
895 }
896
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000897 NumBytes -= PrologueSaveSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000898 assert(NumBytes >= 0 && "Negative stack allocation size!?");
899
900 if (!hasFP(MF)) {
Geoff Berrya1c62692016-02-23 16:54:36 +0000901 bool RedZone = canUseRedZone(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000902 // If this was a redzone leaf function, we don't need to restore the
Geoff Berrya1c62692016-02-23 16:54:36 +0000903 // stack pointer (but we may need to pop stack args for fastcc).
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000904 if (RedZone && AfterCSRPopSize == 0)
Geoff Berrya1c62692016-02-23 16:54:36 +0000905 return;
906
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000907 bool NoCalleeSaveRestore = PrologueSaveSize == 0;
Geoff Berrya1c62692016-02-23 16:54:36 +0000908 int StackRestoreBytes = RedZone ? 0 : NumBytes;
909 if (NoCalleeSaveRestore)
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000910 StackRestoreBytes += AfterCSRPopSize;
Geoff Berrya1c62692016-02-23 16:54:36 +0000911 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
912 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
913 // If we were able to combine the local stack pop with the argument pop,
914 // then we're done.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000915 if (NoCalleeSaveRestore || AfterCSRPopSize == 0)
Geoff Berrya1c62692016-02-23 16:54:36 +0000916 return;
917 NumBytes = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000918 }
919
920 // Restore the original stack pointer.
921 // FIXME: Rather than doing the math here, we should instead just use
922 // non-post-indexed loads for the restores if we aren't actually going to
923 // be able to save any instructions.
Matthias Braun941a7052016-07-28 18:40:00 +0000924 if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
Tim Northover3b0846e2014-05-24 12:50:23 +0000925 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000926 -AFI->getCalleeSavedStackSize() + 16, TII,
927 MachineInstr::FrameDestroy);
Chad Rosier6d986552016-03-14 18:17:41 +0000928 else if (NumBytes)
929 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
930 MachineInstr::FrameDestroy);
Geoff Berrya1c62692016-02-23 16:54:36 +0000931
932 // This must be placed after the callee-save restore code because that code
933 // assumes the SP is at the same location as it was after the callee-save save
934 // code in the prologue.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000935 if (AfterCSRPopSize) {
936 // Sometimes (when we restore in the same order as we save), we can end up
937 // with code like this:
938 //
939 // ldp x26, x25, [sp]
940 // ldp x24, x23, [sp, #16]
941 // ldp x22, x21, [sp, #32]
942 // ldp x20, x19, [sp, #48]
943 // add sp, sp, #64
944 //
945 // In this case, it is always better to put the first ldp at the end, so
946 // that the load-store optimizer can run and merge the ldp and the add into
947 // a post-index ldp.
948 // If we managed to grab the first pop instruction, move it to the end.
949 if (LastPopI != Begin)
950 MBB.splice(MBB.getFirstTerminator(), &MBB, LastPopI);
951 // We should end up with something like this now:
952 //
953 // ldp x24, x23, [sp, #16]
954 // ldp x22, x21, [sp, #32]
955 // ldp x20, x19, [sp, #48]
956 // ldp x26, x25, [sp]
957 // add sp, sp, #64
958 //
959 // and the load-store optimizer can merge the last two instructions into:
960 //
961 // ldp x26, x25, [sp], #64
962 //
Geoff Berrya1c62692016-02-23 16:54:36 +0000963 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000964 AfterCSRPopSize, TII, MachineInstr::FrameDestroy);
965 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000966}
967
Tim Northover3b0846e2014-05-24 12:50:23 +0000968/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
969/// debug info. It's the same as what we use for resolving the code-gen
970/// references for now. FIXME: This can go wrong when references are
971/// SP-relative and simple call frames aren't used.
972int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
973 int FI,
974 unsigned &FrameReg) const {
975 return resolveFrameIndexReference(MF, FI, FrameReg);
976}
977
978int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
979 int FI, unsigned &FrameReg,
980 bool PreferFP) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000981 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000982 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000983 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000984 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000985 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
986 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000987 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000988 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
989 int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16;
Matthias Braun941a7052016-07-28 18:40:00 +0000990 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
991 bool isFixed = MFI.isFixedObjectIndex(FI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000992
993 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +0000994 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
995 // reliable as a base). Make sure useFPForScavengingIndex() does the
996 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +0000997 bool UseFP = false;
998 if (AFI->hasStackFrame()) {
999 // Note: Keeping the following as multiple 'if' statements rather than
1000 // merging to a single expression for readability.
1001 //
1002 // Argument access should always use the FP.
1003 if (isFixed) {
1004 UseFP = hasFP(MF);
Kristof Beyls17cb8982015-04-09 08:49:47 +00001005 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
1006 !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001007 // Use SP or FP, whichever gives us the best chance of the offset
1008 // being in range for direct access. If the FPOffset is positive,
1009 // that'll always be best, as the SP will be even further away.
1010 // If the FPOffset is negative, we have to keep in mind that the
1011 // available offset range for negative offsets is smaller than for
1012 // positive ones. If we have variable sized objects, we're stuck with
1013 // using the FP regardless, though, as the SP offset is unknown
1014 // and we don't have a base pointer available. If an offset is
1015 // available via the FP and the SP, use whichever is closest.
Matthias Braun941a7052016-07-28 18:40:00 +00001016 if (PreferFP || MFI.hasVarSizedObjects() || FPOffset >= 0 ||
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 (FPOffset >= -256 && Offset > -FPOffset))
1018 UseFP = true;
1019 }
1020 }
1021
Kristof Beyls17cb8982015-04-09 08:49:47 +00001022 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
1023 "In the presence of dynamic stack pointer realignment, "
1024 "non-argument objects cannot be accessed through the frame pointer");
1025
Tim Northover3b0846e2014-05-24 12:50:23 +00001026 if (UseFP) {
1027 FrameReg = RegInfo->getFrameRegister(MF);
1028 return FPOffset;
1029 }
1030
1031 // Use the base pointer if we have one.
1032 if (RegInfo->hasBasePointer(MF))
1033 FrameReg = RegInfo->getBaseRegister();
1034 else {
1035 FrameReg = AArch64::SP;
1036 // If we're using the red zone for this function, the SP won't actually
1037 // be adjusted, so the offsets will be negative. They're also all
1038 // within range of the signed 9-bit immediate instructions.
1039 if (canUseRedZone(MF))
1040 Offset -= AFI->getLocalStackSize();
1041 }
1042
1043 return Offset;
1044}
1045
1046static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00001047 // Do not set a kill flag on values that are also marked as live-in. This
1048 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1049 // callee saved registers.
1050 // Omitting the kill flags is conservatively correct even if the live-in
1051 // is not used after all.
1052 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1053 return getKillRegState(!IsLiveIn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001054}
1055
Manman Ren57518142016-04-11 21:08:06 +00001056static bool produceCompactUnwindFrame(MachineFunction &MF) {
1057 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Matthias Braunf1caa282017-12-15 22:22:58 +00001058 AttributeList Attrs = MF.getFunction().getAttributes();
Manman Ren57518142016-04-11 21:08:06 +00001059 return Subtarget.isTargetMachO() &&
1060 !(Subtarget.getTargetLowering()->supportSwiftError() &&
1061 Attrs.hasAttrSomewhere(Attribute::SwiftError));
1062}
1063
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001064namespace {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001065
Geoff Berry29d4a692016-02-01 19:07:06 +00001066struct RegPairInfo {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001067 unsigned Reg1 = AArch64::NoRegister;
1068 unsigned Reg2 = AArch64::NoRegister;
Geoff Berry29d4a692016-02-01 19:07:06 +00001069 int FrameIdx;
1070 int Offset;
1071 bool IsGPR;
Eugene Zelenko11f69072017-01-25 00:29:26 +00001072
1073 RegPairInfo() = default;
1074
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001075 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
Geoff Berry29d4a692016-02-01 19:07:06 +00001076};
Eugene Zelenko11f69072017-01-25 00:29:26 +00001077
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001078} // end anonymous namespace
Geoff Berry29d4a692016-02-01 19:07:06 +00001079
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001080static void computeCalleeSaveRegisterPairs(
1081 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
1082 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001083
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001084 if (CSI.empty())
1085 return;
1086
1087 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001088 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001089 CallingConv::ID CC = MF.getFunction().getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 unsigned Count = CSI.size();
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001091 (void)CC;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001092 // MachO's compact unwind format relies on all registers being stored in
1093 // pairs.
Manman Ren57518142016-04-11 21:08:06 +00001094 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001095 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001096 (Count & 1) == 0) &&
1097 "Odd number of callee-saved regs to spill!");
Martin Storsjo68266fa2017-07-13 17:03:12 +00001098 int Offset = AFI->getCalleeSavedStackSize();
1099
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001100 for (unsigned i = 0; i < Count; ++i) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001101 RegPairInfo RPI;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001102 RPI.Reg1 = CSI[i].getReg();
1103
1104 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
1105 AArch64::FPR64RegClass.contains(RPI.Reg1));
1106 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
1107
1108 // Add the next reg to the pair if it is in the same register class.
1109 if (i + 1 < Count) {
1110 unsigned NextReg = CSI[i + 1].getReg();
1111 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
1112 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
1113 RPI.Reg2 = NextReg;
1114 }
Geoff Berry29d4a692016-02-01 19:07:06 +00001115
Tim Northover3b0846e2014-05-24 12:50:23 +00001116 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1117 // list to come in sorted by frame index so that we can issue the store
1118 // pair instructions directly. Assert if we see anything otherwise.
1119 //
1120 // The order of the registers in the list is controlled by
1121 // getCalleeSavedRegs(), so they will always be in-order, as well.
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001122 assert((!RPI.isPaired() ||
1123 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001124 "Out of order callee saved regs!");
Geoff Berry29d4a692016-02-01 19:07:06 +00001125
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001126 // MachO's compact unwind format relies on all registers being stored in
1127 // adjacent register pairs.
Manman Ren57518142016-04-11 21:08:06 +00001128 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001129 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001130 (RPI.isPaired() &&
1131 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1132 RPI.Reg1 + 1 == RPI.Reg2))) &&
1133 "Callee-save registers not saved as adjacent register pair!");
1134
1135 RPI.FrameIdx = CSI[i].getFrameIdx();
1136
1137 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
1138 // Round up size of non-pair to pair size if we need to pad the
1139 // callee-save area to ensure 16-byte alignment.
1140 Offset -= 16;
Matthias Braun941a7052016-07-28 18:40:00 +00001141 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1142 MFI.setObjectAlignment(RPI.FrameIdx, 16);
Geoff Berry66f6b652016-06-02 16:22:07 +00001143 AFI->setCalleeSaveStackHasFreeSpace(true);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001144 } else
1145 Offset -= RPI.isPaired() ? 16 : 8;
1146 assert(Offset % 8 == 0);
1147 RPI.Offset = Offset / 8;
Geoff Berry29d4a692016-02-01 19:07:06 +00001148 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1149 "Offset out of bounds for LDP/STP immediate");
1150
1151 RegPairs.push_back(RPI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001152 if (RPI.isPaired())
1153 ++i;
Geoff Berry29d4a692016-02-01 19:07:06 +00001154 }
1155}
1156
1157bool AArch64FrameLowering::spillCalleeSavedRegisters(
1158 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1159 const std::vector<CalleeSavedInfo> &CSI,
1160 const TargetRegisterInfo *TRI) const {
1161 MachineFunction &MF = *MBB.getParent();
1162 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1163 DebugLoc DL;
1164 SmallVector<RegPairInfo, 8> RegPairs;
1165
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001166 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Matthias Braun88c8c982017-05-27 03:38:02 +00001167 const MachineRegisterInfo &MRI = MF.getRegInfo();
Geoff Berry29d4a692016-02-01 19:07:06 +00001168
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001169 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +00001170 ++RPII) {
1171 RegPairInfo RPI = *RPII;
1172 unsigned Reg1 = RPI.Reg1;
1173 unsigned Reg2 = RPI.Reg2;
1174 unsigned StrOpc;
1175
Geoff Berrya5335642016-05-06 16:34:59 +00001176 // Issue sequence of spills for cs regs. The first spill may be converted
1177 // to a pre-decrement store later by emitPrologue if the callee-save stack
1178 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001179 // For example:
Geoff Berrya5335642016-05-06 16:34:59 +00001180 // stp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001181 // stp x20, x19, [sp, #16] // addImm(+2)
1182 // stp fp, lr, [sp, #32] // addImm(+4)
1183 // Rationale: This sequence saves uop updates compared to a sequence of
1184 // pre-increment spills like stp xi,xj,[sp,#-16]!
Geoff Berry29d4a692016-02-01 19:07:06 +00001185 // Note: Similar rationale and sequence for restores in epilog.
Geoff Berrya5335642016-05-06 16:34:59 +00001186 if (RPI.IsGPR)
1187 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1188 else
1189 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
Francis Visoiu Mistrihc71cced2017-11-30 16:12:24 +00001190 DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001191 if (RPI.isPaired())
Francis Visoiu Mistrihc71cced2017-11-30 16:12:24 +00001192 dbgs() << ", " << printReg(Reg2, TRI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001193 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1194 if (RPI.isPaired())
1195 dbgs() << ", " << RPI.FrameIdx+1;
1196 dbgs() << ")\n");
Geoff Berry29d4a692016-02-01 19:07:06 +00001197
Tim Northover3b0846e2014-05-24 12:50:23 +00001198 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
Matthias Braun88c8c982017-05-27 03:38:02 +00001199 if (!MRI.isReserved(Reg1))
1200 MBB.addLiveIn(Reg1);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001201 if (RPI.isPaired()) {
Matthias Braun88c8c982017-05-27 03:38:02 +00001202 if (!MRI.isReserved(Reg2))
1203 MBB.addLiveIn(Reg2);
Geoff Berrya5335642016-05-06 16:34:59 +00001204 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
Geoff Berryc3764062016-04-15 15:16:19 +00001205 MIB.addMemOperand(MF.getMachineMemOperand(
1206 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1207 MachineMemOperand::MOStore, 8, 8));
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001208 }
Geoff Berrya5335642016-05-06 16:34:59 +00001209 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1210 .addReg(AArch64::SP)
1211 .addImm(RPI.Offset) // [sp, #offset*8], where factor*8 is implicit
1212 .setMIFlag(MachineInstr::FrameSetup);
Geoff Berryc3764062016-04-15 15:16:19 +00001213 MIB.addMemOperand(MF.getMachineMemOperand(
1214 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1215 MachineMemOperand::MOStore, 8, 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00001216 }
1217 return true;
1218}
1219
1220bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1221 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001222 std::vector<CalleeSavedInfo> &CSI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001223 const TargetRegisterInfo *TRI) const {
1224 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001225 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001226 DebugLoc DL;
Geoff Berry29d4a692016-02-01 19:07:06 +00001227 SmallVector<RegPairInfo, 8> RegPairs;
Tim Northover3b0846e2014-05-24 12:50:23 +00001228
1229 if (MI != MBB.end())
1230 DL = MI->getDebugLoc();
1231
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001232 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
Geoff Berry29d4a692016-02-01 19:07:06 +00001233
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001234 auto EmitMI = [&](const RegPairInfo &RPI) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001235 unsigned Reg1 = RPI.Reg1;
1236 unsigned Reg2 = RPI.Reg2;
1237
Geoff Berrya5335642016-05-06 16:34:59 +00001238 // Issue sequence of restores for cs regs. The last restore may be converted
1239 // to a post-increment load later by emitEpilogue if the callee-save stack
1240 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001241 // For example:
1242 // ldp fp, lr, [sp, #32] // addImm(+4)
1243 // ldp x20, x19, [sp, #16] // addImm(+2)
Geoff Berrya5335642016-05-06 16:34:59 +00001244 // ldp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001245 // Note: see comment in spillCalleeSavedRegisters()
1246 unsigned LdrOpc;
Geoff Berrya5335642016-05-06 16:34:59 +00001247 if (RPI.IsGPR)
1248 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1249 else
1250 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
Francis Visoiu Mistrihc71cced2017-11-30 16:12:24 +00001251 DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001252 if (RPI.isPaired())
Francis Visoiu Mistrihc71cced2017-11-30 16:12:24 +00001253 dbgs() << ", " << printReg(Reg2, TRI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001254 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1255 if (RPI.isPaired())
1256 dbgs() << ", " << RPI.FrameIdx+1;
1257 dbgs() << ")\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001258
Tim Northover3b0846e2014-05-24 12:50:23 +00001259 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
Geoff Berryc3764062016-04-15 15:16:19 +00001260 if (RPI.isPaired()) {
Geoff Berrya5335642016-05-06 16:34:59 +00001261 MIB.addReg(Reg2, getDefRegState(true));
Geoff Berryc3764062016-04-15 15:16:19 +00001262 MIB.addMemOperand(MF.getMachineMemOperand(
1263 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1264 MachineMemOperand::MOLoad, 8, 8));
Geoff Berryc3764062016-04-15 15:16:19 +00001265 }
Geoff Berrya5335642016-05-06 16:34:59 +00001266 MIB.addReg(Reg1, getDefRegState(true))
1267 .addReg(AArch64::SP)
1268 .addImm(RPI.Offset) // [sp, #offset*8] where the factor*8 is implicit
1269 .setMIFlag(MachineInstr::FrameDestroy);
Geoff Berryc3764062016-04-15 15:16:19 +00001270 MIB.addMemOperand(MF.getMachineMemOperand(
1271 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1272 MachineMemOperand::MOLoad, 8, 8));
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001273 };
1274
1275 if (ReverseCSRRestoreSeq)
1276 for (const RegPairInfo &RPI : reverse(RegPairs))
1277 EmitMI(RPI);
1278 else
1279 for (const RegPairInfo &RPI : RegPairs)
1280 EmitMI(RPI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001281 return true;
1282}
1283
Matthias Braun02564862015-07-14 17:17:13 +00001284void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1285 BitVector &SavedRegs,
1286 RegScavenger *RS) const {
1287 // All calls are tail calls in GHC calling conv, and functions have no
1288 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +00001289 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Matthias Braun02564862015-07-14 17:17:13 +00001290 return;
1291
1292 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Tim Northover3b0846e2014-05-24 12:50:23 +00001293 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001294 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001295 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001296 unsigned UnspilledCSGPR = AArch64::NoRegister;
1297 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +00001298
Martin Storsjo2778fd02017-12-20 06:51:45 +00001299 MachineFrameInfo &MFI = MF.getFrameInfo();
1300 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1301
1302 unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
1303 ? RegInfo->getBaseRegister()
1304 : (unsigned)AArch64::NoRegister;
1305
1306 unsigned SpillEstimate = SavedRegs.count();
1307 for (unsigned i = 0; CSRegs[i]; ++i) {
1308 unsigned Reg = CSRegs[i];
1309 unsigned PairedReg = CSRegs[i ^ 1];
1310 if (Reg == BasePointerReg)
1311 SpillEstimate++;
1312 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg))
1313 SpillEstimate++;
1314 }
1315 SpillEstimate += 2; // Conservatively include FP+LR in the estimate
1316 unsigned StackEstimate = MFI.estimateStackSize(MF) + 8 * SpillEstimate;
1317
Tim Northover3b0846e2014-05-24 12:50:23 +00001318 // The frame record needs to be created by saving the appropriate registers
Martin Storsjo2778fd02017-12-20 06:51:45 +00001319 if (hasFP(MF) || windowsRequiresStackProbe(MF, StackEstimate)) {
Matthias Braun02564862015-07-14 17:17:13 +00001320 SavedRegs.set(AArch64::FP);
1321 SavedRegs.set(AArch64::LR);
Tim Northover3b0846e2014-05-24 12:50:23 +00001322 }
1323
Matthias Braund78597e2017-04-21 22:42:08 +00001324 unsigned ExtraCSSpill = 0;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001325 // Figure out which callee-saved registers to save/restore.
1326 for (unsigned i = 0; CSRegs[i]; ++i) {
1327 const unsigned Reg = CSRegs[i];
Tim Northover3b0846e2014-05-24 12:50:23 +00001328
Geoff Berry7e4ba3d2016-02-19 18:27:32 +00001329 // Add the base pointer register to SavedRegs if it is callee-save.
1330 if (Reg == BasePointerReg)
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001331 SavedRegs.set(Reg);
Tim Northover3b0846e2014-05-24 12:50:23 +00001332
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001333 bool RegUsed = SavedRegs.test(Reg);
1334 unsigned PairedReg = CSRegs[i ^ 1];
1335 if (!RegUsed) {
1336 if (AArch64::GPR64RegClass.contains(Reg) &&
1337 !RegInfo->isReservedReg(MF, Reg)) {
1338 UnspilledCSGPR = Reg;
1339 UnspilledCSGPRPaired = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001340 }
1341 continue;
1342 }
1343
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001344 // MachO's compact unwind format relies on all registers being stored in
1345 // pairs.
1346 // FIXME: the usual format is actually better if unwinding isn't needed.
Manman Ren57518142016-04-11 21:08:06 +00001347 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg)) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001348 SavedRegs.set(PairedReg);
Geoff Berry74cb7182016-05-16 20:52:28 +00001349 if (AArch64::GPR64RegClass.contains(PairedReg) &&
1350 !RegInfo->isReservedReg(MF, PairedReg))
Matthias Braund78597e2017-04-21 22:42:08 +00001351 ExtraCSSpill = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001352 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001353 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001354
1355 DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001356 for (unsigned Reg : SavedRegs.set_bits())
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001357 dbgs() << ' ' << printReg(Reg, RegInfo);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001358 dbgs() << "\n";);
1359
1360 // If any callee-saved registers are used, the frame cannot be eliminated.
1361 unsigned NumRegsSpilled = SavedRegs.count();
1362 bool CanEliminateFrame = NumRegsSpilled == 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001363
Tim Northover3b0846e2014-05-24 12:50:23 +00001364 // The CSR spill slots have not been allocated yet, so estimateStackSize
1365 // won't include them.
Matthias Braun941a7052016-07-28 18:40:00 +00001366 unsigned CFSize = MFI.estimateStackSize(MF) + 8 * NumRegsSpilled;
Tim Northover3b0846e2014-05-24 12:50:23 +00001367 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
Kristof Beyls2af1e902017-05-30 06:58:41 +00001368 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
1369 bool BigStack = (CFSize > EstimatedStackSizeLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001370 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1371 AFI->setHasStackFrame(true);
1372
1373 // Estimate if we might need to scavenge a register at some point in order
1374 // to materialize a stack offset. If so, either spill one additional
1375 // callee-saved register or reserve a special spill slot to facilitate
1376 // register scavenging. If we already spilled an extra callee-saved register
1377 // above to keep the number of spills even, we don't need to do anything else
1378 // here.
Matthias Braund78597e2017-04-21 22:42:08 +00001379 if (BigStack) {
1380 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001381 DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
Francis Visoiu Mistrihc71cced2017-11-30 16:12:24 +00001382 << " to get a scratch register.\n");
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001383 SavedRegs.set(UnspilledCSGPR);
1384 // MachO's compact unwind format relies on all registers being stored in
1385 // pairs, so if we need to spill one extra for BigStack, then we need to
1386 // store the pair.
Manman Ren57518142016-04-11 21:08:06 +00001387 if (produceCompactUnwindFrame(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001388 SavedRegs.set(UnspilledCSGPRPaired);
Matthias Braund78597e2017-04-21 22:42:08 +00001389 ExtraCSSpill = UnspilledCSGPRPaired;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001390 NumRegsSpilled = SavedRegs.count();
Tim Northover3b0846e2014-05-24 12:50:23 +00001391 }
1392
1393 // If we didn't find an extra callee-saved register to spill, create
1394 // an emergency spill slot.
Matthias Braund78597e2017-04-21 22:42:08 +00001395 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001396 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1397 const TargetRegisterClass &RC = AArch64::GPR64RegClass;
1398 unsigned Size = TRI->getSpillSize(RC);
1399 unsigned Align = TRI->getSpillAlignment(RC);
1400 int FI = MFI.CreateStackObject(Size, Align, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001401 RS->addScavengingFrameIndex(FI);
1402 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1403 << " as the emergency spill slot.\n");
1404 }
1405 }
Geoff Berry04bf91a2016-02-01 16:29:19 +00001406
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001407 // Round up to register pair alignment to avoid additional SP adjustment
1408 // instructions.
1409 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00001410}
Geoff Berry66f6b652016-06-02 16:22:07 +00001411
1412bool AArch64FrameLowering::enableStackSlotScavenging(
1413 const MachineFunction &MF) const {
1414 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1415 return AFI->hasCalleeSaveStackFreeSpace();
1416}