blob: deb70e89c67c54111625c1d43612c6a44b2b0b31 [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"
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000101#include "llvm/ADT/ScopeExit.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000102#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000103#include "llvm/ADT/Statistic.h"
Matthias Braun332bb5c2016-07-06 21:31:27 +0000104#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000105#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000106#include "llvm/CodeGen/MachineFrameInfo.h"
107#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000108#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000109#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000110#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000111#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000112#include "llvm/CodeGen/MachineOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000113#include "llvm/CodeGen/MachineRegisterInfo.h"
114#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +0000115#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +0000116#include "llvm/CodeGen/TargetRegisterInfo.h"
117#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000118#include "llvm/IR/Attributes.h"
119#include "llvm/IR/CallingConv.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000120#include "llvm/IR/DataLayout.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000121#include "llvm/IR/DebugLoc.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000122#include "llvm/IR/Function.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000123#include "llvm/MC/MCDwarf.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000124#include "llvm/Support/CommandLine.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +0000125#include "llvm/Support/Debug.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000126#include "llvm/Support/ErrorHandling.h"
127#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +0000128#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000129#include "llvm/Target/TargetMachine.h"
130#include "llvm/Target/TargetOptions.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +0000131#include <cassert>
132#include <cstdint>
133#include <iterator>
134#include <vector>
Tim Northover3b0846e2014-05-24 12:50:23 +0000135
136using namespace llvm;
137
138#define DEBUG_TYPE "frame-info"
139
140static cl::opt<bool> EnableRedZone("aarch64-redzone",
141 cl::desc("enable use of redzone on AArch64"),
142 cl::init(false), cl::Hidden);
143
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000144static cl::opt<bool>
145 ReverseCSRRestoreSeq("reverse-csr-restore-seq",
146 cl::desc("reverse the CSR restore sequence"),
147 cl::init(false), cl::Hidden);
148
Tim Northover3b0846e2014-05-24 12:50:23 +0000149STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
150
Matthias Braun5c290dc2018-01-19 03:16:36 +0000151/// This is the biggest offset to the stack pointer we can encode in aarch64
152/// instructions (without using a separate calculation and a temp register).
153/// Note that the exception here are vector stores/loads which cannot encode any
154/// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
155static const unsigned DefaultSafeSPDisplacement = 255;
156
Kristof Beyls2af1e902017-05-30 06:58:41 +0000157/// Look at each instruction that references stack frames and return the stack
158/// size limit beyond which some of these instructions will require a scratch
159/// register during their expansion later.
160static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
161 // FIXME: For now, just conservatively guestimate based on unscaled indexing
162 // range. We'll end up allocating an unnecessary spill slot a lot, but
163 // realistically that's not a big deal at this stage of the game.
164 for (MachineBasicBlock &MBB : MF) {
165 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000166 if (MI.isDebugInstr() || MI.isPseudo() ||
Kristof Beyls2af1e902017-05-30 06:58:41 +0000167 MI.getOpcode() == AArch64::ADDXri ||
168 MI.getOpcode() == AArch64::ADDSXri)
169 continue;
170
Javed Absard13d4192017-10-30 22:00:06 +0000171 for (const MachineOperand &MO : MI.operands()) {
172 if (!MO.isFI())
Kristof Beyls2af1e902017-05-30 06:58:41 +0000173 continue;
174
175 int Offset = 0;
176 if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
177 AArch64FrameOffsetCannotUpdate)
178 return 0;
179 }
180 }
181 }
Matthias Braun5c290dc2018-01-19 03:16:36 +0000182 return DefaultSafeSPDisplacement;
Kristof Beyls2af1e902017-05-30 06:58:41 +0000183}
184
Tim Northover3b0846e2014-05-24 12:50:23 +0000185bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
186 if (!EnableRedZone)
187 return false;
188 // Don't use the red zone if the function explicitly asks us not to.
189 // This is typically used for kernel code.
Matthias Braunf1caa282017-12-15 22:22:58 +0000190 if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone))
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 return false;
192
Matthias Braun941a7052016-07-28 18:40:00 +0000193 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
195 unsigned NumBytes = AFI->getLocalStackSize();
196
Matthias Braun941a7052016-07-28 18:40:00 +0000197 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
Tim Northover3b0846e2014-05-24 12:50:23 +0000198}
199
200/// hasFP - Return true if the specified function should have a dedicated frame
201/// pointer register.
202bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000203 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000204 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Geoff Berry62c1a1e2016-03-02 17:58:31 +0000205 // Retain behavior of always omitting the FP for leaf functions when possible.
Matthias Braun5c290dc2018-01-19 03:16:36 +0000206 if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF))
207 return true;
208 if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
209 MFI.hasStackMap() || MFI.hasPatchPoint() ||
210 RegInfo->needsStackRealignment(MF))
211 return true;
212 // With large callframes around we may need to use FP to access the scavenging
213 // emergency spillslot.
214 //
215 // Unfortunately some calls to hasFP() like machine verifier ->
216 // getReservedReg() -> hasFP in the middle of global isel are too early
217 // to know the max call frame size. Hopefully conservatively returning "true"
218 // in those cases is fine.
219 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
220 if (!MFI.isMaxCallFrameSizeComputed() ||
221 MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
222 return true;
223
224 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000225}
226
227/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
228/// not required, we reserve argument space for call sites in the function
229/// immediately on entry to the current function. This eliminates the need for
230/// add/sub sp brackets around call sites. Returns true if the call frame is
231/// included as part of the stack frame.
232bool
233AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000234 return !MF.getFrameInfo().hasVarSizedObjects();
Tim Northover3b0846e2014-05-24 12:50:23 +0000235}
236
Hans Wennborge1a2e902016-03-31 18:33:38 +0000237MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
Tim Northover3b0846e2014-05-24 12:50:23 +0000238 MachineFunction &MF, MachineBasicBlock &MBB,
239 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000240 const AArch64InstrInfo *TII =
241 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000242 DebugLoc DL = I->getDebugLoc();
Matthias Braunfa3872e2015-05-18 20:27:55 +0000243 unsigned Opc = I->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000244 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
245 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
246
Eric Christopherfc6de422014-08-05 02:39:49 +0000247 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
Tim Northover3b0846e2014-05-24 12:50:23 +0000248 if (!TFI->hasReservedCallFrame(MF)) {
249 unsigned Align = getStackAlignment();
250
251 int64_t Amount = I->getOperand(0).getImm();
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000252 Amount = alignTo(Amount, Align);
Tim Northover3b0846e2014-05-24 12:50:23 +0000253 if (!IsDestroy)
254 Amount = -Amount;
255
256 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
257 // doesn't have to pop anything), then the first operand will be zero too so
258 // this adjustment is a no-op.
259 if (CalleePopAmount == 0) {
260 // FIXME: in-function stack adjustment for calls is limited to 24-bits
261 // because there's no guaranteed temporary register available.
262 //
Sylvestre Ledru469de192014-08-11 18:04:46 +0000263 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
Tim Northover3b0846e2014-05-24 12:50:23 +0000264 // 1) For offset <= 12-bit, we use LSL #0
265 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
266 // LSL #0, and the other uses LSL #12.
267 //
Chad Rosier401a4ab2016-01-19 16:50:45 +0000268 // Most call frames will be allocated at the start of a function so
Tim Northover3b0846e2014-05-24 12:50:23 +0000269 // this is OK, but it is a limitation that needs dealing with.
270 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
271 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
272 }
273 } else if (CalleePopAmount != 0) {
274 // If the calling convention demands that the callee pops arguments from the
275 // stack, we want to add it back if we have a reserved call frame.
276 assert(CalleePopAmount < 0xffffff && "call frame too large");
277 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
278 TII);
279 }
Hans Wennborge1a2e902016-03-31 18:33:38 +0000280 return MBB.erase(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000281}
282
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000283static bool ShouldSignReturnAddress(MachineFunction &MF) {
284 // The function should be signed in the following situations:
285 // - sign-return-address=all
286 // - sign-return-address=non-leaf and the functions spills the LR
287
288 const Function &F = MF.getFunction();
289 if (!F.hasFnAttribute("sign-return-address"))
290 return false;
291
292 StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString();
293 if (Scope.equals("none"))
294 return false;
295
296 if (Scope.equals("all"))
297 return true;
298
299 assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf");
300
301 for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo())
302 if (Info.getReg() == AArch64::LR)
303 return true;
304
305 return false;
306}
307
Tim Northover3b0846e2014-05-24 12:50:23 +0000308void AArch64FrameLowering::emitCalleeSavedFrameMoves(
Geoff Berry62d47252016-02-25 16:36:08 +0000309 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000310 MachineFunction &MF = *MBB.getParent();
Matthias Braun941a7052016-07-28 18:40:00 +0000311 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf23ef432016-11-30 23:48:42 +0000312 const TargetSubtargetInfo &STI = MF.getSubtarget();
313 const MCRegisterInfo *MRI = STI.getRegisterInfo();
314 const TargetInstrInfo *TII = STI.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000315 DebugLoc DL = MBB.findDebugLoc(MBBI);
316
317 // Add callee saved registers to move list.
Matthias Braun941a7052016-07-28 18:40:00 +0000318 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000319 if (CSI.empty())
320 return;
321
Tim Northover3b0846e2014-05-24 12:50:23 +0000322 for (const auto &Info : CSI) {
323 unsigned Reg = Info.getReg();
Geoff Berry62d47252016-02-25 16:36:08 +0000324 int64_t Offset =
Matthias Braun941a7052016-07-28 18:40:00 +0000325 MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
Tim Northover3b0846e2014-05-24 12:50:23 +0000326 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braunf23ef432016-11-30 23:48:42 +0000327 unsigned CFIIndex = MF.addFrameInst(
Geoff Berry62d47252016-02-25 16:36:08 +0000328 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover3b0846e2014-05-24 12:50:23 +0000329 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000330 .addCFIIndex(CFIIndex)
331 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000332 }
333}
334
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000335// Find a scratch register that we can use at the start of the prologue to
336// re-align the stack pointer. We avoid using callee-save registers since they
337// may appear to be free when this is called from canUseAsPrologue (during
338// shrink wrapping), but then no longer be free when this is called from
339// emitPrologue.
340//
341// FIXME: This is a bit conservative, since in the above case we could use one
342// of the callee-save registers as a scratch temp to re-align the stack pointer,
343// but we would then have to make sure that we were in fact saving at least one
344// callee-save register in the prologue, which is additional complexity that
345// doesn't seem worth the benefit.
346static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
347 MachineFunction *MF = MBB->getParent();
348
349 // If MBB is an entry block, use X9 as the scratch register
350 if (&MF->front() == MBB)
351 return AArch64::X9;
352
Eric Christopher60a245e2017-03-31 23:12:27 +0000353 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
Matthias Braunac4307c2017-05-26 21:51:00 +0000354 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
Eric Christopher60a245e2017-03-31 23:12:27 +0000355 LivePhysRegs LiveRegs(TRI);
Matthias Braun332bb5c2016-07-06 21:31:27 +0000356 LiveRegs.addLiveIns(*MBB);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000357
Matthias Braun332bb5c2016-07-06 21:31:27 +0000358 // Mark callee saved registers as used so we will not choose them.
Matthias Braunac4307c2017-05-26 21:51:00 +0000359 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(MF);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000360 for (unsigned i = 0; CSRegs[i]; ++i)
Matthias Braun332bb5c2016-07-06 21:31:27 +0000361 LiveRegs.addReg(CSRegs[i]);
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000362
Matthias Braun332bb5c2016-07-06 21:31:27 +0000363 // Prefer X9 since it was historically used for the prologue scratch reg.
364 const MachineRegisterInfo &MRI = MF->getRegInfo();
365 if (LiveRegs.available(MRI, AArch64::X9))
366 return AArch64::X9;
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000367
Matthias Braun332bb5c2016-07-06 21:31:27 +0000368 for (unsigned Reg : AArch64::GPR64RegClass) {
369 if (LiveRegs.available(MRI, Reg))
370 return Reg;
371 }
Geoff Berry7e4ba3d2016-02-19 18:27:32 +0000372 return AArch64::NoRegister;
373}
374
375bool AArch64FrameLowering::canUseAsPrologue(
376 const MachineBasicBlock &MBB) const {
377 const MachineFunction *MF = MBB.getParent();
378 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
379 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
380 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
381
382 // Don't need a scratch register if we're not going to re-align the stack.
383 if (!RegInfo->needsStackRealignment(*MF))
384 return true;
385 // Otherwise, we can use any block as long as it has a scratch register
386 // available.
387 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
388}
389
Martin Storsjo2778fd02017-12-20 06:51:45 +0000390static bool windowsRequiresStackProbe(MachineFunction &MF,
391 unsigned StackSizeInBytes) {
392 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
393 if (!Subtarget.isTargetWindows())
394 return false;
395 const Function &F = MF.getFunction();
396 // TODO: When implementing stack protectors, take that into account
397 // for the probe threshold.
398 unsigned StackProbeSize = 4096;
399 if (F.hasFnAttribute("stack-probe-size"))
400 F.getFnAttribute("stack-probe-size")
401 .getValueAsString()
402 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000403 return (StackSizeInBytes >= StackProbeSize) &&
404 !F.hasFnAttribute("no-stack-arg-probe");
Martin Storsjo2778fd02017-12-20 06:51:45 +0000405}
406
Geoff Berrya5335642016-05-06 16:34:59 +0000407bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
408 MachineFunction &MF, unsigned StackBumpBytes) const {
409 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000410 const MachineFrameInfo &MFI = MF.getFrameInfo();
Geoff Berrya5335642016-05-06 16:34:59 +0000411 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
412 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
413
414 if (AFI->getLocalStackSize() == 0)
415 return false;
416
417 // 512 is the maximum immediate for stp/ldp that will be used for
418 // callee-save save/restores
Martin Storsjo2778fd02017-12-20 06:51:45 +0000419 if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
Geoff Berrya5335642016-05-06 16:34:59 +0000420 return false;
421
Matthias Braun941a7052016-07-28 18:40:00 +0000422 if (MFI.hasVarSizedObjects())
Geoff Berrya5335642016-05-06 16:34:59 +0000423 return false;
424
425 if (RegInfo->needsStackRealignment(MF))
426 return false;
427
428 // This isn't strictly necessary, but it simplifies things a bit since the
429 // current RedZone handling code assumes the SP is adjusted by the
430 // callee-save save/restore code.
431 if (canUseRedZone(MF))
432 return false;
433
434 return true;
435}
436
437// Convert callee-save register save/restore instruction to do stack pointer
438// decrement/increment to allocate/deallocate the callee-save stack area by
439// converting store/load to use pre/post increment version.
440static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000441 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
442 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc) {
Peter Collingbournef11eb3e2018-04-04 21:55:44 +0000443 // Ignore instructions that do not operate on SP, i.e. shadow call stack
444 // instructions.
445 while (MBBI->getOpcode() == AArch64::STRXpost ||
446 MBBI->getOpcode() == AArch64::LDRXpre) {
447 assert(MBBI->getOperand(0).getReg() != AArch64::SP);
448 ++MBBI;
449 }
450
Geoff Berrya5335642016-05-06 16:34:59 +0000451 unsigned NewOpc;
452 bool NewIsUnscaled = false;
453 switch (MBBI->getOpcode()) {
454 default:
455 llvm_unreachable("Unexpected callee-save save/restore opcode!");
456 case AArch64::STPXi:
457 NewOpc = AArch64::STPXpre;
458 break;
459 case AArch64::STPDi:
460 NewOpc = AArch64::STPDpre;
461 break;
462 case AArch64::STRXui:
463 NewOpc = AArch64::STRXpre;
464 NewIsUnscaled = true;
465 break;
466 case AArch64::STRDui:
467 NewOpc = AArch64::STRDpre;
468 NewIsUnscaled = true;
469 break;
470 case AArch64::LDPXi:
471 NewOpc = AArch64::LDPXpost;
472 break;
473 case AArch64::LDPDi:
474 NewOpc = AArch64::LDPDpost;
475 break;
476 case AArch64::LDRXui:
477 NewOpc = AArch64::LDRXpost;
478 NewIsUnscaled = true;
479 break;
480 case AArch64::LDRDui:
481 NewOpc = AArch64::LDRDpost;
482 NewIsUnscaled = true;
483 break;
484 }
485
486 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
487 MIB.addReg(AArch64::SP, RegState::Define);
488
489 // Copy all operands other than the immediate offset.
490 unsigned OpndIdx = 0;
491 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
492 ++OpndIdx)
Diana Picus116bbab2017-01-13 09:58:52 +0000493 MIB.add(MBBI->getOperand(OpndIdx));
Geoff Berrya5335642016-05-06 16:34:59 +0000494
495 assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
496 "Unexpected immediate offset in first/last callee-save save/restore "
497 "instruction!");
498 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
499 "Unexpected base register in callee-save save/restore instruction!");
500 // Last operand is immediate offset that needs fixing.
501 assert(CSStackSizeInc % 8 == 0);
502 int64_t CSStackSizeIncImm = CSStackSizeInc;
503 if (!NewIsUnscaled)
504 CSStackSizeIncImm /= 8;
505 MIB.addImm(CSStackSizeIncImm);
506
507 MIB.setMIFlags(MBBI->getFlags());
Chandler Carruthc73c0302018-08-16 21:30:05 +0000508 MIB.setMemRefs(MBBI->memoperands());
Geoff Berrya5335642016-05-06 16:34:59 +0000509
510 return std::prev(MBB.erase(MBBI));
511}
512
513// Fixup callee-save register save/restore instructions to take into account
514// combined SP bump by adding the local stack size to the stack offsets.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000515static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
Geoff Berrya5335642016-05-06 16:34:59 +0000516 unsigned LocalStackSize) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000517 unsigned Opc = MI.getOpcode();
Peter Collingbournef11eb3e2018-04-04 21:55:44 +0000518
519 // Ignore instructions that do not operate on SP, i.e. shadow call stack
520 // instructions.
521 if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre) {
522 assert(MI.getOperand(0).getReg() != AArch64::SP);
523 return;
524 }
525
Geoff Berrya5335642016-05-06 16:34:59 +0000526 (void)Opc;
527 assert((Opc == AArch64::STPXi || Opc == AArch64::STPDi ||
528 Opc == AArch64::STRXui || Opc == AArch64::STRDui ||
529 Opc == AArch64::LDPXi || Opc == AArch64::LDPDi ||
530 Opc == AArch64::LDRXui || Opc == AArch64::LDRDui) &&
531 "Unexpected callee-save save/restore opcode!");
532
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000533 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
534 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
Geoff Berrya5335642016-05-06 16:34:59 +0000535 "Unexpected base register in callee-save save/restore instruction!");
536 // Last operand is immediate offset that needs fixing.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000537 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
Geoff Berrya5335642016-05-06 16:34:59 +0000538 // All generated opcodes have scaled offsets.
539 assert(LocalStackSize % 8 == 0);
540 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / 8);
541}
542
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +0000543static void adaptForLdStOpt(MachineBasicBlock &MBB,
544 MachineBasicBlock::iterator FirstSPPopI,
545 MachineBasicBlock::iterator LastPopI) {
546 // Sometimes (when we restore in the same order as we save), we can end up
547 // with code like this:
548 //
549 // ldp x26, x25, [sp]
550 // ldp x24, x23, [sp, #16]
551 // ldp x22, x21, [sp, #32]
552 // ldp x20, x19, [sp, #48]
553 // add sp, sp, #64
554 //
555 // In this case, it is always better to put the first ldp at the end, so
556 // that the load-store optimizer can run and merge the ldp and the add into
557 // a post-index ldp.
558 // If we managed to grab the first pop instruction, move it to the end.
559 if (ReverseCSRRestoreSeq)
560 MBB.splice(FirstSPPopI, &MBB, LastPopI);
561 // We should end up with something like this now:
562 //
563 // ldp x24, x23, [sp, #16]
564 // ldp x22, x21, [sp, #32]
565 // ldp x20, x19, [sp, #48]
566 // ldp x26, x25, [sp]
567 // add sp, sp, #64
568 //
569 // and the load-store optimizer can merge the last two instructions into:
570 //
571 // ldp x26, x25, [sp], #64
572 //
573}
574
Quentin Colombet61b305e2015-05-05 17:38:16 +0000575void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
576 MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000577 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000578 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000579 const Function &F = MF.getFunction();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000580 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
581 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
582 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000583 MachineModuleInfo &MMI = MF.getMMI();
Tim Northover775aaeb2015-11-05 21:54:58 +0000584 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braunf1caa282017-12-15 22:22:58 +0000585 bool needsFrameMoves = MMI.hasDebugInfo() || F.needsUnwindTableEntry();
Tim Northover775aaeb2015-11-05 21:54:58 +0000586 bool HasFP = hasFP(MF);
587
Jessica Paquette8aa6cd52018-04-12 16:16:18 +0000588 // At this point, we're going to decide whether or not the function uses a
589 // redzone. In most cases, the function doesn't have a redzone so let's
590 // assume that's false and set it to true in the case that there's a redzone.
591 AFI->setHasRedZone(false);
592
Tim Northover775aaeb2015-11-05 21:54:58 +0000593 // Debug location must be unknown since the first debug location is used
594 // to determine the end of the prologue.
595 DebugLoc DL;
596
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000597 if (ShouldSignReturnAddress(MF)) {
598 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
599 .setMIFlag(MachineInstr::FrameSetup);
600 }
601
Tim Northover775aaeb2015-11-05 21:54:58 +0000602 // All calls are tail calls in GHC calling conv, and functions have no
603 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000604 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000605 return;
606
Matthias Braun941a7052016-07-28 18:40:00 +0000607 int NumBytes = (int)MFI.getStackSize();
Martin Storsjo2778fd02017-12-20 06:51:45 +0000608 if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000609 assert(!HasFP && "unexpected function without stack frame but with FP");
610
611 // All of the stack allocation is for locals.
612 AFI->setLocalStackSize(NumBytes);
613
Chad Rosier27c352d2016-03-14 18:24:34 +0000614 if (!NumBytes)
615 return;
Tim Northover3b0846e2014-05-24 12:50:23 +0000616 // REDZONE: If the stack size is less than 128 bytes, we don't need
617 // to actually allocate.
Jessica Paquette642f6c62018-04-03 21:56:10 +0000618 if (canUseRedZone(MF)) {
619 AFI->setHasRedZone(true);
Chad Rosier27c352d2016-03-14 18:24:34 +0000620 ++NumRedZoneFunctions;
Jessica Paquette642f6c62018-04-03 21:56:10 +0000621 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +0000622 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
623 MachineInstr::FrameSetup);
624
Chad Rosier27c352d2016-03-14 18:24:34 +0000625 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
626 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000628 unsigned CFIIndex = MF.addFrameInst(
Tim Northover3b0846e2014-05-24 12:50:23 +0000629 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
630 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000631 .addCFIIndex(CFIIndex)
632 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 return;
635 }
636
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000637 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000638 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000639 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
640
641 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Chad Rosier27c352d2016-03-14 18:24:34 +0000642 // All of the remaining stack allocations are for locals.
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000643 AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
Tim Northover3b0846e2014-05-24 12:50:23 +0000644
Geoff Berrya5335642016-05-06 16:34:59 +0000645 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
646 if (CombineSPBump) {
647 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
648 MachineInstr::FrameSetup);
649 NumBytes = 0;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000650 } else if (PrologueSaveSize != 0) {
Geoff Berrya5335642016-05-06 16:34:59 +0000651 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000652 -PrologueSaveSize);
653 NumBytes -= PrologueSaveSize;
Geoff Berrya5335642016-05-06 16:34:59 +0000654 }
655 assert(NumBytes >= 0 && "Negative stack allocation size!?");
656
657 // Move past the saves of the callee-saved registers, fixing up the offsets
658 // and pre-inc if we decided to combine the callee-save and local stack
659 // pointer bump above.
Geoff Berry04bf91a2016-02-01 16:29:19 +0000660 MachineBasicBlock::iterator End = MBB.end();
Geoff Berrya5335642016-05-06 16:34:59 +0000661 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
662 if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000663 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000664 ++MBBI;
Geoff Berrya5335642016-05-06 16:34:59 +0000665 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000666 if (HasFP) {
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000667 // Only set up FP if we actually need to. Frame pointer is fp =
668 // sp - fixedobject - 16.
669 int FPOffset = AFI->getCalleeSavedStackSize() - 16;
Geoff Berrya5335642016-05-06 16:34:59 +0000670 if (CombineSPBump)
671 FPOffset += AFI->getLocalStackSize();
Chad Rosier27c352d2016-03-14 18:24:34 +0000672
Tim Northover3b0846e2014-05-24 12:50:23 +0000673 // Issue sub fp, sp, FPOffset or
674 // mov fp,sp when FPOffset is zero.
675 // Note: All stores of callee-saved registers are marked as "FrameSetup".
676 // This code marks the instruction(s) that set the FP also.
677 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
678 MachineInstr::FrameSetup);
679 }
680
Martin Storsjo2778fd02017-12-20 06:51:45 +0000681 if (windowsRequiresStackProbe(MF, NumBytes)) {
682 uint32_t NumWords = NumBytes >> 4;
683
684 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
685 .addImm(NumWords)
686 .setMIFlags(MachineInstr::FrameSetup);
687
688 switch (MF.getTarget().getCodeModel()) {
689 case CodeModel::Small:
690 case CodeModel::Medium:
691 case CodeModel::Kernel:
692 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
693 .addExternalSymbol("__chkstk")
694 .addReg(AArch64::X15, RegState::Implicit)
695 .setMIFlags(MachineInstr::FrameSetup);
696 break;
697 case CodeModel::Large:
698 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
699 .addReg(AArch64::X16, RegState::Define)
700 .addExternalSymbol("__chkstk")
701 .addExternalSymbol("__chkstk")
702 .setMIFlags(MachineInstr::FrameSetup);
703
704 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
705 .addReg(AArch64::X16, RegState::Kill)
706 .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
707 .setMIFlags(MachineInstr::FrameSetup);
708 break;
709 }
710
711 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
712 .addReg(AArch64::SP, RegState::Kill)
713 .addReg(AArch64::X15, RegState::Kill)
714 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
715 .setMIFlags(MachineInstr::FrameSetup);
716 NumBytes = 0;
717 }
718
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 // Allocate space for the rest of the frame.
Chad Rosier27c352d2016-03-14 18:24:34 +0000720 if (NumBytes) {
721 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
722 unsigned scratchSPReg = AArch64::SP;
Kristof Beyls17cb8982015-04-09 08:49:47 +0000723
Chad Rosier27c352d2016-03-14 18:24:34 +0000724 if (NeedsRealignment) {
725 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
726 assert(scratchSPReg != AArch64::NoRegister);
727 }
Kristof Beyls17cb8982015-04-09 08:49:47 +0000728
Chad Rosier27c352d2016-03-14 18:24:34 +0000729 // If we're a leaf function, try using the red zone.
730 if (!canUseRedZone(MF))
731 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
732 // the correct value here, as NumBytes also includes padding bytes,
733 // which shouldn't be counted here.
734 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
735 MachineInstr::FrameSetup);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000736
Chad Rosier27c352d2016-03-14 18:24:34 +0000737 if (NeedsRealignment) {
Matthias Braun941a7052016-07-28 18:40:00 +0000738 const unsigned Alignment = MFI.getMaxAlignment();
Chad Rosier27c352d2016-03-14 18:24:34 +0000739 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
740 assert(NrBitsToZero > 1);
741 assert(scratchSPReg != AArch64::SP);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000742
Chad Rosier27c352d2016-03-14 18:24:34 +0000743 // SUB X9, SP, NumBytes
744 // -- X9 is temporary register, so shouldn't contain any live data here,
745 // -- free to use. This is already produced by emitFrameOffset above.
746 // AND SP, X9, 0b11111...0000
747 // The logical immediates have a non-trivial encoding. The following
748 // formula computes the encoded immediate with all ones but
749 // NrBitsToZero zero bits as least significant bits.
750 uint32_t andMaskEncoded = (1 << 12) // = N
751 | ((64 - NrBitsToZero) << 6) // immr
752 | ((64 - NrBitsToZero - 1) << 0); // imms
753
754 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
755 .addReg(scratchSPReg, RegState::Kill)
756 .addImm(andMaskEncoded);
757 AFI->setStackRealigned(true);
758 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 }
760
761 // If we need a base pointer, set it up here. It's whatever the value of the
762 // stack pointer is at this point. Any variable size objects will be allocated
763 // after this, so we can still use the base pointer to reference locals.
764 //
765 // FIXME: Clarify FrameSetup flags here.
766 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
767 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000768 if (RegInfo->hasBasePointer(MF)) {
769 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
770 false);
771 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000772
773 if (needsFrameMoves) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000774 const DataLayout &TD = MF.getDataLayout();
775 const int StackGrowth = -TD.getPointerSize(0);
Tim Northover3b0846e2014-05-24 12:50:23 +0000776 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000777 // An example of the prologue:
778 //
779 // .globl __foo
780 // .align 2
781 // __foo:
782 // Ltmp0:
783 // .cfi_startproc
784 // .cfi_personality 155, ___gxx_personality_v0
785 // Leh_func_begin:
786 // .cfi_lsda 16, Lexception33
787 //
788 // stp xa,bx, [sp, -#offset]!
789 // ...
790 // stp x28, x27, [sp, #offset-32]
791 // stp fp, lr, [sp, #offset-16]
792 // add fp, sp, #offset - 16
793 // sub sp, sp, #1360
794 //
795 // The Stack:
796 // +-------------------------------------------+
797 // 10000 | ........ | ........ | ........ | ........ |
798 // 10004 | ........ | ........ | ........ | ........ |
799 // +-------------------------------------------+
800 // 10008 | ........ | ........ | ........ | ........ |
801 // 1000c | ........ | ........ | ........ | ........ |
802 // +===========================================+
803 // 10010 | X28 Register |
804 // 10014 | X28 Register |
805 // +-------------------------------------------+
806 // 10018 | X27 Register |
807 // 1001c | X27 Register |
808 // +===========================================+
809 // 10020 | Frame Pointer |
810 // 10024 | Frame Pointer |
811 // +-------------------------------------------+
812 // 10028 | Link Register |
813 // 1002c | Link Register |
814 // +===========================================+
815 // 10030 | ........ | ........ | ........ | ........ |
816 // 10034 | ........ | ........ | ........ | ........ |
817 // +-------------------------------------------+
818 // 10038 | ........ | ........ | ........ | ........ |
819 // 1003c | ........ | ........ | ........ | ........ |
820 // +-------------------------------------------+
821 //
822 // [sp] = 10030 :: >>initial value<<
823 // sp = 10020 :: stp fp, lr, [sp, #-16]!
824 // fp = sp == 10020 :: mov fp, sp
825 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
826 // sp == 10010 :: >>final value<<
827 //
828 // The frame pointer (w29) points to address 10020. If we use an offset of
829 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
830 // for w27, and -32 for w28:
831 //
832 // Ltmp1:
833 // .cfi_def_cfa w29, 16
834 // Ltmp2:
835 // .cfi_offset w30, -8
836 // Ltmp3:
837 // .cfi_offset w29, -16
838 // Ltmp4:
839 // .cfi_offset w27, -24
840 // Ltmp5:
841 // .cfi_offset w28, -32
842
843 if (HasFP) {
844 // Define the current CFA rule to use the provided FP.
845 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000846 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
847 nullptr, Reg, 2 * StackGrowth - FixedObject));
Tim Northover3b0846e2014-05-24 12:50:23 +0000848 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000849 .addCFIIndex(CFIIndex)
850 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000851 } else {
852 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000853 unsigned CFIIndex = MF.addFrameInst(
Matthias Braun941a7052016-07-28 18:40:00 +0000854 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000855 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000856 .addCFIIndex(CFIIndex)
857 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000858 }
859
Geoff Berry62d47252016-02-25 16:36:08 +0000860 // Now emit the moves for whatever callee saved regs we have (including FP,
861 // LR if those are saved).
862 emitCalleeSavedFrameMoves(MBB, MBBI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000863 }
864}
865
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000866static void InsertReturnAddressAuth(MachineFunction &MF,
867 MachineBasicBlock &MBB) {
868 if (!ShouldSignReturnAddress(MF))
869 return;
870 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
871 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
872
873 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
874 DebugLoc DL;
875 if (MBBI != MBB.end())
876 DL = MBBI->getDebugLoc();
877
878 // The AUTIASP instruction assembles to a hint instruction before v8.3a so
879 // this instruction can safely used for any v8a architecture.
880 // From v8.3a onwards there are optimised authenticate LR and return
881 // instructions, namely RETA{A,B}, that can be used instead.
882 if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
883 MBBI->getOpcode() == AArch64::RET_ReallyLR) {
884 BuildMI(MBB, MBBI, DL, TII->get(AArch64::RETAA)).copyImplicitOps(*MBBI);
885 MBB.erase(MBBI);
886 } else {
887 BuildMI(MBB, MBBI, DL, TII->get(AArch64::AUTIASP))
888 .setMIFlag(MachineInstr::FrameDestroy);
889 }
890}
891
Tim Northover3b0846e2014-05-24 12:50:23 +0000892void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
893 MachineBasicBlock &MBB) const {
894 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Matthias Braun941a7052016-07-28 18:40:00 +0000895 MachineFrameInfo &MFI = MF.getFrameInfo();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000896 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000897 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000898 DebugLoc DL;
899 bool IsTailCallReturn = false;
900 if (MBB.end() != MBBI) {
901 DL = MBBI->getDebugLoc();
902 unsigned RetOpcode = MBBI->getOpcode();
903 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
904 RetOpcode == AArch64::TCRETURNri;
905 }
Matthias Braun941a7052016-07-28 18:40:00 +0000906 int NumBytes = MFI.getStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000907 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
908
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000909 // All calls are tail calls in GHC calling conv, and functions have no
910 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000911 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000912 return;
913
Kristof Beyls17cb8982015-04-09 08:49:47 +0000914 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 // in the epilogue, the residual adjustment is executed first.
916 uint64_t ArgumentPopSize = 0;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000917 if (IsTailCallReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000918 MachineOperand &StackAdjust = MBBI->getOperand(1);
919
920 // For a tail-call in a callee-pops-arguments environment, some or all of
921 // the stack may actually be in use for the call's arguments, this is
922 // calculated during LowerCall and consumed here...
923 ArgumentPopSize = StackAdjust.getImm();
924 } else {
925 // ... otherwise the amount to pop is *all* of the argument space,
926 // conveniently stored in the MachineFunctionInfo by
927 // LowerFormalArguments. This will, of course, be zero for the C calling
928 // convention.
929 ArgumentPopSize = AFI->getArgumentStackToRestore();
930 }
931
932 // The stack frame should be like below,
933 //
934 // ---------------------- ---
935 // | | |
936 // | BytesInStackArgArea| CalleeArgStackSize
937 // | (NumReusableBytes) | (of tail call)
938 // | | ---
939 // | | |
940 // ---------------------| --- |
941 // | | | |
942 // | CalleeSavedReg | | |
Geoff Berry04bf91a2016-02-01 16:29:19 +0000943 // | (CalleeSavedStackSize)| | |
Tim Northover3b0846e2014-05-24 12:50:23 +0000944 // | | | |
945 // ---------------------| | NumBytes
946 // | | StackSize (StackAdjustUp)
947 // | LocalStackSize | | |
948 // | (covering callee | | |
949 // | args) | | |
950 // | | | |
951 // ---------------------- --- ---
952 //
953 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
954 // = StackSize + ArgumentPopSize
955 //
956 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
957 // it as the 2nd argument of AArch64ISD::TC_RETURN.
Tim Northover3b0846e2014-05-24 12:50:23 +0000958
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000959 auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
960
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000961 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000962 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000963 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
964
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000965 uint64_t AfterCSRPopSize = ArgumentPopSize;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000966 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Geoff Berrya5335642016-05-06 16:34:59 +0000967 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000968 // Assume we can't combine the last pop with the sp restore.
Geoff Berrya5335642016-05-06 16:34:59 +0000969
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000970 if (!CombineSPBump && PrologueSaveSize != 0) {
971 MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
972 // Converting the last ldp to a post-index ldp is valid only if the last
973 // ldp's offset is 0.
974 const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
975 // If the offset is 0, convert it to a post-index ldp.
976 if (OffsetOp.getImm() == 0) {
977 convertCalleeSaveRestoreToSPPrePostIncDec(MBB, Pop, DL, TII,
978 PrologueSaveSize);
979 } else {
980 // If not, make sure to emit an add after the last ldp.
981 // We're doing this by transfering the size to be restored from the
982 // adjustment *before* the CSR pops to the adjustment *after* the CSR
983 // pops.
984 AfterCSRPopSize += PrologueSaveSize;
985 }
986 }
Geoff Berrya5335642016-05-06 16:34:59 +0000987
Tim Northover3b0846e2014-05-24 12:50:23 +0000988 // Move past the restores of the callee-saved registers.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000989 // If we plan on combining the sp bump of the local stack size and the callee
990 // save stack size, we might need to adjust the CSR save and restore offsets.
Quentin Colombet61b305e2015-05-05 17:38:16 +0000991 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
Matthias Braun45419292015-12-17 03:18:47 +0000992 MachineBasicBlock::iterator Begin = MBB.begin();
993 while (LastPopI != Begin) {
994 --LastPopI;
Geoff Berry04bf91a2016-02-01 16:29:19 +0000995 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000996 ++LastPopI;
Matthias Braun45419292015-12-17 03:18:47 +0000997 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000998 } else if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000999 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 }
Geoff Berrya5335642016-05-06 16:34:59 +00001001
1002 // If there is a single SP update, insert it before the ret and we're done.
1003 if (CombineSPBump) {
1004 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001005 NumBytes + AfterCSRPopSize, TII,
Geoff Berrya5335642016-05-06 16:34:59 +00001006 MachineInstr::FrameDestroy);
1007 return;
1008 }
1009
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001010 NumBytes -= PrologueSaveSize;
Tim Northover3b0846e2014-05-24 12:50:23 +00001011 assert(NumBytes >= 0 && "Negative stack allocation size!?");
1012
1013 if (!hasFP(MF)) {
Geoff Berrya1c62692016-02-23 16:54:36 +00001014 bool RedZone = canUseRedZone(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +00001015 // If this was a redzone leaf function, we don't need to restore the
Geoff Berrya1c62692016-02-23 16:54:36 +00001016 // stack pointer (but we may need to pop stack args for fastcc).
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001017 if (RedZone && AfterCSRPopSize == 0)
Geoff Berrya1c62692016-02-23 16:54:36 +00001018 return;
1019
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001020 bool NoCalleeSaveRestore = PrologueSaveSize == 0;
Geoff Berrya1c62692016-02-23 16:54:36 +00001021 int StackRestoreBytes = RedZone ? 0 : NumBytes;
1022 if (NoCalleeSaveRestore)
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001023 StackRestoreBytes += AfterCSRPopSize;
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001024
Geoff Berrya1c62692016-02-23 16:54:36 +00001025 // If we were able to combine the local stack pop with the argument pop,
1026 // then we're done.
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001027 bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1028
1029 // If we're done after this, make sure to help the load store optimizer.
1030 if (Done)
1031 adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1032
1033 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1034 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
1035 if (Done)
Geoff Berrya1c62692016-02-23 16:54:36 +00001036 return;
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001037
Geoff Berrya1c62692016-02-23 16:54:36 +00001038 NumBytes = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001039 }
1040
1041 // Restore the original stack pointer.
1042 // FIXME: Rather than doing the math here, we should instead just use
1043 // non-post-indexed loads for the restores if we aren't actually going to
1044 // be able to save any instructions.
Matthias Braun941a7052016-07-28 18:40:00 +00001045 if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
Tim Northover3b0846e2014-05-24 12:50:23 +00001046 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001047 -AFI->getCalleeSavedStackSize() + 16, TII,
1048 MachineInstr::FrameDestroy);
Chad Rosier6d986552016-03-14 18:17:41 +00001049 else if (NumBytes)
1050 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
1051 MachineInstr::FrameDestroy);
Geoff Berrya1c62692016-02-23 16:54:36 +00001052
1053 // This must be placed after the callee-save restore code because that code
1054 // assumes the SP is at the same location as it was after the callee-save save
1055 // code in the prologue.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001056 if (AfterCSRPopSize) {
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001057 // Find an insertion point for the first ldp so that it goes before the
1058 // shadow call stack epilog instruction. This ensures that the restore of
1059 // lr from x18 is placed after the restore from sp.
1060 auto FirstSPPopI = MBB.getFirstTerminator();
1061 while (FirstSPPopI != Begin) {
1062 auto Prev = std::prev(FirstSPPopI);
1063 if (Prev->getOpcode() != AArch64::LDRXpre ||
1064 Prev->getOperand(0).getReg() == AArch64::SP)
1065 break;
1066 FirstSPPopI = Prev;
1067 }
1068
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001069 adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1070
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001071 emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001072 AfterCSRPopSize, TII, MachineInstr::FrameDestroy);
1073 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001074}
1075
Tim Northover3b0846e2014-05-24 12:50:23 +00001076/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1077/// debug info. It's the same as what we use for resolving the code-gen
1078/// references for now. FIXME: This can go wrong when references are
1079/// SP-relative and simple call frames aren't used.
1080int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1081 int FI,
1082 unsigned &FrameReg) const {
1083 return resolveFrameIndexReference(MF, FI, FrameReg);
1084}
1085
1086int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
1087 int FI, unsigned &FrameReg,
1088 bool PreferFP) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001089 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001090 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001091 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001092 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001093 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1094 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +00001095 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001096 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1097 int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16;
Matthias Braun941a7052016-07-28 18:40:00 +00001098 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1099 bool isFixed = MFI.isFixedObjectIndex(FI);
Geoff Berry08ab8c952018-04-26 18:50:45 +00001100 bool isCSR = !isFixed && MFI.getObjectOffset(FI) >=
1101 -((int)AFI->getCalleeSavedStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +00001102
1103 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +00001104 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1105 // reliable as a base). Make sure useFPForScavengingIndex() does the
1106 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +00001107 bool UseFP = false;
1108 if (AFI->hasStackFrame()) {
1109 // Note: Keeping the following as multiple 'if' statements rather than
1110 // merging to a single expression for readability.
1111 //
1112 // Argument access should always use the FP.
1113 if (isFixed) {
1114 UseFP = hasFP(MF);
Geoff Berry08ab8c952018-04-26 18:50:45 +00001115 } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1116 // References to the CSR area must use FP if we're re-aligning the stack
1117 // since the dynamically-sized alignment padding is between the SP/BP and
1118 // the CSR area.
1119 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1120 UseFP = true;
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001121 } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001122 // If the FPOffset is negative, we have to keep in mind that the
1123 // available offset range for negative offsets is smaller than for
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001124 // positive ones. If an offset is
Tim Northover3b0846e2014-05-24 12:50:23 +00001125 // available via the FP and the SP, use whichever is closest.
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001126 bool FPOffsetFits = FPOffset >= -256;
1127 PreferFP |= Offset > -FPOffset;
1128
1129 if (MFI.hasVarSizedObjects()) {
1130 // If we have variable sized objects, we can use either FP or BP, as the
1131 // SP offset is unknown. We can use the base pointer if we have one and
1132 // FP is not preferred. If not, we're stuck with using FP.
1133 bool CanUseBP = RegInfo->hasBasePointer(MF);
1134 if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1135 UseFP = PreferFP;
1136 else if (!CanUseBP) // Can't use BP. Forced to use FP.
1137 UseFP = true;
1138 // else we can use BP and FP, but the offset from FP won't fit.
1139 // That will make us scavenge registers which we can probably avoid by
1140 // using BP. If it won't fit for BP either, we'll scavenge anyway.
Francis Visoiu Mistrih64639222018-04-11 12:36:55 +00001141 } else if (FPOffset >= 0) {
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001142 // Use SP or FP, whichever gives us the best chance of the offset
1143 // being in range for direct access. If the FPOffset is positive,
1144 // that'll always be best, as the SP will be even further away.
Tim Northover3b0846e2014-05-24 12:50:23 +00001145 UseFP = true;
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001146 } else {
1147 // We have the choice between FP and (SP or BP).
1148 if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1149 UseFP = true;
1150 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001151 }
1152 }
1153
Geoff Berry08ab8c952018-04-26 18:50:45 +00001154 assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
Kristof Beyls17cb8982015-04-09 08:49:47 +00001155 "In the presence of dynamic stack pointer realignment, "
Geoff Berry08ab8c952018-04-26 18:50:45 +00001156 "non-argument/CSR objects cannot be accessed through the frame pointer");
Kristof Beyls17cb8982015-04-09 08:49:47 +00001157
Tim Northover3b0846e2014-05-24 12:50:23 +00001158 if (UseFP) {
1159 FrameReg = RegInfo->getFrameRegister(MF);
1160 return FPOffset;
1161 }
1162
1163 // Use the base pointer if we have one.
1164 if (RegInfo->hasBasePointer(MF))
1165 FrameReg = RegInfo->getBaseRegister();
1166 else {
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001167 assert(!MFI.hasVarSizedObjects() &&
1168 "Can't use SP when we have var sized objects.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001169 FrameReg = AArch64::SP;
1170 // If we're using the red zone for this function, the SP won't actually
1171 // be adjusted, so the offsets will be negative. They're also all
1172 // within range of the signed 9-bit immediate instructions.
1173 if (canUseRedZone(MF))
1174 Offset -= AFI->getLocalStackSize();
1175 }
1176
1177 return Offset;
1178}
1179
1180static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00001181 // Do not set a kill flag on values that are also marked as live-in. This
1182 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1183 // callee saved registers.
1184 // Omitting the kill flags is conservatively correct even if the live-in
1185 // is not used after all.
1186 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1187 return getKillRegState(!IsLiveIn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001188}
1189
Manman Ren57518142016-04-11 21:08:06 +00001190static bool produceCompactUnwindFrame(MachineFunction &MF) {
1191 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Matthias Braunf1caa282017-12-15 22:22:58 +00001192 AttributeList Attrs = MF.getFunction().getAttributes();
Manman Ren57518142016-04-11 21:08:06 +00001193 return Subtarget.isTargetMachO() &&
1194 !(Subtarget.getTargetLowering()->supportSwiftError() &&
1195 Attrs.hasAttrSomewhere(Attribute::SwiftError));
1196}
1197
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001198namespace {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001199
Geoff Berry29d4a692016-02-01 19:07:06 +00001200struct RegPairInfo {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001201 unsigned Reg1 = AArch64::NoRegister;
1202 unsigned Reg2 = AArch64::NoRegister;
Geoff Berry29d4a692016-02-01 19:07:06 +00001203 int FrameIdx;
1204 int Offset;
1205 bool IsGPR;
Eugene Zelenko11f69072017-01-25 00:29:26 +00001206
1207 RegPairInfo() = default;
1208
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001209 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
Geoff Berry29d4a692016-02-01 19:07:06 +00001210};
Eugene Zelenko11f69072017-01-25 00:29:26 +00001211
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001212} // end anonymous namespace
Geoff Berry29d4a692016-02-01 19:07:06 +00001213
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001214static void computeCalleeSaveRegisterPairs(
1215 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001216 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1217 bool &NeedShadowCallStackProlog) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001218
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001219 if (CSI.empty())
1220 return;
1221
1222 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001223 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001224 CallingConv::ID CC = MF.getFunction().getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00001225 unsigned Count = CSI.size();
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001226 (void)CC;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001227 // MachO's compact unwind format relies on all registers being stored in
1228 // pairs.
Manman Ren57518142016-04-11 21:08:06 +00001229 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001230 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001231 (Count & 1) == 0) &&
1232 "Odd number of callee-saved regs to spill!");
Martin Storsjo68266fa2017-07-13 17:03:12 +00001233 int Offset = AFI->getCalleeSavedStackSize();
1234
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001235 for (unsigned i = 0; i < Count; ++i) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001236 RegPairInfo RPI;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001237 RPI.Reg1 = CSI[i].getReg();
1238
1239 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
1240 AArch64::FPR64RegClass.contains(RPI.Reg1));
1241 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
1242
1243 // Add the next reg to the pair if it is in the same register class.
1244 if (i + 1 < Count) {
1245 unsigned NextReg = CSI[i + 1].getReg();
1246 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
1247 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
1248 RPI.Reg2 = NextReg;
1249 }
Geoff Berry29d4a692016-02-01 19:07:06 +00001250
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001251 // If either of the registers to be saved is the lr register, it means that
1252 // we also need to save lr in the shadow call stack.
1253 if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
1254 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
1255 if (!MF.getSubtarget<AArch64Subtarget>().isX18Reserved())
1256 report_fatal_error("Must reserve x18 to use shadow call stack");
1257 NeedShadowCallStackProlog = true;
1258 }
1259
Tim Northover3b0846e2014-05-24 12:50:23 +00001260 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1261 // list to come in sorted by frame index so that we can issue the store
1262 // pair instructions directly. Assert if we see anything otherwise.
1263 //
1264 // The order of the registers in the list is controlled by
1265 // getCalleeSavedRegs(), so they will always be in-order, as well.
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001266 assert((!RPI.isPaired() ||
1267 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001268 "Out of order callee saved regs!");
Geoff Berry29d4a692016-02-01 19:07:06 +00001269
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001270 // MachO's compact unwind format relies on all registers being stored in
1271 // adjacent register pairs.
Manman Ren57518142016-04-11 21:08:06 +00001272 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001273 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001274 (RPI.isPaired() &&
1275 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1276 RPI.Reg1 + 1 == RPI.Reg2))) &&
1277 "Callee-save registers not saved as adjacent register pair!");
1278
1279 RPI.FrameIdx = CSI[i].getFrameIdx();
1280
1281 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
1282 // Round up size of non-pair to pair size if we need to pad the
1283 // callee-save area to ensure 16-byte alignment.
1284 Offset -= 16;
Matthias Braun941a7052016-07-28 18:40:00 +00001285 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1286 MFI.setObjectAlignment(RPI.FrameIdx, 16);
Geoff Berry66f6b652016-06-02 16:22:07 +00001287 AFI->setCalleeSaveStackHasFreeSpace(true);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001288 } else
1289 Offset -= RPI.isPaired() ? 16 : 8;
1290 assert(Offset % 8 == 0);
1291 RPI.Offset = Offset / 8;
Geoff Berry29d4a692016-02-01 19:07:06 +00001292 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1293 "Offset out of bounds for LDP/STP immediate");
1294
1295 RegPairs.push_back(RPI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001296 if (RPI.isPaired())
1297 ++i;
Geoff Berry29d4a692016-02-01 19:07:06 +00001298 }
1299}
1300
1301bool AArch64FrameLowering::spillCalleeSavedRegisters(
1302 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1303 const std::vector<CalleeSavedInfo> &CSI,
1304 const TargetRegisterInfo *TRI) const {
1305 MachineFunction &MF = *MBB.getParent();
1306 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1307 DebugLoc DL;
1308 SmallVector<RegPairInfo, 8> RegPairs;
1309
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001310 bool NeedShadowCallStackProlog = false;
1311 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1312 NeedShadowCallStackProlog);
Matthias Braun88c8c982017-05-27 03:38:02 +00001313 const MachineRegisterInfo &MRI = MF.getRegInfo();
Geoff Berry29d4a692016-02-01 19:07:06 +00001314
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001315 if (NeedShadowCallStackProlog) {
1316 // Shadow call stack prolog: str x30, [x18], #8
1317 BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
1318 .addReg(AArch64::X18, RegState::Define)
1319 .addReg(AArch64::LR)
1320 .addReg(AArch64::X18)
1321 .addImm(8)
1322 .setMIFlag(MachineInstr::FrameSetup);
1323
1324 // This instruction also makes x18 live-in to the entry block.
1325 MBB.addLiveIn(AArch64::X18);
1326 }
1327
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001328 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +00001329 ++RPII) {
1330 RegPairInfo RPI = *RPII;
1331 unsigned Reg1 = RPI.Reg1;
1332 unsigned Reg2 = RPI.Reg2;
1333 unsigned StrOpc;
1334
Geoff Berrya5335642016-05-06 16:34:59 +00001335 // Issue sequence of spills for cs regs. The first spill may be converted
1336 // to a pre-decrement store later by emitPrologue if the callee-save stack
1337 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001338 // For example:
Geoff Berrya5335642016-05-06 16:34:59 +00001339 // stp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001340 // stp x20, x19, [sp, #16] // addImm(+2)
1341 // stp fp, lr, [sp, #32] // addImm(+4)
1342 // Rationale: This sequence saves uop updates compared to a sequence of
1343 // pre-increment spills like stp xi,xj,[sp,#-16]!
Geoff Berry29d4a692016-02-01 19:07:06 +00001344 // Note: Similar rationale and sequence for restores in epilog.
Geoff Berrya5335642016-05-06 16:34:59 +00001345 if (RPI.IsGPR)
1346 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1347 else
1348 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001349 LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
1350 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1351 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1352 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1353 dbgs() << ")\n");
Geoff Berry29d4a692016-02-01 19:07:06 +00001354
Tim Northover3b0846e2014-05-24 12:50:23 +00001355 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
Matthias Braun88c8c982017-05-27 03:38:02 +00001356 if (!MRI.isReserved(Reg1))
1357 MBB.addLiveIn(Reg1);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001358 if (RPI.isPaired()) {
Matthias Braun88c8c982017-05-27 03:38:02 +00001359 if (!MRI.isReserved(Reg2))
1360 MBB.addLiveIn(Reg2);
Geoff Berrya5335642016-05-06 16:34:59 +00001361 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
Geoff Berryc3764062016-04-15 15:16:19 +00001362 MIB.addMemOperand(MF.getMachineMemOperand(
1363 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1364 MachineMemOperand::MOStore, 8, 8));
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001365 }
Geoff Berrya5335642016-05-06 16:34:59 +00001366 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1367 .addReg(AArch64::SP)
1368 .addImm(RPI.Offset) // [sp, #offset*8], where factor*8 is implicit
1369 .setMIFlag(MachineInstr::FrameSetup);
Geoff Berryc3764062016-04-15 15:16:19 +00001370 MIB.addMemOperand(MF.getMachineMemOperand(
1371 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1372 MachineMemOperand::MOStore, 8, 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00001373 }
1374 return true;
1375}
1376
1377bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1378 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001379 std::vector<CalleeSavedInfo> &CSI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001380 const TargetRegisterInfo *TRI) const {
1381 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001382 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001383 DebugLoc DL;
Geoff Berry29d4a692016-02-01 19:07:06 +00001384 SmallVector<RegPairInfo, 8> RegPairs;
Tim Northover3b0846e2014-05-24 12:50:23 +00001385
1386 if (MI != MBB.end())
1387 DL = MI->getDebugLoc();
1388
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001389 bool NeedShadowCallStackProlog = false;
1390 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1391 NeedShadowCallStackProlog);
Geoff Berry29d4a692016-02-01 19:07:06 +00001392
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001393 auto EmitMI = [&](const RegPairInfo &RPI) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001394 unsigned Reg1 = RPI.Reg1;
1395 unsigned Reg2 = RPI.Reg2;
1396
Geoff Berrya5335642016-05-06 16:34:59 +00001397 // Issue sequence of restores for cs regs. The last restore may be converted
1398 // to a post-increment load later by emitEpilogue if the callee-save stack
1399 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001400 // For example:
1401 // ldp fp, lr, [sp, #32] // addImm(+4)
1402 // ldp x20, x19, [sp, #16] // addImm(+2)
Geoff Berrya5335642016-05-06 16:34:59 +00001403 // ldp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001404 // Note: see comment in spillCalleeSavedRegisters()
1405 unsigned LdrOpc;
Geoff Berrya5335642016-05-06 16:34:59 +00001406 if (RPI.IsGPR)
1407 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1408 else
1409 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001410 LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
1411 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1412 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1413 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1414 dbgs() << ")\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001415
Tim Northover3b0846e2014-05-24 12:50:23 +00001416 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
Geoff Berryc3764062016-04-15 15:16:19 +00001417 if (RPI.isPaired()) {
Geoff Berrya5335642016-05-06 16:34:59 +00001418 MIB.addReg(Reg2, getDefRegState(true));
Geoff Berryc3764062016-04-15 15:16:19 +00001419 MIB.addMemOperand(MF.getMachineMemOperand(
1420 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1421 MachineMemOperand::MOLoad, 8, 8));
Geoff Berryc3764062016-04-15 15:16:19 +00001422 }
Geoff Berrya5335642016-05-06 16:34:59 +00001423 MIB.addReg(Reg1, getDefRegState(true))
1424 .addReg(AArch64::SP)
1425 .addImm(RPI.Offset) // [sp, #offset*8] where the factor*8 is implicit
1426 .setMIFlag(MachineInstr::FrameDestroy);
Geoff Berryc3764062016-04-15 15:16:19 +00001427 MIB.addMemOperand(MF.getMachineMemOperand(
1428 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1429 MachineMemOperand::MOLoad, 8, 8));
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001430 };
1431
1432 if (ReverseCSRRestoreSeq)
1433 for (const RegPairInfo &RPI : reverse(RegPairs))
1434 EmitMI(RPI);
1435 else
1436 for (const RegPairInfo &RPI : RegPairs)
1437 EmitMI(RPI);
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001438
1439 if (NeedShadowCallStackProlog) {
1440 // Shadow call stack epilog: ldr x30, [x18, #-8]!
1441 BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
1442 .addReg(AArch64::X18, RegState::Define)
1443 .addReg(AArch64::LR, RegState::Define)
1444 .addReg(AArch64::X18)
1445 .addImm(-8)
1446 .setMIFlag(MachineInstr::FrameDestroy);
1447 }
1448
Tim Northover3b0846e2014-05-24 12:50:23 +00001449 return true;
1450}
1451
Matthias Braun02564862015-07-14 17:17:13 +00001452void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1453 BitVector &SavedRegs,
1454 RegScavenger *RS) const {
1455 // All calls are tail calls in GHC calling conv, and functions have no
1456 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +00001457 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Matthias Braun02564862015-07-14 17:17:13 +00001458 return;
1459
1460 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001462 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001463 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001464 unsigned UnspilledCSGPR = AArch64::NoRegister;
1465 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +00001466
Martin Storsjo2778fd02017-12-20 06:51:45 +00001467 MachineFrameInfo &MFI = MF.getFrameInfo();
1468 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1469
1470 unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
1471 ? RegInfo->getBaseRegister()
1472 : (unsigned)AArch64::NoRegister;
1473
1474 unsigned SpillEstimate = SavedRegs.count();
1475 for (unsigned i = 0; CSRegs[i]; ++i) {
1476 unsigned Reg = CSRegs[i];
1477 unsigned PairedReg = CSRegs[i ^ 1];
1478 if (Reg == BasePointerReg)
1479 SpillEstimate++;
1480 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg))
1481 SpillEstimate++;
1482 }
1483 SpillEstimate += 2; // Conservatively include FP+LR in the estimate
1484 unsigned StackEstimate = MFI.estimateStackSize(MF) + 8 * SpillEstimate;
1485
Tim Northover3b0846e2014-05-24 12:50:23 +00001486 // The frame record needs to be created by saving the appropriate registers
Martin Storsjo2778fd02017-12-20 06:51:45 +00001487 if (hasFP(MF) || windowsRequiresStackProbe(MF, StackEstimate)) {
Matthias Braun02564862015-07-14 17:17:13 +00001488 SavedRegs.set(AArch64::FP);
1489 SavedRegs.set(AArch64::LR);
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 }
1491
Matthias Braund78597e2017-04-21 22:42:08 +00001492 unsigned ExtraCSSpill = 0;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001493 // Figure out which callee-saved registers to save/restore.
1494 for (unsigned i = 0; CSRegs[i]; ++i) {
1495 const unsigned Reg = CSRegs[i];
Tim Northover3b0846e2014-05-24 12:50:23 +00001496
Geoff Berry7e4ba3d2016-02-19 18:27:32 +00001497 // Add the base pointer register to SavedRegs if it is callee-save.
1498 if (Reg == BasePointerReg)
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001499 SavedRegs.set(Reg);
Tim Northover3b0846e2014-05-24 12:50:23 +00001500
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001501 bool RegUsed = SavedRegs.test(Reg);
1502 unsigned PairedReg = CSRegs[i ^ 1];
1503 if (!RegUsed) {
1504 if (AArch64::GPR64RegClass.contains(Reg) &&
1505 !RegInfo->isReservedReg(MF, Reg)) {
1506 UnspilledCSGPR = Reg;
1507 UnspilledCSGPRPaired = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001508 }
1509 continue;
1510 }
1511
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001512 // MachO's compact unwind format relies on all registers being stored in
1513 // pairs.
1514 // FIXME: the usual format is actually better if unwinding isn't needed.
Manman Ren57518142016-04-11 21:08:06 +00001515 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg)) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001516 SavedRegs.set(PairedReg);
Geoff Berry74cb7182016-05-16 20:52:28 +00001517 if (AArch64::GPR64RegClass.contains(PairedReg) &&
1518 !RegInfo->isReservedReg(MF, PairedReg))
Matthias Braund78597e2017-04-21 22:42:08 +00001519 ExtraCSSpill = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001520 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001521 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001522
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001523 LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1524 for (unsigned Reg
1525 : SavedRegs.set_bits()) dbgs()
1526 << ' ' << printReg(Reg, RegInfo);
1527 dbgs() << "\n";);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001528
1529 // If any callee-saved registers are used, the frame cannot be eliminated.
1530 unsigned NumRegsSpilled = SavedRegs.count();
1531 bool CanEliminateFrame = NumRegsSpilled == 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001532
Tim Northover3b0846e2014-05-24 12:50:23 +00001533 // The CSR spill slots have not been allocated yet, so estimateStackSize
1534 // won't include them.
Matthias Braun941a7052016-07-28 18:40:00 +00001535 unsigned CFSize = MFI.estimateStackSize(MF) + 8 * NumRegsSpilled;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001536 LLVM_DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
Kristof Beyls2af1e902017-05-30 06:58:41 +00001537 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
1538 bool BigStack = (CFSize > EstimatedStackSizeLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001539 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1540 AFI->setHasStackFrame(true);
1541
1542 // Estimate if we might need to scavenge a register at some point in order
1543 // to materialize a stack offset. If so, either spill one additional
1544 // callee-saved register or reserve a special spill slot to facilitate
1545 // register scavenging. If we already spilled an extra callee-saved register
1546 // above to keep the number of spills even, we don't need to do anything else
1547 // here.
Matthias Braund78597e2017-04-21 22:42:08 +00001548 if (BigStack) {
1549 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001550 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
1551 << " to get a scratch register.\n");
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001552 SavedRegs.set(UnspilledCSGPR);
1553 // MachO's compact unwind format relies on all registers being stored in
1554 // pairs, so if we need to spill one extra for BigStack, then we need to
1555 // store the pair.
Manman Ren57518142016-04-11 21:08:06 +00001556 if (produceCompactUnwindFrame(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001557 SavedRegs.set(UnspilledCSGPRPaired);
Matthias Braund78597e2017-04-21 22:42:08 +00001558 ExtraCSSpill = UnspilledCSGPRPaired;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001559 NumRegsSpilled = SavedRegs.count();
Tim Northover3b0846e2014-05-24 12:50:23 +00001560 }
1561
1562 // If we didn't find an extra callee-saved register to spill, create
1563 // an emergency spill slot.
Matthias Braund78597e2017-04-21 22:42:08 +00001564 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001565 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1566 const TargetRegisterClass &RC = AArch64::GPR64RegClass;
1567 unsigned Size = TRI->getSpillSize(RC);
1568 unsigned Align = TRI->getSpillAlignment(RC);
1569 int FI = MFI.CreateStackObject(Size, Align, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001570 RS->addScavengingFrameIndex(FI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001571 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1572 << " as the emergency spill slot.\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001573 }
1574 }
Geoff Berry04bf91a2016-02-01 16:29:19 +00001575
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001576 // Round up to register pair alignment to avoid additional SP adjustment
1577 // instructions.
1578 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00001579}
Geoff Berry66f6b652016-06-02 16:22:07 +00001580
1581bool AArch64FrameLowering::enableStackSlotScavenging(
1582 const MachineFunction &MF) const {
1583 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1584 return AFI->hasCalleeSaveStackFreeSpace();
1585}