blob: 40efcbe5278d65b5e18a2a59ef3fc0ffd060b1e8 [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;
Sander de Smalen71403632018-09-12 09:44:46 +0000452 int Scale = 1;
Geoff Berrya5335642016-05-06 16:34:59 +0000453 switch (MBBI->getOpcode()) {
454 default:
455 llvm_unreachable("Unexpected callee-save save/restore opcode!");
456 case AArch64::STPXi:
457 NewOpc = AArch64::STPXpre;
Sander de Smalen71403632018-09-12 09:44:46 +0000458 Scale = 8;
Geoff Berrya5335642016-05-06 16:34:59 +0000459 break;
460 case AArch64::STPDi:
461 NewOpc = AArch64::STPDpre;
Sander de Smalen71403632018-09-12 09:44:46 +0000462 Scale = 8;
Geoff Berrya5335642016-05-06 16:34:59 +0000463 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +0000464 case AArch64::STPQi:
465 NewOpc = AArch64::STPQpre;
466 Scale = 16;
467 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000468 case AArch64::STRXui:
469 NewOpc = AArch64::STRXpre;
Geoff Berrya5335642016-05-06 16:34:59 +0000470 break;
471 case AArch64::STRDui:
472 NewOpc = AArch64::STRDpre;
Geoff Berrya5335642016-05-06 16:34:59 +0000473 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +0000474 case AArch64::STRQui:
475 NewOpc = AArch64::STRQpre;
476 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000477 case AArch64::LDPXi:
478 NewOpc = AArch64::LDPXpost;
Sander de Smalen71403632018-09-12 09:44:46 +0000479 Scale = 8;
Geoff Berrya5335642016-05-06 16:34:59 +0000480 break;
481 case AArch64::LDPDi:
482 NewOpc = AArch64::LDPDpost;
Sander de Smalen71403632018-09-12 09:44:46 +0000483 Scale = 8;
Geoff Berrya5335642016-05-06 16:34:59 +0000484 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +0000485 case AArch64::LDPQi:
486 NewOpc = AArch64::LDPQpost;
487 Scale = 16;
488 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000489 case AArch64::LDRXui:
490 NewOpc = AArch64::LDRXpost;
Geoff Berrya5335642016-05-06 16:34:59 +0000491 break;
492 case AArch64::LDRDui:
493 NewOpc = AArch64::LDRDpost;
Geoff Berrya5335642016-05-06 16:34:59 +0000494 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +0000495 case AArch64::LDRQui:
496 NewOpc = AArch64::LDRQpost;
497 break;
Geoff Berrya5335642016-05-06 16:34:59 +0000498 }
499
500 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
501 MIB.addReg(AArch64::SP, RegState::Define);
502
503 // Copy all operands other than the immediate offset.
504 unsigned OpndIdx = 0;
505 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
506 ++OpndIdx)
Diana Picus116bbab2017-01-13 09:58:52 +0000507 MIB.add(MBBI->getOperand(OpndIdx));
Geoff Berrya5335642016-05-06 16:34:59 +0000508
509 assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
510 "Unexpected immediate offset in first/last callee-save save/restore "
511 "instruction!");
512 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
513 "Unexpected base register in callee-save save/restore instruction!");
Sander de Smalen71403632018-09-12 09:44:46 +0000514 assert(CSStackSizeInc % Scale == 0);
515 MIB.addImm(CSStackSizeInc / Scale);
Geoff Berrya5335642016-05-06 16:34:59 +0000516
517 MIB.setMIFlags(MBBI->getFlags());
Chandler Carruthc73c0302018-08-16 21:30:05 +0000518 MIB.setMemRefs(MBBI->memoperands());
Geoff Berrya5335642016-05-06 16:34:59 +0000519
520 return std::prev(MBB.erase(MBBI));
521}
522
523// Fixup callee-save register save/restore instructions to take into account
524// combined SP bump by adding the local stack size to the stack offsets.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000525static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
Geoff Berrya5335642016-05-06 16:34:59 +0000526 unsigned LocalStackSize) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000527 unsigned Opc = MI.getOpcode();
Peter Collingbournef11eb3e2018-04-04 21:55:44 +0000528
529 // Ignore instructions that do not operate on SP, i.e. shadow call stack
530 // instructions.
531 if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre) {
532 assert(MI.getOperand(0).getReg() != AArch64::SP);
533 return;
534 }
535
Sander de Smalen71403632018-09-12 09:44:46 +0000536 unsigned Scale;
537 switch (Opc) {
538 case AArch64::STPXi:
539 case AArch64::STRXui:
540 case AArch64::STPDi:
541 case AArch64::STRDui:
542 case AArch64::LDPXi:
543 case AArch64::LDRXui:
544 case AArch64::LDPDi:
545 case AArch64::LDRDui:
546 Scale = 8;
547 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +0000548 case AArch64::STPQi:
549 case AArch64::STRQui:
550 case AArch64::LDPQi:
551 case AArch64::LDRQui:
552 Scale = 16;
553 break;
Sander de Smalen71403632018-09-12 09:44:46 +0000554 default:
555 llvm_unreachable("Unexpected callee-save save/restore opcode!");
556 }
Geoff Berrya5335642016-05-06 16:34:59 +0000557
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000558 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
559 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
Geoff Berrya5335642016-05-06 16:34:59 +0000560 "Unexpected base register in callee-save save/restore instruction!");
561 // Last operand is immediate offset that needs fixing.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000562 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
Geoff Berrya5335642016-05-06 16:34:59 +0000563 // All generated opcodes have scaled offsets.
Sander de Smalen2d77e782018-09-12 12:10:22 +0000564 assert(LocalStackSize % Scale == 0);
Sander de Smalen71403632018-09-12 09:44:46 +0000565 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
Geoff Berrya5335642016-05-06 16:34:59 +0000566}
567
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +0000568static void adaptForLdStOpt(MachineBasicBlock &MBB,
569 MachineBasicBlock::iterator FirstSPPopI,
570 MachineBasicBlock::iterator LastPopI) {
571 // Sometimes (when we restore in the same order as we save), we can end up
572 // with code like this:
573 //
574 // ldp x26, x25, [sp]
575 // ldp x24, x23, [sp, #16]
576 // ldp x22, x21, [sp, #32]
577 // ldp x20, x19, [sp, #48]
578 // add sp, sp, #64
579 //
580 // In this case, it is always better to put the first ldp at the end, so
581 // that the load-store optimizer can run and merge the ldp and the add into
582 // a post-index ldp.
583 // If we managed to grab the first pop instruction, move it to the end.
584 if (ReverseCSRRestoreSeq)
585 MBB.splice(FirstSPPopI, &MBB, LastPopI);
586 // We should end up with something like this now:
587 //
588 // ldp x24, x23, [sp, #16]
589 // ldp x22, x21, [sp, #32]
590 // ldp x20, x19, [sp, #48]
591 // ldp x26, x25, [sp]
592 // add sp, sp, #64
593 //
594 // and the load-store optimizer can merge the last two instructions into:
595 //
596 // ldp x26, x25, [sp], #64
597 //
598}
599
Quentin Colombet61b305e2015-05-05 17:38:16 +0000600void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
601 MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000602 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000603 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000604 const Function &F = MF.getFunction();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000605 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
606 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
607 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000608 MachineModuleInfo &MMI = MF.getMMI();
Tim Northover775aaeb2015-11-05 21:54:58 +0000609 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braunf1caa282017-12-15 22:22:58 +0000610 bool needsFrameMoves = MMI.hasDebugInfo() || F.needsUnwindTableEntry();
Tim Northover775aaeb2015-11-05 21:54:58 +0000611 bool HasFP = hasFP(MF);
612
Jessica Paquette8aa6cd52018-04-12 16:16:18 +0000613 // At this point, we're going to decide whether or not the function uses a
614 // redzone. In most cases, the function doesn't have a redzone so let's
615 // assume that's false and set it to true in the case that there's a redzone.
616 AFI->setHasRedZone(false);
617
Tim Northover775aaeb2015-11-05 21:54:58 +0000618 // Debug location must be unknown since the first debug location is used
619 // to determine the end of the prologue.
620 DebugLoc DL;
621
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000622 if (ShouldSignReturnAddress(MF)) {
623 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP))
624 .setMIFlag(MachineInstr::FrameSetup);
625 }
626
Tim Northover775aaeb2015-11-05 21:54:58 +0000627 // All calls are tail calls in GHC calling conv, and functions have no
628 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000629 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000630 return;
631
Matthias Braun941a7052016-07-28 18:40:00 +0000632 int NumBytes = (int)MFI.getStackSize();
Martin Storsjo2778fd02017-12-20 06:51:45 +0000633 if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 assert(!HasFP && "unexpected function without stack frame but with FP");
635
636 // All of the stack allocation is for locals.
637 AFI->setLocalStackSize(NumBytes);
638
Chad Rosier27c352d2016-03-14 18:24:34 +0000639 if (!NumBytes)
640 return;
Tim Northover3b0846e2014-05-24 12:50:23 +0000641 // REDZONE: If the stack size is less than 128 bytes, we don't need
642 // to actually allocate.
Jessica Paquette642f6c62018-04-03 21:56:10 +0000643 if (canUseRedZone(MF)) {
644 AFI->setHasRedZone(true);
Chad Rosier27c352d2016-03-14 18:24:34 +0000645 ++NumRedZoneFunctions;
Jessica Paquette642f6c62018-04-03 21:56:10 +0000646 } else {
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
648 MachineInstr::FrameSetup);
649
Chad Rosier27c352d2016-03-14 18:24:34 +0000650 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
651 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
Tim Northover3b0846e2014-05-24 12:50:23 +0000652 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000653 unsigned CFIIndex = MF.addFrameInst(
Tim Northover3b0846e2014-05-24 12:50:23 +0000654 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
655 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000656 .addCFIIndex(CFIIndex)
657 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000658 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000659 return;
660 }
661
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000662 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000663 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000664 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
665
666 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Chad Rosier27c352d2016-03-14 18:24:34 +0000667 // All of the remaining stack allocations are for locals.
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000668 AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
Tim Northover3b0846e2014-05-24 12:50:23 +0000669
Geoff Berrya5335642016-05-06 16:34:59 +0000670 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
671 if (CombineSPBump) {
672 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
673 MachineInstr::FrameSetup);
674 NumBytes = 0;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000675 } else if (PrologueSaveSize != 0) {
Geoff Berrya5335642016-05-06 16:34:59 +0000676 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000677 -PrologueSaveSize);
678 NumBytes -= PrologueSaveSize;
Geoff Berrya5335642016-05-06 16:34:59 +0000679 }
680 assert(NumBytes >= 0 && "Negative stack allocation size!?");
681
682 // Move past the saves of the callee-saved registers, fixing up the offsets
683 // and pre-inc if we decided to combine the callee-save and local stack
684 // pointer bump above.
Geoff Berry04bf91a2016-02-01 16:29:19 +0000685 MachineBasicBlock::iterator End = MBB.end();
Geoff Berrya5335642016-05-06 16:34:59 +0000686 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
687 if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000688 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 ++MBBI;
Geoff Berrya5335642016-05-06 16:34:59 +0000690 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000691 if (HasFP) {
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000692 // Only set up FP if we actually need to. Frame pointer is fp =
693 // sp - fixedobject - 16.
694 int FPOffset = AFI->getCalleeSavedStackSize() - 16;
Geoff Berrya5335642016-05-06 16:34:59 +0000695 if (CombineSPBump)
696 FPOffset += AFI->getLocalStackSize();
Chad Rosier27c352d2016-03-14 18:24:34 +0000697
Tim Northover3b0846e2014-05-24 12:50:23 +0000698 // Issue sub fp, sp, FPOffset or
699 // mov fp,sp when FPOffset is zero.
700 // Note: All stores of callee-saved registers are marked as "FrameSetup".
701 // This code marks the instruction(s) that set the FP also.
702 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
703 MachineInstr::FrameSetup);
704 }
705
Martin Storsjo2778fd02017-12-20 06:51:45 +0000706 if (windowsRequiresStackProbe(MF, NumBytes)) {
707 uint32_t NumWords = NumBytes >> 4;
708
709 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
710 .addImm(NumWords)
711 .setMIFlags(MachineInstr::FrameSetup);
712
713 switch (MF.getTarget().getCodeModel()) {
David Green9dd1d452018-08-22 11:31:39 +0000714 case CodeModel::Tiny:
Martin Storsjo2778fd02017-12-20 06:51:45 +0000715 case CodeModel::Small:
716 case CodeModel::Medium:
717 case CodeModel::Kernel:
718 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
719 .addExternalSymbol("__chkstk")
720 .addReg(AArch64::X15, RegState::Implicit)
721 .setMIFlags(MachineInstr::FrameSetup);
722 break;
723 case CodeModel::Large:
724 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
725 .addReg(AArch64::X16, RegState::Define)
726 .addExternalSymbol("__chkstk")
727 .addExternalSymbol("__chkstk")
728 .setMIFlags(MachineInstr::FrameSetup);
729
730 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR))
731 .addReg(AArch64::X16, RegState::Kill)
732 .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
733 .setMIFlags(MachineInstr::FrameSetup);
734 break;
735 }
736
737 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
738 .addReg(AArch64::SP, RegState::Kill)
739 .addReg(AArch64::X15, RegState::Kill)
740 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
741 .setMIFlags(MachineInstr::FrameSetup);
742 NumBytes = 0;
743 }
744
Tim Northover3b0846e2014-05-24 12:50:23 +0000745 // Allocate space for the rest of the frame.
Chad Rosier27c352d2016-03-14 18:24:34 +0000746 if (NumBytes) {
747 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
748 unsigned scratchSPReg = AArch64::SP;
Kristof Beyls17cb8982015-04-09 08:49:47 +0000749
Chad Rosier27c352d2016-03-14 18:24:34 +0000750 if (NeedsRealignment) {
751 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
752 assert(scratchSPReg != AArch64::NoRegister);
753 }
Kristof Beyls17cb8982015-04-09 08:49:47 +0000754
Chad Rosier27c352d2016-03-14 18:24:34 +0000755 // If we're a leaf function, try using the red zone.
756 if (!canUseRedZone(MF))
757 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
758 // the correct value here, as NumBytes also includes padding bytes,
759 // which shouldn't be counted here.
760 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
761 MachineInstr::FrameSetup);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000762
Chad Rosier27c352d2016-03-14 18:24:34 +0000763 if (NeedsRealignment) {
Matthias Braun941a7052016-07-28 18:40:00 +0000764 const unsigned Alignment = MFI.getMaxAlignment();
Chad Rosier27c352d2016-03-14 18:24:34 +0000765 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
766 assert(NrBitsToZero > 1);
767 assert(scratchSPReg != AArch64::SP);
Kristof Beyls17cb8982015-04-09 08:49:47 +0000768
Chad Rosier27c352d2016-03-14 18:24:34 +0000769 // SUB X9, SP, NumBytes
770 // -- X9 is temporary register, so shouldn't contain any live data here,
771 // -- free to use. This is already produced by emitFrameOffset above.
772 // AND SP, X9, 0b11111...0000
773 // The logical immediates have a non-trivial encoding. The following
774 // formula computes the encoded immediate with all ones but
775 // NrBitsToZero zero bits as least significant bits.
776 uint32_t andMaskEncoded = (1 << 12) // = N
777 | ((64 - NrBitsToZero) << 6) // immr
778 | ((64 - NrBitsToZero - 1) << 0); // imms
779
780 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
781 .addReg(scratchSPReg, RegState::Kill)
782 .addImm(andMaskEncoded);
783 AFI->setStackRealigned(true);
784 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000785 }
786
787 // If we need a base pointer, set it up here. It's whatever the value of the
788 // stack pointer is at this point. Any variable size objects will be allocated
789 // after this, so we can still use the base pointer to reference locals.
790 //
791 // FIXME: Clarify FrameSetup flags here.
792 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
793 // needed.
Kristof Beyls17cb8982015-04-09 08:49:47 +0000794 if (RegInfo->hasBasePointer(MF)) {
795 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
796 false);
797 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000798
799 if (needsFrameMoves) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000800 const DataLayout &TD = MF.getDataLayout();
801 const int StackGrowth = -TD.getPointerSize(0);
Tim Northover3b0846e2014-05-24 12:50:23 +0000802 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +0000803 // An example of the prologue:
804 //
805 // .globl __foo
806 // .align 2
807 // __foo:
808 // Ltmp0:
809 // .cfi_startproc
810 // .cfi_personality 155, ___gxx_personality_v0
811 // Leh_func_begin:
812 // .cfi_lsda 16, Lexception33
813 //
814 // stp xa,bx, [sp, -#offset]!
815 // ...
816 // stp x28, x27, [sp, #offset-32]
817 // stp fp, lr, [sp, #offset-16]
818 // add fp, sp, #offset - 16
819 // sub sp, sp, #1360
820 //
821 // The Stack:
822 // +-------------------------------------------+
823 // 10000 | ........ | ........ | ........ | ........ |
824 // 10004 | ........ | ........ | ........ | ........ |
825 // +-------------------------------------------+
826 // 10008 | ........ | ........ | ........ | ........ |
827 // 1000c | ........ | ........ | ........ | ........ |
828 // +===========================================+
829 // 10010 | X28 Register |
830 // 10014 | X28 Register |
831 // +-------------------------------------------+
832 // 10018 | X27 Register |
833 // 1001c | X27 Register |
834 // +===========================================+
835 // 10020 | Frame Pointer |
836 // 10024 | Frame Pointer |
837 // +-------------------------------------------+
838 // 10028 | Link Register |
839 // 1002c | Link Register |
840 // +===========================================+
841 // 10030 | ........ | ........ | ........ | ........ |
842 // 10034 | ........ | ........ | ........ | ........ |
843 // +-------------------------------------------+
844 // 10038 | ........ | ........ | ........ | ........ |
845 // 1003c | ........ | ........ | ........ | ........ |
846 // +-------------------------------------------+
847 //
848 // [sp] = 10030 :: >>initial value<<
849 // sp = 10020 :: stp fp, lr, [sp, #-16]!
850 // fp = sp == 10020 :: mov fp, sp
851 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
852 // sp == 10010 :: >>final value<<
853 //
854 // The frame pointer (w29) points to address 10020. If we use an offset of
855 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
856 // for w27, and -32 for w28:
857 //
858 // Ltmp1:
859 // .cfi_def_cfa w29, 16
860 // Ltmp2:
861 // .cfi_offset w30, -8
862 // Ltmp3:
863 // .cfi_offset w29, -16
864 // Ltmp4:
865 // .cfi_offset w27, -24
866 // Ltmp5:
867 // .cfi_offset w28, -32
868
869 if (HasFP) {
870 // Define the current CFA rule to use the provided FP.
871 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000872 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
873 nullptr, Reg, 2 * StackGrowth - FixedObject));
Tim Northover3b0846e2014-05-24 12:50:23 +0000874 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000875 .addCFIIndex(CFIIndex)
876 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000877 } else {
878 // Encode the stack size of the leaf function.
Matthias Braunf23ef432016-11-30 23:48:42 +0000879 unsigned CFIIndex = MF.addFrameInst(
Matthias Braun941a7052016-07-28 18:40:00 +0000880 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
Tim Northover3b0846e2014-05-24 12:50:23 +0000881 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000882 .addCFIIndex(CFIIndex)
883 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover3b0846e2014-05-24 12:50:23 +0000884 }
885
Geoff Berry62d47252016-02-25 16:36:08 +0000886 // Now emit the moves for whatever callee saved regs we have (including FP,
887 // LR if those are saved).
888 emitCalleeSavedFrameMoves(MBB, MBBI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000889 }
890}
891
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000892static void InsertReturnAddressAuth(MachineFunction &MF,
893 MachineBasicBlock &MBB) {
894 if (!ShouldSignReturnAddress(MF))
895 return;
896 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
897 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
898
899 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
900 DebugLoc DL;
901 if (MBBI != MBB.end())
902 DL = MBBI->getDebugLoc();
903
904 // The AUTIASP instruction assembles to a hint instruction before v8.3a so
905 // this instruction can safely used for any v8a architecture.
906 // From v8.3a onwards there are optimised authenticate LR and return
907 // instructions, namely RETA{A,B}, that can be used instead.
908 if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() &&
909 MBBI->getOpcode() == AArch64::RET_ReallyLR) {
910 BuildMI(MBB, MBBI, DL, TII->get(AArch64::RETAA)).copyImplicitOps(*MBBI);
911 MBB.erase(MBBI);
912 } else {
913 BuildMI(MBB, MBBI, DL, TII->get(AArch64::AUTIASP))
914 .setMIFlag(MachineInstr::FrameDestroy);
915 }
916}
917
Tim Northover3b0846e2014-05-24 12:50:23 +0000918void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
919 MachineBasicBlock &MBB) const {
920 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Matthias Braun941a7052016-07-28 18:40:00 +0000921 MachineFrameInfo &MFI = MF.getFrameInfo();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000922 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Ahmed Bougacha66834ec2015-12-16 22:54:06 +0000923 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
Quentin Colombet61b305e2015-05-05 17:38:16 +0000924 DebugLoc DL;
925 bool IsTailCallReturn = false;
926 if (MBB.end() != MBBI) {
927 DL = MBBI->getDebugLoc();
928 unsigned RetOpcode = MBBI->getOpcode();
929 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
930 RetOpcode == AArch64::TCRETURNri;
931 }
Matthias Braun941a7052016-07-28 18:40:00 +0000932 int NumBytes = MFI.getStackSize();
Tim Northover3b0846e2014-05-24 12:50:23 +0000933 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
934
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000935 // All calls are tail calls in GHC calling conv, and functions have no
936 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000937 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +0000938 return;
939
Kristof Beyls17cb8982015-04-09 08:49:47 +0000940 // Initial and residual are named for consistency with the prologue. Note that
Tim Northover3b0846e2014-05-24 12:50:23 +0000941 // in the epilogue, the residual adjustment is executed first.
942 uint64_t ArgumentPopSize = 0;
Quentin Colombet61b305e2015-05-05 17:38:16 +0000943 if (IsTailCallReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000944 MachineOperand &StackAdjust = MBBI->getOperand(1);
945
946 // For a tail-call in a callee-pops-arguments environment, some or all of
947 // the stack may actually be in use for the call's arguments, this is
948 // calculated during LowerCall and consumed here...
949 ArgumentPopSize = StackAdjust.getImm();
950 } else {
951 // ... otherwise the amount to pop is *all* of the argument space,
952 // conveniently stored in the MachineFunctionInfo by
953 // LowerFormalArguments. This will, of course, be zero for the C calling
954 // convention.
955 ArgumentPopSize = AFI->getArgumentStackToRestore();
956 }
957
958 // The stack frame should be like below,
959 //
960 // ---------------------- ---
961 // | | |
962 // | BytesInStackArgArea| CalleeArgStackSize
963 // | (NumReusableBytes) | (of tail call)
964 // | | ---
965 // | | |
966 // ---------------------| --- |
967 // | | | |
968 // | CalleeSavedReg | | |
Geoff Berry04bf91a2016-02-01 16:29:19 +0000969 // | (CalleeSavedStackSize)| | |
Tim Northover3b0846e2014-05-24 12:50:23 +0000970 // | | | |
971 // ---------------------| | NumBytes
972 // | | StackSize (StackAdjustUp)
973 // | LocalStackSize | | |
974 // | (covering callee | | |
975 // | args) | | |
976 // | | | |
977 // ---------------------- --- ---
978 //
979 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
980 // = StackSize + ArgumentPopSize
981 //
982 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
983 // it as the 2nd argument of AArch64ISD::TC_RETURN.
Tim Northover3b0846e2014-05-24 12:50:23 +0000984
Luke Cheeseman64dcdec2018-08-17 12:53:22 +0000985 auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); });
986
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000987 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +0000988 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000989 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
990
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000991 uint64_t AfterCSRPopSize = ArgumentPopSize;
Martin Storsjoeacf4e42017-08-01 21:13:54 +0000992 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
Geoff Berrya5335642016-05-06 16:34:59 +0000993 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000994 // Assume we can't combine the last pop with the sp restore.
Geoff Berrya5335642016-05-06 16:34:59 +0000995
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +0000996 if (!CombineSPBump && PrologueSaveSize != 0) {
997 MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
998 // Converting the last ldp to a post-index ldp is valid only if the last
999 // ldp's offset is 0.
1000 const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
1001 // If the offset is 0, convert it to a post-index ldp.
1002 if (OffsetOp.getImm() == 0) {
1003 convertCalleeSaveRestoreToSPPrePostIncDec(MBB, Pop, DL, TII,
1004 PrologueSaveSize);
1005 } else {
1006 // If not, make sure to emit an add after the last ldp.
1007 // We're doing this by transfering the size to be restored from the
1008 // adjustment *before* the CSR pops to the adjustment *after* the CSR
1009 // pops.
1010 AfterCSRPopSize += PrologueSaveSize;
1011 }
1012 }
Geoff Berrya5335642016-05-06 16:34:59 +00001013
Tim Northover3b0846e2014-05-24 12:50:23 +00001014 // Move past the restores of the callee-saved registers.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001015 // If we plan on combining the sp bump of the local stack size and the callee
1016 // save stack size, we might need to adjust the CSR save and restore offsets.
Quentin Colombet61b305e2015-05-05 17:38:16 +00001017 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
Matthias Braun45419292015-12-17 03:18:47 +00001018 MachineBasicBlock::iterator Begin = MBB.begin();
1019 while (LastPopI != Begin) {
1020 --LastPopI;
Geoff Berry04bf91a2016-02-01 16:29:19 +00001021 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001022 ++LastPopI;
Matthias Braun45419292015-12-17 03:18:47 +00001023 break;
Geoff Berrya5335642016-05-06 16:34:59 +00001024 } else if (CombineSPBump)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001025 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +00001026 }
Geoff Berrya5335642016-05-06 16:34:59 +00001027
1028 // If there is a single SP update, insert it before the ret and we're done.
1029 if (CombineSPBump) {
1030 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001031 NumBytes + AfterCSRPopSize, TII,
Geoff Berrya5335642016-05-06 16:34:59 +00001032 MachineInstr::FrameDestroy);
1033 return;
1034 }
1035
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001036 NumBytes -= PrologueSaveSize;
Tim Northover3b0846e2014-05-24 12:50:23 +00001037 assert(NumBytes >= 0 && "Negative stack allocation size!?");
1038
1039 if (!hasFP(MF)) {
Geoff Berrya1c62692016-02-23 16:54:36 +00001040 bool RedZone = canUseRedZone(MF);
Tim Northover3b0846e2014-05-24 12:50:23 +00001041 // If this was a redzone leaf function, we don't need to restore the
Geoff Berrya1c62692016-02-23 16:54:36 +00001042 // stack pointer (but we may need to pop stack args for fastcc).
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001043 if (RedZone && AfterCSRPopSize == 0)
Geoff Berrya1c62692016-02-23 16:54:36 +00001044 return;
1045
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001046 bool NoCalleeSaveRestore = PrologueSaveSize == 0;
Geoff Berrya1c62692016-02-23 16:54:36 +00001047 int StackRestoreBytes = RedZone ? 0 : NumBytes;
1048 if (NoCalleeSaveRestore)
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001049 StackRestoreBytes += AfterCSRPopSize;
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001050
Geoff Berrya1c62692016-02-23 16:54:36 +00001051 // If we were able to combine the local stack pop with the argument pop,
1052 // then we're done.
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001053 bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0;
1054
1055 // If we're done after this, make sure to help the load store optimizer.
1056 if (Done)
1057 adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI);
1058
1059 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
1060 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
1061 if (Done)
Geoff Berrya1c62692016-02-23 16:54:36 +00001062 return;
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001063
Geoff Berrya1c62692016-02-23 16:54:36 +00001064 NumBytes = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001065 }
1066
1067 // Restore the original stack pointer.
1068 // FIXME: Rather than doing the math here, we should instead just use
1069 // non-post-indexed loads for the restores if we aren't actually going to
1070 // be able to save any instructions.
Matthias Braun941a7052016-07-28 18:40:00 +00001071 if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
Tim Northover3b0846e2014-05-24 12:50:23 +00001072 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001073 -AFI->getCalleeSavedStackSize() + 16, TII,
1074 MachineInstr::FrameDestroy);
Chad Rosier6d986552016-03-14 18:17:41 +00001075 else if (NumBytes)
1076 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
1077 MachineInstr::FrameDestroy);
Geoff Berrya1c62692016-02-23 16:54:36 +00001078
1079 // This must be placed after the callee-save restore code because that code
1080 // assumes the SP is at the same location as it was after the callee-save save
1081 // code in the prologue.
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001082 if (AfterCSRPopSize) {
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001083 // Find an insertion point for the first ldp so that it goes before the
1084 // shadow call stack epilog instruction. This ensures that the restore of
1085 // lr from x18 is placed after the restore from sp.
1086 auto FirstSPPopI = MBB.getFirstTerminator();
1087 while (FirstSPPopI != Begin) {
1088 auto Prev = std::prev(FirstSPPopI);
1089 if (Prev->getOpcode() != AArch64::LDRXpre ||
1090 Prev->getOperand(0).getReg() == AArch64::SP)
1091 break;
1092 FirstSPPopI = Prev;
1093 }
1094
Francis Visoiu Mistrihc855e922018-04-27 15:30:54 +00001095 adaptForLdStOpt(MBB, FirstSPPopI, LastPopI);
1096
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001097 emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP,
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001098 AfterCSRPopSize, TII, MachineInstr::FrameDestroy);
1099 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001100}
1101
Tim Northover3b0846e2014-05-24 12:50:23 +00001102/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1103/// debug info. It's the same as what we use for resolving the code-gen
1104/// references for now. FIXME: This can go wrong when references are
1105/// SP-relative and simple call frames aren't used.
1106int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
1107 int FI,
1108 unsigned &FrameReg) const {
1109 return resolveFrameIndexReference(MF, FI, FrameReg);
1110}
1111
1112int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
1113 int FI, unsigned &FrameReg,
1114 bool PreferFP) const {
Matthias Braun941a7052016-07-28 18:40:00 +00001115 const MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001116 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001117 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001118 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001119 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1120 bool IsWin64 =
Matthias Braunf1caa282017-12-15 22:22:58 +00001121 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
Martin Storsjoeacf4e42017-08-01 21:13:54 +00001122 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0;
1123 int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16;
Matthias Braun941a7052016-07-28 18:40:00 +00001124 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1125 bool isFixed = MFI.isFixedObjectIndex(FI);
Geoff Berry08ab8c952018-04-26 18:50:45 +00001126 bool isCSR = !isFixed && MFI.getObjectOffset(FI) >=
1127 -((int)AFI->getCalleeSavedStackSize());
Tim Northover3b0846e2014-05-24 12:50:23 +00001128
1129 // Use frame pointer to reference fixed objects. Use it for locals if
Kristof Beyls17cb8982015-04-09 08:49:47 +00001130 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1131 // reliable as a base). Make sure useFPForScavengingIndex() does the
1132 // right thing for the emergency spill slot.
Tim Northover3b0846e2014-05-24 12:50:23 +00001133 bool UseFP = false;
1134 if (AFI->hasStackFrame()) {
1135 // Note: Keeping the following as multiple 'if' statements rather than
1136 // merging to a single expression for readability.
1137 //
1138 // Argument access should always use the FP.
1139 if (isFixed) {
1140 UseFP = hasFP(MF);
Geoff Berry08ab8c952018-04-26 18:50:45 +00001141 } else if (isCSR && RegInfo->needsStackRealignment(MF)) {
1142 // References to the CSR area must use FP if we're re-aligning the stack
1143 // since the dynamically-sized alignment padding is between the SP/BP and
1144 // the CSR area.
1145 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1146 UseFP = true;
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001147 } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001148 // If the FPOffset is negative, we have to keep in mind that the
1149 // available offset range for negative offsets is smaller than for
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001150 // positive ones. If an offset is
Tim Northover3b0846e2014-05-24 12:50:23 +00001151 // available via the FP and the SP, use whichever is closest.
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001152 bool FPOffsetFits = FPOffset >= -256;
1153 PreferFP |= Offset > -FPOffset;
1154
1155 if (MFI.hasVarSizedObjects()) {
1156 // If we have variable sized objects, we can use either FP or BP, as the
1157 // SP offset is unknown. We can use the base pointer if we have one and
1158 // FP is not preferred. If not, we're stuck with using FP.
1159 bool CanUseBP = RegInfo->hasBasePointer(MF);
1160 if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1161 UseFP = PreferFP;
1162 else if (!CanUseBP) // Can't use BP. Forced to use FP.
1163 UseFP = true;
1164 // else we can use BP and FP, but the offset from FP won't fit.
1165 // That will make us scavenge registers which we can probably avoid by
1166 // using BP. If it won't fit for BP either, we'll scavenge anyway.
Francis Visoiu Mistrih64639222018-04-11 12:36:55 +00001167 } else if (FPOffset >= 0) {
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001168 // Use SP or FP, whichever gives us the best chance of the offset
1169 // being in range for direct access. If the FPOffset is positive,
1170 // that'll always be best, as the SP will be even further away.
Tim Northover3b0846e2014-05-24 12:50:23 +00001171 UseFP = true;
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001172 } else {
1173 // We have the choice between FP and (SP or BP).
1174 if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1175 UseFP = true;
1176 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 }
1178 }
1179
Geoff Berry08ab8c952018-04-26 18:50:45 +00001180 assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
Kristof Beyls17cb8982015-04-09 08:49:47 +00001181 "In the presence of dynamic stack pointer realignment, "
Geoff Berry08ab8c952018-04-26 18:50:45 +00001182 "non-argument/CSR objects cannot be accessed through the frame pointer");
Kristof Beyls17cb8982015-04-09 08:49:47 +00001183
Tim Northover3b0846e2014-05-24 12:50:23 +00001184 if (UseFP) {
1185 FrameReg = RegInfo->getFrameRegister(MF);
1186 return FPOffset;
1187 }
1188
1189 // Use the base pointer if we have one.
1190 if (RegInfo->hasBasePointer(MF))
1191 FrameReg = RegInfo->getBaseRegister();
1192 else {
Francis Visoiu Mistrihf2c22052018-04-10 11:29:40 +00001193 assert(!MFI.hasVarSizedObjects() &&
1194 "Can't use SP when we have var sized objects.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001195 FrameReg = AArch64::SP;
1196 // If we're using the red zone for this function, the SP won't actually
1197 // be adjusted, so the offsets will be negative. They're also all
1198 // within range of the signed 9-bit immediate instructions.
1199 if (canUseRedZone(MF))
1200 Offset -= AFI->getLocalStackSize();
1201 }
1202
1203 return Offset;
1204}
1205
1206static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00001207 // Do not set a kill flag on values that are also marked as live-in. This
1208 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1209 // callee saved registers.
1210 // Omitting the kill flags is conservatively correct even if the live-in
1211 // is not used after all.
1212 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1213 return getKillRegState(!IsLiveIn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001214}
1215
Manman Ren57518142016-04-11 21:08:06 +00001216static bool produceCompactUnwindFrame(MachineFunction &MF) {
1217 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
Matthias Braunf1caa282017-12-15 22:22:58 +00001218 AttributeList Attrs = MF.getFunction().getAttributes();
Manman Ren57518142016-04-11 21:08:06 +00001219 return Subtarget.isTargetMachO() &&
1220 !(Subtarget.getTargetLowering()->supportSwiftError() &&
1221 Attrs.hasAttrSomewhere(Attribute::SwiftError));
1222}
1223
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001224namespace {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001225
Geoff Berry29d4a692016-02-01 19:07:06 +00001226struct RegPairInfo {
Eugene Zelenko11f69072017-01-25 00:29:26 +00001227 unsigned Reg1 = AArch64::NoRegister;
1228 unsigned Reg2 = AArch64::NoRegister;
Geoff Berry29d4a692016-02-01 19:07:06 +00001229 int FrameIdx;
1230 int Offset;
Sander de Smalen2d77e782018-09-12 12:10:22 +00001231 enum RegType { GPR, FPR64, FPR128 } Type;
Eugene Zelenko11f69072017-01-25 00:29:26 +00001232
1233 RegPairInfo() = default;
1234
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001235 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
Geoff Berry29d4a692016-02-01 19:07:06 +00001236};
Eugene Zelenko11f69072017-01-25 00:29:26 +00001237
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001238} // end anonymous namespace
Geoff Berry29d4a692016-02-01 19:07:06 +00001239
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001240static void computeCalleeSaveRegisterPairs(
1241 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001242 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
1243 bool &NeedShadowCallStackProlog) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001244
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001245 if (CSI.empty())
1246 return;
1247
1248 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001249 MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001250 CallingConv::ID CC = MF.getFunction().getCallingConv();
Tim Northover3b0846e2014-05-24 12:50:23 +00001251 unsigned Count = CSI.size();
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001252 (void)CC;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001253 // MachO's compact unwind format relies on all registers being stored in
1254 // pairs.
Manman Ren57518142016-04-11 21:08:06 +00001255 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001256 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001257 (Count & 1) == 0) &&
1258 "Odd number of callee-saved regs to spill!");
Martin Storsjo68266fa2017-07-13 17:03:12 +00001259 int Offset = AFI->getCalleeSavedStackSize();
1260
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001261 for (unsigned i = 0; i < Count; ++i) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001262 RegPairInfo RPI;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001263 RPI.Reg1 = CSI[i].getReg();
1264
Sander de Smalen71403632018-09-12 09:44:46 +00001265 if (AArch64::GPR64RegClass.contains(RPI.Reg1))
1266 RPI.Type = RegPairInfo::GPR;
1267 else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
1268 RPI.Type = RegPairInfo::FPR64;
Sander de Smalen2d77e782018-09-12 12:10:22 +00001269 else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
1270 RPI.Type = RegPairInfo::FPR128;
Sander de Smalen71403632018-09-12 09:44:46 +00001271 else
1272 llvm_unreachable("Unsupported register class.");
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001273
1274 // Add the next reg to the pair if it is in the same register class.
1275 if (i + 1 < Count) {
1276 unsigned NextReg = CSI[i + 1].getReg();
Sander de Smalen71403632018-09-12 09:44:46 +00001277 switch (RPI.Type) {
1278 case RegPairInfo::GPR:
1279 if (AArch64::GPR64RegClass.contains(NextReg))
1280 RPI.Reg2 = NextReg;
1281 break;
1282 case RegPairInfo::FPR64:
1283 if (AArch64::FPR64RegClass.contains(NextReg))
1284 RPI.Reg2 = NextReg;
1285 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +00001286 case RegPairInfo::FPR128:
1287 if (AArch64::FPR128RegClass.contains(NextReg))
1288 RPI.Reg2 = NextReg;
1289 break;
Sander de Smalen71403632018-09-12 09:44:46 +00001290 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001291 }
Geoff Berry29d4a692016-02-01 19:07:06 +00001292
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001293 // If either of the registers to be saved is the lr register, it means that
1294 // we also need to save lr in the shadow call stack.
1295 if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) &&
1296 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
Nick Desaulniers287a3be2018-09-07 20:58:57 +00001297 if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001298 report_fatal_error("Must reserve x18 to use shadow call stack");
1299 NeedShadowCallStackProlog = true;
1300 }
1301
Tim Northover3b0846e2014-05-24 12:50:23 +00001302 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1303 // list to come in sorted by frame index so that we can issue the store
1304 // pair instructions directly. Assert if we see anything otherwise.
1305 //
1306 // The order of the registers in the list is controlled by
1307 // getCalleeSavedRegs(), so they will always be in-order, as well.
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001308 assert((!RPI.isPaired() ||
1309 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 "Out of order callee saved regs!");
Geoff Berry29d4a692016-02-01 19:07:06 +00001311
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001312 // MachO's compact unwind format relies on all registers being stored in
1313 // adjacent register pairs.
Manman Ren57518142016-04-11 21:08:06 +00001314 assert((!produceCompactUnwindFrame(MF) ||
Roman Levenstein2792b3f2016-03-10 04:35:09 +00001315 CC == CallingConv::PreserveMost ||
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001316 (RPI.isPaired() &&
1317 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
1318 RPI.Reg1 + 1 == RPI.Reg2))) &&
1319 "Callee-save registers not saved as adjacent register pair!");
1320
1321 RPI.FrameIdx = CSI[i].getFrameIdx();
1322
Sander de Smalen2d77e782018-09-12 12:10:22 +00001323 int Scale = RPI.Type == RegPairInfo::FPR128 ? 16 : 8;
1324 Offset -= RPI.isPaired() ? 2 * Scale : Scale;
1325
1326 // Round up size of non-pair to pair size if we need to pad the
1327 // callee-save area to ensure 16-byte alignment.
1328 if (AFI->hasCalleeSaveStackFreeSpace() &&
1329 RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired()) {
1330 Offset -= 8;
1331 assert(Offset % 16 == 0);
Matthias Braun941a7052016-07-28 18:40:00 +00001332 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
1333 MFI.setObjectAlignment(RPI.FrameIdx, 16);
Sander de Smalen2d77e782018-09-12 12:10:22 +00001334 }
1335
1336 assert(Offset % Scale == 0);
1337 RPI.Offset = Offset / Scale;
Geoff Berry29d4a692016-02-01 19:07:06 +00001338 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
1339 "Offset out of bounds for LDP/STP immediate");
1340
1341 RegPairs.push_back(RPI);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001342 if (RPI.isPaired())
1343 ++i;
Geoff Berry29d4a692016-02-01 19:07:06 +00001344 }
1345}
1346
1347bool AArch64FrameLowering::spillCalleeSavedRegisters(
1348 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1349 const std::vector<CalleeSavedInfo> &CSI,
1350 const TargetRegisterInfo *TRI) const {
1351 MachineFunction &MF = *MBB.getParent();
1352 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1353 DebugLoc DL;
1354 SmallVector<RegPairInfo, 8> RegPairs;
1355
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001356 bool NeedShadowCallStackProlog = false;
1357 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1358 NeedShadowCallStackProlog);
Matthias Braun88c8c982017-05-27 03:38:02 +00001359 const MachineRegisterInfo &MRI = MF.getRegInfo();
Geoff Berry29d4a692016-02-01 19:07:06 +00001360
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001361 if (NeedShadowCallStackProlog) {
1362 // Shadow call stack prolog: str x30, [x18], #8
1363 BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost))
1364 .addReg(AArch64::X18, RegState::Define)
1365 .addReg(AArch64::LR)
1366 .addReg(AArch64::X18)
1367 .addImm(8)
1368 .setMIFlag(MachineInstr::FrameSetup);
1369
1370 // This instruction also makes x18 live-in to the entry block.
1371 MBB.addLiveIn(AArch64::X18);
1372 }
1373
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001374 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
Geoff Berry29d4a692016-02-01 19:07:06 +00001375 ++RPII) {
1376 RegPairInfo RPI = *RPII;
1377 unsigned Reg1 = RPI.Reg1;
1378 unsigned Reg2 = RPI.Reg2;
1379 unsigned StrOpc;
1380
Geoff Berrya5335642016-05-06 16:34:59 +00001381 // Issue sequence of spills for cs regs. The first spill may be converted
1382 // to a pre-decrement store later by emitPrologue if the callee-save stack
1383 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001384 // For example:
Geoff Berrya5335642016-05-06 16:34:59 +00001385 // stp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001386 // stp x20, x19, [sp, #16] // addImm(+2)
1387 // stp fp, lr, [sp, #32] // addImm(+4)
1388 // Rationale: This sequence saves uop updates compared to a sequence of
1389 // pre-increment spills like stp xi,xj,[sp,#-16]!
Geoff Berry29d4a692016-02-01 19:07:06 +00001390 // Note: Similar rationale and sequence for restores in epilog.
Sander de Smalen71403632018-09-12 09:44:46 +00001391 unsigned Size, Align;
1392 switch (RPI.Type) {
1393 case RegPairInfo::GPR:
1394 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1395 Size = 8;
1396 Align = 8;
1397 break;
1398 case RegPairInfo::FPR64:
1399 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1400 Size = 8;
1401 Align = 8;
1402 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +00001403 case RegPairInfo::FPR128:
1404 StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
1405 Size = 16;
1406 Align = 16;
1407 break;
Sander de Smalen71403632018-09-12 09:44:46 +00001408 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001409 LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
1410 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1411 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1412 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1413 dbgs() << ")\n");
Geoff Berry29d4a692016-02-01 19:07:06 +00001414
Tim Northover3b0846e2014-05-24 12:50:23 +00001415 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
Matthias Braun88c8c982017-05-27 03:38:02 +00001416 if (!MRI.isReserved(Reg1))
1417 MBB.addLiveIn(Reg1);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001418 if (RPI.isPaired()) {
Matthias Braun88c8c982017-05-27 03:38:02 +00001419 if (!MRI.isReserved(Reg2))
1420 MBB.addLiveIn(Reg2);
Geoff Berrya5335642016-05-06 16:34:59 +00001421 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
Geoff Berryc3764062016-04-15 15:16:19 +00001422 MIB.addMemOperand(MF.getMachineMemOperand(
1423 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
Sander de Smalen71403632018-09-12 09:44:46 +00001424 MachineMemOperand::MOStore, Size, Align));
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001425 }
Geoff Berrya5335642016-05-06 16:34:59 +00001426 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1427 .addReg(AArch64::SP)
Sander de Smalen71403632018-09-12 09:44:46 +00001428 .addImm(RPI.Offset) // [sp, #offset*scale],
1429 // where factor*scale is implicit
Geoff Berrya5335642016-05-06 16:34:59 +00001430 .setMIFlag(MachineInstr::FrameSetup);
Geoff Berryc3764062016-04-15 15:16:19 +00001431 MIB.addMemOperand(MF.getMachineMemOperand(
1432 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
Sander de Smalen71403632018-09-12 09:44:46 +00001433 MachineMemOperand::MOStore, Size, Align));
Tim Northover3b0846e2014-05-24 12:50:23 +00001434 }
1435 return true;
1436}
1437
1438bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1439 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001440 std::vector<CalleeSavedInfo> &CSI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001441 const TargetRegisterInfo *TRI) const {
1442 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001443 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001444 DebugLoc DL;
Geoff Berry29d4a692016-02-01 19:07:06 +00001445 SmallVector<RegPairInfo, 8> RegPairs;
Tim Northover3b0846e2014-05-24 12:50:23 +00001446
1447 if (MI != MBB.end())
1448 DL = MI->getDebugLoc();
1449
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001450 bool NeedShadowCallStackProlog = false;
1451 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs,
1452 NeedShadowCallStackProlog);
Geoff Berry29d4a692016-02-01 19:07:06 +00001453
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001454 auto EmitMI = [&](const RegPairInfo &RPI) {
Geoff Berry29d4a692016-02-01 19:07:06 +00001455 unsigned Reg1 = RPI.Reg1;
1456 unsigned Reg2 = RPI.Reg2;
1457
Geoff Berrya5335642016-05-06 16:34:59 +00001458 // Issue sequence of restores for cs regs. The last restore may be converted
1459 // to a post-increment load later by emitEpilogue if the callee-save stack
1460 // area allocation can't be combined with the local stack area allocation.
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 // For example:
1462 // ldp fp, lr, [sp, #32] // addImm(+4)
1463 // ldp x20, x19, [sp, #16] // addImm(+2)
Geoff Berrya5335642016-05-06 16:34:59 +00001464 // ldp x22, x21, [sp, #0] // addImm(+0)
Tim Northover3b0846e2014-05-24 12:50:23 +00001465 // Note: see comment in spillCalleeSavedRegisters()
1466 unsigned LdrOpc;
Sander de Smalen71403632018-09-12 09:44:46 +00001467 unsigned Size, Align;
1468 switch (RPI.Type) {
1469 case RegPairInfo::GPR:
1470 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1471 Size = 8;
1472 Align = 8;
1473 break;
1474 case RegPairInfo::FPR64:
1475 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1476 Size = 8;
1477 Align = 8;
1478 break;
Sander de Smalen2d77e782018-09-12 12:10:22 +00001479 case RegPairInfo::FPR128:
1480 LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
1481 Size = 16;
1482 Align = 16;
1483 break;
Sander de Smalen71403632018-09-12 09:44:46 +00001484 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001485 LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
1486 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
1487 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1488 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
1489 dbgs() << ")\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001490
Tim Northover3b0846e2014-05-24 12:50:23 +00001491 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
Geoff Berryc3764062016-04-15 15:16:19 +00001492 if (RPI.isPaired()) {
Geoff Berrya5335642016-05-06 16:34:59 +00001493 MIB.addReg(Reg2, getDefRegState(true));
Geoff Berryc3764062016-04-15 15:16:19 +00001494 MIB.addMemOperand(MF.getMachineMemOperand(
1495 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
Sander de Smalen71403632018-09-12 09:44:46 +00001496 MachineMemOperand::MOLoad, Size, Align));
Geoff Berryc3764062016-04-15 15:16:19 +00001497 }
Geoff Berrya5335642016-05-06 16:34:59 +00001498 MIB.addReg(Reg1, getDefRegState(true))
1499 .addReg(AArch64::SP)
Sander de Smalen71403632018-09-12 09:44:46 +00001500 .addImm(RPI.Offset) // [sp, #offset*scale]
1501 // where factor*scale is implicit
Geoff Berrya5335642016-05-06 16:34:59 +00001502 .setMIFlag(MachineInstr::FrameDestroy);
Geoff Berryc3764062016-04-15 15:16:19 +00001503 MIB.addMemOperand(MF.getMachineMemOperand(
1504 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
Sander de Smalen71403632018-09-12 09:44:46 +00001505 MachineMemOperand::MOLoad, Size, Align));
Francis Visoiu Mistrih164560b2018-03-14 20:34:03 +00001506 };
1507
1508 if (ReverseCSRRestoreSeq)
1509 for (const RegPairInfo &RPI : reverse(RegPairs))
1510 EmitMI(RPI);
1511 else
1512 for (const RegPairInfo &RPI : RegPairs)
1513 EmitMI(RPI);
Peter Collingbournef11eb3e2018-04-04 21:55:44 +00001514
1515 if (NeedShadowCallStackProlog) {
1516 // Shadow call stack epilog: ldr x30, [x18, #-8]!
1517 BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre))
1518 .addReg(AArch64::X18, RegState::Define)
1519 .addReg(AArch64::LR, RegState::Define)
1520 .addReg(AArch64::X18)
1521 .addImm(-8)
1522 .setMIFlag(MachineInstr::FrameDestroy);
1523 }
1524
Tim Northover3b0846e2014-05-24 12:50:23 +00001525 return true;
1526}
1527
Matthias Braun02564862015-07-14 17:17:13 +00001528void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1529 BitVector &SavedRegs,
1530 RegScavenger *RS) const {
1531 // All calls are tail calls in GHC calling conv, and functions have no
1532 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +00001533 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Matthias Braun02564862015-07-14 17:17:13 +00001534 return;
1535
1536 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Tim Northover3b0846e2014-05-24 12:50:23 +00001537 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001538 MF.getSubtarget().getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00001539 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001540 unsigned UnspilledCSGPR = AArch64::NoRegister;
1541 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
Tim Northover3b0846e2014-05-24 12:50:23 +00001542
Martin Storsjo2778fd02017-12-20 06:51:45 +00001543 MachineFrameInfo &MFI = MF.getFrameInfo();
1544 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1545
1546 unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
1547 ? RegInfo->getBaseRegister()
1548 : (unsigned)AArch64::NoRegister;
1549
Matthias Braund78597e2017-04-21 22:42:08 +00001550 unsigned ExtraCSSpill = 0;
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001551 // Figure out which callee-saved registers to save/restore.
1552 for (unsigned i = 0; CSRegs[i]; ++i) {
1553 const unsigned Reg = CSRegs[i];
Tim Northover3b0846e2014-05-24 12:50:23 +00001554
Geoff Berry7e4ba3d2016-02-19 18:27:32 +00001555 // Add the base pointer register to SavedRegs if it is callee-save.
1556 if (Reg == BasePointerReg)
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001557 SavedRegs.set(Reg);
Tim Northover3b0846e2014-05-24 12:50:23 +00001558
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001559 bool RegUsed = SavedRegs.test(Reg);
1560 unsigned PairedReg = CSRegs[i ^ 1];
1561 if (!RegUsed) {
1562 if (AArch64::GPR64RegClass.contains(Reg) &&
1563 !RegInfo->isReservedReg(MF, Reg)) {
1564 UnspilledCSGPR = Reg;
1565 UnspilledCSGPRPaired = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001566 }
1567 continue;
1568 }
1569
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001570 // MachO's compact unwind format relies on all registers being stored in
1571 // pairs.
1572 // FIXME: the usual format is actually better if unwinding isn't needed.
Sander de Smalen2d77e782018-09-12 12:10:22 +00001573 if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister &&
1574 !SavedRegs.test(PairedReg)) {
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001575 SavedRegs.set(PairedReg);
Geoff Berry74cb7182016-05-16 20:52:28 +00001576 if (AArch64::GPR64RegClass.contains(PairedReg) &&
1577 !RegInfo->isReservedReg(MF, PairedReg))
Matthias Braund78597e2017-04-21 22:42:08 +00001578 ExtraCSSpill = PairedReg;
Tim Northover3b0846e2014-05-24 12:50:23 +00001579 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001580 }
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001581
Sander de Smalen2d77e782018-09-12 12:10:22 +00001582 // Calculates the callee saved stack size.
1583 unsigned CSStackSize = 0;
1584 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1585 const MachineRegisterInfo &MRI = MF.getRegInfo();
1586 for (unsigned Reg : SavedRegs.set_bits())
1587 CSStackSize += TRI->getRegSizeInBits(Reg, MRI) / 8;
1588
1589 // Save number of saved regs, so we can easily update CSStackSize later.
1590 unsigned NumSavedRegs = SavedRegs.count();
1591
1592 // The frame record needs to be created by saving the appropriate registers
1593 unsigned EstimatedStackSize = MFI.estimateStackSize(MF);
1594 if (hasFP(MF) ||
1595 windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
1596 SavedRegs.set(AArch64::FP);
1597 SavedRegs.set(AArch64::LR);
1598 }
1599
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001600 LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1601 for (unsigned Reg
1602 : SavedRegs.set_bits()) dbgs()
1603 << ' ' << printReg(Reg, RegInfo);
1604 dbgs() << "\n";);
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001605
1606 // If any callee-saved registers are used, the frame cannot be eliminated.
Sander de Smalen2d77e782018-09-12 12:10:22 +00001607 bool CanEliminateFrame = SavedRegs.count() == 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00001608
Tim Northover3b0846e2014-05-24 12:50:23 +00001609 // The CSR spill slots have not been allocated yet, so estimateStackSize
1610 // won't include them.
Kristof Beyls2af1e902017-05-30 06:58:41 +00001611 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
Sander de Smalen2d77e782018-09-12 12:10:22 +00001612 bool BigStack = (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
Tim Northover3b0846e2014-05-24 12:50:23 +00001613 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1614 AFI->setHasStackFrame(true);
1615
1616 // Estimate if we might need to scavenge a register at some point in order
1617 // to materialize a stack offset. If so, either spill one additional
1618 // callee-saved register or reserve a special spill slot to facilitate
1619 // register scavenging. If we already spilled an extra callee-saved register
1620 // above to keep the number of spills even, we don't need to do anything else
1621 // here.
Matthias Braund78597e2017-04-21 22:42:08 +00001622 if (BigStack) {
1623 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001624 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
1625 << " to get a scratch register.\n");
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001626 SavedRegs.set(UnspilledCSGPR);
1627 // MachO's compact unwind format relies on all registers being stored in
1628 // pairs, so if we need to spill one extra for BigStack, then we need to
1629 // store the pair.
Manman Ren57518142016-04-11 21:08:06 +00001630 if (produceCompactUnwindFrame(MF))
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001631 SavedRegs.set(UnspilledCSGPRPaired);
Matthias Braund78597e2017-04-21 22:42:08 +00001632 ExtraCSSpill = UnspilledCSGPRPaired;
Tim Northover3b0846e2014-05-24 12:50:23 +00001633 }
1634
1635 // If we didn't find an extra callee-saved register to spill, create
1636 // an emergency spill slot.
Matthias Braund78597e2017-04-21 22:42:08 +00001637 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001638 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1639 const TargetRegisterClass &RC = AArch64::GPR64RegClass;
1640 unsigned Size = TRI->getSpillSize(RC);
1641 unsigned Align = TRI->getSpillAlignment(RC);
1642 int FI = MFI.CreateStackObject(Size, Align, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001643 RS->addScavengingFrameIndex(FI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001644 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1645 << " as the emergency spill slot.\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001646 }
1647 }
Geoff Berry04bf91a2016-02-01 16:29:19 +00001648
Sander de Smalen2d77e782018-09-12 12:10:22 +00001649 // Adding the size of additional 64bit GPR saves.
1650 CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
1651 unsigned AlignedCSStackSize = alignTo(CSStackSize, 16);
1652 LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
1653 << EstimatedStackSize + AlignedCSStackSize
1654 << " bytes.\n");
1655
Geoff Berryc25d3bd2016-02-12 16:31:41 +00001656 // Round up to register pair alignment to avoid additional SP adjustment
1657 // instructions.
Sander de Smalen2d77e782018-09-12 12:10:22 +00001658 AFI->setCalleeSavedStackSize(AlignedCSStackSize);
1659 AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
Tim Northover3b0846e2014-05-24 12:50:23 +00001660}
Geoff Berry66f6b652016-06-02 16:22:07 +00001661
1662bool AArch64FrameLowering::enableStackSlotScavenging(
1663 const MachineFunction &MF) const {
1664 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1665 return AFI->hasCalleeSaveStackFreeSpace();
1666}