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 =
51 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
53 // iOS requires FP not to be clobbered for backtracing purpose.
54 if (STI.isTargetIOS())
57 const MachineFrameInfo *MFI = MF.getFrameInfo();
58 // Always eliminate non-leaf frame pointers.
59 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
61 RegInfo->needsStackRealignment(MF) ||
62 MFI->hasVarSizedObjects() ||
63 MFI->isFrameAddressTaken());
66 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
67 /// not required, we reserve argument space for call sites in the function
68 /// immediately on entry to the current function. This eliminates the need for
69 /// add/sub sp brackets around call sites. Returns true if the call frame is
70 /// included as part of the stack frame.
71 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
72 const MachineFrameInfo *FFI = MF.getFrameInfo();
73 unsigned CFSize = FFI->getMaxCallFrameSize();
74 // It's not always a good idea to include the call frame as part of the
75 // stack frame. ARM (especially Thumb) has small immediate offset to
76 // address the stack frame. So a large call frame can cause poor codegen
77 // and may even makes it impossible to scavenge a register.
78 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
81 return !MF.getFrameInfo()->hasVarSizedObjects();
84 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
85 /// call frame pseudos can be simplified. Unlike most targets, having a FP
86 /// is not sufficient here since we still may reference some objects via SP
87 /// even when FP is available in Thumb2 mode.
89 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
90 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
93 static bool isCSRestore(MachineInstr *MI,
94 const ARMBaseInstrInfo &TII,
95 const MCPhysReg *CSRegs) {
96 // Integer spill area is handled with "pop".
97 if (isPopOpcode(MI->getOpcode())) {
98 // The first two operands are predicates. The last two are
99 // imp-def and imp-use of SP. Check everything in between.
100 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
101 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
105 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
106 MI->getOpcode() == ARM::LDR_POST_REG ||
107 MI->getOpcode() == ARM::t2LDR_POST) &&
108 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
109 MI->getOperand(1).getReg() == ARM::SP)
115 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
116 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
117 const ARMBaseInstrInfo &TII, unsigned DestReg,
118 unsigned SrcReg, int NumBytes,
119 unsigned MIFlags = MachineInstr::NoFlags,
120 ARMCC::CondCodes Pred = ARMCC::AL,
121 unsigned PredReg = 0) {
123 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
124 Pred, PredReg, TII, MIFlags);
126 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
127 Pred, PredReg, TII, MIFlags);
130 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
131 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
132 const ARMBaseInstrInfo &TII, int NumBytes,
133 unsigned MIFlags = MachineInstr::NoFlags,
134 ARMCC::CondCodes Pred = ARMCC::AL,
135 unsigned PredReg = 0) {
136 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
137 MIFlags, Pred, PredReg);
140 static int sizeOfSPAdjustment(const MachineInstr *MI) {
141 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
143 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
144 // pred) so the list starts at 4.
145 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
150 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
151 size_t StackSizeInBytes) {
152 const MachineFrameInfo *MFI = MF.getFrameInfo();
153 if (MFI->getStackProtectorIndex() > 0)
154 return StackSizeInBytes >= 4080;
155 return StackSizeInBytes >= 4096;
158 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
159 MachineBasicBlock &MBB = MF.front();
160 MachineBasicBlock::iterator MBBI = MBB.begin();
161 MachineFrameInfo *MFI = MF.getFrameInfo();
162 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
163 MachineModuleInfo &MMI = MF.getMMI();
164 MCContext &Context = MMI.getContext();
165 const TargetMachine &TM = MF.getTarget();
166 const MCRegisterInfo *MRI = Context.getRegisterInfo();
167 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
168 TM.getSubtargetImpl()->getRegisterInfo());
169 const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
170 TM.getSubtargetImpl()->getInstrInfo());
171 assert(!AFI->isThumb1OnlyFunction() &&
172 "This emitPrologue does not support Thumb1!");
173 bool isARM = !AFI->isThumbFunction();
175 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
176 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
177 unsigned NumBytes = MFI->getStackSize();
178 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
179 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
180 unsigned FramePtr = RegInfo->getFrameRegister(MF);
183 // Determine the sizes of each callee-save spill areas and record which frame
184 // belongs to which callee-save spill areas.
185 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
186 int FramePtrSpillFI = 0;
189 // All calls are tail calls in GHC calling conv, and functions have no
190 // prologue/epilogue.
191 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
194 // Allocate the vararg register save area.
195 if (ArgRegsSaveSize) {
196 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
197 MachineInstr::FrameSetup);
198 CFAOffset -= ArgRegsSaveSize;
199 unsigned CFIIndex = MMI.addFrameInst(
200 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
201 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
202 .addCFIIndex(CFIIndex);
205 if (!AFI->hasStackFrame() &&
206 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
207 if (NumBytes - ArgRegsSaveSize != 0) {
208 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
209 MachineInstr::FrameSetup);
210 CFAOffset -= NumBytes - ArgRegsSaveSize;
211 unsigned CFIIndex = MMI.addFrameInst(
212 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
213 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
214 .addCFIIndex(CFIIndex);
219 // Determine spill area sizes.
220 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
221 unsigned Reg = CSI[i].getReg();
222 int FI = CSI[i].getFrameIdx();
229 if (STI.isTargetDarwin()) {
244 FramePtrSpillFI = FI;
248 // This is a DPR. Exclude the aligned DPRCS2 spills.
251 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
257 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
260 GPRCS1Push = LastPush = MBBI++;
262 // Determine starting offsets of spill areas.
263 bool HasFP = hasFP(MF);
264 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
265 + GPRCS2Size + DPRCSSize);
266 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
267 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
268 int FramePtrOffsetInPush = 0;
270 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
271 + GPRCS1Size + ArgRegsSaveSize;
272 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
275 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
276 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
277 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
281 GPRCS2Push = LastPush = MBBI++;
286 // Since vpush register list cannot have gaps, there may be multiple vpush
287 // instructions in the prologue.
288 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
292 // Move past the aligned DPRCS2 area.
293 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
294 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
295 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
296 // leaves the stack pointer pointing to the DPRCS2 area.
298 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
299 NumBytes += MFI->getObjectOffset(D8SpillFI);
301 NumBytes = DPRCSOffset;
303 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
304 uint32_t NumWords = NumBytes >> 2;
306 if (NumWords < 65536)
307 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
309 .setMIFlags(MachineInstr::FrameSetup));
311 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
313 .setMIFlags(MachineInstr::FrameSetup);
315 switch (TM.getCodeModel()) {
316 case CodeModel::Small:
317 case CodeModel::Medium:
318 case CodeModel::Default:
319 case CodeModel::Kernel:
320 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
321 .addImm((unsigned)ARMCC::AL).addReg(0)
322 .addExternalSymbol("__chkstk")
323 .addReg(ARM::R4, RegState::Implicit)
324 .setMIFlags(MachineInstr::FrameSetup);
326 case CodeModel::Large:
327 case CodeModel::JITDefault:
328 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
329 .addExternalSymbol("__chkstk")
330 .setMIFlags(MachineInstr::FrameSetup);
332 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
333 .addImm((unsigned)ARMCC::AL).addReg(0)
334 .addReg(ARM::R12, RegState::Kill)
335 .addReg(ARM::R4, RegState::Implicit)
336 .setMIFlags(MachineInstr::FrameSetup);
340 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
342 .addReg(ARM::SP, RegState::Define)
343 .addReg(ARM::R4, RegState::Kill)
344 .setMIFlags(MachineInstr::FrameSetup)));
348 unsigned adjustedGPRCS1Size = GPRCS1Size;
350 // Adjust SP after all the callee-save spills.
351 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
352 if (LastPush == GPRCS1Push) {
353 FramePtrOffsetInPush += NumBytes;
354 adjustedGPRCS1Size += NumBytes;
358 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
359 MachineInstr::FrameSetup);
362 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
363 // Note it's not safe to do this in Thumb2 mode because it would have
364 // taken two instructions:
367 // If an interrupt is taken between the two instructions, then sp is in
368 // an inconsistent state (pointing to the middle of callee-saved area).
369 // The interrupt handler can end up clobbering the registers.
370 AFI->setShouldRestoreSPFromFP(true);
373 if (adjustedGPRCS1Size > 0) {
374 CFAOffset -= adjustedGPRCS1Size;
375 unsigned CFIIndex = MMI.addFrameInst(
376 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
377 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
378 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
379 .addCFIIndex(CFIIndex);
380 for (const auto &Entry : CSI) {
381 unsigned Reg = Entry.getReg();
382 int FI = Entry.getFrameIdx();
389 if (STI.isTargetDarwin())
401 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
402 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
403 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
404 .addCFIIndex(CFIIndex);
410 // Set FP to point to the stack slot that contains the previous FP.
411 // For iOS, FP is R7, which has now been stored in spill area 1.
412 // Otherwise, if this is not iOS, all the callee-saved registers go
413 // into spill area 1, including the FP in R11. In either case, it
414 // is in area one and the adjustment needs to take place just after
417 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
418 FramePtr, ARM::SP, FramePtrOffsetInPush,
419 MachineInstr::FrameSetup);
420 if (FramePtrOffsetInPush) {
421 CFAOffset += FramePtrOffsetInPush;
422 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
423 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
424 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
425 .addCFIIndex(CFIIndex);
429 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
430 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
431 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
432 .addCFIIndex(CFIIndex);
436 if (GPRCS2Size > 0) {
437 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
439 CFAOffset -= GPRCS2Size;
440 unsigned CFIIndex = MMI.addFrameInst(
441 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
442 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
443 .addCFIIndex(CFIIndex);
445 for (const auto &Entry : CSI) {
446 unsigned Reg = Entry.getReg();
447 int FI = Entry.getFrameIdx();
454 if (STI.isTargetDarwin()) {
455 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
456 unsigned Offset = MFI->getObjectOffset(FI);
457 unsigned CFIIndex = MMI.addFrameInst(
458 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
459 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
460 .addCFIIndex(CFIIndex);
468 // Since vpush register list cannot have gaps, there may be multiple vpush
469 // instructions in the prologue.
471 MachineBasicBlock::iterator Push = DPRCSPush++;
473 CFAOffset -= sizeOfSPAdjustment(Push);
474 unsigned CFIIndex = MMI.addFrameInst(
475 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
476 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
477 .addCFIIndex(CFIIndex);
479 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
481 for (const auto &Entry : CSI) {
482 unsigned Reg = Entry.getReg();
483 int FI = Entry.getFrameIdx();
484 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
485 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
486 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
487 unsigned Offset = MFI->getObjectOffset(FI);
488 unsigned CFIIndex = MMI.addFrameInst(
489 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
490 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
491 .addCFIIndex(CFIIndex);
498 CFAOffset -= NumBytes;
499 unsigned CFIIndex = MMI.addFrameInst(
500 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
501 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
502 .addCFIIndex(CFIIndex);
506 if (STI.isTargetELF() && hasFP(MF))
507 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
508 AFI->getFramePtrSpillOffset());
510 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
511 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
512 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
514 // If we need dynamic stack realignment, do it here. Be paranoid and make
515 // sure if we also have VLAs, we have a base pointer for frame access.
516 // If aligned NEON registers were spilled, the stack has already been
518 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
519 unsigned MaxAlign = MFI->getMaxAlignment();
520 assert (!AFI->isThumb1OnlyFunction());
521 if (!AFI->isThumbFunction()) {
522 // Emit bic sp, sp, MaxAlign
523 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
524 TII.get(ARM::BICri), ARM::SP)
525 .addReg(ARM::SP, RegState::Kill)
526 .addImm(MaxAlign-1)));
528 // We cannot use sp as source/dest register here, thus we're emitting the
529 // following sequence:
531 // bic r4, r4, MaxAlign
533 // FIXME: It will be better just to find spare register here.
534 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
535 .addReg(ARM::SP, RegState::Kill));
536 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
537 TII.get(ARM::t2BICri), ARM::R4)
538 .addReg(ARM::R4, RegState::Kill)
539 .addImm(MaxAlign-1)));
540 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
541 .addReg(ARM::R4, RegState::Kill));
544 AFI->setShouldRestoreSPFromFP(true);
547 // If we need a base pointer, set it up here. It's whatever the value
548 // of the stack pointer is at this point. Any variable size objects
549 // will be allocated after this, so we can still use the base pointer
550 // to reference locals.
551 // FIXME: Clarify FrameSetup flags here.
552 if (RegInfo->hasBasePointer(MF)) {
554 BuildMI(MBB, MBBI, dl,
555 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
557 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
559 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
560 RegInfo->getBaseRegister())
564 // If the frame has variable sized objects then the epilogue must restore
565 // the sp from fp. We can assume there's an FP here since hasFP already
566 // checks for hasVarSizedObjects.
567 if (MFI->hasVarSizedObjects())
568 AFI->setShouldRestoreSPFromFP(true);
571 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
572 MachineBasicBlock &MBB) const {
573 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
574 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
575 unsigned RetOpcode = MBBI->getOpcode();
576 DebugLoc dl = MBBI->getDebugLoc();
577 MachineFrameInfo *MFI = MF.getFrameInfo();
578 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
579 const TargetRegisterInfo *RegInfo =
580 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
581 const ARMBaseInstrInfo &TII =
582 *static_cast<const ARMBaseInstrInfo *>(
583 MF.getTarget().getSubtargetImpl()->getInstrInfo());
584 assert(!AFI->isThumb1OnlyFunction() &&
585 "This emitEpilogue does not support Thumb1!");
586 bool isARM = !AFI->isThumbFunction();
588 unsigned Align = MF.getTarget()
591 ->getStackAlignment();
592 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
593 int NumBytes = (int)MFI->getStackSize();
594 unsigned FramePtr = RegInfo->getFrameRegister(MF);
596 // All calls are tail calls in GHC calling conv, and functions have no
597 // prologue/epilogue.
598 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
601 if (!AFI->hasStackFrame()) {
602 if (NumBytes - ArgRegsSaveSize != 0)
603 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
605 // Unwind MBBI to point to first LDR / VLDRD.
606 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
607 if (MBBI != MBB.begin()) {
610 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
611 if (!isCSRestore(MBBI, TII, CSRegs))
615 // Move SP to start of FP callee save spill area.
616 NumBytes -= (ArgRegsSaveSize +
617 AFI->getGPRCalleeSavedArea1Size() +
618 AFI->getGPRCalleeSavedArea2Size() +
619 AFI->getDPRCalleeSavedAreaSize());
621 // Reset SP based on frame pointer only if the stack frame extends beyond
622 // frame pointer stack slot or target is ELF and the function has FP.
623 if (AFI->shouldRestoreSPFromFP()) {
624 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
627 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
630 // It's not possible to restore SP from FP in a single instruction.
631 // For iOS, this looks like:
634 // This is bad, if an interrupt is taken after the mov, sp is in an
635 // inconsistent state.
636 // Use the first callee-saved register as a scratch register.
637 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
638 "No scratch register to restore SP from FP!");
639 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
641 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
648 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
649 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
651 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
655 } else if (NumBytes &&
656 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
657 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
659 // Increment past our save areas.
660 if (AFI->getDPRCalleeSavedAreaSize()) {
662 // Since vpop register list cannot have gaps, there may be multiple vpop
663 // instructions in the epilogue.
664 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
667 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
668 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
671 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
672 // Tail call return: adjust the stack pointer and jump to callee.
673 MBBI = MBB.getLastNonDebugInstr();
674 MachineOperand &JumpTarget = MBBI->getOperand(0);
676 // Jump to label or value in register.
677 if (RetOpcode == ARM::TCRETURNdi) {
678 unsigned TCOpcode = STI.isThumb() ?
679 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
681 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
682 if (JumpTarget.isGlobal())
683 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
684 JumpTarget.getTargetFlags());
686 assert(JumpTarget.isSymbol());
687 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
688 JumpTarget.getTargetFlags());
691 // Add the default predicate in Thumb mode.
692 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
693 } else if (RetOpcode == ARM::TCRETURNri) {
694 BuildMI(MBB, MBBI, dl,
695 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
696 addReg(JumpTarget.getReg(), RegState::Kill);
699 MachineInstr *NewMI = std::prev(MBBI);
700 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
701 NewMI->addOperand(MBBI->getOperand(i));
703 // Delete the pseudo instruction TCRETURN.
709 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
712 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
713 /// debug info. It's the same as what we use for resolving the code-gen
714 /// references for now. FIXME: This can go wrong when references are
715 /// SP-relative and simple call frames aren't used.
717 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
718 unsigned &FrameReg) const {
719 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
723 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
724 int FI, unsigned &FrameReg,
726 const MachineFrameInfo *MFI = MF.getFrameInfo();
727 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
728 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
729 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
730 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
731 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
732 bool isFixed = MFI->isFixedObjectIndex(FI);
737 // SP can move around if there are allocas. We may also lose track of SP
738 // when emergency spilling inside a non-reserved call frame setup.
739 bool hasMovingSP = !hasReservedCallFrame(MF);
741 // When dynamically realigning the stack, use the frame pointer for
742 // parameters, and the stack/base pointer for locals.
743 if (RegInfo->needsStackRealignment(MF)) {
744 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
746 FrameReg = RegInfo->getFrameRegister(MF);
748 } else if (hasMovingSP) {
749 assert(RegInfo->hasBasePointer(MF) &&
750 "VLAs and dynamic stack alignment, but missing base pointer!");
751 FrameReg = RegInfo->getBaseRegister();
756 // If there is a frame pointer, use it when we can.
757 if (hasFP(MF) && AFI->hasStackFrame()) {
758 // Use frame pointer to reference fixed objects. Use it for locals if
759 // there are VLAs (and thus the SP isn't reliable as a base).
760 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
761 FrameReg = RegInfo->getFrameRegister(MF);
763 } else if (hasMovingSP) {
764 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
765 if (AFI->isThumb2Function()) {
766 // Try to use the frame pointer if we can, else use the base pointer
767 // since it's available. This is handy for the emergency spill slot, in
769 if (FPOffset >= -255 && FPOffset < 0) {
770 FrameReg = RegInfo->getFrameRegister(MF);
774 } else if (AFI->isThumb2Function()) {
775 // Use add <rd>, sp, #<imm8>
776 // ldr <rd>, [sp, #<imm8>]
777 // if at all possible to save space.
778 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
780 // In Thumb2 mode, the negative offset is very limited. Try to avoid
781 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
782 if (FPOffset >= -255 && FPOffset < 0) {
783 FrameReg = RegInfo->getFrameRegister(MF);
786 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
787 // Otherwise, use SP or FP, whichever is closer to the stack slot.
788 FrameReg = RegInfo->getFrameRegister(MF);
792 // Use the base pointer if we have one.
793 if (RegInfo->hasBasePointer(MF))
794 FrameReg = RegInfo->getBaseRegister();
798 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
801 return getFrameIndexReference(MF, FI, FrameReg);
804 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
805 MachineBasicBlock::iterator MI,
806 const std::vector<CalleeSavedInfo> &CSI,
807 unsigned StmOpc, unsigned StrOpc,
809 bool(*Func)(unsigned, bool),
810 unsigned NumAlignedDPRCS2Regs,
811 unsigned MIFlags) const {
812 MachineFunction &MF = *MBB.getParent();
813 const TargetInstrInfo &TII =
814 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
817 if (MI != MBB.end()) DL = MI->getDebugLoc();
819 SmallVector<std::pair<unsigned,bool>, 4> Regs;
820 unsigned i = CSI.size();
822 unsigned LastReg = 0;
823 for (; i != 0; --i) {
824 unsigned Reg = CSI[i-1].getReg();
825 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
827 // D-registers in the aligned area DPRCS2 are NOT spilled here.
828 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
831 // Add the callee-saved register as live-in unless it's LR and
832 // @llvm.returnaddress is called. If LR is returned for
833 // @llvm.returnaddress then it's already added to the function and
834 // entry block live-in sets.
836 if (Reg == ARM::LR) {
837 if (MF.getFrameInfo()->isReturnAddressTaken() &&
838 MF.getRegInfo().isLiveIn(Reg))
845 // If NoGap is true, push consecutive registers and then leave the rest
846 // for other instructions. e.g.
847 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
848 if (NoGap && LastReg && LastReg != Reg-1)
851 Regs.push_back(std::make_pair(Reg, isKill));
856 if (Regs.size() > 1 || StrOpc== 0) {
857 MachineInstrBuilder MIB =
858 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
859 .addReg(ARM::SP).setMIFlags(MIFlags));
860 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
861 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
862 } else if (Regs.size() == 1) {
863 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
865 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
866 .addReg(ARM::SP).setMIFlags(MIFlags)
872 // Put any subsequent vpush instructions before this one: they will refer to
873 // higher register numbers so need to be pushed first in order to preserve
879 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
880 MachineBasicBlock::iterator MI,
881 const std::vector<CalleeSavedInfo> &CSI,
882 unsigned LdmOpc, unsigned LdrOpc,
883 bool isVarArg, bool NoGap,
884 bool(*Func)(unsigned, bool),
885 unsigned NumAlignedDPRCS2Regs) const {
886 MachineFunction &MF = *MBB.getParent();
887 const TargetInstrInfo &TII =
888 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
889 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
890 DebugLoc DL = MI->getDebugLoc();
891 unsigned RetOpcode = MI->getOpcode();
892 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
893 RetOpcode == ARM::TCRETURNri);
895 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
897 SmallVector<unsigned, 4> Regs;
898 unsigned i = CSI.size();
900 unsigned LastReg = 0;
901 bool DeleteRet = false;
902 for (; i != 0; --i) {
903 unsigned Reg = CSI[i-1].getReg();
904 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
906 // The aligned reloads from area DPRCS2 are not inserted here.
907 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
910 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
913 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
914 // Fold the return instruction into the LDM.
918 // If NoGap is true, pop consecutive registers and then leave the rest
919 // for other instructions. e.g.
920 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
921 if (NoGap && LastReg && LastReg != Reg-1)
930 if (Regs.size() > 1 || LdrOpc == 0) {
931 MachineInstrBuilder MIB =
932 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
934 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
935 MIB.addReg(Regs[i], getDefRegState(true));
937 MIB.copyImplicitOps(&*MI);
938 MI->eraseFromParent();
941 } else if (Regs.size() == 1) {
942 // If we adjusted the reg to PC from LR above, switch it back here. We
943 // only do that for LDM.
944 if (Regs[0] == ARM::PC)
946 MachineInstrBuilder MIB =
947 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
948 .addReg(ARM::SP, RegState::Define)
950 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
951 // that refactoring is complete (eventually).
952 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
954 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
961 // Put any subsequent vpop instructions after this one: they will refer to
962 // higher register numbers so need to be popped afterwards.
967 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
968 /// starting from d8. Also insert stack realignment code and leave the stack
969 /// pointer pointing to the d8 spill slot.
970 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
971 MachineBasicBlock::iterator MI,
972 unsigned NumAlignedDPRCS2Regs,
973 const std::vector<CalleeSavedInfo> &CSI,
974 const TargetRegisterInfo *TRI) {
975 MachineFunction &MF = *MBB.getParent();
976 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
977 DebugLoc DL = MI->getDebugLoc();
978 const TargetInstrInfo &TII =
979 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
980 MachineFrameInfo &MFI = *MF.getFrameInfo();
982 // Mark the D-register spill slots as properly aligned. Since MFI computes
983 // stack slot layout backwards, this can actually mean that the d-reg stack
984 // slot offsets can be wrong. The offset for d8 will always be correct.
985 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
986 unsigned DNum = CSI[i].getReg() - ARM::D8;
989 int FI = CSI[i].getFrameIdx();
990 // The even-numbered registers will be 16-byte aligned, the odd-numbered
991 // registers will be 8-byte aligned.
992 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
994 // The stack slot for D8 needs to be maximally aligned because this is
995 // actually the point where we align the stack pointer. MachineFrameInfo
996 // computes all offsets relative to the incoming stack pointer which is a
997 // bit weird when realigning the stack. Any extra padding for this
998 // over-alignment is not realized because the code inserted below adjusts
999 // the stack pointer by numregs * 8 before aligning the stack pointer.
1001 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1004 // Move the stack pointer to the d8 spill slot, and align it at the same
1005 // time. Leave the stack slot address in the scratch register r4.
1007 // sub r4, sp, #numregs * 8
1008 // bic r4, r4, #align - 1
1011 bool isThumb = AFI->isThumbFunction();
1012 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1013 AFI->setShouldRestoreSPFromFP(true);
1015 // sub r4, sp, #numregs * 8
1016 // The immediate is <= 64, so it doesn't need any special encoding.
1017 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1018 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1020 .addImm(8 * NumAlignedDPRCS2Regs)));
1022 // bic r4, r4, #align-1
1023 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1024 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1025 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1026 .addReg(ARM::R4, RegState::Kill)
1027 .addImm(MaxAlign - 1)));
1030 // The stack pointer must be adjusted before spilling anything, otherwise
1031 // the stack slots could be clobbered by an interrupt handler.
1032 // Leave r4 live, it is used below.
1033 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1034 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1036 MIB = AddDefaultPred(MIB);
1040 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1041 // r4 holds the stack slot address.
1042 unsigned NextReg = ARM::D8;
1044 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1045 // The writeback is only needed when emitting two vst1.64 instructions.
1046 if (NumAlignedDPRCS2Regs >= 6) {
1047 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1048 &ARM::QQPRRegClass);
1049 MBB.addLiveIn(SupReg);
1050 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1052 .addReg(ARM::R4, RegState::Kill).addImm(16)
1054 .addReg(SupReg, RegState::ImplicitKill));
1056 NumAlignedDPRCS2Regs -= 4;
1059 // We won't modify r4 beyond this point. It currently points to the next
1060 // register to be spilled.
1061 unsigned R4BaseReg = NextReg;
1063 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1064 if (NumAlignedDPRCS2Regs >= 4) {
1065 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1066 &ARM::QQPRRegClass);
1067 MBB.addLiveIn(SupReg);
1068 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1069 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1070 .addReg(SupReg, RegState::ImplicitKill));
1072 NumAlignedDPRCS2Regs -= 4;
1075 // 16-byte aligned vst1.64 with 2 d-regs.
1076 if (NumAlignedDPRCS2Regs >= 2) {
1077 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1079 MBB.addLiveIn(SupReg);
1080 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1081 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1083 NumAlignedDPRCS2Regs -= 2;
1086 // Finally, use a vanilla vstr.64 for the odd last register.
1087 if (NumAlignedDPRCS2Regs) {
1088 MBB.addLiveIn(NextReg);
1089 // vstr.64 uses addrmode5 which has an offset scale of 4.
1090 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1092 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1095 // The last spill instruction inserted should kill the scratch register r4.
1096 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1099 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1100 /// iterator to the following instruction.
1101 static MachineBasicBlock::iterator
1102 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1103 unsigned NumAlignedDPRCS2Regs) {
1104 // sub r4, sp, #numregs * 8
1105 // bic r4, r4, #align - 1
1108 assert(MI->mayStore() && "Expecting spill instruction");
1110 // These switches all fall through.
1111 switch(NumAlignedDPRCS2Regs) {
1114 assert(MI->mayStore() && "Expecting spill instruction");
1117 assert(MI->mayStore() && "Expecting spill instruction");
1121 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1127 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1128 /// starting from d8. These instructions are assumed to execute while the
1129 /// stack is still aligned, unlike the code inserted by emitPopInst.
1130 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1131 MachineBasicBlock::iterator MI,
1132 unsigned NumAlignedDPRCS2Regs,
1133 const std::vector<CalleeSavedInfo> &CSI,
1134 const TargetRegisterInfo *TRI) {
1135 MachineFunction &MF = *MBB.getParent();
1136 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1137 DebugLoc DL = MI->getDebugLoc();
1138 const TargetInstrInfo &TII =
1139 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
1141 // Find the frame index assigned to d8.
1143 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1144 if (CSI[i].getReg() == ARM::D8) {
1145 D8SpillFI = CSI[i].getFrameIdx();
1149 // Materialize the address of the d8 spill slot into the scratch register r4.
1150 // This can be fairly complicated if the stack frame is large, so just use
1151 // the normal frame index elimination mechanism to do it. This code runs as
1152 // the initial part of the epilog where the stack and base pointers haven't
1153 // been changed yet.
1154 bool isThumb = AFI->isThumbFunction();
1155 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1157 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1158 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1159 .addFrameIndex(D8SpillFI).addImm(0)));
1161 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1162 unsigned NextReg = ARM::D8;
1164 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1165 if (NumAlignedDPRCS2Regs >= 6) {
1166 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1167 &ARM::QQPRRegClass);
1168 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1169 .addReg(ARM::R4, RegState::Define)
1170 .addReg(ARM::R4, RegState::Kill).addImm(16)
1171 .addReg(SupReg, RegState::ImplicitDefine));
1173 NumAlignedDPRCS2Regs -= 4;
1176 // We won't modify r4 beyond this point. It currently points to the next
1177 // register to be spilled.
1178 unsigned R4BaseReg = NextReg;
1180 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1181 if (NumAlignedDPRCS2Regs >= 4) {
1182 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1183 &ARM::QQPRRegClass);
1184 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1185 .addReg(ARM::R4).addImm(16)
1186 .addReg(SupReg, RegState::ImplicitDefine));
1188 NumAlignedDPRCS2Regs -= 4;
1191 // 16-byte aligned vld1.64 with 2 d-regs.
1192 if (NumAlignedDPRCS2Regs >= 2) {
1193 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1195 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1196 .addReg(ARM::R4).addImm(16));
1198 NumAlignedDPRCS2Regs -= 2;
1201 // Finally, use a vanilla vldr.64 for the remaining odd register.
1202 if (NumAlignedDPRCS2Regs)
1203 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1204 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1206 // Last store kills r4.
1207 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1210 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1211 MachineBasicBlock::iterator MI,
1212 const std::vector<CalleeSavedInfo> &CSI,
1213 const TargetRegisterInfo *TRI) const {
1217 MachineFunction &MF = *MBB.getParent();
1218 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1220 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1221 unsigned PushOneOpc = AFI->isThumbFunction() ?
1222 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1223 unsigned FltOpc = ARM::VSTMDDB_UPD;
1224 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1225 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1226 MachineInstr::FrameSetup);
1227 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1228 MachineInstr::FrameSetup);
1229 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1230 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1232 // The code above does not insert spill code for the aligned DPRCS2 registers.
1233 // The stack realignment code will be inserted between the push instructions
1234 // and these spills.
1235 if (NumAlignedDPRCS2Regs)
1236 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1241 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1242 MachineBasicBlock::iterator MI,
1243 const std::vector<CalleeSavedInfo> &CSI,
1244 const TargetRegisterInfo *TRI) const {
1248 MachineFunction &MF = *MBB.getParent();
1249 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1250 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1251 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1253 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1254 // registers. Do that here instead.
1255 if (NumAlignedDPRCS2Regs)
1256 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1258 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1259 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1260 unsigned FltOpc = ARM::VLDMDIA_UPD;
1261 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1262 NumAlignedDPRCS2Regs);
1263 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1264 &isARMArea2Register, 0);
1265 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1266 &isARMArea1Register, 0);
1271 // FIXME: Make generic?
1272 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1273 const ARMBaseInstrInfo &TII) {
1274 unsigned FnSize = 0;
1275 for (auto &MBB : MF) {
1276 for (auto &MI : MBB)
1277 FnSize += TII.GetInstSizeInBytes(&MI);
1282 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1283 /// frames and return the stack size limit beyond which some of these
1284 /// instructions will require a scratch register during their expansion later.
1285 // FIXME: Move to TII?
1286 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1287 const TargetFrameLowering *TFI) {
1288 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1289 unsigned Limit = (1 << 12) - 1;
1290 for (auto &MBB : MF) {
1291 for (auto &MI : MBB) {
1292 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1293 if (!MI.getOperand(i).isFI())
1296 // When using ADDri to get the address of a stack object, 255 is the
1297 // largest offset guaranteed to fit in the immediate offset.
1298 if (MI.getOpcode() == ARM::ADDri) {
1299 Limit = std::min(Limit, (1U << 8) - 1);
1303 // Otherwise check the addressing mode.
1304 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1305 case ARMII::AddrMode3:
1306 case ARMII::AddrModeT2_i8:
1307 Limit = std::min(Limit, (1U << 8) - 1);
1309 case ARMII::AddrMode5:
1310 case ARMII::AddrModeT2_i8s4:
1311 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1313 case ARMII::AddrModeT2_i12:
1314 // i12 supports only positive offset so these will be converted to
1315 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1316 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1317 Limit = std::min(Limit, (1U << 8) - 1);
1319 case ARMII::AddrMode4:
1320 case ARMII::AddrMode6:
1321 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1322 // immediate offset for stack references.
1327 break; // At most one FI per instruction
1335 // In functions that realign the stack, it can be an advantage to spill the
1336 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1337 // instructions take alignment hints that can improve performance.
1339 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1340 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1341 if (!SpillAlignedNEONRegs)
1344 // Naked functions don't spill callee-saved registers.
1345 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1349 // We are planning to use NEON instructions vst1 / vld1.
1350 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1353 // Don't bother if the default stack alignment is sufficiently high.
1356 ->getFrameLowering()
1357 ->getStackAlignment() >= 8)
1360 // Aligned spills require stack realignment.
1361 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1362 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1363 if (!RegInfo->canRealignStack(MF))
1366 // We always spill contiguous d-registers starting from d8. Count how many
1367 // needs spilling. The register allocator will almost always use the
1368 // callee-saved registers in order, but it can happen that there are holes in
1369 // the range. Registers above the hole will be spilled to the standard DPRCS
1371 MachineRegisterInfo &MRI = MF.getRegInfo();
1372 unsigned NumSpills = 0;
1373 for (; NumSpills < 8; ++NumSpills)
1374 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1377 // Don't do this for just one d-register. It's not worth it.
1381 // Spill the first NumSpills D-registers after realigning the stack.
1382 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1384 // A scratch register is required for the vst1 / vld1 instructions.
1385 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1389 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1390 RegScavenger *RS) const {
1391 // This tells PEI to spill the FP as if it is any other callee-save register
1392 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1393 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1394 // to combine multiple loads / stores.
1395 bool CanEliminateFrame = true;
1396 bool CS1Spilled = false;
1397 bool LRSpilled = false;
1398 unsigned NumGPRSpills = 0;
1399 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1400 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1401 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1402 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
1403 const ARMBaseInstrInfo &TII =
1404 *static_cast<const ARMBaseInstrInfo *>(
1405 MF.getTarget().getSubtargetImpl()->getInstrInfo());
1406 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1407 MachineFrameInfo *MFI = MF.getFrameInfo();
1408 MachineRegisterInfo &MRI = MF.getRegInfo();
1409 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1411 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1412 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1413 // since it's not always possible to restore sp from fp in a single
1415 // FIXME: It will be better just to find spare register here.
1416 if (AFI->isThumb2Function() &&
1417 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1418 MRI.setPhysRegUsed(ARM::R4);
1420 if (AFI->isThumb1OnlyFunction()) {
1421 // Spill LR if Thumb1 function uses variable length argument lists.
1422 if (AFI->getArgRegsSaveSize() > 0)
1423 MRI.setPhysRegUsed(ARM::LR);
1425 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1426 // for sure what the stack size will be, but for this, an estimate is good
1427 // enough. If there anything changes it, it'll be a spill, which implies
1428 // we've used all the registers and so R4 is already used, so not marking
1429 // it here will be OK.
1430 // FIXME: It will be better just to find spare register here.
1431 unsigned StackSize = MFI->estimateStackSize(MF);
1432 if (MFI->hasVarSizedObjects() || StackSize > 508)
1433 MRI.setPhysRegUsed(ARM::R4);
1436 // See if we can spill vector registers to aligned stack.
1437 checkNumAlignedDPRCS2Regs(MF);
1439 // Spill the BasePtr if it's used.
1440 if (RegInfo->hasBasePointer(MF))
1441 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1443 // Don't spill FP if the frame can be eliminated. This is determined
1444 // by scanning the callee-save registers to see if any is used.
1445 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1446 for (unsigned i = 0; CSRegs[i]; ++i) {
1447 unsigned Reg = CSRegs[i];
1448 bool Spilled = false;
1449 if (MRI.isPhysRegUsed(Reg)) {
1451 CanEliminateFrame = false;
1454 if (!ARM::GPRRegClass.contains(Reg))
1460 if (!STI.isTargetDarwin()) {
1467 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1472 case ARM::R0: case ARM::R1:
1473 case ARM::R2: case ARM::R3:
1474 case ARM::R4: case ARM::R5:
1475 case ARM::R6: case ARM::R7:
1482 if (!STI.isTargetDarwin()) {
1483 UnspilledCS1GPRs.push_back(Reg);
1488 case ARM::R0: case ARM::R1:
1489 case ARM::R2: case ARM::R3:
1490 case ARM::R4: case ARM::R5:
1491 case ARM::R6: case ARM::R7:
1493 UnspilledCS1GPRs.push_back(Reg);
1496 UnspilledCS2GPRs.push_back(Reg);
1502 bool ForceLRSpill = false;
1503 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1504 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1505 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1506 // use of BL to implement far jump. If it turns out that it's not needed
1507 // then the branch fix up path will undo it.
1508 if (FnSize >= (1 << 11)) {
1509 CanEliminateFrame = false;
1510 ForceLRSpill = true;
1514 // If any of the stack slot references may be out of range of an immediate
1515 // offset, make sure a register (or a spill slot) is available for the
1516 // register scavenger. Note that if we're indexing off the frame pointer, the
1517 // effective stack size is 4 bytes larger since the FP points to the stack
1518 // slot of the previous FP. Also, if we have variable sized objects in the
1519 // function, stack slot references will often be negative, and some of
1520 // our instructions are positive-offset only, so conservatively consider
1521 // that case to want a spill slot (or register) as well. Similarly, if
1522 // the function adjusts the stack pointer during execution and the
1523 // adjustments aren't already part of our stack size estimate, our offset
1524 // calculations may be off, so be conservative.
1525 // FIXME: We could add logic to be more precise about negative offsets
1526 // and which instructions will need a scratch register for them. Is it
1527 // worth the effort and added fragility?
1530 (MFI->estimateStackSize(MF) +
1531 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1532 estimateRSStackSizeLimit(MF, this)))
1533 || MFI->hasVarSizedObjects()
1534 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1536 bool ExtraCSSpill = false;
1537 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1538 AFI->setHasStackFrame(true);
1540 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1541 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1542 if (!LRSpilled && CS1Spilled) {
1543 MRI.setPhysRegUsed(ARM::LR);
1545 SmallVectorImpl<unsigned>::iterator LRPos;
1546 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1548 if (LRPos != UnspilledCS1GPRs.end())
1549 UnspilledCS1GPRs.erase(LRPos);
1551 ForceLRSpill = false;
1552 ExtraCSSpill = true;
1556 MRI.setPhysRegUsed(FramePtr);
1557 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1559 if (FPPos != UnspilledCS1GPRs.end())
1560 UnspilledCS1GPRs.erase(FPPos);
1564 // If stack and double are 8-byte aligned and we are spilling an odd number
1565 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1566 // the integer and double callee save areas.
1567 unsigned TargetAlign = getStackAlignment();
1568 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1569 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1570 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1571 unsigned Reg = UnspilledCS1GPRs[i];
1572 // Don't spill high register if the function is thumb1
1573 if (!AFI->isThumb1OnlyFunction() ||
1574 isARMLowRegister(Reg) || Reg == ARM::LR) {
1575 MRI.setPhysRegUsed(Reg);
1576 if (!MRI.isReserved(Reg))
1577 ExtraCSSpill = true;
1581 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1582 unsigned Reg = UnspilledCS2GPRs.front();
1583 MRI.setPhysRegUsed(Reg);
1584 if (!MRI.isReserved(Reg))
1585 ExtraCSSpill = true;
1589 // Estimate if we might need to scavenge a register at some point in order
1590 // to materialize a stack offset. If so, either spill one additional
1591 // callee-saved register or reserve a special spill slot to facilitate
1592 // register scavenging. Thumb1 needs a spill slot for stack pointer
1593 // adjustments also, even when the frame itself is small.
1594 if (BigStack && !ExtraCSSpill) {
1595 // If any non-reserved CS register isn't spilled, just spill one or two
1596 // extra. That should take care of it!
1597 unsigned NumExtras = TargetAlign / 4;
1598 SmallVector<unsigned, 2> Extras;
1599 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1600 unsigned Reg = UnspilledCS1GPRs.back();
1601 UnspilledCS1GPRs.pop_back();
1602 if (!MRI.isReserved(Reg) &&
1603 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1605 Extras.push_back(Reg);
1609 // For non-Thumb1 functions, also check for hi-reg CS registers
1610 if (!AFI->isThumb1OnlyFunction()) {
1611 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1612 unsigned Reg = UnspilledCS2GPRs.back();
1613 UnspilledCS2GPRs.pop_back();
1614 if (!MRI.isReserved(Reg)) {
1615 Extras.push_back(Reg);
1620 if (Extras.size() && NumExtras == 0) {
1621 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1622 MRI.setPhysRegUsed(Extras[i]);
1624 } else if (!AFI->isThumb1OnlyFunction()) {
1625 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1626 // closest to SP or frame pointer.
1627 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1628 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1636 MRI.setPhysRegUsed(ARM::LR);
1637 AFI->setLRIsSpilledForFarJump(true);
1642 void ARMFrameLowering::
1643 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1644 MachineBasicBlock::iterator I) const {
1645 const ARMBaseInstrInfo &TII =
1646 *static_cast<const ARMBaseInstrInfo *>(
1647 MF.getTarget().getSubtargetImpl()->getInstrInfo());
1648 if (!hasReservedCallFrame(MF)) {
1649 // If we have alloca, convert as follows:
1650 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1651 // ADJCALLSTACKUP -> add, sp, sp, amount
1652 MachineInstr *Old = I;
1653 DebugLoc dl = Old->getDebugLoc();
1654 unsigned Amount = Old->getOperand(0).getImm();
1656 // We need to keep the stack aligned properly. To do this, we round the
1657 // amount of space needed for the outgoing arguments up to the next
1658 // alignment boundary.
1659 unsigned Align = getStackAlignment();
1660 Amount = (Amount+Align-1)/Align*Align;
1662 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1663 assert(!AFI->isThumb1OnlyFunction() &&
1664 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1665 bool isARM = !AFI->isThumbFunction();
1667 // Replace the pseudo instruction with a new instruction...
1668 unsigned Opc = Old->getOpcode();
1669 int PIdx = Old->findFirstPredOperandIdx();
1670 ARMCC::CondCodes Pred = (PIdx == -1)
1671 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1672 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1673 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1674 unsigned PredReg = Old->getOperand(2).getReg();
1675 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1678 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1679 unsigned PredReg = Old->getOperand(3).getReg();
1680 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1681 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1689 /// Get the minimum constant for ARM that is greater than or equal to the
1690 /// argument. In ARM, constants can have any value that can be produced by
1691 /// rotating an 8-bit value to the right by an even number of bits within a
1693 static uint32_t alignToARMConstant(uint32_t Value) {
1694 unsigned Shifted = 0;
1699 while (!(Value & 0xC0000000)) {
1704 bool Carry = (Value & 0x00FFFFFF);
1705 Value = ((Value & 0xFF000000) >> 24) + Carry;
1707 if (Value & 0x0000100)
1708 Value = Value & 0x000001FC;
1711 Value = Value >> (Shifted - 24);
1713 Value = Value << (24 - Shifted);
1718 // The stack limit in the TCB is set to this many bytes above the actual
1720 static const uint64_t kSplitStackAvailable = 256;
1722 // Adjust the function prologue to enable split stacks. This currently only
1723 // supports android and linux.
1725 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1726 // must be well defined in order to allow for consistent implementations of the
1727 // __morestack helper function. The ABI is also not a normal ABI in that it
1728 // doesn't follow the normal calling conventions because this allows the
1729 // prologue of each function to be optimized further.
1731 // Currently, the ABI looks like (when calling __morestack)
1733 // * r4 holds the minimum stack size requested for this function call
1734 // * r5 holds the stack size of the arguments to the function
1735 // * the beginning of the function is 3 instructions after the call to
1738 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1739 // place the arguments on to the new stack, and the 3-instruction knowledge to
1740 // jump directly to the body of the function when working on the new stack.
1742 // An old (and possibly no longer compatible) implementation of __morestack for
1743 // ARM can be found at [1].
1745 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1746 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1749 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1750 bool Thumb = ST->isThumb();
1752 // Sadly, this currently doesn't support varargs, platforms other than
1753 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1754 if (MF.getFunction()->isVarArg())
1755 report_fatal_error("Segmented stacks do not support vararg functions.");
1756 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1757 report_fatal_error("Segmented stacks not supported on this platform.");
1759 MachineBasicBlock &prologueMBB = MF.front();
1760 MachineFrameInfo *MFI = MF.getFrameInfo();
1761 MachineModuleInfo &MMI = MF.getMMI();
1762 MCContext &Context = MMI.getContext();
1763 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1764 const ARMBaseInstrInfo &TII =
1765 *static_cast<const ARMBaseInstrInfo *>(
1766 MF.getTarget().getSubtargetImpl()->getInstrInfo());
1767 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1770 uint64_t StackSize = MFI->getStackSize();
1772 // Do not generate a prologue for functions with a stack of size zero
1776 // Use R4 and R5 as scratch registers.
1777 // We save R4 and R5 before use and restore them before leaving the function.
1778 unsigned ScratchReg0 = ARM::R4;
1779 unsigned ScratchReg1 = ARM::R5;
1780 uint64_t AlignedStackSize;
1782 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1783 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1784 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1785 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1786 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1788 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1789 e = prologueMBB.livein_end();
1791 AllocMBB->addLiveIn(*i);
1792 GetMBB->addLiveIn(*i);
1793 McrMBB->addLiveIn(*i);
1794 PrevStackMBB->addLiveIn(*i);
1795 PostStackMBB->addLiveIn(*i);
1798 MF.push_front(PostStackMBB);
1799 MF.push_front(AllocMBB);
1800 MF.push_front(GetMBB);
1801 MF.push_front(McrMBB);
1802 MF.push_front(PrevStackMBB);
1804 // The required stack size that is aligned to ARM constant criterion.
1805 AlignedStackSize = alignToARMConstant(StackSize);
1807 // When the frame size is less than 256 we just compare the stack
1808 // boundary directly to the value of the stack pointer, per gcc.
1809 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1811 // We will use two of the callee save registers as scratch registers so we
1812 // need to save those registers onto the stack.
1813 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1814 // requested and arguments for __morestack().
1815 // SR0: Scratch Register #0
1816 // SR1: Scratch Register #1
1819 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1820 .addReg(ScratchReg0).addReg(ScratchReg1);
1822 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1823 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1824 .addReg(ScratchReg0).addReg(ScratchReg1);
1827 // Emit the relevant DWARF information about the change in stack pointer as
1828 // well as where to find both r4 and r5 (the callee-save registers)
1830 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1831 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1832 .addCFIIndex(CFIIndex);
1833 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1834 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1835 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1836 .addCFIIndex(CFIIndex);
1837 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1838 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1839 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1840 .addCFIIndex(CFIIndex);
1844 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1846 } else if (CompareStackPointer) {
1847 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1848 .addReg(ARM::SP)).addReg(0);
1851 // sub SR1, sp, #StackSize
1852 if (!CompareStackPointer && Thumb) {
1854 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1855 .addReg(ScratchReg1).addImm(AlignedStackSize));
1856 } else if (!CompareStackPointer) {
1857 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1858 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1861 if (Thumb && ST->isThumb1Only()) {
1862 unsigned PCLabelId = ARMFI->createPICLabelUId();
1863 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1864 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1865 MachineConstantPool *MCP = MF.getConstantPool();
1866 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1868 // ldr SR0, [pc, offset(STACK_LIMIT)]
1869 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1870 .addConstantPoolIndex(CPI));
1873 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1874 .addReg(ScratchReg0).addImm(0));
1876 // Get TLS base address from the coprocessor
1877 // mrc p15, #0, SR0, c13, c0, #3
1878 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1885 // Use the last tls slot on android and a private field of the TCP on linux.
1886 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1887 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1889 // Get the stack limit from the right offset
1890 // ldr SR0, [sr0, #4 * TlsOffset]
1891 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1892 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1895 // Compare stack limit with stack size requested.
1897 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1898 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1899 .addReg(ScratchReg0)
1900 .addReg(ScratchReg1));
1902 // This jump is taken if StackLimit < SP - stack required.
1903 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1904 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1909 // Calling __morestack(StackSize, Size of stack arguments).
1910 // __morestack knows that the stack size requested is in SR0(r4)
1911 // and amount size of stack arguments is in SR1(r5).
1913 // Pass first argument for the __morestack by Scratch Register #0.
1914 // The amount size of stack required
1916 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1917 ScratchReg0)).addImm(AlignedStackSize));
1919 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1920 .addImm(AlignedStackSize)).addReg(0);
1922 // Pass second argument for the __morestack by Scratch Register #1.
1923 // The amount size of stack consumed to save function arguments.
1926 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1927 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1929 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1930 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1934 // push {lr} - Save return address of this function.
1936 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1939 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1940 .addReg(ARM::SP, RegState::Define)
1945 // Emit the DWARF info about the change in stack as well as where to find the
1946 // previous link register
1948 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1949 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1950 .addCFIIndex(CFIIndex);
1951 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1952 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1953 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1954 .addCFIIndex(CFIIndex);
1956 // Call __morestack().
1958 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1959 .addExternalSymbol("__morestack");
1961 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1962 .addExternalSymbol("__morestack");
1965 // pop {lr} - Restore return address of this original function.
1967 if (ST->isThumb1Only()) {
1968 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1969 .addReg(ScratchReg0);
1970 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1971 .addReg(ScratchReg0));
1973 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1974 .addReg(ARM::LR, RegState::Define)
1975 .addReg(ARM::SP, RegState::Define)
1980 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1981 .addReg(ARM::SP, RegState::Define)
1986 // Restore SR0 and SR1 in case of __morestack() was called.
1987 // __morestack() will skip PostStackMBB block so we need to restore
1988 // scratch registers from here.
1991 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1992 .addReg(ScratchReg0)
1993 .addReg(ScratchReg1);
1995 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1996 .addReg(ARM::SP, RegState::Define)
1998 .addReg(ScratchReg0)
1999 .addReg(ScratchReg1);
2002 // Update the CFA offset now that we've popped
2003 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2004 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2005 .addCFIIndex(CFIIndex);
2007 // bx lr - Return from this function.
2008 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2009 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2011 // Restore SR0 and SR1 in case of __morestack() was not called.
2014 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2015 .addReg(ScratchReg0)
2016 .addReg(ScratchReg1);
2018 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2019 .addReg(ARM::SP, RegState::Define)
2021 .addReg(ScratchReg0)
2022 .addReg(ScratchReg1);
2025 // Update the CFA offset now that we've popped
2026 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2027 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2028 .addCFIIndex(CFIIndex);
2030 // Tell debuggers that r4 and r5 are now the same as they were in the
2031 // previous function, that they're the "Same Value".
2032 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2033 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2034 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2035 .addCFIIndex(CFIIndex);
2036 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2037 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2038 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2039 .addCFIIndex(CFIIndex);
2041 // Organizing MBB lists
2042 PostStackMBB->addSuccessor(&prologueMBB);
2044 AllocMBB->addSuccessor(PostStackMBB);
2046 GetMBB->addSuccessor(PostStackMBB);
2047 GetMBB->addSuccessor(AllocMBB);
2049 McrMBB->addSuccessor(GetMBB);
2051 PrevStackMBB->addSuccessor(McrMBB);