1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the AArch64 implementation of TargetFrameLowering class.
12 // On AArch64, stack frames are structured as follows:
14 // The stack grows downward.
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
20 // At function entry, the "frame" looks as follows:
23 // |-----------------------------------|
25 // | arguments passed on the stack |
27 // |-----------------------------------| <- sp
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
38 // |-----------------------------------|
40 // | arguments passed on the stack |
42 // |-----------------------------------|
44 // | prev_fp, prev_lr |
45 // | (a.k.a. "frame record") |
46 // |-----------------------------------| <- fp(=x29)
48 // | other callee-saved registers |
50 // |-----------------------------------|
51 // |.empty.space.to.make.part.below....|
52 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
53 // |.the.standard.16-byte.alignment....| compile time; if present)
54 // |-----------------------------------|
56 // | local variables of fixed size |
57 // | including spill slots |
58 // |-----------------------------------| <- bp(not defined by ABI,
59 // |.variable-sized.local.variables....| LLVM chooses X19)
60 // |.(VLAs)............................| (size of this area is unknown at
61 // |...................................| compile time)
62 // |-----------------------------------| <- sp
66 // To access the data in a frame, at-compile time, a constant offset must be
67 // computable from one of the pointers (fp, bp, sp) to access it. The size
68 // of the areas with a dotted background cannot be computed at compile-time
69 // if they are present, making it required to have all three of fp, bp and
70 // sp to be set up to be able to access all contents in the frame areas,
71 // assuming all of the frame areas are non-empty.
73 // For most functions, some of the frame areas are empty. For those functions,
74 // it may not be necessary to set up fp or bp:
75 // * A base pointer is definitely needed when there are both VLAs and local
76 // variables with more-than-default alignment requirements.
77 // * A frame pointer is definitely needed when there are local variables with
78 // more-than-default alignment requirements.
80 // In some cases when a base pointer is not strictly needed, it is generated
81 // anyway when offsets from the frame pointer to access local variables become
82 // so large that the offset can't be encoded in the immediate fields of loads
85 // FIXME: also explain the redzone concept.
86 // FIXME: also explain the concept of reserved call frames.
88 //===----------------------------------------------------------------------===//
90 #include "AArch64FrameLowering.h"
91 #include "AArch64InstrInfo.h"
92 #include "AArch64MachineFunctionInfo.h"
93 #include "AArch64RegisterInfo.h"
94 #include "AArch64Subtarget.h"
95 #include "AArch64TargetMachine.h"
96 #include "llvm/ADT/SmallVector.h"
97 #include "llvm/ADT/Statistic.h"
98 #include "llvm/CodeGen/LivePhysRegs.h"
99 #include "llvm/CodeGen/MachineBasicBlock.h"
100 #include "llvm/CodeGen/MachineFrameInfo.h"
101 #include "llvm/CodeGen/MachineFunction.h"
102 #include "llvm/CodeGen/MachineInstr.h"
103 #include "llvm/CodeGen/MachineInstrBuilder.h"
104 #include "llvm/CodeGen/MachineMemOperand.h"
105 #include "llvm/CodeGen/MachineModuleInfo.h"
106 #include "llvm/CodeGen/MachineOperand.h"
107 #include "llvm/CodeGen/MachineRegisterInfo.h"
108 #include "llvm/CodeGen/RegisterScavenging.h"
109 #include "llvm/IR/Attributes.h"
110 #include "llvm/IR/CallingConv.h"
111 #include "llvm/IR/DataLayout.h"
112 #include "llvm/IR/DebugLoc.h"
113 #include "llvm/IR/Function.h"
114 #include "llvm/MC/MCDwarf.h"
115 #include "llvm/Support/CommandLine.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/ErrorHandling.h"
118 #include "llvm/Support/MathExtras.h"
119 #include "llvm/Support/raw_ostream.h"
120 #include "llvm/Target/TargetInstrInfo.h"
121 #include "llvm/Target/TargetMachine.h"
122 #include "llvm/Target/TargetOptions.h"
123 #include "llvm/Target/TargetRegisterInfo.h"
124 #include "llvm/Target/TargetSubtargetInfo.h"
130 using namespace llvm;
132 #define DEBUG_TYPE "frame-info"
134 static cl::opt<bool> EnableRedZone("aarch64-redzone",
135 cl::desc("enable use of redzone on AArch64"),
136 cl::init(false), cl::Hidden);
138 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
140 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
143 // Don't use the red zone if the function explicitly asks us not to.
144 // This is typically used for kernel code.
145 if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone))
148 const MachineFrameInfo &MFI = MF.getFrameInfo();
149 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
150 unsigned NumBytes = AFI->getLocalStackSize();
152 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128);
155 /// hasFP - Return true if the specified function should have a dedicated frame
156 /// pointer register.
157 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
158 const MachineFrameInfo &MFI = MF.getFrameInfo();
159 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
160 // Retain behavior of always omitting the FP for leaf functions when possible.
161 return (MFI.hasCalls() &&
162 MF.getTarget().Options.DisableFramePointerElim(MF)) ||
163 MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
164 MFI.hasStackMap() || MFI.hasPatchPoint() ||
165 RegInfo->needsStackRealignment(MF);
168 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
169 /// not required, we reserve argument space for call sites in the function
170 /// immediately on entry to the current function. This eliminates the need for
171 /// add/sub sp brackets around call sites. Returns true if the call frame is
172 /// included as part of the stack frame.
174 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
175 return !MF.getFrameInfo().hasVarSizedObjects();
178 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
179 MachineFunction &MF, MachineBasicBlock &MBB,
180 MachineBasicBlock::iterator I) const {
181 const AArch64InstrInfo *TII =
182 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
183 DebugLoc DL = I->getDebugLoc();
184 unsigned Opc = I->getOpcode();
185 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
186 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
188 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
189 if (!TFI->hasReservedCallFrame(MF)) {
190 unsigned Align = getStackAlignment();
192 int64_t Amount = I->getOperand(0).getImm();
193 Amount = alignTo(Amount, Align);
197 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
198 // doesn't have to pop anything), then the first operand will be zero too so
199 // this adjustment is a no-op.
200 if (CalleePopAmount == 0) {
201 // FIXME: in-function stack adjustment for calls is limited to 24-bits
202 // because there's no guaranteed temporary register available.
204 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
205 // 1) For offset <= 12-bit, we use LSL #0
206 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
207 // LSL #0, and the other uses LSL #12.
209 // Most call frames will be allocated at the start of a function so
210 // this is OK, but it is a limitation that needs dealing with.
211 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
212 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
214 } else if (CalleePopAmount != 0) {
215 // If the calling convention demands that the callee pops arguments from the
216 // stack, we want to add it back if we have a reserved call frame.
217 assert(CalleePopAmount < 0xffffff && "call frame too large");
218 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
224 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
225 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
226 MachineFunction &MF = *MBB.getParent();
227 MachineFrameInfo &MFI = MF.getFrameInfo();
228 const TargetSubtargetInfo &STI = MF.getSubtarget();
229 const MCRegisterInfo *MRI = STI.getRegisterInfo();
230 const TargetInstrInfo *TII = STI.getInstrInfo();
231 DebugLoc DL = MBB.findDebugLoc(MBBI);
233 // Add callee saved registers to move list.
234 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
238 for (const auto &Info : CSI) {
239 unsigned Reg = Info.getReg();
241 MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
242 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
243 unsigned CFIIndex = MF.addFrameInst(
244 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
245 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
246 .addCFIIndex(CFIIndex)
247 .setMIFlags(MachineInstr::FrameSetup);
251 // Find a scratch register that we can use at the start of the prologue to
252 // re-align the stack pointer. We avoid using callee-save registers since they
253 // may appear to be free when this is called from canUseAsPrologue (during
254 // shrink wrapping), but then no longer be free when this is called from
257 // FIXME: This is a bit conservative, since in the above case we could use one
258 // of the callee-save registers as a scratch temp to re-align the stack pointer,
259 // but we would then have to make sure that we were in fact saving at least one
260 // callee-save register in the prologue, which is additional complexity that
261 // doesn't seem worth the benefit.
262 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
263 MachineFunction *MF = MBB->getParent();
265 // If MBB is an entry block, use X9 as the scratch register
266 if (&MF->front() == MBB)
269 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
270 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
271 LivePhysRegs LiveRegs(TRI);
272 LiveRegs.addLiveIns(*MBB);
274 // Mark callee saved registers as used so we will not choose them.
275 const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(MF);
276 for (unsigned i = 0; CSRegs[i]; ++i)
277 LiveRegs.addReg(CSRegs[i]);
279 // Prefer X9 since it was historically used for the prologue scratch reg.
280 const MachineRegisterInfo &MRI = MF->getRegInfo();
281 if (LiveRegs.available(MRI, AArch64::X9))
284 for (unsigned Reg : AArch64::GPR64RegClass) {
285 if (LiveRegs.available(MRI, Reg))
288 return AArch64::NoRegister;
291 bool AArch64FrameLowering::canUseAsPrologue(
292 const MachineBasicBlock &MBB) const {
293 const MachineFunction *MF = MBB.getParent();
294 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
295 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
296 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
298 // Don't need a scratch register if we're not going to re-align the stack.
299 if (!RegInfo->needsStackRealignment(*MF))
301 // Otherwise, we can use any block as long as it has a scratch register
303 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
306 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
307 MachineFunction &MF, unsigned StackBumpBytes) const {
308 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
309 const MachineFrameInfo &MFI = MF.getFrameInfo();
310 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
311 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
313 if (AFI->getLocalStackSize() == 0)
316 // 512 is the maximum immediate for stp/ldp that will be used for
317 // callee-save save/restores
318 if (StackBumpBytes >= 512)
321 if (MFI.hasVarSizedObjects())
324 if (RegInfo->needsStackRealignment(MF))
327 // This isn't strictly necessary, but it simplifies things a bit since the
328 // current RedZone handling code assumes the SP is adjusted by the
329 // callee-save save/restore code.
330 if (canUseRedZone(MF))
336 // Convert callee-save register save/restore instruction to do stack pointer
337 // decrement/increment to allocate/deallocate the callee-save stack area by
338 // converting store/load to use pre/post increment version.
339 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
340 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
341 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc) {
343 bool NewIsUnscaled = false;
344 switch (MBBI->getOpcode()) {
346 llvm_unreachable("Unexpected callee-save save/restore opcode!");
348 NewOpc = AArch64::STPXpre;
351 NewOpc = AArch64::STPDpre;
353 case AArch64::STRXui:
354 NewOpc = AArch64::STRXpre;
355 NewIsUnscaled = true;
357 case AArch64::STRDui:
358 NewOpc = AArch64::STRDpre;
359 NewIsUnscaled = true;
362 NewOpc = AArch64::LDPXpost;
365 NewOpc = AArch64::LDPDpost;
367 case AArch64::LDRXui:
368 NewOpc = AArch64::LDRXpost;
369 NewIsUnscaled = true;
371 case AArch64::LDRDui:
372 NewOpc = AArch64::LDRDpost;
373 NewIsUnscaled = true;
377 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
378 MIB.addReg(AArch64::SP, RegState::Define);
380 // Copy all operands other than the immediate offset.
381 unsigned OpndIdx = 0;
382 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
384 MIB.add(MBBI->getOperand(OpndIdx));
386 assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
387 "Unexpected immediate offset in first/last callee-save save/restore "
389 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
390 "Unexpected base register in callee-save save/restore instruction!");
391 // Last operand is immediate offset that needs fixing.
392 assert(CSStackSizeInc % 8 == 0);
393 int64_t CSStackSizeIncImm = CSStackSizeInc;
395 CSStackSizeIncImm /= 8;
396 MIB.addImm(CSStackSizeIncImm);
398 MIB.setMIFlags(MBBI->getFlags());
399 MIB.setMemRefs(MBBI->memoperands_begin(), MBBI->memoperands_end());
401 return std::prev(MBB.erase(MBBI));
404 // Fixup callee-save register save/restore instructions to take into account
405 // combined SP bump by adding the local stack size to the stack offsets.
406 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
407 unsigned LocalStackSize) {
408 unsigned Opc = MI.getOpcode();
410 assert((Opc == AArch64::STPXi || Opc == AArch64::STPDi ||
411 Opc == AArch64::STRXui || Opc == AArch64::STRDui ||
412 Opc == AArch64::LDPXi || Opc == AArch64::LDPDi ||
413 Opc == AArch64::LDRXui || Opc == AArch64::LDRDui) &&
414 "Unexpected callee-save save/restore opcode!");
416 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
417 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
418 "Unexpected base register in callee-save save/restore instruction!");
419 // Last operand is immediate offset that needs fixing.
420 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
421 // All generated opcodes have scaled offsets.
422 assert(LocalStackSize % 8 == 0);
423 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / 8);
426 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
427 MachineBasicBlock &MBB) const {
428 MachineBasicBlock::iterator MBBI = MBB.begin();
429 const MachineFrameInfo &MFI = MF.getFrameInfo();
430 const Function *Fn = MF.getFunction();
431 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
432 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
433 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
434 MachineModuleInfo &MMI = MF.getMMI();
435 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
436 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
437 bool HasFP = hasFP(MF);
439 // Debug location must be unknown since the first debug location is used
440 // to determine the end of the prologue.
443 // All calls are tail calls in GHC calling conv, and functions have no
444 // prologue/epilogue.
445 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
448 int NumBytes = (int)MFI.getStackSize();
449 if (!AFI->hasStackFrame()) {
450 assert(!HasFP && "unexpected function without stack frame but with FP");
452 // All of the stack allocation is for locals.
453 AFI->setLocalStackSize(NumBytes);
457 // REDZONE: If the stack size is less than 128 bytes, we don't need
458 // to actually allocate.
459 if (canUseRedZone(MF))
460 ++NumRedZoneFunctions;
462 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
463 MachineInstr::FrameSetup);
465 // Label used to tie together the PROLOG_LABEL and the MachineMoves.
466 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
467 // Encode the stack size of the leaf function.
468 unsigned CFIIndex = MF.addFrameInst(
469 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
470 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
471 .addCFIIndex(CFIIndex)
472 .setMIFlags(MachineInstr::FrameSetup);
477 auto CSStackSize = AFI->getCalleeSavedStackSize();
478 // All of the remaining stack allocations are for locals.
479 AFI->setLocalStackSize(NumBytes - CSStackSize);
481 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
483 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
484 MachineInstr::FrameSetup);
486 } else if (CSStackSize != 0) {
487 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(MBB, MBBI, DL, TII,
489 NumBytes -= CSStackSize;
491 assert(NumBytes >= 0 && "Negative stack allocation size!?");
493 // Move past the saves of the callee-saved registers, fixing up the offsets
494 // and pre-inc if we decided to combine the callee-save and local stack
495 // pointer bump above.
496 MachineBasicBlock::iterator End = MBB.end();
497 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) {
499 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize());
503 // Only set up FP if we actually need to. Frame pointer is fp = sp - 16.
504 int FPOffset = CSStackSize - 16;
506 FPOffset += AFI->getLocalStackSize();
508 // Issue sub fp, sp, FPOffset or
509 // mov fp,sp when FPOffset is zero.
510 // Note: All stores of callee-saved registers are marked as "FrameSetup".
511 // This code marks the instruction(s) that set the FP also.
512 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
513 MachineInstr::FrameSetup);
516 // Allocate space for the rest of the frame.
518 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
519 unsigned scratchSPReg = AArch64::SP;
521 if (NeedsRealignment) {
522 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
523 assert(scratchSPReg != AArch64::NoRegister);
526 // If we're a leaf function, try using the red zone.
527 if (!canUseRedZone(MF))
528 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
529 // the correct value here, as NumBytes also includes padding bytes,
530 // which shouldn't be counted here.
531 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
532 MachineInstr::FrameSetup);
534 if (NeedsRealignment) {
535 const unsigned Alignment = MFI.getMaxAlignment();
536 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
537 assert(NrBitsToZero > 1);
538 assert(scratchSPReg != AArch64::SP);
540 // SUB X9, SP, NumBytes
541 // -- X9 is temporary register, so shouldn't contain any live data here,
542 // -- free to use. This is already produced by emitFrameOffset above.
543 // AND SP, X9, 0b11111...0000
544 // The logical immediates have a non-trivial encoding. The following
545 // formula computes the encoded immediate with all ones but
546 // NrBitsToZero zero bits as least significant bits.
547 uint32_t andMaskEncoded = (1 << 12) // = N
548 | ((64 - NrBitsToZero) << 6) // immr
549 | ((64 - NrBitsToZero - 1) << 0); // imms
551 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
552 .addReg(scratchSPReg, RegState::Kill)
553 .addImm(andMaskEncoded);
554 AFI->setStackRealigned(true);
558 // If we need a base pointer, set it up here. It's whatever the value of the
559 // stack pointer is at this point. Any variable size objects will be allocated
560 // after this, so we can still use the base pointer to reference locals.
562 // FIXME: Clarify FrameSetup flags here.
563 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
565 if (RegInfo->hasBasePointer(MF)) {
566 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
570 if (needsFrameMoves) {
571 const DataLayout &TD = MF.getDataLayout();
572 const int StackGrowth = -TD.getPointerSize(0);
573 unsigned FramePtr = RegInfo->getFrameRegister(MF);
574 // An example of the prologue:
581 // .cfi_personality 155, ___gxx_personality_v0
583 // .cfi_lsda 16, Lexception33
585 // stp xa,bx, [sp, -#offset]!
587 // stp x28, x27, [sp, #offset-32]
588 // stp fp, lr, [sp, #offset-16]
589 // add fp, sp, #offset - 16
593 // +-------------------------------------------+
594 // 10000 | ........ | ........ | ........ | ........ |
595 // 10004 | ........ | ........ | ........ | ........ |
596 // +-------------------------------------------+
597 // 10008 | ........ | ........ | ........ | ........ |
598 // 1000c | ........ | ........ | ........ | ........ |
599 // +===========================================+
600 // 10010 | X28 Register |
601 // 10014 | X28 Register |
602 // +-------------------------------------------+
603 // 10018 | X27 Register |
604 // 1001c | X27 Register |
605 // +===========================================+
606 // 10020 | Frame Pointer |
607 // 10024 | Frame Pointer |
608 // +-------------------------------------------+
609 // 10028 | Link Register |
610 // 1002c | Link Register |
611 // +===========================================+
612 // 10030 | ........ | ........ | ........ | ........ |
613 // 10034 | ........ | ........ | ........ | ........ |
614 // +-------------------------------------------+
615 // 10038 | ........ | ........ | ........ | ........ |
616 // 1003c | ........ | ........ | ........ | ........ |
617 // +-------------------------------------------+
619 // [sp] = 10030 :: >>initial value<<
620 // sp = 10020 :: stp fp, lr, [sp, #-16]!
621 // fp = sp == 10020 :: mov fp, sp
622 // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
623 // sp == 10010 :: >>final value<<
625 // The frame pointer (w29) points to address 10020. If we use an offset of
626 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
627 // for w27, and -32 for w28:
630 // .cfi_def_cfa w29, 16
632 // .cfi_offset w30, -8
634 // .cfi_offset w29, -16
636 // .cfi_offset w27, -24
638 // .cfi_offset w28, -32
641 // Define the current CFA rule to use the provided FP.
642 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
643 unsigned CFIIndex = MF.addFrameInst(
644 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
645 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
646 .addCFIIndex(CFIIndex)
647 .setMIFlags(MachineInstr::FrameSetup);
649 // Encode the stack size of the leaf function.
650 unsigned CFIIndex = MF.addFrameInst(
651 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize()));
652 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
653 .addCFIIndex(CFIIndex)
654 .setMIFlags(MachineInstr::FrameSetup);
657 // Now emit the moves for whatever callee saved regs we have (including FP,
658 // LR if those are saved).
659 emitCalleeSavedFrameMoves(MBB, MBBI);
663 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
664 MachineBasicBlock &MBB) const {
665 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
666 MachineFrameInfo &MFI = MF.getFrameInfo();
667 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
668 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
670 bool IsTailCallReturn = false;
671 if (MBB.end() != MBBI) {
672 DL = MBBI->getDebugLoc();
673 unsigned RetOpcode = MBBI->getOpcode();
674 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
675 RetOpcode == AArch64::TCRETURNri;
677 int NumBytes = MFI.getStackSize();
678 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
680 // All calls are tail calls in GHC calling conv, and functions have no
681 // prologue/epilogue.
682 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
685 // Initial and residual are named for consistency with the prologue. Note that
686 // in the epilogue, the residual adjustment is executed first.
687 uint64_t ArgumentPopSize = 0;
688 if (IsTailCallReturn) {
689 MachineOperand &StackAdjust = MBBI->getOperand(1);
691 // For a tail-call in a callee-pops-arguments environment, some or all of
692 // the stack may actually be in use for the call's arguments, this is
693 // calculated during LowerCall and consumed here...
694 ArgumentPopSize = StackAdjust.getImm();
696 // ... otherwise the amount to pop is *all* of the argument space,
697 // conveniently stored in the MachineFunctionInfo by
698 // LowerFormalArguments. This will, of course, be zero for the C calling
700 ArgumentPopSize = AFI->getArgumentStackToRestore();
703 // The stack frame should be like below,
705 // ---------------------- ---
707 // | BytesInStackArgArea| CalleeArgStackSize
708 // | (NumReusableBytes) | (of tail call)
711 // ---------------------| --- |
713 // | CalleeSavedReg | | |
714 // | (CalleeSavedStackSize)| | |
716 // ---------------------| | NumBytes
717 // | | StackSize (StackAdjustUp)
718 // | LocalStackSize | | |
719 // | (covering callee | | |
722 // ---------------------- --- ---
724 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
725 // = StackSize + ArgumentPopSize
727 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
728 // it as the 2nd argument of AArch64ISD::TC_RETURN.
730 auto CSStackSize = AFI->getCalleeSavedStackSize();
731 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
733 if (!CombineSPBump && CSStackSize != 0)
734 convertCalleeSaveRestoreToSPPrePostIncDec(
735 MBB, std::prev(MBB.getFirstTerminator()), DL, TII, CSStackSize);
737 // Move past the restores of the callee-saved registers.
738 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
739 MachineBasicBlock::iterator Begin = MBB.begin();
740 while (LastPopI != Begin) {
742 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) {
745 } else if (CombineSPBump)
746 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize());
749 // If there is a single SP update, insert it before the ret and we're done.
751 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
752 NumBytes + ArgumentPopSize, TII,
753 MachineInstr::FrameDestroy);
757 NumBytes -= CSStackSize;
758 assert(NumBytes >= 0 && "Negative stack allocation size!?");
761 bool RedZone = canUseRedZone(MF);
762 // If this was a redzone leaf function, we don't need to restore the
763 // stack pointer (but we may need to pop stack args for fastcc).
764 if (RedZone && ArgumentPopSize == 0)
767 bool NoCalleeSaveRestore = CSStackSize == 0;
768 int StackRestoreBytes = RedZone ? 0 : NumBytes;
769 if (NoCalleeSaveRestore)
770 StackRestoreBytes += ArgumentPopSize;
771 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
772 StackRestoreBytes, TII, MachineInstr::FrameDestroy);
773 // If we were able to combine the local stack pop with the argument pop,
775 if (NoCalleeSaveRestore || ArgumentPopSize == 0)
780 // Restore the original stack pointer.
781 // FIXME: Rather than doing the math here, we should instead just use
782 // non-post-indexed loads for the restores if we aren't actually going to
783 // be able to save any instructions.
784 if (MFI.hasVarSizedObjects() || AFI->isStackRealigned())
785 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
786 -CSStackSize + 16, TII, MachineInstr::FrameDestroy);
788 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII,
789 MachineInstr::FrameDestroy);
791 // This must be placed after the callee-save restore code because that code
792 // assumes the SP is at the same location as it was after the callee-save save
793 // code in the prologue.
795 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
796 ArgumentPopSize, TII, MachineInstr::FrameDestroy);
799 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
800 /// debug info. It's the same as what we use for resolving the code-gen
801 /// references for now. FIXME: This can go wrong when references are
802 /// SP-relative and simple call frames aren't used.
803 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
805 unsigned &FrameReg) const {
806 return resolveFrameIndexReference(MF, FI, FrameReg);
809 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
810 int FI, unsigned &FrameReg,
811 bool PreferFP) const {
812 const MachineFrameInfo &MFI = MF.getFrameInfo();
813 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
814 MF.getSubtarget().getRegisterInfo());
815 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
816 int FPOffset = MFI.getObjectOffset(FI) + 16;
817 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
818 bool isFixed = MFI.isFixedObjectIndex(FI);
820 // Use frame pointer to reference fixed objects. Use it for locals if
821 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
822 // reliable as a base). Make sure useFPForScavengingIndex() does the
823 // right thing for the emergency spill slot.
825 if (AFI->hasStackFrame()) {
826 // Note: Keeping the following as multiple 'if' statements rather than
827 // merging to a single expression for readability.
829 // Argument access should always use the FP.
832 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
833 !RegInfo->needsStackRealignment(MF)) {
834 // Use SP or FP, whichever gives us the best chance of the offset
835 // being in range for direct access. If the FPOffset is positive,
836 // that'll always be best, as the SP will be even further away.
837 // If the FPOffset is negative, we have to keep in mind that the
838 // available offset range for negative offsets is smaller than for
839 // positive ones. If we have variable sized objects, we're stuck with
840 // using the FP regardless, though, as the SP offset is unknown
841 // and we don't have a base pointer available. If an offset is
842 // available via the FP and the SP, use whichever is closest.
843 if (PreferFP || MFI.hasVarSizedObjects() || FPOffset >= 0 ||
844 (FPOffset >= -256 && Offset > -FPOffset))
849 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
850 "In the presence of dynamic stack pointer realignment, "
851 "non-argument objects cannot be accessed through the frame pointer");
854 FrameReg = RegInfo->getFrameRegister(MF);
858 // Use the base pointer if we have one.
859 if (RegInfo->hasBasePointer(MF))
860 FrameReg = RegInfo->getBaseRegister();
862 FrameReg = AArch64::SP;
863 // If we're using the red zone for this function, the SP won't actually
864 // be adjusted, so the offsets will be negative. They're also all
865 // within range of the signed 9-bit immediate instructions.
866 if (canUseRedZone(MF))
867 Offset -= AFI->getLocalStackSize();
873 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
874 // Do not set a kill flag on values that are also marked as live-in. This
875 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
876 // callee saved registers.
877 // Omitting the kill flags is conservatively correct even if the live-in
878 // is not used after all.
879 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
880 return getKillRegState(!IsLiveIn);
883 static bool produceCompactUnwindFrame(MachineFunction &MF) {
884 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
885 AttributeList Attrs = MF.getFunction()->getAttributes();
886 return Subtarget.isTargetMachO() &&
887 !(Subtarget.getTargetLowering()->supportSwiftError() &&
888 Attrs.hasAttrSomewhere(Attribute::SwiftError));
894 unsigned Reg1 = AArch64::NoRegister;
895 unsigned Reg2 = AArch64::NoRegister;
900 RegPairInfo() = default;
902 bool isPaired() const { return Reg2 != AArch64::NoRegister; }
905 } // end anonymous namespace
907 static void computeCalleeSaveRegisterPairs(
908 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI,
909 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) {
914 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
915 MachineFrameInfo &MFI = MF.getFrameInfo();
916 CallingConv::ID CC = MF.getFunction()->getCallingConv();
917 unsigned Count = CSI.size();
919 // MachO's compact unwind format relies on all registers being stored in
921 assert((!produceCompactUnwindFrame(MF) ||
922 CC == CallingConv::PreserveMost ||
924 "Odd number of callee-saved regs to spill!");
925 unsigned Offset = AFI->getCalleeSavedStackSize();
927 for (unsigned i = 0; i < Count; ++i) {
929 RPI.Reg1 = CSI[i].getReg();
931 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) ||
932 AArch64::FPR64RegClass.contains(RPI.Reg1));
933 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1);
935 // Add the next reg to the pair if it is in the same register class.
937 unsigned NextReg = CSI[i + 1].getReg();
938 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) ||
939 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg)))
943 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
944 // list to come in sorted by frame index so that we can issue the store
945 // pair instructions directly. Assert if we see anything otherwise.
947 // The order of the registers in the list is controlled by
948 // getCalleeSavedRegs(), so they will always be in-order, as well.
949 assert((!RPI.isPaired() ||
950 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) &&
951 "Out of order callee saved regs!");
953 // MachO's compact unwind format relies on all registers being stored in
954 // adjacent register pairs.
955 assert((!produceCompactUnwindFrame(MF) ||
956 CC == CallingConv::PreserveMost ||
958 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
959 RPI.Reg1 + 1 == RPI.Reg2))) &&
960 "Callee-save registers not saved as adjacent register pair!");
962 RPI.FrameIdx = CSI[i].getFrameIdx();
964 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) {
965 // Round up size of non-pair to pair size if we need to pad the
966 // callee-save area to ensure 16-byte alignment.
968 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16);
969 MFI.setObjectAlignment(RPI.FrameIdx, 16);
970 AFI->setCalleeSaveStackHasFreeSpace(true);
972 Offset -= RPI.isPaired() ? 16 : 8;
973 assert(Offset % 8 == 0);
974 RPI.Offset = Offset / 8;
975 assert((RPI.Offset >= -64 && RPI.Offset <= 63) &&
976 "Offset out of bounds for LDP/STP immediate");
978 RegPairs.push_back(RPI);
984 bool AArch64FrameLowering::spillCalleeSavedRegisters(
985 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
986 const std::vector<CalleeSavedInfo> &CSI,
987 const TargetRegisterInfo *TRI) const {
988 MachineFunction &MF = *MBB.getParent();
989 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
991 SmallVector<RegPairInfo, 8> RegPairs;
993 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
994 const MachineRegisterInfo &MRI = MF.getRegInfo();
996 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE;
998 RegPairInfo RPI = *RPII;
999 unsigned Reg1 = RPI.Reg1;
1000 unsigned Reg2 = RPI.Reg2;
1003 // Issue sequence of spills for cs regs. The first spill may be converted
1004 // to a pre-decrement store later by emitPrologue if the callee-save stack
1005 // area allocation can't be combined with the local stack area allocation.
1007 // stp x22, x21, [sp, #0] // addImm(+0)
1008 // stp x20, x19, [sp, #16] // addImm(+2)
1009 // stp fp, lr, [sp, #32] // addImm(+4)
1010 // Rationale: This sequence saves uop updates compared to a sequence of
1011 // pre-increment spills like stp xi,xj,[sp,#-16]!
1012 // Note: Similar rationale and sequence for restores in epilog.
1014 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
1016 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
1017 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1);
1019 dbgs() << ", " << TRI->getName(Reg2);
1020 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1022 dbgs() << ", " << RPI.FrameIdx+1;
1025 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
1026 if (!MRI.isReserved(Reg1))
1027 MBB.addLiveIn(Reg1);
1028 if (RPI.isPaired()) {
1029 if (!MRI.isReserved(Reg2))
1030 MBB.addLiveIn(Reg2);
1031 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
1032 MIB.addMemOperand(MF.getMachineMemOperand(
1033 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1034 MachineMemOperand::MOStore, 8, 8));
1036 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
1037 .addReg(AArch64::SP)
1038 .addImm(RPI.Offset) // [sp, #offset*8], where factor*8 is implicit
1039 .setMIFlag(MachineInstr::FrameSetup);
1040 MIB.addMemOperand(MF.getMachineMemOperand(
1041 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1042 MachineMemOperand::MOStore, 8, 8));
1047 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
1048 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1049 const std::vector<CalleeSavedInfo> &CSI,
1050 const TargetRegisterInfo *TRI) const {
1051 MachineFunction &MF = *MBB.getParent();
1052 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1054 SmallVector<RegPairInfo, 8> RegPairs;
1056 if (MI != MBB.end())
1057 DL = MI->getDebugLoc();
1059 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs);
1061 for (auto RPII = RegPairs.begin(), RPIE = RegPairs.end(); RPII != RPIE;
1063 RegPairInfo RPI = *RPII;
1064 unsigned Reg1 = RPI.Reg1;
1065 unsigned Reg2 = RPI.Reg2;
1067 // Issue sequence of restores for cs regs. The last restore may be converted
1068 // to a post-increment load later by emitEpilogue if the callee-save stack
1069 // area allocation can't be combined with the local stack area allocation.
1071 // ldp fp, lr, [sp, #32] // addImm(+4)
1072 // ldp x20, x19, [sp, #16] // addImm(+2)
1073 // ldp x22, x21, [sp, #0] // addImm(+0)
1074 // Note: see comment in spillCalleeSavedRegisters()
1077 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
1079 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
1080 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1);
1082 dbgs() << ", " << TRI->getName(Reg2);
1083 dbgs() << ") -> fi#(" << RPI.FrameIdx;
1085 dbgs() << ", " << RPI.FrameIdx+1;
1088 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
1089 if (RPI.isPaired()) {
1090 MIB.addReg(Reg2, getDefRegState(true));
1091 MIB.addMemOperand(MF.getMachineMemOperand(
1092 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx + 1),
1093 MachineMemOperand::MOLoad, 8, 8));
1095 MIB.addReg(Reg1, getDefRegState(true))
1096 .addReg(AArch64::SP)
1097 .addImm(RPI.Offset) // [sp, #offset*8] where the factor*8 is implicit
1098 .setMIFlag(MachineInstr::FrameDestroy);
1099 MIB.addMemOperand(MF.getMachineMemOperand(
1100 MachinePointerInfo::getFixedStack(MF, RPI.FrameIdx),
1101 MachineMemOperand::MOLoad, 8, 8));
1106 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
1107 BitVector &SavedRegs,
1108 RegScavenger *RS) const {
1109 // All calls are tail calls in GHC calling conv, and functions have no
1110 // prologue/epilogue.
1111 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
1114 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1115 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
1116 MF.getSubtarget().getRegisterInfo());
1117 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1118 unsigned UnspilledCSGPR = AArch64::NoRegister;
1119 unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
1121 // The frame record needs to be created by saving the appropriate registers
1123 SavedRegs.set(AArch64::FP);
1124 SavedRegs.set(AArch64::LR);
1127 unsigned BasePointerReg = AArch64::NoRegister;
1128 if (RegInfo->hasBasePointer(MF))
1129 BasePointerReg = RegInfo->getBaseRegister();
1131 unsigned ExtraCSSpill = 0;
1132 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1133 // Figure out which callee-saved registers to save/restore.
1134 for (unsigned i = 0; CSRegs[i]; ++i) {
1135 const unsigned Reg = CSRegs[i];
1137 // Add the base pointer register to SavedRegs if it is callee-save.
1138 if (Reg == BasePointerReg)
1141 bool RegUsed = SavedRegs.test(Reg);
1142 unsigned PairedReg = CSRegs[i ^ 1];
1144 if (AArch64::GPR64RegClass.contains(Reg) &&
1145 !RegInfo->isReservedReg(MF, Reg)) {
1146 UnspilledCSGPR = Reg;
1147 UnspilledCSGPRPaired = PairedReg;
1152 // MachO's compact unwind format relies on all registers being stored in
1154 // FIXME: the usual format is actually better if unwinding isn't needed.
1155 if (produceCompactUnwindFrame(MF) && !SavedRegs.test(PairedReg)) {
1156 SavedRegs.set(PairedReg);
1157 if (AArch64::GPR64RegClass.contains(PairedReg) &&
1158 !RegInfo->isReservedReg(MF, PairedReg))
1159 ExtraCSSpill = PairedReg;
1163 DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:";
1164 for (unsigned Reg : SavedRegs.set_bits())
1165 dbgs() << ' ' << PrintReg(Reg, RegInfo);
1168 // If any callee-saved registers are used, the frame cannot be eliminated.
1169 unsigned NumRegsSpilled = SavedRegs.count();
1170 bool CanEliminateFrame = NumRegsSpilled == 0;
1172 // FIXME: Set BigStack if any stack slot references may be out of range.
1173 // For now, just conservatively guestimate based on unscaled indexing
1174 // range. We'll end up allocating an unnecessary spill slot a lot, but
1175 // realistically that's not a big deal at this stage of the game.
1176 // The CSR spill slots have not been allocated yet, so estimateStackSize
1177 // won't include them.
1178 MachineFrameInfo &MFI = MF.getFrameInfo();
1179 unsigned CFSize = MFI.estimateStackSize(MF) + 8 * NumRegsSpilled;
1180 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
1181 bool BigStack = (CFSize >= 256);
1182 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
1183 AFI->setHasStackFrame(true);
1185 // Estimate if we might need to scavenge a register at some point in order
1186 // to materialize a stack offset. If so, either spill one additional
1187 // callee-saved register or reserve a special spill slot to facilitate
1188 // register scavenging. If we already spilled an extra callee-saved register
1189 // above to keep the number of spills even, we don't need to do anything else
1192 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
1193 DEBUG(dbgs() << "Spilling " << PrintReg(UnspilledCSGPR, RegInfo)
1194 << " to get a scratch register.\n");
1195 SavedRegs.set(UnspilledCSGPR);
1196 // MachO's compact unwind format relies on all registers being stored in
1197 // pairs, so if we need to spill one extra for BigStack, then we need to
1199 if (produceCompactUnwindFrame(MF))
1200 SavedRegs.set(UnspilledCSGPRPaired);
1201 ExtraCSSpill = UnspilledCSGPRPaired;
1202 NumRegsSpilled = SavedRegs.count();
1205 // If we didn't find an extra callee-saved register to spill, create
1206 // an emergency spill slot.
1207 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
1208 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1209 const TargetRegisterClass &RC = AArch64::GPR64RegClass;
1210 unsigned Size = TRI->getSpillSize(RC);
1211 unsigned Align = TRI->getSpillAlignment(RC);
1212 int FI = MFI.CreateStackObject(Size, Align, false);
1213 RS->addScavengingFrameIndex(FI);
1214 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1215 << " as the emergency spill slot.\n");
1219 // Round up to register pair alignment to avoid additional SP adjustment
1221 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16));
1224 bool AArch64FrameLowering::enableStackSlotScavenging(
1225 const MachineFunction &MF) const {
1226 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
1227 return AFI->hasCalleeSaveStackFreeSpace();