1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
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 ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "MCTargetDesc/ARMAddressingModes.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetOptions.h"
36 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
37 cl::desc("Align ARM NEON spills in prolog and epilog"));
39 static MachineBasicBlock::iterator
40 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
41 unsigned NumAlignedDPRCS2Regs);
43 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
44 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
47 bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
48 // iOS always has a FP for backtracking, force other targets to keep their FP
49 // when doing FastISel. The emitted code is currently superior, and in cases
50 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
51 return TargetFrameLowering::noFramePointerElim(MF) ||
52 MF.getSubtarget<ARMSubtarget>().useFastISel();
55 /// hasFP - Return true if the specified function should have a dedicated frame
56 /// pointer register. This is true if the function has variable sized allocas
57 /// or if frame pointer elimination is disabled.
58 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
59 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
61 // iOS requires FP not to be clobbered for backtracing purpose.
62 if (STI.isTargetIOS() || STI.isTargetWatchOS())
65 const MachineFrameInfo *MFI = MF.getFrameInfo();
66 // Always eliminate non-leaf frame pointers.
67 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
69 RegInfo->needsStackRealignment(MF) ||
70 MFI->hasVarSizedObjects() ||
71 MFI->isFrameAddressTaken());
74 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
75 /// not required, we reserve argument space for call sites in the function
76 /// immediately on entry to the current function. This eliminates the need for
77 /// add/sub sp brackets around call sites. Returns true if the call frame is
78 /// included as part of the stack frame.
79 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
80 const MachineFrameInfo *FFI = MF.getFrameInfo();
81 unsigned CFSize = FFI->getMaxCallFrameSize();
82 // It's not always a good idea to include the call frame as part of the
83 // stack frame. ARM (especially Thumb) has small immediate offset to
84 // address the stack frame. So a large call frame can cause poor codegen
85 // and may even makes it impossible to scavenge a register.
86 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
89 return !MF.getFrameInfo()->hasVarSizedObjects();
92 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
93 /// call frame pseudos can be simplified. Unlike most targets, having a FP
94 /// is not sufficient here since we still may reference some objects via SP
95 /// even when FP is available in Thumb2 mode.
97 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
98 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
101 static bool isCSRestore(MachineInstr *MI,
102 const ARMBaseInstrInfo &TII,
103 const MCPhysReg *CSRegs) {
104 // Integer spill area is handled with "pop".
105 if (isPopOpcode(MI->getOpcode())) {
106 // The first two operands are predicates. The last two are
107 // imp-def and imp-use of SP. Check everything in between.
108 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
109 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
113 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
114 MI->getOpcode() == ARM::LDR_POST_REG ||
115 MI->getOpcode() == ARM::t2LDR_POST) &&
116 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
117 MI->getOperand(1).getReg() == ARM::SP)
123 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
124 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
125 const ARMBaseInstrInfo &TII, unsigned DestReg,
126 unsigned SrcReg, int NumBytes,
127 unsigned MIFlags = MachineInstr::NoFlags,
128 ARMCC::CondCodes Pred = ARMCC::AL,
129 unsigned PredReg = 0) {
131 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
132 Pred, PredReg, TII, MIFlags);
134 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
135 Pred, PredReg, TII, MIFlags);
138 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
140 const ARMBaseInstrInfo &TII, int NumBytes,
141 unsigned MIFlags = MachineInstr::NoFlags,
142 ARMCC::CondCodes Pred = ARMCC::AL,
143 unsigned PredReg = 0) {
144 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
145 MIFlags, Pred, PredReg);
148 static int sizeOfSPAdjustment(const MachineInstr *MI) {
150 switch (MI->getOpcode()) {
151 case ARM::VSTMDDB_UPD:
155 case ARM::t2STMDB_UPD:
159 case ARM::STR_PRE_IMM:
162 llvm_unreachable("Unknown push or pop like instruction");
166 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
167 // pred) so the list starts at 4.
168 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
173 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
174 size_t StackSizeInBytes) {
175 const MachineFrameInfo *MFI = MF.getFrameInfo();
176 const Function *F = MF.getFunction();
177 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
178 if (F->hasFnAttribute("stack-probe-size"))
179 F->getFnAttribute("stack-probe-size")
181 .getAsInteger(0, StackProbeSize);
182 return StackSizeInBytes >= StackProbeSize;
186 struct StackAdjustingInsts {
188 MachineBasicBlock::iterator I;
193 SmallVector<InstInfo, 4> Insts;
195 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
196 bool BeforeFPSet = false) {
197 InstInfo Info = {I, SPAdjust, BeforeFPSet};
198 Insts.push_back(Info);
201 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
202 auto Info = std::find_if(Insts.begin(), Insts.end(),
203 [&](InstInfo &Info) { return Info.I == I; });
204 assert(Info != Insts.end() && "invalid sp adjusting instruction");
205 Info->SPAdjust += ExtraBytes;
208 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
209 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
210 unsigned CFAOffset = 0;
211 for (auto &Info : Insts) {
212 if (HasFP && !Info.BeforeFPSet)
215 CFAOffset -= Info.SPAdjust;
216 unsigned CFIIndex = MMI.addFrameInst(
217 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
218 BuildMI(MBB, std::next(Info.I), dl,
219 TII.get(TargetOpcode::CFI_INSTRUCTION))
220 .addCFIIndex(CFIIndex)
221 .setMIFlags(MachineInstr::FrameSetup);
227 /// Emit an instruction sequence that will align the address in
228 /// register Reg by zero-ing out the lower bits. For versions of the
229 /// architecture that support Neon, this must be done in a single
230 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
231 /// single instruction. That function only gets called when optimizing
232 /// spilling of D registers on a core with the Neon instruction set
234 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
235 const TargetInstrInfo &TII,
236 MachineBasicBlock &MBB,
237 MachineBasicBlock::iterator MBBI,
238 DebugLoc DL, const unsigned Reg,
239 const unsigned Alignment,
240 const bool MustBeSingleInstruction) {
241 const ARMSubtarget &AST =
242 static_cast<const ARMSubtarget &>(MF.getSubtarget());
243 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
244 const unsigned AlignMask = Alignment - 1;
245 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
246 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
247 if (!AFI->isThumbFunction()) {
248 // if the BFC instruction is available, use that to zero the lower
250 // bfc Reg, #0, log2(Alignment)
251 // otherwise use BIC, if the mask to zero the required number of bits
252 // can be encoded in the bic immediate field
253 // bic Reg, Reg, Alignment-1
255 // lsr Reg, Reg, log2(Alignment)
256 // lsl Reg, Reg, log2(Alignment)
258 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
259 .addReg(Reg, RegState::Kill)
260 .addImm(~AlignMask));
261 } else if (AlignMask <= 255) {
263 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
264 .addReg(Reg, RegState::Kill)
265 .addImm(AlignMask)));
267 assert(!MustBeSingleInstruction &&
268 "Shouldn't call emitAligningInstructions demanding a single "
269 "instruction to be emitted for large stack alignment for a target "
271 AddDefaultCC(AddDefaultPred(
272 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
273 .addReg(Reg, RegState::Kill)
274 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
275 AddDefaultCC(AddDefaultPred(
276 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
277 .addReg(Reg, RegState::Kill)
278 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
281 // Since this is only reached for Thumb-2 targets, the BFC instruction
282 // should always be available.
284 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
285 .addReg(Reg, RegState::Kill)
286 .addImm(~AlignMask));
290 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
291 MachineBasicBlock &MBB) const {
292 MachineBasicBlock::iterator MBBI = MBB.begin();
293 MachineFrameInfo *MFI = MF.getFrameInfo();
294 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
295 MachineModuleInfo &MMI = MF.getMMI();
296 MCContext &Context = MMI.getContext();
297 const TargetMachine &TM = MF.getTarget();
298 const MCRegisterInfo *MRI = Context.getRegisterInfo();
299 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
300 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
301 assert(!AFI->isThumb1OnlyFunction() &&
302 "This emitPrologue does not support Thumb1!");
303 bool isARM = !AFI->isThumbFunction();
304 unsigned Align = STI.getFrameLowering()->getStackAlignment();
305 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
306 unsigned NumBytes = MFI->getStackSize();
307 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
308 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
309 unsigned FramePtr = RegInfo->getFrameRegister(MF);
311 // Determine the sizes of each callee-save spill areas and record which frame
312 // belongs to which callee-save spill areas.
313 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
314 int FramePtrSpillFI = 0;
317 // All calls are tail calls in GHC calling conv, and functions have no
318 // prologue/epilogue.
319 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
322 StackAdjustingInsts DefCFAOffsetCandidates;
323 bool HasFP = hasFP(MF);
325 // Allocate the vararg register save area.
326 if (ArgRegsSaveSize) {
327 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
328 MachineInstr::FrameSetup);
329 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
332 if (!AFI->hasStackFrame() &&
333 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
334 if (NumBytes - ArgRegsSaveSize != 0) {
335 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
336 MachineInstr::FrameSetup);
337 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
338 NumBytes - ArgRegsSaveSize, true);
340 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
344 // Determine spill area sizes.
345 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
346 unsigned Reg = CSI[i].getReg();
347 int FI = CSI[i].getFrameIdx();
354 if (STI.isTargetDarwin()) {
369 FramePtrSpillFI = FI;
373 // This is a DPR. Exclude the aligned DPRCS2 spills.
376 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
382 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
383 if (GPRCS1Size > 0) {
384 GPRCS1Push = LastPush = MBBI++;
385 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
388 // Determine starting offsets of spill areas.
389 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
390 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
391 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
392 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
393 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
394 int FramePtrOffsetInPush = 0;
396 FramePtrOffsetInPush =
397 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
398 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
401 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
402 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
403 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
406 if (GPRCS2Size > 0) {
407 GPRCS2Push = LastPush = MBBI++;
408 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
411 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
412 // .cfi_offset operations will reflect that.
414 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
415 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
416 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
418 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
419 MachineInstr::FrameSetup);
420 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
426 // Since vpush register list cannot have gaps, there may be multiple vpush
427 // instructions in the prologue.
428 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
429 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
434 // Move past the aligned DPRCS2 area.
435 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
436 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
437 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
438 // leaves the stack pointer pointing to the DPRCS2 area.
440 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
441 NumBytes += MFI->getObjectOffset(D8SpillFI);
443 NumBytes = DPRCSOffset;
445 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
446 uint32_t NumWords = NumBytes >> 2;
448 if (NumWords < 65536)
449 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
451 .setMIFlags(MachineInstr::FrameSetup));
453 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
455 .setMIFlags(MachineInstr::FrameSetup);
457 switch (TM.getCodeModel()) {
458 case CodeModel::Small:
459 case CodeModel::Medium:
460 case CodeModel::Default:
461 case CodeModel::Kernel:
462 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
463 .addImm((unsigned)ARMCC::AL).addReg(0)
464 .addExternalSymbol("__chkstk")
465 .addReg(ARM::R4, RegState::Implicit)
466 .setMIFlags(MachineInstr::FrameSetup);
468 case CodeModel::Large:
469 case CodeModel::JITDefault:
470 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
471 .addExternalSymbol("__chkstk")
472 .setMIFlags(MachineInstr::FrameSetup);
474 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
475 .addImm((unsigned)ARMCC::AL).addReg(0)
476 .addReg(ARM::R12, RegState::Kill)
477 .addReg(ARM::R4, RegState::Implicit)
478 .setMIFlags(MachineInstr::FrameSetup);
482 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
484 .addReg(ARM::SP, RegState::Define)
485 .addReg(ARM::R4, RegState::Kill)
486 .setMIFlags(MachineInstr::FrameSetup)));
491 // Adjust SP after all the callee-save spills.
492 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
493 tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
494 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
496 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
497 MachineInstr::FrameSetup);
498 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
502 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
503 // Note it's not safe to do this in Thumb2 mode because it would have
504 // taken two instructions:
507 // If an interrupt is taken between the two instructions, then sp is in
508 // an inconsistent state (pointing to the middle of callee-saved area).
509 // The interrupt handler can end up clobbering the registers.
510 AFI->setShouldRestoreSPFromFP(true);
513 // Set FP to point to the stack slot that contains the previous FP.
514 // For iOS, FP is R7, which has now been stored in spill area 1.
515 // Otherwise, if this is not iOS, all the callee-saved registers go
516 // into spill area 1, including the FP in R11. In either case, it
517 // is in area one and the adjustment needs to take place just after
520 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
521 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
522 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
523 dl, TII, FramePtr, ARM::SP,
524 PushSize + FramePtrOffsetInPush,
525 MachineInstr::FrameSetup);
526 if (FramePtrOffsetInPush + PushSize != 0) {
527 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
528 nullptr, MRI->getDwarfRegNum(FramePtr, true),
529 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
530 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
531 .addCFIIndex(CFIIndex)
532 .setMIFlags(MachineInstr::FrameSetup);
535 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
536 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
537 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
538 .addCFIIndex(CFIIndex)
539 .setMIFlags(MachineInstr::FrameSetup);
543 // Now that the prologue's actual instructions are finalised, we can insert
544 // the necessary DWARF cf instructions to describe the situation. Start by
545 // recording where each register ended up:
546 if (GPRCS1Size > 0) {
547 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
549 for (const auto &Entry : CSI) {
550 unsigned Reg = Entry.getReg();
551 int FI = Entry.getFrameIdx();
558 if (STI.isTargetDarwin())
570 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
571 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
572 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
573 .addCFIIndex(CFIIndex)
574 .setMIFlags(MachineInstr::FrameSetup);
580 if (GPRCS2Size > 0) {
581 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
582 for (const auto &Entry : CSI) {
583 unsigned Reg = Entry.getReg();
584 int FI = Entry.getFrameIdx();
591 if (STI.isTargetDarwin()) {
592 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
593 unsigned Offset = MFI->getObjectOffset(FI);
594 unsigned CFIIndex = MMI.addFrameInst(
595 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
596 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
597 .addCFIIndex(CFIIndex)
598 .setMIFlags(MachineInstr::FrameSetup);
606 // Since vpush register list cannot have gaps, there may be multiple vpush
607 // instructions in the prologue.
608 MachineBasicBlock::iterator Pos = std::next(LastPush);
609 for (const auto &Entry : CSI) {
610 unsigned Reg = Entry.getReg();
611 int FI = Entry.getFrameIdx();
612 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
613 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
614 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
615 unsigned Offset = MFI->getObjectOffset(FI);
616 unsigned CFIIndex = MMI.addFrameInst(
617 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
618 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
619 .addCFIIndex(CFIIndex)
620 .setMIFlags(MachineInstr::FrameSetup);
625 // Now we can emit descriptions of where the canonical frame address was
626 // throughout the process. If we have a frame pointer, it takes over the job
627 // half-way through, so only the first few .cfi_def_cfa_offset instructions
628 // actually get emitted.
629 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
631 if (STI.isTargetELF() && hasFP(MF))
632 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
633 AFI->getFramePtrSpillOffset());
635 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
636 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
637 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
638 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
640 // If we need dynamic stack realignment, do it here. Be paranoid and make
641 // sure if we also have VLAs, we have a base pointer for frame access.
642 // If aligned NEON registers were spilled, the stack has already been
644 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
645 unsigned MaxAlign = MFI->getMaxAlignment();
646 assert(!AFI->isThumb1OnlyFunction());
647 if (!AFI->isThumbFunction()) {
648 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
651 // We cannot use sp as source/dest register here, thus we're using r4 to
652 // perform the calculations. We're emitting the following sequence:
654 // -- use emitAligningInstructions to produce best sequence to zero
655 // -- out lower bits in r4
657 // FIXME: It will be better just to find spare register here.
658 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
659 .addReg(ARM::SP, RegState::Kill));
660 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
662 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
663 .addReg(ARM::R4, RegState::Kill));
666 AFI->setShouldRestoreSPFromFP(true);
669 // If we need a base pointer, set it up here. It's whatever the value
670 // of the stack pointer is at this point. Any variable size objects
671 // will be allocated after this, so we can still use the base pointer
672 // to reference locals.
673 // FIXME: Clarify FrameSetup flags here.
674 if (RegInfo->hasBasePointer(MF)) {
676 BuildMI(MBB, MBBI, dl,
677 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
679 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
681 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
682 RegInfo->getBaseRegister())
686 // If the frame has variable sized objects then the epilogue must restore
687 // the sp from fp. We can assume there's an FP here since hasFP already
688 // checks for hasVarSizedObjects.
689 if (MFI->hasVarSizedObjects())
690 AFI->setShouldRestoreSPFromFP(true);
693 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
694 MachineBasicBlock &MBB) const {
695 MachineFrameInfo *MFI = MF.getFrameInfo();
696 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
697 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
698 const ARMBaseInstrInfo &TII =
699 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
700 assert(!AFI->isThumb1OnlyFunction() &&
701 "This emitEpilogue does not support Thumb1!");
702 bool isARM = !AFI->isThumbFunction();
704 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
705 int NumBytes = (int)MFI->getStackSize();
706 unsigned FramePtr = RegInfo->getFrameRegister(MF);
708 // All calls are tail calls in GHC calling conv, and functions have no
709 // prologue/epilogue.
710 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
713 // First put ourselves on the first (from top) terminator instructions.
714 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
715 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
717 if (!AFI->hasStackFrame()) {
718 if (NumBytes - ArgRegsSaveSize != 0)
719 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
721 // Unwind MBBI to point to first LDR / VLDRD.
722 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
723 if (MBBI != MBB.begin()) {
726 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
727 if (!isCSRestore(MBBI, TII, CSRegs))
731 // Move SP to start of FP callee save spill area.
732 NumBytes -= (ArgRegsSaveSize +
733 AFI->getGPRCalleeSavedArea1Size() +
734 AFI->getGPRCalleeSavedArea2Size() +
735 AFI->getDPRCalleeSavedGapSize() +
736 AFI->getDPRCalleeSavedAreaSize());
738 // Reset SP based on frame pointer only if the stack frame extends beyond
739 // frame pointer stack slot or target is ELF and the function has FP.
740 if (AFI->shouldRestoreSPFromFP()) {
741 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
744 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
747 // It's not possible to restore SP from FP in a single instruction.
748 // For iOS, this looks like:
751 // This is bad, if an interrupt is taken after the mov, sp is in an
752 // inconsistent state.
753 // Use the first callee-saved register as a scratch register.
754 assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
755 "No scratch register to restore SP from FP!");
756 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
758 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
765 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
766 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
768 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
772 } else if (NumBytes &&
773 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
774 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
776 // Increment past our save areas.
777 if (AFI->getDPRCalleeSavedAreaSize()) {
779 // Since vpop register list cannot have gaps, there may be multiple vpop
780 // instructions in the epilogue.
781 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
784 if (AFI->getDPRCalleeSavedGapSize()) {
785 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
786 "unexpected DPR alignment gap");
787 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
790 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
791 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
795 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
798 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
799 /// debug info. It's the same as what we use for resolving the code-gen
800 /// references for now. FIXME: This can go wrong when references are
801 /// SP-relative and simple call frames aren't used.
803 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
804 unsigned &FrameReg) const {
805 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
809 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
810 int FI, unsigned &FrameReg,
812 const MachineFrameInfo *MFI = MF.getFrameInfo();
813 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
814 MF.getSubtarget().getRegisterInfo());
815 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
816 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
817 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
818 bool isFixed = MFI->isFixedObjectIndex(FI);
823 // SP can move around if there are allocas. We may also lose track of SP
824 // when emergency spilling inside a non-reserved call frame setup.
825 bool hasMovingSP = !hasReservedCallFrame(MF);
827 // When dynamically realigning the stack, use the frame pointer for
828 // parameters, and the stack/base pointer for locals.
829 if (RegInfo->needsStackRealignment(MF)) {
830 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
832 FrameReg = RegInfo->getFrameRegister(MF);
834 } else if (hasMovingSP) {
835 assert(RegInfo->hasBasePointer(MF) &&
836 "VLAs and dynamic stack alignment, but missing base pointer!");
837 FrameReg = RegInfo->getBaseRegister();
842 // If there is a frame pointer, use it when we can.
843 if (hasFP(MF) && AFI->hasStackFrame()) {
844 // Use frame pointer to reference fixed objects. Use it for locals if
845 // there are VLAs (and thus the SP isn't reliable as a base).
846 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
847 FrameReg = RegInfo->getFrameRegister(MF);
849 } else if (hasMovingSP) {
850 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
851 if (AFI->isThumb2Function()) {
852 // Try to use the frame pointer if we can, else use the base pointer
853 // since it's available. This is handy for the emergency spill slot, in
855 if (FPOffset >= -255 && FPOffset < 0) {
856 FrameReg = RegInfo->getFrameRegister(MF);
860 } else if (AFI->isThumb2Function()) {
861 // Use add <rd>, sp, #<imm8>
862 // ldr <rd>, [sp, #<imm8>]
863 // if at all possible to save space.
864 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
866 // In Thumb2 mode, the negative offset is very limited. Try to avoid
867 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
868 if (FPOffset >= -255 && FPOffset < 0) {
869 FrameReg = RegInfo->getFrameRegister(MF);
872 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
873 // Otherwise, use SP or FP, whichever is closer to the stack slot.
874 FrameReg = RegInfo->getFrameRegister(MF);
878 // Use the base pointer if we have one.
879 if (RegInfo->hasBasePointer(MF))
880 FrameReg = RegInfo->getBaseRegister();
884 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
885 MachineBasicBlock::iterator MI,
886 const std::vector<CalleeSavedInfo> &CSI,
887 unsigned StmOpc, unsigned StrOpc,
889 bool(*Func)(unsigned, bool),
890 unsigned NumAlignedDPRCS2Regs,
891 unsigned MIFlags) const {
892 MachineFunction &MF = *MBB.getParent();
893 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
896 if (MI != MBB.end()) DL = MI->getDebugLoc();
898 SmallVector<std::pair<unsigned,bool>, 4> Regs;
899 unsigned i = CSI.size();
901 unsigned LastReg = 0;
902 for (; i != 0; --i) {
903 unsigned Reg = CSI[i-1].getReg();
904 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
906 // D-registers in the aligned area DPRCS2 are NOT spilled here.
907 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
910 // Add the callee-saved register as live-in unless it's LR and
911 // @llvm.returnaddress is called. If LR is returned for
912 // @llvm.returnaddress then it's already added to the function and
913 // entry block live-in sets.
915 if (Reg == ARM::LR) {
916 if (MF.getFrameInfo()->isReturnAddressTaken() &&
917 MF.getRegInfo().isLiveIn(Reg))
924 // If NoGap is true, push consecutive registers and then leave the rest
925 // for other instructions. e.g.
926 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
927 if (NoGap && LastReg && LastReg != Reg-1)
930 Regs.push_back(std::make_pair(Reg, isKill));
935 if (Regs.size() > 1 || StrOpc== 0) {
936 MachineInstrBuilder MIB =
937 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
938 .addReg(ARM::SP).setMIFlags(MIFlags));
939 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
940 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
941 } else if (Regs.size() == 1) {
942 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
944 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
945 .addReg(ARM::SP).setMIFlags(MIFlags)
951 // Put any subsequent vpush instructions before this one: they will refer to
952 // higher register numbers so need to be pushed first in order to preserve
954 if (MI != MBB.begin())
959 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
960 MachineBasicBlock::iterator MI,
961 const std::vector<CalleeSavedInfo> &CSI,
962 unsigned LdmOpc, unsigned LdrOpc,
963 bool isVarArg, bool NoGap,
964 bool(*Func)(unsigned, bool),
965 unsigned NumAlignedDPRCS2Regs) const {
966 MachineFunction &MF = *MBB.getParent();
967 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
968 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
970 bool isTailCall = false;
971 bool isInterrupt = false;
973 if (MBB.end() != MI) {
974 DL = MI->getDebugLoc();
975 unsigned RetOpcode = MI->getOpcode();
976 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
978 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
980 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
981 RetOpcode == ARM::tTRAP;
984 SmallVector<unsigned, 4> Regs;
985 unsigned i = CSI.size();
987 unsigned LastReg = 0;
988 bool DeleteRet = false;
989 for (; i != 0; --i) {
990 unsigned Reg = CSI[i-1].getReg();
991 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
993 // The aligned reloads from area DPRCS2 are not inserted here.
994 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
997 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
998 !isTrap && STI.hasV5TOps()) {
999 if (MBB.succ_empty()) {
1002 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1004 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1005 // Fold the return instruction into the LDM.
1008 // If NoGap is true, pop consecutive registers and then leave the rest
1009 // for other instructions. e.g.
1010 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1011 if (NoGap && LastReg && LastReg != Reg-1)
1015 Regs.push_back(Reg);
1020 if (Regs.size() > 1 || LdrOpc == 0) {
1021 MachineInstrBuilder MIB =
1022 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1024 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1025 MIB.addReg(Regs[i], getDefRegState(true));
1026 if (DeleteRet && MI != MBB.end()) {
1027 MIB.copyImplicitOps(&*MI);
1028 MI->eraseFromParent();
1031 } else if (Regs.size() == 1) {
1032 // If we adjusted the reg to PC from LR above, switch it back here. We
1033 // only do that for LDM.
1034 if (Regs[0] == ARM::PC)
1036 MachineInstrBuilder MIB =
1037 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1038 .addReg(ARM::SP, RegState::Define)
1040 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1041 // that refactoring is complete (eventually).
1042 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1044 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1047 AddDefaultPred(MIB);
1051 // Put any subsequent vpop instructions after this one: they will refer to
1052 // higher register numbers so need to be popped afterwards.
1053 if (MI != MBB.end())
1058 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1059 /// starting from d8. Also insert stack realignment code and leave the stack
1060 /// pointer pointing to the d8 spill slot.
1061 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1062 MachineBasicBlock::iterator MI,
1063 unsigned NumAlignedDPRCS2Regs,
1064 const std::vector<CalleeSavedInfo> &CSI,
1065 const TargetRegisterInfo *TRI) {
1066 MachineFunction &MF = *MBB.getParent();
1067 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1068 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1069 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1070 MachineFrameInfo &MFI = *MF.getFrameInfo();
1072 // Mark the D-register spill slots as properly aligned. Since MFI computes
1073 // stack slot layout backwards, this can actually mean that the d-reg stack
1074 // slot offsets can be wrong. The offset for d8 will always be correct.
1075 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1076 unsigned DNum = CSI[i].getReg() - ARM::D8;
1077 if (DNum > NumAlignedDPRCS2Regs - 1)
1079 int FI = CSI[i].getFrameIdx();
1080 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1081 // registers will be 8-byte aligned.
1082 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1084 // The stack slot for D8 needs to be maximally aligned because this is
1085 // actually the point where we align the stack pointer. MachineFrameInfo
1086 // computes all offsets relative to the incoming stack pointer which is a
1087 // bit weird when realigning the stack. Any extra padding for this
1088 // over-alignment is not realized because the code inserted below adjusts
1089 // the stack pointer by numregs * 8 before aligning the stack pointer.
1091 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1094 // Move the stack pointer to the d8 spill slot, and align it at the same
1095 // time. Leave the stack slot address in the scratch register r4.
1097 // sub r4, sp, #numregs * 8
1098 // bic r4, r4, #align - 1
1101 bool isThumb = AFI->isThumbFunction();
1102 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1103 AFI->setShouldRestoreSPFromFP(true);
1105 // sub r4, sp, #numregs * 8
1106 // The immediate is <= 64, so it doesn't need any special encoding.
1107 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1108 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1110 .addImm(8 * NumAlignedDPRCS2Regs)));
1112 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1113 // We must set parameter MustBeSingleInstruction to true, since
1114 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1115 // stack alignment. Luckily, this can always be done since all ARM
1116 // architecture versions that support Neon also support the BFC
1118 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1121 // The stack pointer must be adjusted before spilling anything, otherwise
1122 // the stack slots could be clobbered by an interrupt handler.
1123 // Leave r4 live, it is used below.
1124 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1125 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1127 MIB = AddDefaultPred(MIB);
1131 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1132 // r4 holds the stack slot address.
1133 unsigned NextReg = ARM::D8;
1135 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1136 // The writeback is only needed when emitting two vst1.64 instructions.
1137 if (NumAlignedDPRCS2Regs >= 6) {
1138 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1139 &ARM::QQPRRegClass);
1140 MBB.addLiveIn(SupReg);
1141 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1143 .addReg(ARM::R4, RegState::Kill).addImm(16)
1145 .addReg(SupReg, RegState::ImplicitKill));
1147 NumAlignedDPRCS2Regs -= 4;
1150 // We won't modify r4 beyond this point. It currently points to the next
1151 // register to be spilled.
1152 unsigned R4BaseReg = NextReg;
1154 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1155 if (NumAlignedDPRCS2Regs >= 4) {
1156 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1157 &ARM::QQPRRegClass);
1158 MBB.addLiveIn(SupReg);
1159 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1160 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1161 .addReg(SupReg, RegState::ImplicitKill));
1163 NumAlignedDPRCS2Regs -= 4;
1166 // 16-byte aligned vst1.64 with 2 d-regs.
1167 if (NumAlignedDPRCS2Regs >= 2) {
1168 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1170 MBB.addLiveIn(SupReg);
1171 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1172 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1174 NumAlignedDPRCS2Regs -= 2;
1177 // Finally, use a vanilla vstr.64 for the odd last register.
1178 if (NumAlignedDPRCS2Regs) {
1179 MBB.addLiveIn(NextReg);
1180 // vstr.64 uses addrmode5 which has an offset scale of 4.
1181 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1183 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1186 // The last spill instruction inserted should kill the scratch register r4.
1187 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1190 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1191 /// iterator to the following instruction.
1192 static MachineBasicBlock::iterator
1193 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1194 unsigned NumAlignedDPRCS2Regs) {
1195 // sub r4, sp, #numregs * 8
1196 // bic r4, r4, #align - 1
1199 assert(MI->mayStore() && "Expecting spill instruction");
1201 // These switches all fall through.
1202 switch(NumAlignedDPRCS2Regs) {
1205 assert(MI->mayStore() && "Expecting spill instruction");
1208 assert(MI->mayStore() && "Expecting spill instruction");
1212 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1218 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1219 /// starting from d8. These instructions are assumed to execute while the
1220 /// stack is still aligned, unlike the code inserted by emitPopInst.
1221 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1222 MachineBasicBlock::iterator MI,
1223 unsigned NumAlignedDPRCS2Regs,
1224 const std::vector<CalleeSavedInfo> &CSI,
1225 const TargetRegisterInfo *TRI) {
1226 MachineFunction &MF = *MBB.getParent();
1227 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1228 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1229 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1231 // Find the frame index assigned to d8.
1233 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1234 if (CSI[i].getReg() == ARM::D8) {
1235 D8SpillFI = CSI[i].getFrameIdx();
1239 // Materialize the address of the d8 spill slot into the scratch register r4.
1240 // This can be fairly complicated if the stack frame is large, so just use
1241 // the normal frame index elimination mechanism to do it. This code runs as
1242 // the initial part of the epilog where the stack and base pointers haven't
1243 // been changed yet.
1244 bool isThumb = AFI->isThumbFunction();
1245 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1247 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1248 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1249 .addFrameIndex(D8SpillFI).addImm(0)));
1251 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1252 unsigned NextReg = ARM::D8;
1254 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1255 if (NumAlignedDPRCS2Regs >= 6) {
1256 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1257 &ARM::QQPRRegClass);
1258 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1259 .addReg(ARM::R4, RegState::Define)
1260 .addReg(ARM::R4, RegState::Kill).addImm(16)
1261 .addReg(SupReg, RegState::ImplicitDefine));
1263 NumAlignedDPRCS2Regs -= 4;
1266 // We won't modify r4 beyond this point. It currently points to the next
1267 // register to be spilled.
1268 unsigned R4BaseReg = NextReg;
1270 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1271 if (NumAlignedDPRCS2Regs >= 4) {
1272 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1273 &ARM::QQPRRegClass);
1274 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1275 .addReg(ARM::R4).addImm(16)
1276 .addReg(SupReg, RegState::ImplicitDefine));
1278 NumAlignedDPRCS2Regs -= 4;
1281 // 16-byte aligned vld1.64 with 2 d-regs.
1282 if (NumAlignedDPRCS2Regs >= 2) {
1283 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1285 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1286 .addReg(ARM::R4).addImm(16));
1288 NumAlignedDPRCS2Regs -= 2;
1291 // Finally, use a vanilla vldr.64 for the remaining odd register.
1292 if (NumAlignedDPRCS2Regs)
1293 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1294 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1296 // Last store kills r4.
1297 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1300 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1301 MachineBasicBlock::iterator MI,
1302 const std::vector<CalleeSavedInfo> &CSI,
1303 const TargetRegisterInfo *TRI) const {
1307 MachineFunction &MF = *MBB.getParent();
1308 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1310 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1311 unsigned PushOneOpc = AFI->isThumbFunction() ?
1312 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1313 unsigned FltOpc = ARM::VSTMDDB_UPD;
1314 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1315 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1316 MachineInstr::FrameSetup);
1317 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1318 MachineInstr::FrameSetup);
1319 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1320 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1322 // The code above does not insert spill code for the aligned DPRCS2 registers.
1323 // The stack realignment code will be inserted between the push instructions
1324 // and these spills.
1325 if (NumAlignedDPRCS2Regs)
1326 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1331 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1332 MachineBasicBlock::iterator MI,
1333 const std::vector<CalleeSavedInfo> &CSI,
1334 const TargetRegisterInfo *TRI) const {
1338 MachineFunction &MF = *MBB.getParent();
1339 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1340 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1341 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1343 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1344 // registers. Do that here instead.
1345 if (NumAlignedDPRCS2Regs)
1346 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1348 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1349 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1350 unsigned FltOpc = ARM::VLDMDIA_UPD;
1351 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1352 NumAlignedDPRCS2Regs);
1353 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1354 &isARMArea2Register, 0);
1355 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1356 &isARMArea1Register, 0);
1361 // FIXME: Make generic?
1362 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1363 const ARMBaseInstrInfo &TII) {
1364 unsigned FnSize = 0;
1365 for (auto &MBB : MF) {
1366 for (auto &MI : MBB)
1367 FnSize += TII.GetInstSizeInBytes(&MI);
1372 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1373 /// frames and return the stack size limit beyond which some of these
1374 /// instructions will require a scratch register during their expansion later.
1375 // FIXME: Move to TII?
1376 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1377 const TargetFrameLowering *TFI) {
1378 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1379 unsigned Limit = (1 << 12) - 1;
1380 for (auto &MBB : MF) {
1381 for (auto &MI : MBB) {
1382 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1383 if (!MI.getOperand(i).isFI())
1386 // When using ADDri to get the address of a stack object, 255 is the
1387 // largest offset guaranteed to fit in the immediate offset.
1388 if (MI.getOpcode() == ARM::ADDri) {
1389 Limit = std::min(Limit, (1U << 8) - 1);
1393 // Otherwise check the addressing mode.
1394 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1395 case ARMII::AddrMode3:
1396 case ARMII::AddrModeT2_i8:
1397 Limit = std::min(Limit, (1U << 8) - 1);
1399 case ARMII::AddrMode5:
1400 case ARMII::AddrModeT2_i8s4:
1401 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1403 case ARMII::AddrModeT2_i12:
1404 // i12 supports only positive offset so these will be converted to
1405 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1406 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1407 Limit = std::min(Limit, (1U << 8) - 1);
1409 case ARMII::AddrMode4:
1410 case ARMII::AddrMode6:
1411 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1412 // immediate offset for stack references.
1417 break; // At most one FI per instruction
1425 // In functions that realign the stack, it can be an advantage to spill the
1426 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1427 // instructions take alignment hints that can improve performance.
1430 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1431 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1432 if (!SpillAlignedNEONRegs)
1435 // Naked functions don't spill callee-saved registers.
1436 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1439 // We are planning to use NEON instructions vst1 / vld1.
1440 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1443 // Don't bother if the default stack alignment is sufficiently high.
1444 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1447 // Aligned spills require stack realignment.
1448 if (!static_cast<const ARMBaseRegisterInfo *>(
1449 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1452 // We always spill contiguous d-registers starting from d8. Count how many
1453 // needs spilling. The register allocator will almost always use the
1454 // callee-saved registers in order, but it can happen that there are holes in
1455 // the range. Registers above the hole will be spilled to the standard DPRCS
1457 unsigned NumSpills = 0;
1458 for (; NumSpills < 8; ++NumSpills)
1459 if (!SavedRegs.test(ARM::D8 + NumSpills))
1462 // Don't do this for just one d-register. It's not worth it.
1466 // Spill the first NumSpills D-registers after realigning the stack.
1467 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1469 // A scratch register is required for the vst1 / vld1 instructions.
1470 SavedRegs.set(ARM::R4);
1473 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1474 BitVector &SavedRegs,
1475 RegScavenger *RS) const {
1476 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1477 // This tells PEI to spill the FP as if it is any other callee-save register
1478 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1479 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1480 // to combine multiple loads / stores.
1481 bool CanEliminateFrame = true;
1482 bool CS1Spilled = false;
1483 bool LRSpilled = false;
1484 unsigned NumGPRSpills = 0;
1485 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1486 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1487 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1488 MF.getSubtarget().getRegisterInfo());
1489 const ARMBaseInstrInfo &TII =
1490 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1491 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1492 MachineFrameInfo *MFI = MF.getFrameInfo();
1493 MachineRegisterInfo &MRI = MF.getRegInfo();
1494 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1496 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1497 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1498 // since it's not always possible to restore sp from fp in a single
1500 // FIXME: It will be better just to find spare register here.
1501 if (AFI->isThumb2Function() &&
1502 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1503 SavedRegs.set(ARM::R4);
1505 if (AFI->isThumb1OnlyFunction()) {
1506 // Spill LR if Thumb1 function uses variable length argument lists.
1507 if (AFI->getArgRegsSaveSize() > 0)
1508 SavedRegs.set(ARM::LR);
1510 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1511 // for sure what the stack size will be, but for this, an estimate is good
1512 // enough. If there anything changes it, it'll be a spill, which implies
1513 // we've used all the registers and so R4 is already used, so not marking
1514 // it here will be OK.
1515 // FIXME: It will be better just to find spare register here.
1516 unsigned StackSize = MFI->estimateStackSize(MF);
1517 if (MFI->hasVarSizedObjects() || StackSize > 508)
1518 SavedRegs.set(ARM::R4);
1521 // See if we can spill vector registers to aligned stack.
1522 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1524 // Spill the BasePtr if it's used.
1525 if (RegInfo->hasBasePointer(MF))
1526 SavedRegs.set(RegInfo->getBaseRegister());
1528 // Don't spill FP if the frame can be eliminated. This is determined
1529 // by scanning the callee-save registers to see if any is modified.
1530 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1531 for (unsigned i = 0; CSRegs[i]; ++i) {
1532 unsigned Reg = CSRegs[i];
1533 bool Spilled = false;
1534 if (SavedRegs.test(Reg)) {
1536 CanEliminateFrame = false;
1539 if (!ARM::GPRRegClass.contains(Reg))
1545 if (!STI.isTargetDarwin()) {
1552 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1557 case ARM::R0: case ARM::R1:
1558 case ARM::R2: case ARM::R3:
1559 case ARM::R4: case ARM::R5:
1560 case ARM::R6: case ARM::R7:
1567 if (!STI.isTargetDarwin()) {
1568 UnspilledCS1GPRs.push_back(Reg);
1573 case ARM::R0: case ARM::R1:
1574 case ARM::R2: case ARM::R3:
1575 case ARM::R4: case ARM::R5:
1576 case ARM::R6: case ARM::R7:
1578 UnspilledCS1GPRs.push_back(Reg);
1581 UnspilledCS2GPRs.push_back(Reg);
1587 bool ForceLRSpill = false;
1588 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1589 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1590 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1591 // use of BL to implement far jump. If it turns out that it's not needed
1592 // then the branch fix up path will undo it.
1593 if (FnSize >= (1 << 11)) {
1594 CanEliminateFrame = false;
1595 ForceLRSpill = true;
1599 // If any of the stack slot references may be out of range of an immediate
1600 // offset, make sure a register (or a spill slot) is available for the
1601 // register scavenger. Note that if we're indexing off the frame pointer, the
1602 // effective stack size is 4 bytes larger since the FP points to the stack
1603 // slot of the previous FP. Also, if we have variable sized objects in the
1604 // function, stack slot references will often be negative, and some of
1605 // our instructions are positive-offset only, so conservatively consider
1606 // that case to want a spill slot (or register) as well. Similarly, if
1607 // the function adjusts the stack pointer during execution and the
1608 // adjustments aren't already part of our stack size estimate, our offset
1609 // calculations may be off, so be conservative.
1610 // FIXME: We could add logic to be more precise about negative offsets
1611 // and which instructions will need a scratch register for them. Is it
1612 // worth the effort and added fragility?
1613 bool BigStack = (RS && (MFI->estimateStackSize(MF) +
1614 ((hasFP(MF) && AFI->hasStackFrame()) ? 4 : 0) >=
1615 estimateRSStackSizeLimit(MF, this))) ||
1616 MFI->hasVarSizedObjects() ||
1617 (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1619 bool ExtraCSSpill = false;
1620 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1621 AFI->setHasStackFrame(true);
1623 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1624 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1625 if (!LRSpilled && CS1Spilled) {
1626 SavedRegs.set(ARM::LR);
1628 SmallVectorImpl<unsigned>::iterator LRPos;
1629 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1631 if (LRPos != UnspilledCS1GPRs.end())
1632 UnspilledCS1GPRs.erase(LRPos);
1634 ForceLRSpill = false;
1635 ExtraCSSpill = true;
1639 SavedRegs.set(FramePtr);
1640 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1642 if (FPPos != UnspilledCS1GPRs.end())
1643 UnspilledCS1GPRs.erase(FPPos);
1647 // If stack and double are 8-byte aligned and we are spilling an odd number
1648 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1649 // the integer and double callee save areas.
1650 unsigned TargetAlign = getStackAlignment();
1651 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1652 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1653 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1654 unsigned Reg = UnspilledCS1GPRs[i];
1655 // Don't spill high register if the function is thumb. In the case of
1656 // Windows on ARM, accept R11 (frame pointer)
1657 if (!AFI->isThumbFunction() ||
1658 (STI.isTargetWindows() && Reg == ARM::R11) ||
1659 isARMLowRegister(Reg) || Reg == ARM::LR) {
1661 if (!MRI.isReserved(Reg))
1662 ExtraCSSpill = true;
1666 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1667 unsigned Reg = UnspilledCS2GPRs.front();
1669 if (!MRI.isReserved(Reg))
1670 ExtraCSSpill = true;
1674 // Estimate if we might need to scavenge a register at some point in order
1675 // to materialize a stack offset. If so, either spill one additional
1676 // callee-saved register or reserve a special spill slot to facilitate
1677 // register scavenging. Thumb1 needs a spill slot for stack pointer
1678 // adjustments also, even when the frame itself is small.
1679 if (BigStack && !ExtraCSSpill) {
1680 // If any non-reserved CS register isn't spilled, just spill one or two
1681 // extra. That should take care of it!
1682 unsigned NumExtras = TargetAlign / 4;
1683 SmallVector<unsigned, 2> Extras;
1684 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1685 unsigned Reg = UnspilledCS1GPRs.back();
1686 UnspilledCS1GPRs.pop_back();
1687 if (!MRI.isReserved(Reg) &&
1688 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1690 Extras.push_back(Reg);
1694 // For non-Thumb1 functions, also check for hi-reg CS registers
1695 if (!AFI->isThumb1OnlyFunction()) {
1696 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1697 unsigned Reg = UnspilledCS2GPRs.back();
1698 UnspilledCS2GPRs.pop_back();
1699 if (!MRI.isReserved(Reg)) {
1700 Extras.push_back(Reg);
1705 if (Extras.size() && NumExtras == 0) {
1706 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1707 SavedRegs.set(Extras[i]);
1709 } else if (!AFI->isThumb1OnlyFunction()) {
1710 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1711 // closest to SP or frame pointer.
1712 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1713 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1721 SavedRegs.set(ARM::LR);
1722 AFI->setLRIsSpilledForFarJump(true);
1727 void ARMFrameLowering::
1728 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1729 MachineBasicBlock::iterator I) const {
1730 const ARMBaseInstrInfo &TII =
1731 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1732 if (!hasReservedCallFrame(MF)) {
1733 // If we have alloca, convert as follows:
1734 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1735 // ADJCALLSTACKUP -> add, sp, sp, amount
1736 MachineInstr *Old = I;
1737 DebugLoc dl = Old->getDebugLoc();
1738 unsigned Amount = Old->getOperand(0).getImm();
1740 // We need to keep the stack aligned properly. To do this, we round the
1741 // amount of space needed for the outgoing arguments up to the next
1742 // alignment boundary.
1743 Amount = alignSPAdjust(Amount);
1745 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1746 assert(!AFI->isThumb1OnlyFunction() &&
1747 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1748 bool isARM = !AFI->isThumbFunction();
1750 // Replace the pseudo instruction with a new instruction...
1751 unsigned Opc = Old->getOpcode();
1752 int PIdx = Old->findFirstPredOperandIdx();
1753 ARMCC::CondCodes Pred = (PIdx == -1)
1754 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1755 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1756 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1757 unsigned PredReg = Old->getOperand(2).getReg();
1758 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1761 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1762 unsigned PredReg = Old->getOperand(3).getReg();
1763 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1764 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1772 /// Get the minimum constant for ARM that is greater than or equal to the
1773 /// argument. In ARM, constants can have any value that can be produced by
1774 /// rotating an 8-bit value to the right by an even number of bits within a
1776 static uint32_t alignToARMConstant(uint32_t Value) {
1777 unsigned Shifted = 0;
1782 while (!(Value & 0xC0000000)) {
1787 bool Carry = (Value & 0x00FFFFFF);
1788 Value = ((Value & 0xFF000000) >> 24) + Carry;
1790 if (Value & 0x0000100)
1791 Value = Value & 0x000001FC;
1794 Value = Value >> (Shifted - 24);
1796 Value = Value << (24 - Shifted);
1801 // The stack limit in the TCB is set to this many bytes above the actual
1803 static const uint64_t kSplitStackAvailable = 256;
1805 // Adjust the function prologue to enable split stacks. This currently only
1806 // supports android and linux.
1808 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1809 // must be well defined in order to allow for consistent implementations of the
1810 // __morestack helper function. The ABI is also not a normal ABI in that it
1811 // doesn't follow the normal calling conventions because this allows the
1812 // prologue of each function to be optimized further.
1814 // Currently, the ABI looks like (when calling __morestack)
1816 // * r4 holds the minimum stack size requested for this function call
1817 // * r5 holds the stack size of the arguments to the function
1818 // * the beginning of the function is 3 instructions after the call to
1821 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1822 // place the arguments on to the new stack, and the 3-instruction knowledge to
1823 // jump directly to the body of the function when working on the new stack.
1825 // An old (and possibly no longer compatible) implementation of __morestack for
1826 // ARM can be found at [1].
1828 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1829 void ARMFrameLowering::adjustForSegmentedStacks(
1830 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1833 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
1834 bool Thumb = ST->isThumb();
1836 // Sadly, this currently doesn't support varargs, platforms other than
1837 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1838 if (MF.getFunction()->isVarArg())
1839 report_fatal_error("Segmented stacks do not support vararg functions.");
1840 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1841 report_fatal_error("Segmented stacks not supported on this platform.");
1843 MachineFrameInfo *MFI = MF.getFrameInfo();
1844 MachineModuleInfo &MMI = MF.getMMI();
1845 MCContext &Context = MMI.getContext();
1846 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1847 const ARMBaseInstrInfo &TII =
1848 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1849 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1852 uint64_t StackSize = MFI->getStackSize();
1854 // Do not generate a prologue for functions with a stack of size zero
1858 // Use R4 and R5 as scratch registers.
1859 // We save R4 and R5 before use and restore them before leaving the function.
1860 unsigned ScratchReg0 = ARM::R4;
1861 unsigned ScratchReg1 = ARM::R5;
1862 uint64_t AlignedStackSize;
1864 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1865 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1866 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1867 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1868 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1870 // Grab everything that reaches PrologueMBB to update there liveness as well.
1871 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
1872 SmallVector<MachineBasicBlock *, 2> WalkList;
1873 WalkList.push_back(&PrologueMBB);
1876 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
1877 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
1878 if (BeforePrologueRegion.insert(PredBB).second)
1879 WalkList.push_back(PredBB);
1881 } while (!WalkList.empty());
1883 // The order in that list is important.
1884 // The blocks will all be inserted before PrologueMBB using that order.
1885 // Therefore the block that should appear first in the CFG should appear
1886 // first in the list.
1887 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
1889 const int NbAddedBlocks = sizeof(AddedBlocks) / sizeof(AddedBlocks[0]);
1891 for (int Idx = 0; Idx < NbAddedBlocks; ++Idx)
1892 BeforePrologueRegion.insert(AddedBlocks[Idx]);
1894 for (const auto &LI : PrologueMBB.liveins()) {
1895 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
1896 PredBB->addLiveIn(LI);
1899 // Remove the newly added blocks from the list, since we know
1900 // we do not have to do the following updates for them.
1901 for (int Idx = 0; Idx < NbAddedBlocks; ++Idx) {
1902 BeforePrologueRegion.erase(AddedBlocks[Idx]);
1903 MF.insert(PrologueMBB.getIterator(), AddedBlocks[Idx]);
1906 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
1907 // Make sure the LiveIns are still sorted and unique.
1908 MBB->sortUniqueLiveIns();
1909 // Replace the edges to PrologueMBB by edges to the sequences
1910 // we are about to add.
1911 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
1914 // The required stack size that is aligned to ARM constant criterion.
1915 AlignedStackSize = alignToARMConstant(StackSize);
1917 // When the frame size is less than 256 we just compare the stack
1918 // boundary directly to the value of the stack pointer, per gcc.
1919 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1921 // We will use two of the callee save registers as scratch registers so we
1922 // need to save those registers onto the stack.
1923 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1924 // requested and arguments for __morestack().
1925 // SR0: Scratch Register #0
1926 // SR1: Scratch Register #1
1929 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1930 .addReg(ScratchReg0).addReg(ScratchReg1);
1932 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1933 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1934 .addReg(ScratchReg0).addReg(ScratchReg1);
1937 // Emit the relevant DWARF information about the change in stack pointer as
1938 // well as where to find both r4 and r5 (the callee-save registers)
1940 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1941 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1942 .addCFIIndex(CFIIndex);
1943 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1944 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1945 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1946 .addCFIIndex(CFIIndex);
1947 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1948 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1949 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1950 .addCFIIndex(CFIIndex);
1954 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1956 } else if (CompareStackPointer) {
1957 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1958 .addReg(ARM::SP)).addReg(0);
1961 // sub SR1, sp, #StackSize
1962 if (!CompareStackPointer && Thumb) {
1964 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1965 .addReg(ScratchReg1).addImm(AlignedStackSize));
1966 } else if (!CompareStackPointer) {
1967 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1968 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1971 if (Thumb && ST->isThumb1Only()) {
1972 unsigned PCLabelId = ARMFI->createPICLabelUId();
1973 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1974 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1975 MachineConstantPool *MCP = MF.getConstantPool();
1976 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
1978 // ldr SR0, [pc, offset(STACK_LIMIT)]
1979 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1980 .addConstantPoolIndex(CPI));
1983 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1984 .addReg(ScratchReg0).addImm(0));
1986 // Get TLS base address from the coprocessor
1987 // mrc p15, #0, SR0, c13, c0, #3
1988 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1995 // Use the last tls slot on android and a private field of the TCP on linux.
1996 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1997 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1999 // Get the stack limit from the right offset
2000 // ldr SR0, [sr0, #4 * TlsOffset]
2001 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2002 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2005 // Compare stack limit with stack size requested.
2007 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2008 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2009 .addReg(ScratchReg0)
2010 .addReg(ScratchReg1));
2012 // This jump is taken if StackLimit < SP - stack required.
2013 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2014 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2019 // Calling __morestack(StackSize, Size of stack arguments).
2020 // __morestack knows that the stack size requested is in SR0(r4)
2021 // and amount size of stack arguments is in SR1(r5).
2023 // Pass first argument for the __morestack by Scratch Register #0.
2024 // The amount size of stack required
2026 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2027 ScratchReg0)).addImm(AlignedStackSize));
2029 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2030 .addImm(AlignedStackSize)).addReg(0);
2032 // Pass second argument for the __morestack by Scratch Register #1.
2033 // The amount size of stack consumed to save function arguments.
2036 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2037 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2039 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2040 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2044 // push {lr} - Save return address of this function.
2046 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2049 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2050 .addReg(ARM::SP, RegState::Define)
2055 // Emit the DWARF info about the change in stack as well as where to find the
2056 // previous link register
2058 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2059 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2060 .addCFIIndex(CFIIndex);
2061 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2062 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2063 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2064 .addCFIIndex(CFIIndex);
2066 // Call __morestack().
2068 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2069 .addExternalSymbol("__morestack");
2071 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2072 .addExternalSymbol("__morestack");
2075 // pop {lr} - Restore return address of this original function.
2077 if (ST->isThumb1Only()) {
2078 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2079 .addReg(ScratchReg0);
2080 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2081 .addReg(ScratchReg0));
2083 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2084 .addReg(ARM::LR, RegState::Define)
2085 .addReg(ARM::SP, RegState::Define)
2090 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2091 .addReg(ARM::SP, RegState::Define)
2096 // Restore SR0 and SR1 in case of __morestack() was called.
2097 // __morestack() will skip PostStackMBB block so we need to restore
2098 // scratch registers from here.
2101 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2102 .addReg(ScratchReg0)
2103 .addReg(ScratchReg1);
2105 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2106 .addReg(ARM::SP, RegState::Define)
2108 .addReg(ScratchReg0)
2109 .addReg(ScratchReg1);
2112 // Update the CFA offset now that we've popped
2113 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2114 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2115 .addCFIIndex(CFIIndex);
2117 // bx lr - Return from this function.
2118 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2119 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2121 // Restore SR0 and SR1 in case of __morestack() was not called.
2124 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2125 .addReg(ScratchReg0)
2126 .addReg(ScratchReg1);
2128 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2129 .addReg(ARM::SP, RegState::Define)
2131 .addReg(ScratchReg0)
2132 .addReg(ScratchReg1);
2135 // Update the CFA offset now that we've popped
2136 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2137 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2138 .addCFIIndex(CFIIndex);
2140 // Tell debuggers that r4 and r5 are now the same as they were in the
2141 // previous function, that they're the "Same Value".
2142 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2143 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2144 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2145 .addCFIIndex(CFIIndex);
2146 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2147 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2148 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2149 .addCFIIndex(CFIIndex);
2151 // Organizing MBB lists
2152 PostStackMBB->addSuccessor(&PrologueMBB);
2154 AllocMBB->addSuccessor(PostStackMBB);
2156 GetMBB->addSuccessor(PostStackMBB);
2157 GetMBB->addSuccessor(AllocMBB);
2159 McrMBB->addSuccessor(GetMBB);
2161 PrevStackMBB->addSuccessor(McrMBB);