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/IR/CallingConv.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Target/TargetOptions.h"
35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36 cl::desc("Align ARM NEON spills in prolog and epilog"));
38 static MachineBasicBlock::iterator
39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
42 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
46 /// hasFP - Return true if the specified function should have a dedicated frame
47 /// pointer register. This is true if the function has variable sized allocas
48 /// or if frame pointer elimination is disabled.
49 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
52 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
58 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
60 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
65 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66 /// not required, we reserve argument space for call sites in the function
67 /// immediately on entry to the current function. This eliminates the need for
68 /// add/sub sp brackets around call sites. Returns true if the call frame is
69 /// included as part of the stack frame.
70 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
71 const MachineFrameInfo *FFI = MF.getFrameInfo();
72 unsigned CFSize = FFI->getMaxCallFrameSize();
73 // It's not always a good idea to include the call frame as part of the
74 // stack frame. ARM (especially Thumb) has small immediate offset to
75 // address the stack frame. So a large call frame can cause poor codegen
76 // and may even makes it impossible to scavenge a register.
77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
80 return !MF.getFrameInfo()->hasVarSizedObjects();
83 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84 /// call frame pseudos can be simplified. Unlike most targets, having a FP
85 /// is not sufficient here since we still may reference some objects via SP
86 /// even when FP is available in Thumb2 mode.
88 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
89 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
92 static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
94 const MCPhysReg *CSRegs) {
95 // Integer spill area is handled with "pop".
96 if (isPopOpcode(MI->getOpcode())) {
97 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
114 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123 Pred, PredReg, TII, MIFlags);
125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126 Pred, PredReg, TII, MIFlags);
129 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
139 static int sizeOfSPAdjustment(const MachineInstr *MI) {
141 switch (MI->getOpcode()) {
142 case ARM::VSTMDDB_UPD:
146 case ARM::t2STMDB_UPD:
150 case ARM::STR_PRE_IMM:
153 llvm_unreachable("Unknown push or pop like instruction");
157 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
158 // pred) so the list starts at 4.
159 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
164 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
165 size_t StackSizeInBytes) {
166 const MachineFrameInfo *MFI = MF.getFrameInfo();
167 const Function *F = MF.getFunction();
168 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
169 if (F->hasFnAttribute("stack-probe-size"))
170 F->getFnAttribute("stack-probe-size")
172 .getAsInteger(0, StackProbeSize);
173 return StackSizeInBytes >= StackProbeSize;
177 struct StackAdjustingInsts {
179 MachineBasicBlock::iterator I;
184 SmallVector<InstInfo, 4> Insts;
186 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
187 bool BeforeFPSet = false) {
188 InstInfo Info = {I, SPAdjust, BeforeFPSet};
189 Insts.push_back(Info);
192 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
193 auto Info = std::find_if(Insts.begin(), Insts.end(),
194 [&](InstInfo &Info) { return Info.I == I; });
195 assert(Info != Insts.end() && "invalid sp adjusting instruction");
196 Info->SPAdjust += ExtraBytes;
199 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
200 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
201 unsigned CFAOffset = 0;
202 for (auto &Info : Insts) {
203 if (HasFP && !Info.BeforeFPSet)
206 CFAOffset -= Info.SPAdjust;
207 unsigned CFIIndex = MMI.addFrameInst(
208 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
209 BuildMI(MBB, std::next(Info.I), dl,
210 TII.get(TargetOpcode::CFI_INSTRUCTION))
211 .addCFIIndex(CFIIndex)
212 .setMIFlags(MachineInstr::FrameSetup);
218 /// Emit an instruction sequence that will align the address in
219 /// register Reg by zero-ing out the lower bits. For versions of the
220 /// architecture that support Neon, this must be done in a single
221 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
222 /// single instruction. That function only gets called when optimizing
223 /// spilling of D registers on a core with the Neon instruction set
225 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
226 const TargetInstrInfo &TII,
227 MachineBasicBlock &MBB,
228 MachineBasicBlock::iterator MBBI,
229 DebugLoc DL, const unsigned Reg,
230 const unsigned Alignment,
231 const bool MustBeSingleInstruction) {
232 const ARMSubtarget &AST =
233 static_cast<const ARMSubtarget &>(MF.getSubtarget());
234 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
235 const unsigned AlignMask = Alignment - 1;
236 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
237 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
238 if (!AFI->isThumbFunction()) {
239 // if the BFC instruction is available, use that to zero the lower
241 // bfc Reg, #0, log2(Alignment)
242 // otherwise use BIC, if the mask to zero the required number of bits
243 // can be encoded in the bic immediate field
244 // bic Reg, Reg, Alignment-1
246 // lsr Reg, Reg, log2(Alignment)
247 // lsl Reg, Reg, log2(Alignment)
249 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
250 .addReg(Reg, RegState::Kill)
251 .addImm(~AlignMask));
252 } else if (AlignMask <= 255) {
254 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
255 .addReg(Reg, RegState::Kill)
256 .addImm(AlignMask)));
258 assert(!MustBeSingleInstruction &&
259 "Shouldn't call emitAligningInstructions demanding a single "
260 "instruction to be emitted for large stack alignment for a target "
262 AddDefaultCC(AddDefaultPred(
263 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
264 .addReg(Reg, RegState::Kill)
265 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
266 AddDefaultCC(AddDefaultPred(
267 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
268 .addReg(Reg, RegState::Kill)
269 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
272 // Since this is only reached for Thumb-2 targets, the BFC instruction
273 // should always be available.
275 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
276 .addReg(Reg, RegState::Kill)
277 .addImm(~AlignMask));
281 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
282 MachineBasicBlock &MBB = MF.front();
283 MachineBasicBlock::iterator MBBI = MBB.begin();
284 MachineFrameInfo *MFI = MF.getFrameInfo();
285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
286 MachineModuleInfo &MMI = MF.getMMI();
287 MCContext &Context = MMI.getContext();
288 const TargetMachine &TM = MF.getTarget();
289 const MCRegisterInfo *MRI = Context.getRegisterInfo();
290 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
291 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
292 assert(!AFI->isThumb1OnlyFunction() &&
293 "This emitPrologue does not support Thumb1!");
294 bool isARM = !AFI->isThumbFunction();
295 unsigned Align = STI.getFrameLowering()->getStackAlignment();
296 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
297 unsigned NumBytes = MFI->getStackSize();
298 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
299 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
300 unsigned FramePtr = RegInfo->getFrameRegister(MF);
302 // Determine the sizes of each callee-save spill areas and record which frame
303 // belongs to which callee-save spill areas.
304 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
305 int FramePtrSpillFI = 0;
308 // All calls are tail calls in GHC calling conv, and functions have no
309 // prologue/epilogue.
310 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
313 StackAdjustingInsts DefCFAOffsetCandidates;
315 // Allocate the vararg register save area.
316 if (ArgRegsSaveSize) {
317 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
318 MachineInstr::FrameSetup);
319 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
322 if (!AFI->hasStackFrame() &&
323 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
324 if (NumBytes - ArgRegsSaveSize != 0) {
325 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
326 MachineInstr::FrameSetup);
327 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
328 NumBytes - ArgRegsSaveSize, true);
333 // Determine spill area sizes.
334 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
335 unsigned Reg = CSI[i].getReg();
336 int FI = CSI[i].getFrameIdx();
343 if (STI.isTargetDarwin()) {
358 FramePtrSpillFI = FI;
362 // This is a DPR. Exclude the aligned DPRCS2 spills.
365 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
371 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
372 if (GPRCS1Size > 0) {
373 GPRCS1Push = LastPush = MBBI++;
374 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
377 // Determine starting offsets of spill areas.
378 bool HasFP = hasFP(MF);
379 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
380 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
381 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
382 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
383 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
384 int FramePtrOffsetInPush = 0;
386 FramePtrOffsetInPush =
387 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
388 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
391 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
392 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
393 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
396 if (GPRCS2Size > 0) {
397 GPRCS2Push = LastPush = MBBI++;
398 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
401 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
402 // .cfi_offset operations will reflect that.
404 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
405 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
406 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
408 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
409 MachineInstr::FrameSetup);
410 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
416 // Since vpush register list cannot have gaps, there may be multiple vpush
417 // instructions in the prologue.
418 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
419 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
424 // Move past the aligned DPRCS2 area.
425 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
426 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
427 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
428 // leaves the stack pointer pointing to the DPRCS2 area.
430 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
431 NumBytes += MFI->getObjectOffset(D8SpillFI);
433 NumBytes = DPRCSOffset;
435 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
436 uint32_t NumWords = NumBytes >> 2;
438 if (NumWords < 65536)
439 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
441 .setMIFlags(MachineInstr::FrameSetup));
443 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
445 .setMIFlags(MachineInstr::FrameSetup);
447 switch (TM.getCodeModel()) {
448 case CodeModel::Small:
449 case CodeModel::Medium:
450 case CodeModel::Default:
451 case CodeModel::Kernel:
452 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
453 .addImm((unsigned)ARMCC::AL).addReg(0)
454 .addExternalSymbol("__chkstk")
455 .addReg(ARM::R4, RegState::Implicit)
456 .setMIFlags(MachineInstr::FrameSetup);
458 case CodeModel::Large:
459 case CodeModel::JITDefault:
460 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
461 .addExternalSymbol("__chkstk")
462 .setMIFlags(MachineInstr::FrameSetup);
464 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
465 .addImm((unsigned)ARMCC::AL).addReg(0)
466 .addReg(ARM::R12, RegState::Kill)
467 .addReg(ARM::R4, RegState::Implicit)
468 .setMIFlags(MachineInstr::FrameSetup);
472 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
474 .addReg(ARM::SP, RegState::Define)
475 .addReg(ARM::R4, RegState::Kill)
476 .setMIFlags(MachineInstr::FrameSetup)));
481 // Adjust SP after all the callee-save spills.
482 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
483 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
485 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
486 MachineInstr::FrameSetup);
487 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
491 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
492 // Note it's not safe to do this in Thumb2 mode because it would have
493 // taken two instructions:
496 // If an interrupt is taken between the two instructions, then sp is in
497 // an inconsistent state (pointing to the middle of callee-saved area).
498 // The interrupt handler can end up clobbering the registers.
499 AFI->setShouldRestoreSPFromFP(true);
502 // Set FP to point to the stack slot that contains the previous FP.
503 // For iOS, FP is R7, which has now been stored in spill area 1.
504 // Otherwise, if this is not iOS, all the callee-saved registers go
505 // into spill area 1, including the FP in R11. In either case, it
506 // is in area one and the adjustment needs to take place just after
509 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
510 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
511 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
512 dl, TII, FramePtr, ARM::SP,
513 PushSize + FramePtrOffsetInPush,
514 MachineInstr::FrameSetup);
515 if (FramePtrOffsetInPush + PushSize != 0) {
516 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
517 nullptr, MRI->getDwarfRegNum(FramePtr, true),
518 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
519 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
520 .addCFIIndex(CFIIndex)
521 .setMIFlags(MachineInstr::FrameSetup);
524 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
525 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
526 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
527 .addCFIIndex(CFIIndex)
528 .setMIFlags(MachineInstr::FrameSetup);
532 // Now that the prologue's actual instructions are finalised, we can insert
533 // the necessary DWARF cf instructions to describe the situation. Start by
534 // recording where each register ended up:
535 if (GPRCS1Size > 0) {
536 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
538 for (const auto &Entry : CSI) {
539 unsigned Reg = Entry.getReg();
540 int FI = Entry.getFrameIdx();
547 if (STI.isTargetDarwin())
559 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
560 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
561 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
562 .addCFIIndex(CFIIndex)
563 .setMIFlags(MachineInstr::FrameSetup);
569 if (GPRCS2Size > 0) {
570 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
571 for (const auto &Entry : CSI) {
572 unsigned Reg = Entry.getReg();
573 int FI = Entry.getFrameIdx();
580 if (STI.isTargetDarwin()) {
581 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
582 unsigned Offset = MFI->getObjectOffset(FI);
583 unsigned CFIIndex = MMI.addFrameInst(
584 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
585 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
586 .addCFIIndex(CFIIndex)
587 .setMIFlags(MachineInstr::FrameSetup);
595 // Since vpush register list cannot have gaps, there may be multiple vpush
596 // instructions in the prologue.
597 MachineBasicBlock::iterator Pos = std::next(LastPush);
598 for (const auto &Entry : CSI) {
599 unsigned Reg = Entry.getReg();
600 int FI = Entry.getFrameIdx();
601 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
602 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
603 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
604 unsigned Offset = MFI->getObjectOffset(FI);
605 unsigned CFIIndex = MMI.addFrameInst(
606 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
607 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
608 .addCFIIndex(CFIIndex)
609 .setMIFlags(MachineInstr::FrameSetup);
614 // Now we can emit descriptions of where the canonical frame address was
615 // throughout the process. If we have a frame pointer, it takes over the job
616 // half-way through, so only the first few .cfi_def_cfa_offset instructions
617 // actually get emitted.
618 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
620 if (STI.isTargetELF() && hasFP(MF))
621 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
622 AFI->getFramePtrSpillOffset());
624 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
625 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
626 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
627 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
629 // If we need dynamic stack realignment, do it here. Be paranoid and make
630 // sure if we also have VLAs, we have a base pointer for frame access.
631 // If aligned NEON registers were spilled, the stack has already been
633 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
634 unsigned MaxAlign = MFI->getMaxAlignment();
635 assert(!AFI->isThumb1OnlyFunction());
636 if (!AFI->isThumbFunction()) {
637 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
640 // We cannot use sp as source/dest register here, thus we're using r4 to
641 // perform the calculations. We're emitting the following sequence:
643 // -- use emitAligningInstructions to produce best sequence to zero
644 // -- out lower bits in r4
646 // FIXME: It will be better just to find spare register here.
647 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
648 .addReg(ARM::SP, RegState::Kill));
649 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
651 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
652 .addReg(ARM::R4, RegState::Kill));
655 AFI->setShouldRestoreSPFromFP(true);
658 // If we need a base pointer, set it up here. It's whatever the value
659 // of the stack pointer is at this point. Any variable size objects
660 // will be allocated after this, so we can still use the base pointer
661 // to reference locals.
662 // FIXME: Clarify FrameSetup flags here.
663 if (RegInfo->hasBasePointer(MF)) {
665 BuildMI(MBB, MBBI, dl,
666 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
668 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
670 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
671 RegInfo->getBaseRegister())
675 // If the frame has variable sized objects then the epilogue must restore
676 // the sp from fp. We can assume there's an FP here since hasFP already
677 // checks for hasVarSizedObjects.
678 if (MFI->hasVarSizedObjects())
679 AFI->setShouldRestoreSPFromFP(true);
682 // Resolve TCReturn pseudo-instruction
683 void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
684 MachineBasicBlock &MBB) const {
685 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
686 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
687 unsigned RetOpcode = MBBI->getOpcode();
688 DebugLoc dl = MBBI->getDebugLoc();
689 const ARMBaseInstrInfo &TII =
690 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
692 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
695 // Tail call return: adjust the stack pointer and jump to callee.
696 MBBI = MBB.getLastNonDebugInstr();
697 MachineOperand &JumpTarget = MBBI->getOperand(0);
699 // Jump to label or value in register.
700 if (RetOpcode == ARM::TCRETURNdi) {
701 unsigned TCOpcode = STI.isThumb() ?
702 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
704 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
705 if (JumpTarget.isGlobal())
706 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
707 JumpTarget.getTargetFlags());
709 assert(JumpTarget.isSymbol());
710 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
711 JumpTarget.getTargetFlags());
714 // Add the default predicate in Thumb mode.
715 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
716 } else if (RetOpcode == ARM::TCRETURNri) {
717 BuildMI(MBB, MBBI, dl,
718 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
719 addReg(JumpTarget.getReg(), RegState::Kill);
722 MachineInstr *NewMI = std::prev(MBBI);
723 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
724 NewMI->addOperand(MBBI->getOperand(i));
726 // Delete the pseudo instruction TCRETURN.
731 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
732 MachineBasicBlock &MBB) const {
733 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
734 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
735 DebugLoc dl = MBBI->getDebugLoc();
736 MachineFrameInfo *MFI = MF.getFrameInfo();
737 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
738 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
739 const ARMBaseInstrInfo &TII =
740 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
741 assert(!AFI->isThumb1OnlyFunction() &&
742 "This emitEpilogue does not support Thumb1!");
743 bool isARM = !AFI->isThumbFunction();
745 unsigned Align = STI.getFrameLowering()->getStackAlignment();
746 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
747 int NumBytes = (int)MFI->getStackSize();
748 unsigned FramePtr = RegInfo->getFrameRegister(MF);
750 // All calls are tail calls in GHC calling conv, and functions have no
751 // prologue/epilogue.
752 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
753 fixTCReturn(MF, MBB);
757 if (!AFI->hasStackFrame()) {
758 if (NumBytes - ArgRegsSaveSize != 0)
759 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
761 // Unwind MBBI to point to first LDR / VLDRD.
762 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
763 if (MBBI != MBB.begin()) {
766 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
767 if (!isCSRestore(MBBI, TII, CSRegs))
771 // Move SP to start of FP callee save spill area.
772 NumBytes -= (ArgRegsSaveSize +
773 AFI->getGPRCalleeSavedArea1Size() +
774 AFI->getGPRCalleeSavedArea2Size() +
775 AFI->getDPRCalleeSavedGapSize() +
776 AFI->getDPRCalleeSavedAreaSize());
778 // Reset SP based on frame pointer only if the stack frame extends beyond
779 // frame pointer stack slot or target is ELF and the function has FP.
780 if (AFI->shouldRestoreSPFromFP()) {
781 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
784 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
787 // It's not possible to restore SP from FP in a single instruction.
788 // For iOS, this looks like:
791 // This is bad, if an interrupt is taken after the mov, sp is in an
792 // inconsistent state.
793 // Use the first callee-saved register as a scratch register.
794 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
795 "No scratch register to restore SP from FP!");
796 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
798 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
805 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
806 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
808 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
812 } else if (NumBytes &&
813 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
814 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
816 // Increment past our save areas.
817 if (AFI->getDPRCalleeSavedAreaSize()) {
819 // Since vpop register list cannot have gaps, there may be multiple vpop
820 // instructions in the epilogue.
821 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
824 if (AFI->getDPRCalleeSavedGapSize()) {
825 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
826 "unexpected DPR alignment gap");
827 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
830 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
831 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
834 fixTCReturn(MF, MBB);
837 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
840 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
841 /// debug info. It's the same as what we use for resolving the code-gen
842 /// references for now. FIXME: This can go wrong when references are
843 /// SP-relative and simple call frames aren't used.
845 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
846 unsigned &FrameReg) const {
847 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
851 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
852 int FI, unsigned &FrameReg,
854 const MachineFrameInfo *MFI = MF.getFrameInfo();
855 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
856 MF.getSubtarget().getRegisterInfo());
857 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
858 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
859 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
860 bool isFixed = MFI->isFixedObjectIndex(FI);
865 // SP can move around if there are allocas. We may also lose track of SP
866 // when emergency spilling inside a non-reserved call frame setup.
867 bool hasMovingSP = !hasReservedCallFrame(MF);
869 // When dynamically realigning the stack, use the frame pointer for
870 // parameters, and the stack/base pointer for locals.
871 if (RegInfo->needsStackRealignment(MF)) {
872 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
874 FrameReg = RegInfo->getFrameRegister(MF);
876 } else if (hasMovingSP) {
877 assert(RegInfo->hasBasePointer(MF) &&
878 "VLAs and dynamic stack alignment, but missing base pointer!");
879 FrameReg = RegInfo->getBaseRegister();
884 // If there is a frame pointer, use it when we can.
885 if (hasFP(MF) && AFI->hasStackFrame()) {
886 // Use frame pointer to reference fixed objects. Use it for locals if
887 // there are VLAs (and thus the SP isn't reliable as a base).
888 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
889 FrameReg = RegInfo->getFrameRegister(MF);
891 } else if (hasMovingSP) {
892 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
893 if (AFI->isThumb2Function()) {
894 // Try to use the frame pointer if we can, else use the base pointer
895 // since it's available. This is handy for the emergency spill slot, in
897 if (FPOffset >= -255 && FPOffset < 0) {
898 FrameReg = RegInfo->getFrameRegister(MF);
902 } else if (AFI->isThumb2Function()) {
903 // Use add <rd>, sp, #<imm8>
904 // ldr <rd>, [sp, #<imm8>]
905 // if at all possible to save space.
906 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
908 // In Thumb2 mode, the negative offset is very limited. Try to avoid
909 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
910 if (FPOffset >= -255 && FPOffset < 0) {
911 FrameReg = RegInfo->getFrameRegister(MF);
914 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
915 // Otherwise, use SP or FP, whichever is closer to the stack slot.
916 FrameReg = RegInfo->getFrameRegister(MF);
920 // Use the base pointer if we have one.
921 if (RegInfo->hasBasePointer(MF))
922 FrameReg = RegInfo->getBaseRegister();
926 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
929 return getFrameIndexReference(MF, FI, FrameReg);
932 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
933 MachineBasicBlock::iterator MI,
934 const std::vector<CalleeSavedInfo> &CSI,
935 unsigned StmOpc, unsigned StrOpc,
937 bool(*Func)(unsigned, bool),
938 unsigned NumAlignedDPRCS2Regs,
939 unsigned MIFlags) const {
940 MachineFunction &MF = *MBB.getParent();
941 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
944 if (MI != MBB.end()) DL = MI->getDebugLoc();
946 SmallVector<std::pair<unsigned,bool>, 4> Regs;
947 unsigned i = CSI.size();
949 unsigned LastReg = 0;
950 for (; i != 0; --i) {
951 unsigned Reg = CSI[i-1].getReg();
952 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
954 // D-registers in the aligned area DPRCS2 are NOT spilled here.
955 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
958 // Add the callee-saved register as live-in unless it's LR and
959 // @llvm.returnaddress is called. If LR is returned for
960 // @llvm.returnaddress then it's already added to the function and
961 // entry block live-in sets.
963 if (Reg == ARM::LR) {
964 if (MF.getFrameInfo()->isReturnAddressTaken() &&
965 MF.getRegInfo().isLiveIn(Reg))
972 // If NoGap is true, push consecutive registers and then leave the rest
973 // for other instructions. e.g.
974 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
975 if (NoGap && LastReg && LastReg != Reg-1)
978 Regs.push_back(std::make_pair(Reg, isKill));
983 if (Regs.size() > 1 || StrOpc== 0) {
984 MachineInstrBuilder MIB =
985 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
986 .addReg(ARM::SP).setMIFlags(MIFlags));
987 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
988 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
989 } else if (Regs.size() == 1) {
990 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
992 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
993 .addReg(ARM::SP).setMIFlags(MIFlags)
999 // Put any subsequent vpush instructions before this one: they will refer to
1000 // higher register numbers so need to be pushed first in order to preserve
1006 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1007 MachineBasicBlock::iterator MI,
1008 const std::vector<CalleeSavedInfo> &CSI,
1009 unsigned LdmOpc, unsigned LdrOpc,
1010 bool isVarArg, bool NoGap,
1011 bool(*Func)(unsigned, bool),
1012 unsigned NumAlignedDPRCS2Regs) const {
1013 MachineFunction &MF = *MBB.getParent();
1014 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1015 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1016 DebugLoc DL = MI->getDebugLoc();
1017 unsigned RetOpcode = MI->getOpcode();
1018 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
1019 RetOpcode == ARM::TCRETURNri);
1021 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1023 SmallVector<unsigned, 4> Regs;
1024 unsigned i = CSI.size();
1026 unsigned LastReg = 0;
1027 bool DeleteRet = false;
1028 for (; i != 0; --i) {
1029 unsigned Reg = CSI[i-1].getReg();
1030 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
1032 // The aligned reloads from area DPRCS2 are not inserted here.
1033 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1036 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1039 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1040 // Fold the return instruction into the LDM.
1044 // If NoGap is true, pop consecutive registers and then leave the rest
1045 // for other instructions. e.g.
1046 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1047 if (NoGap && LastReg && LastReg != Reg-1)
1051 Regs.push_back(Reg);
1056 if (Regs.size() > 1 || LdrOpc == 0) {
1057 MachineInstrBuilder MIB =
1058 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1060 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1061 MIB.addReg(Regs[i], getDefRegState(true));
1063 MIB.copyImplicitOps(&*MI);
1064 MI->eraseFromParent();
1067 } else if (Regs.size() == 1) {
1068 // If we adjusted the reg to PC from LR above, switch it back here. We
1069 // only do that for LDM.
1070 if (Regs[0] == ARM::PC)
1072 MachineInstrBuilder MIB =
1073 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1074 .addReg(ARM::SP, RegState::Define)
1076 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1077 // that refactoring is complete (eventually).
1078 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1080 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1083 AddDefaultPred(MIB);
1087 // Put any subsequent vpop instructions after this one: they will refer to
1088 // higher register numbers so need to be popped afterwards.
1093 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1094 /// starting from d8. Also insert stack realignment code and leave the stack
1095 /// pointer pointing to the d8 spill slot.
1096 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1097 MachineBasicBlock::iterator MI,
1098 unsigned NumAlignedDPRCS2Regs,
1099 const std::vector<CalleeSavedInfo> &CSI,
1100 const TargetRegisterInfo *TRI) {
1101 MachineFunction &MF = *MBB.getParent();
1102 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1103 DebugLoc DL = MI->getDebugLoc();
1104 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1105 MachineFrameInfo &MFI = *MF.getFrameInfo();
1107 // Mark the D-register spill slots as properly aligned. Since MFI computes
1108 // stack slot layout backwards, this can actually mean that the d-reg stack
1109 // slot offsets can be wrong. The offset for d8 will always be correct.
1110 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1111 unsigned DNum = CSI[i].getReg() - ARM::D8;
1114 int FI = CSI[i].getFrameIdx();
1115 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1116 // registers will be 8-byte aligned.
1117 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1119 // The stack slot for D8 needs to be maximally aligned because this is
1120 // actually the point where we align the stack pointer. MachineFrameInfo
1121 // computes all offsets relative to the incoming stack pointer which is a
1122 // bit weird when realigning the stack. Any extra padding for this
1123 // over-alignment is not realized because the code inserted below adjusts
1124 // the stack pointer by numregs * 8 before aligning the stack pointer.
1126 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1129 // Move the stack pointer to the d8 spill slot, and align it at the same
1130 // time. Leave the stack slot address in the scratch register r4.
1132 // sub r4, sp, #numregs * 8
1133 // bic r4, r4, #align - 1
1136 bool isThumb = AFI->isThumbFunction();
1137 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1138 AFI->setShouldRestoreSPFromFP(true);
1140 // sub r4, sp, #numregs * 8
1141 // The immediate is <= 64, so it doesn't need any special encoding.
1142 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1143 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1145 .addImm(8 * NumAlignedDPRCS2Regs)));
1147 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1148 // We must set parameter MustBeSingleInstruction to true, since
1149 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1150 // stack alignment. Luckily, this can always be done since all ARM
1151 // architecture versions that support Neon also support the BFC
1153 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1156 // The stack pointer must be adjusted before spilling anything, otherwise
1157 // the stack slots could be clobbered by an interrupt handler.
1158 // Leave r4 live, it is used below.
1159 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1160 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1162 MIB = AddDefaultPred(MIB);
1166 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1167 // r4 holds the stack slot address.
1168 unsigned NextReg = ARM::D8;
1170 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1171 // The writeback is only needed when emitting two vst1.64 instructions.
1172 if (NumAlignedDPRCS2Regs >= 6) {
1173 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1174 &ARM::QQPRRegClass);
1175 MBB.addLiveIn(SupReg);
1176 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1178 .addReg(ARM::R4, RegState::Kill).addImm(16)
1180 .addReg(SupReg, RegState::ImplicitKill));
1182 NumAlignedDPRCS2Regs -= 4;
1185 // We won't modify r4 beyond this point. It currently points to the next
1186 // register to be spilled.
1187 unsigned R4BaseReg = NextReg;
1189 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1190 if (NumAlignedDPRCS2Regs >= 4) {
1191 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1192 &ARM::QQPRRegClass);
1193 MBB.addLiveIn(SupReg);
1194 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1195 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1196 .addReg(SupReg, RegState::ImplicitKill));
1198 NumAlignedDPRCS2Regs -= 4;
1201 // 16-byte aligned vst1.64 with 2 d-regs.
1202 if (NumAlignedDPRCS2Regs >= 2) {
1203 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1205 MBB.addLiveIn(SupReg);
1206 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1207 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1209 NumAlignedDPRCS2Regs -= 2;
1212 // Finally, use a vanilla vstr.64 for the odd last register.
1213 if (NumAlignedDPRCS2Regs) {
1214 MBB.addLiveIn(NextReg);
1215 // vstr.64 uses addrmode5 which has an offset scale of 4.
1216 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1218 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1221 // The last spill instruction inserted should kill the scratch register r4.
1222 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1225 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1226 /// iterator to the following instruction.
1227 static MachineBasicBlock::iterator
1228 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1229 unsigned NumAlignedDPRCS2Regs) {
1230 // sub r4, sp, #numregs * 8
1231 // bic r4, r4, #align - 1
1234 assert(MI->mayStore() && "Expecting spill instruction");
1236 // These switches all fall through.
1237 switch(NumAlignedDPRCS2Regs) {
1240 assert(MI->mayStore() && "Expecting spill instruction");
1243 assert(MI->mayStore() && "Expecting spill instruction");
1247 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1253 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1254 /// starting from d8. These instructions are assumed to execute while the
1255 /// stack is still aligned, unlike the code inserted by emitPopInst.
1256 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1257 MachineBasicBlock::iterator MI,
1258 unsigned NumAlignedDPRCS2Regs,
1259 const std::vector<CalleeSavedInfo> &CSI,
1260 const TargetRegisterInfo *TRI) {
1261 MachineFunction &MF = *MBB.getParent();
1262 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1263 DebugLoc DL = MI->getDebugLoc();
1264 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1266 // Find the frame index assigned to d8.
1268 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1269 if (CSI[i].getReg() == ARM::D8) {
1270 D8SpillFI = CSI[i].getFrameIdx();
1274 // Materialize the address of the d8 spill slot into the scratch register r4.
1275 // This can be fairly complicated if the stack frame is large, so just use
1276 // the normal frame index elimination mechanism to do it. This code runs as
1277 // the initial part of the epilog where the stack and base pointers haven't
1278 // been changed yet.
1279 bool isThumb = AFI->isThumbFunction();
1280 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1282 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1283 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1284 .addFrameIndex(D8SpillFI).addImm(0)));
1286 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1287 unsigned NextReg = ARM::D8;
1289 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1290 if (NumAlignedDPRCS2Regs >= 6) {
1291 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1292 &ARM::QQPRRegClass);
1293 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1294 .addReg(ARM::R4, RegState::Define)
1295 .addReg(ARM::R4, RegState::Kill).addImm(16)
1296 .addReg(SupReg, RegState::ImplicitDefine));
1298 NumAlignedDPRCS2Regs -= 4;
1301 // We won't modify r4 beyond this point. It currently points to the next
1302 // register to be spilled.
1303 unsigned R4BaseReg = NextReg;
1305 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1306 if (NumAlignedDPRCS2Regs >= 4) {
1307 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1308 &ARM::QQPRRegClass);
1309 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1310 .addReg(ARM::R4).addImm(16)
1311 .addReg(SupReg, RegState::ImplicitDefine));
1313 NumAlignedDPRCS2Regs -= 4;
1316 // 16-byte aligned vld1.64 with 2 d-regs.
1317 if (NumAlignedDPRCS2Regs >= 2) {
1318 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1320 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1321 .addReg(ARM::R4).addImm(16));
1323 NumAlignedDPRCS2Regs -= 2;
1326 // Finally, use a vanilla vldr.64 for the remaining odd register.
1327 if (NumAlignedDPRCS2Regs)
1328 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1329 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1331 // Last store kills r4.
1332 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1335 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1336 MachineBasicBlock::iterator MI,
1337 const std::vector<CalleeSavedInfo> &CSI,
1338 const TargetRegisterInfo *TRI) const {
1342 MachineFunction &MF = *MBB.getParent();
1343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1345 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1346 unsigned PushOneOpc = AFI->isThumbFunction() ?
1347 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1348 unsigned FltOpc = ARM::VSTMDDB_UPD;
1349 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1350 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1351 MachineInstr::FrameSetup);
1352 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1353 MachineInstr::FrameSetup);
1354 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1355 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1357 // The code above does not insert spill code for the aligned DPRCS2 registers.
1358 // The stack realignment code will be inserted between the push instructions
1359 // and these spills.
1360 if (NumAlignedDPRCS2Regs)
1361 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1366 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1367 MachineBasicBlock::iterator MI,
1368 const std::vector<CalleeSavedInfo> &CSI,
1369 const TargetRegisterInfo *TRI) const {
1373 MachineFunction &MF = *MBB.getParent();
1374 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1375 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1376 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1378 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1379 // registers. Do that here instead.
1380 if (NumAlignedDPRCS2Regs)
1381 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1383 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1384 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1385 unsigned FltOpc = ARM::VLDMDIA_UPD;
1386 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1387 NumAlignedDPRCS2Regs);
1388 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1389 &isARMArea2Register, 0);
1390 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1391 &isARMArea1Register, 0);
1396 // FIXME: Make generic?
1397 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1398 const ARMBaseInstrInfo &TII) {
1399 unsigned FnSize = 0;
1400 for (auto &MBB : MF) {
1401 for (auto &MI : MBB)
1402 FnSize += TII.GetInstSizeInBytes(&MI);
1407 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1408 /// frames and return the stack size limit beyond which some of these
1409 /// instructions will require a scratch register during their expansion later.
1410 // FIXME: Move to TII?
1411 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1412 const TargetFrameLowering *TFI) {
1413 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1414 unsigned Limit = (1 << 12) - 1;
1415 for (auto &MBB : MF) {
1416 for (auto &MI : MBB) {
1417 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1418 if (!MI.getOperand(i).isFI())
1421 // When using ADDri to get the address of a stack object, 255 is the
1422 // largest offset guaranteed to fit in the immediate offset.
1423 if (MI.getOpcode() == ARM::ADDri) {
1424 Limit = std::min(Limit, (1U << 8) - 1);
1428 // Otherwise check the addressing mode.
1429 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1430 case ARMII::AddrMode3:
1431 case ARMII::AddrModeT2_i8:
1432 Limit = std::min(Limit, (1U << 8) - 1);
1434 case ARMII::AddrMode5:
1435 case ARMII::AddrModeT2_i8s4:
1436 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1438 case ARMII::AddrModeT2_i12:
1439 // i12 supports only positive offset so these will be converted to
1440 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1441 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1442 Limit = std::min(Limit, (1U << 8) - 1);
1444 case ARMII::AddrMode4:
1445 case ARMII::AddrMode6:
1446 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1447 // immediate offset for stack references.
1452 break; // At most one FI per instruction
1460 // In functions that realign the stack, it can be an advantage to spill the
1461 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1462 // instructions take alignment hints that can improve performance.
1464 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1465 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1466 if (!SpillAlignedNEONRegs)
1469 // Naked functions don't spill callee-saved registers.
1470 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1473 // We are planning to use NEON instructions vst1 / vld1.
1474 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1477 // Don't bother if the default stack alignment is sufficiently high.
1478 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1481 // Aligned spills require stack realignment.
1482 if (!static_cast<const ARMBaseRegisterInfo *>(
1483 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1486 // We always spill contiguous d-registers starting from d8. Count how many
1487 // needs spilling. The register allocator will almost always use the
1488 // callee-saved registers in order, but it can happen that there are holes in
1489 // the range. Registers above the hole will be spilled to the standard DPRCS
1491 MachineRegisterInfo &MRI = MF.getRegInfo();
1492 unsigned NumSpills = 0;
1493 for (; NumSpills < 8; ++NumSpills)
1494 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1497 // Don't do this for just one d-register. It's not worth it.
1501 // Spill the first NumSpills D-registers after realigning the stack.
1502 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1504 // A scratch register is required for the vst1 / vld1 instructions.
1505 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1509 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1510 RegScavenger *RS) const {
1511 // This tells PEI to spill the FP as if it is any other callee-save register
1512 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1513 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1514 // to combine multiple loads / stores.
1515 bool CanEliminateFrame = true;
1516 bool CS1Spilled = false;
1517 bool LRSpilled = false;
1518 unsigned NumGPRSpills = 0;
1519 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1520 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1521 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1522 MF.getSubtarget().getRegisterInfo());
1523 const ARMBaseInstrInfo &TII =
1524 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1525 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1526 MachineFrameInfo *MFI = MF.getFrameInfo();
1527 MachineRegisterInfo &MRI = MF.getRegInfo();
1528 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1530 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1531 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1532 // since it's not always possible to restore sp from fp in a single
1534 // FIXME: It will be better just to find spare register here.
1535 if (AFI->isThumb2Function() &&
1536 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1537 MRI.setPhysRegUsed(ARM::R4);
1539 if (AFI->isThumb1OnlyFunction()) {
1540 // Spill LR if Thumb1 function uses variable length argument lists.
1541 if (AFI->getArgRegsSaveSize() > 0)
1542 MRI.setPhysRegUsed(ARM::LR);
1544 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1545 // for sure what the stack size will be, but for this, an estimate is good
1546 // enough. If there anything changes it, it'll be a spill, which implies
1547 // we've used all the registers and so R4 is already used, so not marking
1548 // it here will be OK.
1549 // FIXME: It will be better just to find spare register here.
1550 unsigned StackSize = MFI->estimateStackSize(MF);
1551 if (MFI->hasVarSizedObjects() || StackSize > 508)
1552 MRI.setPhysRegUsed(ARM::R4);
1555 // See if we can spill vector registers to aligned stack.
1556 checkNumAlignedDPRCS2Regs(MF);
1558 // Spill the BasePtr if it's used.
1559 if (RegInfo->hasBasePointer(MF))
1560 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1562 // Don't spill FP if the frame can be eliminated. This is determined
1563 // by scanning the callee-save registers to see if any is used.
1564 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1565 for (unsigned i = 0; CSRegs[i]; ++i) {
1566 unsigned Reg = CSRegs[i];
1567 bool Spilled = false;
1568 if (MRI.isPhysRegUsed(Reg)) {
1570 CanEliminateFrame = false;
1573 if (!ARM::GPRRegClass.contains(Reg))
1579 if (!STI.isTargetDarwin()) {
1586 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1591 case ARM::R0: case ARM::R1:
1592 case ARM::R2: case ARM::R3:
1593 case ARM::R4: case ARM::R5:
1594 case ARM::R6: case ARM::R7:
1601 if (!STI.isTargetDarwin()) {
1602 UnspilledCS1GPRs.push_back(Reg);
1607 case ARM::R0: case ARM::R1:
1608 case ARM::R2: case ARM::R3:
1609 case ARM::R4: case ARM::R5:
1610 case ARM::R6: case ARM::R7:
1612 UnspilledCS1GPRs.push_back(Reg);
1615 UnspilledCS2GPRs.push_back(Reg);
1621 bool ForceLRSpill = false;
1622 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1623 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1624 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1625 // use of BL to implement far jump. If it turns out that it's not needed
1626 // then the branch fix up path will undo it.
1627 if (FnSize >= (1 << 11)) {
1628 CanEliminateFrame = false;
1629 ForceLRSpill = true;
1633 // If any of the stack slot references may be out of range of an immediate
1634 // offset, make sure a register (or a spill slot) is available for the
1635 // register scavenger. Note that if we're indexing off the frame pointer, the
1636 // effective stack size is 4 bytes larger since the FP points to the stack
1637 // slot of the previous FP. Also, if we have variable sized objects in the
1638 // function, stack slot references will often be negative, and some of
1639 // our instructions are positive-offset only, so conservatively consider
1640 // that case to want a spill slot (or register) as well. Similarly, if
1641 // the function adjusts the stack pointer during execution and the
1642 // adjustments aren't already part of our stack size estimate, our offset
1643 // calculations may be off, so be conservative.
1644 // FIXME: We could add logic to be more precise about negative offsets
1645 // and which instructions will need a scratch register for them. Is it
1646 // worth the effort and added fragility?
1649 (MFI->estimateStackSize(MF) +
1650 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1651 estimateRSStackSizeLimit(MF, this)))
1652 || MFI->hasVarSizedObjects()
1653 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1655 bool ExtraCSSpill = false;
1656 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1657 AFI->setHasStackFrame(true);
1659 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1660 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1661 if (!LRSpilled && CS1Spilled) {
1662 MRI.setPhysRegUsed(ARM::LR);
1664 SmallVectorImpl<unsigned>::iterator LRPos;
1665 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1667 if (LRPos != UnspilledCS1GPRs.end())
1668 UnspilledCS1GPRs.erase(LRPos);
1670 ForceLRSpill = false;
1671 ExtraCSSpill = true;
1675 MRI.setPhysRegUsed(FramePtr);
1676 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1678 if (FPPos != UnspilledCS1GPRs.end())
1679 UnspilledCS1GPRs.erase(FPPos);
1683 // If stack and double are 8-byte aligned and we are spilling an odd number
1684 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1685 // the integer and double callee save areas.
1686 unsigned TargetAlign = getStackAlignment();
1687 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1688 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1689 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1690 unsigned Reg = UnspilledCS1GPRs[i];
1691 // Don't spill high register if the function is thumb1
1692 if (!AFI->isThumb1OnlyFunction() ||
1693 isARMLowRegister(Reg) || Reg == ARM::LR) {
1694 MRI.setPhysRegUsed(Reg);
1695 if (!MRI.isReserved(Reg))
1696 ExtraCSSpill = true;
1700 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1701 unsigned Reg = UnspilledCS2GPRs.front();
1702 MRI.setPhysRegUsed(Reg);
1703 if (!MRI.isReserved(Reg))
1704 ExtraCSSpill = true;
1708 // Estimate if we might need to scavenge a register at some point in order
1709 // to materialize a stack offset. If so, either spill one additional
1710 // callee-saved register or reserve a special spill slot to facilitate
1711 // register scavenging. Thumb1 needs a spill slot for stack pointer
1712 // adjustments also, even when the frame itself is small.
1713 if (BigStack && !ExtraCSSpill) {
1714 // If any non-reserved CS register isn't spilled, just spill one or two
1715 // extra. That should take care of it!
1716 unsigned NumExtras = TargetAlign / 4;
1717 SmallVector<unsigned, 2> Extras;
1718 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1719 unsigned Reg = UnspilledCS1GPRs.back();
1720 UnspilledCS1GPRs.pop_back();
1721 if (!MRI.isReserved(Reg) &&
1722 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1724 Extras.push_back(Reg);
1728 // For non-Thumb1 functions, also check for hi-reg CS registers
1729 if (!AFI->isThumb1OnlyFunction()) {
1730 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1731 unsigned Reg = UnspilledCS2GPRs.back();
1732 UnspilledCS2GPRs.pop_back();
1733 if (!MRI.isReserved(Reg)) {
1734 Extras.push_back(Reg);
1739 if (Extras.size() && NumExtras == 0) {
1740 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1741 MRI.setPhysRegUsed(Extras[i]);
1743 } else if (!AFI->isThumb1OnlyFunction()) {
1744 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1745 // closest to SP or frame pointer.
1746 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1747 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1755 MRI.setPhysRegUsed(ARM::LR);
1756 AFI->setLRIsSpilledForFarJump(true);
1761 void ARMFrameLowering::
1762 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1763 MachineBasicBlock::iterator I) const {
1764 const ARMBaseInstrInfo &TII =
1765 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1766 if (!hasReservedCallFrame(MF)) {
1767 // If we have alloca, convert as follows:
1768 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1769 // ADJCALLSTACKUP -> add, sp, sp, amount
1770 MachineInstr *Old = I;
1771 DebugLoc dl = Old->getDebugLoc();
1772 unsigned Amount = Old->getOperand(0).getImm();
1774 // We need to keep the stack aligned properly. To do this, we round the
1775 // amount of space needed for the outgoing arguments up to the next
1776 // alignment boundary.
1777 unsigned Align = getStackAlignment();
1778 Amount = (Amount+Align-1)/Align*Align;
1780 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1781 assert(!AFI->isThumb1OnlyFunction() &&
1782 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1783 bool isARM = !AFI->isThumbFunction();
1785 // Replace the pseudo instruction with a new instruction...
1786 unsigned Opc = Old->getOpcode();
1787 int PIdx = Old->findFirstPredOperandIdx();
1788 ARMCC::CondCodes Pred = (PIdx == -1)
1789 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1790 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1791 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1792 unsigned PredReg = Old->getOperand(2).getReg();
1793 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1796 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1797 unsigned PredReg = Old->getOperand(3).getReg();
1798 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1799 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1807 /// Get the minimum constant for ARM that is greater than or equal to the
1808 /// argument. In ARM, constants can have any value that can be produced by
1809 /// rotating an 8-bit value to the right by an even number of bits within a
1811 static uint32_t alignToARMConstant(uint32_t Value) {
1812 unsigned Shifted = 0;
1817 while (!(Value & 0xC0000000)) {
1822 bool Carry = (Value & 0x00FFFFFF);
1823 Value = ((Value & 0xFF000000) >> 24) + Carry;
1825 if (Value & 0x0000100)
1826 Value = Value & 0x000001FC;
1829 Value = Value >> (Shifted - 24);
1831 Value = Value << (24 - Shifted);
1836 // The stack limit in the TCB is set to this many bytes above the actual
1838 static const uint64_t kSplitStackAvailable = 256;
1840 // Adjust the function prologue to enable split stacks. This currently only
1841 // supports android and linux.
1843 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1844 // must be well defined in order to allow for consistent implementations of the
1845 // __morestack helper function. The ABI is also not a normal ABI in that it
1846 // doesn't follow the normal calling conventions because this allows the
1847 // prologue of each function to be optimized further.
1849 // Currently, the ABI looks like (when calling __morestack)
1851 // * r4 holds the minimum stack size requested for this function call
1852 // * r5 holds the stack size of the arguments to the function
1853 // * the beginning of the function is 3 instructions after the call to
1856 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1857 // place the arguments on to the new stack, and the 3-instruction knowledge to
1858 // jump directly to the body of the function when working on the new stack.
1860 // An old (and possibly no longer compatible) implementation of __morestack for
1861 // ARM can be found at [1].
1863 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1864 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1867 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1868 bool Thumb = ST->isThumb();
1870 // Sadly, this currently doesn't support varargs, platforms other than
1871 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1872 if (MF.getFunction()->isVarArg())
1873 report_fatal_error("Segmented stacks do not support vararg functions.");
1874 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1875 report_fatal_error("Segmented stacks not supported on this platform.");
1877 MachineBasicBlock &prologueMBB = MF.front();
1878 MachineFrameInfo *MFI = MF.getFrameInfo();
1879 MachineModuleInfo &MMI = MF.getMMI();
1880 MCContext &Context = MMI.getContext();
1881 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1882 const ARMBaseInstrInfo &TII =
1883 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1884 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1887 uint64_t StackSize = MFI->getStackSize();
1889 // Do not generate a prologue for functions with a stack of size zero
1893 // Use R4 and R5 as scratch registers.
1894 // We save R4 and R5 before use and restore them before leaving the function.
1895 unsigned ScratchReg0 = ARM::R4;
1896 unsigned ScratchReg1 = ARM::R5;
1897 uint64_t AlignedStackSize;
1899 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1900 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1901 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1902 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1903 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1905 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1906 e = prologueMBB.livein_end();
1908 AllocMBB->addLiveIn(*i);
1909 GetMBB->addLiveIn(*i);
1910 McrMBB->addLiveIn(*i);
1911 PrevStackMBB->addLiveIn(*i);
1912 PostStackMBB->addLiveIn(*i);
1915 MF.push_front(PostStackMBB);
1916 MF.push_front(AllocMBB);
1917 MF.push_front(GetMBB);
1918 MF.push_front(McrMBB);
1919 MF.push_front(PrevStackMBB);
1921 // The required stack size that is aligned to ARM constant criterion.
1922 AlignedStackSize = alignToARMConstant(StackSize);
1924 // When the frame size is less than 256 we just compare the stack
1925 // boundary directly to the value of the stack pointer, per gcc.
1926 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1928 // We will use two of the callee save registers as scratch registers so we
1929 // need to save those registers onto the stack.
1930 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1931 // requested and arguments for __morestack().
1932 // SR0: Scratch Register #0
1933 // SR1: Scratch Register #1
1936 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1937 .addReg(ScratchReg0).addReg(ScratchReg1);
1939 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1940 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1941 .addReg(ScratchReg0).addReg(ScratchReg1);
1944 // Emit the relevant DWARF information about the change in stack pointer as
1945 // well as where to find both r4 and r5 (the callee-save registers)
1947 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1948 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1949 .addCFIIndex(CFIIndex);
1950 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1951 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1952 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1953 .addCFIIndex(CFIIndex);
1954 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1955 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1956 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1957 .addCFIIndex(CFIIndex);
1961 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1963 } else if (CompareStackPointer) {
1964 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1965 .addReg(ARM::SP)).addReg(0);
1968 // sub SR1, sp, #StackSize
1969 if (!CompareStackPointer && Thumb) {
1971 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1972 .addReg(ScratchReg1).addImm(AlignedStackSize));
1973 } else if (!CompareStackPointer) {
1974 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1975 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1978 if (Thumb && ST->isThumb1Only()) {
1979 unsigned PCLabelId = ARMFI->createPICLabelUId();
1980 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1981 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1982 MachineConstantPool *MCP = MF.getConstantPool();
1983 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1985 // ldr SR0, [pc, offset(STACK_LIMIT)]
1986 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1987 .addConstantPoolIndex(CPI));
1990 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1991 .addReg(ScratchReg0).addImm(0));
1993 // Get TLS base address from the coprocessor
1994 // mrc p15, #0, SR0, c13, c0, #3
1995 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2002 // Use the last tls slot on android and a private field of the TCP on linux.
2003 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2004 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2006 // Get the stack limit from the right offset
2007 // ldr SR0, [sr0, #4 * TlsOffset]
2008 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2009 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2012 // Compare stack limit with stack size requested.
2014 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2015 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2016 .addReg(ScratchReg0)
2017 .addReg(ScratchReg1));
2019 // This jump is taken if StackLimit < SP - stack required.
2020 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2021 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2026 // Calling __morestack(StackSize, Size of stack arguments).
2027 // __morestack knows that the stack size requested is in SR0(r4)
2028 // and amount size of stack arguments is in SR1(r5).
2030 // Pass first argument for the __morestack by Scratch Register #0.
2031 // The amount size of stack required
2033 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2034 ScratchReg0)).addImm(AlignedStackSize));
2036 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2037 .addImm(AlignedStackSize)).addReg(0);
2039 // Pass second argument for the __morestack by Scratch Register #1.
2040 // The amount size of stack consumed to save function arguments.
2043 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2044 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2046 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2047 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2051 // push {lr} - Save return address of this function.
2053 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2056 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2057 .addReg(ARM::SP, RegState::Define)
2062 // Emit the DWARF info about the change in stack as well as where to find the
2063 // previous link register
2065 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2066 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2067 .addCFIIndex(CFIIndex);
2068 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2069 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2070 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2071 .addCFIIndex(CFIIndex);
2073 // Call __morestack().
2075 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2076 .addExternalSymbol("__morestack");
2078 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2079 .addExternalSymbol("__morestack");
2082 // pop {lr} - Restore return address of this original function.
2084 if (ST->isThumb1Only()) {
2085 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2086 .addReg(ScratchReg0);
2087 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2088 .addReg(ScratchReg0));
2090 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2091 .addReg(ARM::LR, RegState::Define)
2092 .addReg(ARM::SP, RegState::Define)
2097 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2098 .addReg(ARM::SP, RegState::Define)
2103 // Restore SR0 and SR1 in case of __morestack() was called.
2104 // __morestack() will skip PostStackMBB block so we need to restore
2105 // scratch registers from here.
2108 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2109 .addReg(ScratchReg0)
2110 .addReg(ScratchReg1);
2112 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2113 .addReg(ARM::SP, RegState::Define)
2115 .addReg(ScratchReg0)
2116 .addReg(ScratchReg1);
2119 // Update the CFA offset now that we've popped
2120 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2121 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2122 .addCFIIndex(CFIIndex);
2124 // bx lr - Return from this function.
2125 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2126 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2128 // Restore SR0 and SR1 in case of __morestack() was not called.
2131 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2132 .addReg(ScratchReg0)
2133 .addReg(ScratchReg1);
2135 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2136 .addReg(ARM::SP, RegState::Define)
2138 .addReg(ScratchReg0)
2139 .addReg(ScratchReg1);
2142 // Update the CFA offset now that we've popped
2143 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2144 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2145 .addCFIIndex(CFIIndex);
2147 // Tell debuggers that r4 and r5 are now the same as they were in the
2148 // previous function, that they're the "Same Value".
2149 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2150 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2151 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2152 .addCFIIndex(CFIIndex);
2153 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2154 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2155 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2156 .addCFIIndex(CFIIndex);
2158 // Organizing MBB lists
2159 PostStackMBB->addSuccessor(&prologueMBB);
2161 AllocMBB->addSuccessor(PostStackMBB);
2163 GetMBB->addSuccessor(PostStackMBB);
2164 GetMBB->addSuccessor(AllocMBB);
2166 McrMBB->addSuccessor(GetMBB);
2168 PrevStackMBB->addSuccessor(McrMBB);