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) {
140 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
142 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
143 // pred) so the list starts at 4.
144 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
149 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
150 size_t StackSizeInBytes) {
151 const MachineFrameInfo *MFI = MF.getFrameInfo();
152 if (MFI->getStackProtectorIndex() > 0)
153 return StackSizeInBytes >= 4080;
154 return StackSizeInBytes >= 4096;
157 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
158 MachineBasicBlock &MBB = MF.front();
159 MachineBasicBlock::iterator MBBI = MBB.begin();
160 MachineFrameInfo *MFI = MF.getFrameInfo();
161 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
162 MachineModuleInfo &MMI = MF.getMMI();
163 MCContext &Context = MMI.getContext();
164 const TargetMachine &TM = MF.getTarget();
165 const MCRegisterInfo *MRI = Context.getRegisterInfo();
166 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
167 TM.getSubtargetImpl()->getRegisterInfo());
168 const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
169 TM.getSubtargetImpl()->getInstrInfo());
170 assert(!AFI->isThumb1OnlyFunction() &&
171 "This emitPrologue does not support Thumb1!");
172 bool isARM = !AFI->isThumbFunction();
174 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
175 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
176 unsigned NumBytes = MFI->getStackSize();
177 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
178 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
179 unsigned FramePtr = RegInfo->getFrameRegister(MF);
182 // Determine the sizes of each callee-save spill areas and record which frame
183 // belongs to which callee-save spill areas.
184 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
185 int FramePtrSpillFI = 0;
188 // All calls are tail calls in GHC calling conv, and functions have no
189 // prologue/epilogue.
190 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
193 // Allocate the vararg register save area.
194 if (ArgRegsSaveSize) {
195 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
196 MachineInstr::FrameSetup);
197 CFAOffset -= ArgRegsSaveSize;
198 unsigned CFIIndex = MMI.addFrameInst(
199 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
200 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
201 .addCFIIndex(CFIIndex);
204 if (!AFI->hasStackFrame() &&
205 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
206 if (NumBytes - ArgRegsSaveSize != 0) {
207 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
208 MachineInstr::FrameSetup);
209 CFAOffset -= NumBytes - ArgRegsSaveSize;
210 unsigned CFIIndex = MMI.addFrameInst(
211 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
212 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
213 .addCFIIndex(CFIIndex);
218 // Determine spill area sizes.
219 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
220 unsigned Reg = CSI[i].getReg();
221 int FI = CSI[i].getFrameIdx();
228 if (STI.isTargetDarwin()) {
243 FramePtrSpillFI = FI;
247 // This is a DPR. Exclude the aligned DPRCS2 spills.
250 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
256 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
259 GPRCS1Push = LastPush = MBBI++;
261 // Determine starting offsets of spill areas.
262 bool HasFP = hasFP(MF);
263 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
264 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
265 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
266 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
267 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
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++;
283 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
284 // .cfi_offset operations will reflect that.
285 unsigned adjustedGPRCS1Size = GPRCS1Size;
287 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
288 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize)) {
289 if (LastPush == GPRCS1Push) {
290 FramePtrOffsetInPush += DPRGapSize;
291 adjustedGPRCS1Size += DPRGapSize;
294 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
295 MachineInstr::FrameSetup);
301 // Since vpush register list cannot have gaps, there may be multiple vpush
302 // instructions in the prologue.
303 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
307 // Move past the aligned DPRCS2 area.
308 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
309 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
310 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
311 // leaves the stack pointer pointing to the DPRCS2 area.
313 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
314 NumBytes += MFI->getObjectOffset(D8SpillFI);
316 NumBytes = DPRCSOffset;
318 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
319 uint32_t NumWords = NumBytes >> 2;
321 if (NumWords < 65536)
322 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
324 .setMIFlags(MachineInstr::FrameSetup));
326 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
328 .setMIFlags(MachineInstr::FrameSetup);
330 switch (TM.getCodeModel()) {
331 case CodeModel::Small:
332 case CodeModel::Medium:
333 case CodeModel::Default:
334 case CodeModel::Kernel:
335 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
336 .addImm((unsigned)ARMCC::AL).addReg(0)
337 .addExternalSymbol("__chkstk")
338 .addReg(ARM::R4, RegState::Implicit)
339 .setMIFlags(MachineInstr::FrameSetup);
341 case CodeModel::Large:
342 case CodeModel::JITDefault:
343 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
344 .addExternalSymbol("__chkstk")
345 .setMIFlags(MachineInstr::FrameSetup);
347 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
348 .addImm((unsigned)ARMCC::AL).addReg(0)
349 .addReg(ARM::R12, RegState::Kill)
350 .addReg(ARM::R4, RegState::Implicit)
351 .setMIFlags(MachineInstr::FrameSetup);
355 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
357 .addReg(ARM::SP, RegState::Define)
358 .addReg(ARM::R4, RegState::Kill)
359 .setMIFlags(MachineInstr::FrameSetup)));
364 // Adjust SP after all the callee-save spills.
365 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
366 if (LastPush == GPRCS1Push) {
367 FramePtrOffsetInPush += NumBytes;
368 adjustedGPRCS1Size += NumBytes;
372 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
373 MachineInstr::FrameSetup);
376 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
377 // Note it's not safe to do this in Thumb2 mode because it would have
378 // taken two instructions:
381 // If an interrupt is taken between the two instructions, then sp is in
382 // an inconsistent state (pointing to the middle of callee-saved area).
383 // The interrupt handler can end up clobbering the registers.
384 AFI->setShouldRestoreSPFromFP(true);
387 if (adjustedGPRCS1Size > 0) {
388 CFAOffset -= adjustedGPRCS1Size;
389 unsigned CFIIndex = MMI.addFrameInst(
390 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
391 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
392 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
393 .addCFIIndex(CFIIndex);
394 for (const auto &Entry : CSI) {
395 unsigned Reg = Entry.getReg();
396 int FI = Entry.getFrameIdx();
403 if (STI.isTargetDarwin())
415 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
416 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
417 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
418 .addCFIIndex(CFIIndex);
424 // Set FP to point to the stack slot that contains the previous FP.
425 // For iOS, FP is R7, which has now been stored in spill area 1.
426 // Otherwise, if this is not iOS, all the callee-saved registers go
427 // into spill area 1, including the FP in R11. In either case, it
428 // is in area one and the adjustment needs to take place just after
431 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
432 FramePtr, ARM::SP, FramePtrOffsetInPush,
433 MachineInstr::FrameSetup);
434 if (FramePtrOffsetInPush) {
435 CFAOffset += FramePtrOffsetInPush;
436 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
437 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
438 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
439 .addCFIIndex(CFIIndex);
443 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
444 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
445 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
446 .addCFIIndex(CFIIndex);
450 if (GPRCS2Size > 0) {
451 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
453 CFAOffset -= GPRCS2Size;
454 unsigned CFIIndex = MMI.addFrameInst(
455 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
456 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
457 .addCFIIndex(CFIIndex);
459 for (const auto &Entry : CSI) {
460 unsigned Reg = Entry.getReg();
461 int FI = Entry.getFrameIdx();
468 if (STI.isTargetDarwin()) {
469 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
470 unsigned Offset = MFI->getObjectOffset(FI);
471 unsigned CFIIndex = MMI.addFrameInst(
472 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
473 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
474 .addCFIIndex(CFIIndex);
482 // Since vpush register list cannot have gaps, there may be multiple vpush
483 // instructions in the prologue.
485 MachineBasicBlock::iterator Push = DPRCSPush++;
487 CFAOffset -= sizeOfSPAdjustment(Push);
488 unsigned CFIIndex = MMI.addFrameInst(
489 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
490 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
491 .addCFIIndex(CFIIndex);
493 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
495 for (const auto &Entry : CSI) {
496 unsigned Reg = Entry.getReg();
497 int FI = Entry.getFrameIdx();
498 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
499 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
500 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
501 unsigned Offset = MFI->getObjectOffset(FI);
502 unsigned CFIIndex = MMI.addFrameInst(
503 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
504 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
505 .addCFIIndex(CFIIndex);
512 CFAOffset -= NumBytes;
513 unsigned CFIIndex = MMI.addFrameInst(
514 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
515 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
516 .addCFIIndex(CFIIndex);
520 if (STI.isTargetELF() && hasFP(MF))
521 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
522 AFI->getFramePtrSpillOffset());
524 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
525 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
526 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
527 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
529 // If we need dynamic stack realignment, do it here. Be paranoid and make
530 // sure if we also have VLAs, we have a base pointer for frame access.
531 // If aligned NEON registers were spilled, the stack has already been
533 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
534 unsigned MaxAlign = MFI->getMaxAlignment();
535 assert (!AFI->isThumb1OnlyFunction());
536 if (!AFI->isThumbFunction()) {
537 // Emit bic sp, sp, MaxAlign
538 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
539 TII.get(ARM::BICri), ARM::SP)
540 .addReg(ARM::SP, RegState::Kill)
541 .addImm(MaxAlign-1)));
543 // We cannot use sp as source/dest register here, thus we're emitting the
544 // following sequence:
546 // bic r4, r4, MaxAlign
548 // FIXME: It will be better just to find spare register here.
549 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
550 .addReg(ARM::SP, RegState::Kill));
551 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
552 TII.get(ARM::t2BICri), ARM::R4)
553 .addReg(ARM::R4, RegState::Kill)
554 .addImm(MaxAlign-1)));
555 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
556 .addReg(ARM::R4, RegState::Kill));
559 AFI->setShouldRestoreSPFromFP(true);
562 // If we need a base pointer, set it up here. It's whatever the value
563 // of the stack pointer is at this point. Any variable size objects
564 // will be allocated after this, so we can still use the base pointer
565 // to reference locals.
566 // FIXME: Clarify FrameSetup flags here.
567 if (RegInfo->hasBasePointer(MF)) {
569 BuildMI(MBB, MBBI, dl,
570 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
572 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
574 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
575 RegInfo->getBaseRegister())
579 // If the frame has variable sized objects then the epilogue must restore
580 // the sp from fp. We can assume there's an FP here since hasFP already
581 // checks for hasVarSizedObjects.
582 if (MFI->hasVarSizedObjects())
583 AFI->setShouldRestoreSPFromFP(true);
586 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
587 MachineBasicBlock &MBB) const {
588 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
589 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
590 unsigned RetOpcode = MBBI->getOpcode();
591 DebugLoc dl = MBBI->getDebugLoc();
592 MachineFrameInfo *MFI = MF.getFrameInfo();
593 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
594 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
595 const ARMBaseInstrInfo &TII =
596 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
597 assert(!AFI->isThumb1OnlyFunction() &&
598 "This emitEpilogue does not support Thumb1!");
599 bool isARM = !AFI->isThumbFunction();
601 unsigned Align = MF.getTarget()
604 ->getStackAlignment();
605 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
606 int NumBytes = (int)MFI->getStackSize();
607 unsigned FramePtr = RegInfo->getFrameRegister(MF);
609 // All calls are tail calls in GHC calling conv, and functions have no
610 // prologue/epilogue.
611 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
614 if (!AFI->hasStackFrame()) {
615 if (NumBytes - ArgRegsSaveSize != 0)
616 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
618 // Unwind MBBI to point to first LDR / VLDRD.
619 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
620 if (MBBI != MBB.begin()) {
623 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
624 if (!isCSRestore(MBBI, TII, CSRegs))
628 // Move SP to start of FP callee save spill area.
629 NumBytes -= (ArgRegsSaveSize +
630 AFI->getGPRCalleeSavedArea1Size() +
631 AFI->getGPRCalleeSavedArea2Size() +
632 AFI->getDPRCalleeSavedGapSize() +
633 AFI->getDPRCalleeSavedAreaSize());
635 // Reset SP based on frame pointer only if the stack frame extends beyond
636 // frame pointer stack slot or target is ELF and the function has FP.
637 if (AFI->shouldRestoreSPFromFP()) {
638 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
641 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
644 // It's not possible to restore SP from FP in a single instruction.
645 // For iOS, this looks like:
648 // This is bad, if an interrupt is taken after the mov, sp is in an
649 // inconsistent state.
650 // Use the first callee-saved register as a scratch register.
651 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
652 "No scratch register to restore SP from FP!");
653 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
655 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
662 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
663 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
665 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
669 } else if (NumBytes &&
670 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
671 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
673 // Increment past our save areas.
674 if (AFI->getDPRCalleeSavedAreaSize()) {
676 // Since vpop register list cannot have gaps, there may be multiple vpop
677 // instructions in the epilogue.
678 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
681 if (AFI->getDPRCalleeSavedGapSize()) {
682 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
683 "unexpected DPR alignment gap");
684 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
687 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
688 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
691 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
692 // Tail call return: adjust the stack pointer and jump to callee.
693 MBBI = MBB.getLastNonDebugInstr();
694 MachineOperand &JumpTarget = MBBI->getOperand(0);
696 // Jump to label or value in register.
697 if (RetOpcode == ARM::TCRETURNdi) {
698 unsigned TCOpcode = STI.isThumb() ?
699 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
701 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
702 if (JumpTarget.isGlobal())
703 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
704 JumpTarget.getTargetFlags());
706 assert(JumpTarget.isSymbol());
707 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
708 JumpTarget.getTargetFlags());
711 // Add the default predicate in Thumb mode.
712 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
713 } else if (RetOpcode == ARM::TCRETURNri) {
714 BuildMI(MBB, MBBI, dl,
715 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
716 addReg(JumpTarget.getReg(), RegState::Kill);
719 MachineInstr *NewMI = std::prev(MBBI);
720 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
721 NewMI->addOperand(MBBI->getOperand(i));
723 // Delete the pseudo instruction TCRETURN.
729 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
732 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
733 /// debug info. It's the same as what we use for resolving the code-gen
734 /// references for now. FIXME: This can go wrong when references are
735 /// SP-relative and simple call frames aren't used.
737 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
738 unsigned &FrameReg) const {
739 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
743 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
744 int FI, unsigned &FrameReg,
746 const MachineFrameInfo *MFI = MF.getFrameInfo();
747 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
748 MF.getSubtarget().getRegisterInfo());
749 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
750 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
751 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
752 bool isFixed = MFI->isFixedObjectIndex(FI);
757 // SP can move around if there are allocas. We may also lose track of SP
758 // when emergency spilling inside a non-reserved call frame setup.
759 bool hasMovingSP = !hasReservedCallFrame(MF);
761 // When dynamically realigning the stack, use the frame pointer for
762 // parameters, and the stack/base pointer for locals.
763 if (RegInfo->needsStackRealignment(MF)) {
764 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
766 FrameReg = RegInfo->getFrameRegister(MF);
768 } else if (hasMovingSP) {
769 assert(RegInfo->hasBasePointer(MF) &&
770 "VLAs and dynamic stack alignment, but missing base pointer!");
771 FrameReg = RegInfo->getBaseRegister();
776 // If there is a frame pointer, use it when we can.
777 if (hasFP(MF) && AFI->hasStackFrame()) {
778 // Use frame pointer to reference fixed objects. Use it for locals if
779 // there are VLAs (and thus the SP isn't reliable as a base).
780 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
781 FrameReg = RegInfo->getFrameRegister(MF);
783 } else if (hasMovingSP) {
784 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
785 if (AFI->isThumb2Function()) {
786 // Try to use the frame pointer if we can, else use the base pointer
787 // since it's available. This is handy for the emergency spill slot, in
789 if (FPOffset >= -255 && FPOffset < 0) {
790 FrameReg = RegInfo->getFrameRegister(MF);
794 } else if (AFI->isThumb2Function()) {
795 // Use add <rd>, sp, #<imm8>
796 // ldr <rd>, [sp, #<imm8>]
797 // if at all possible to save space.
798 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
800 // In Thumb2 mode, the negative offset is very limited. Try to avoid
801 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
802 if (FPOffset >= -255 && FPOffset < 0) {
803 FrameReg = RegInfo->getFrameRegister(MF);
806 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
807 // Otherwise, use SP or FP, whichever is closer to the stack slot.
808 FrameReg = RegInfo->getFrameRegister(MF);
812 // Use the base pointer if we have one.
813 if (RegInfo->hasBasePointer(MF))
814 FrameReg = RegInfo->getBaseRegister();
818 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
821 return getFrameIndexReference(MF, FI, FrameReg);
824 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
825 MachineBasicBlock::iterator MI,
826 const std::vector<CalleeSavedInfo> &CSI,
827 unsigned StmOpc, unsigned StrOpc,
829 bool(*Func)(unsigned, bool),
830 unsigned NumAlignedDPRCS2Regs,
831 unsigned MIFlags) const {
832 MachineFunction &MF = *MBB.getParent();
833 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
836 if (MI != MBB.end()) DL = MI->getDebugLoc();
838 SmallVector<std::pair<unsigned,bool>, 4> Regs;
839 unsigned i = CSI.size();
841 unsigned LastReg = 0;
842 for (; i != 0; --i) {
843 unsigned Reg = CSI[i-1].getReg();
844 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
846 // D-registers in the aligned area DPRCS2 are NOT spilled here.
847 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
850 // Add the callee-saved register as live-in unless it's LR and
851 // @llvm.returnaddress is called. If LR is returned for
852 // @llvm.returnaddress then it's already added to the function and
853 // entry block live-in sets.
855 if (Reg == ARM::LR) {
856 if (MF.getFrameInfo()->isReturnAddressTaken() &&
857 MF.getRegInfo().isLiveIn(Reg))
864 // If NoGap is true, push consecutive registers and then leave the rest
865 // for other instructions. e.g.
866 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
867 if (NoGap && LastReg && LastReg != Reg-1)
870 Regs.push_back(std::make_pair(Reg, isKill));
875 if (Regs.size() > 1 || StrOpc== 0) {
876 MachineInstrBuilder MIB =
877 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
878 .addReg(ARM::SP).setMIFlags(MIFlags));
879 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
880 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
881 } else if (Regs.size() == 1) {
882 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
884 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
885 .addReg(ARM::SP).setMIFlags(MIFlags)
891 // Put any subsequent vpush instructions before this one: they will refer to
892 // higher register numbers so need to be pushed first in order to preserve
898 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
899 MachineBasicBlock::iterator MI,
900 const std::vector<CalleeSavedInfo> &CSI,
901 unsigned LdmOpc, unsigned LdrOpc,
902 bool isVarArg, bool NoGap,
903 bool(*Func)(unsigned, bool),
904 unsigned NumAlignedDPRCS2Regs) const {
905 MachineFunction &MF = *MBB.getParent();
906 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
907 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
908 DebugLoc DL = MI->getDebugLoc();
909 unsigned RetOpcode = MI->getOpcode();
910 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
911 RetOpcode == ARM::TCRETURNri);
913 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
915 SmallVector<unsigned, 4> Regs;
916 unsigned i = CSI.size();
918 unsigned LastReg = 0;
919 bool DeleteRet = false;
920 for (; i != 0; --i) {
921 unsigned Reg = CSI[i-1].getReg();
922 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
924 // The aligned reloads from area DPRCS2 are not inserted here.
925 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
928 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
931 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
932 // Fold the return instruction into the LDM.
936 // If NoGap is true, pop consecutive registers and then leave the rest
937 // for other instructions. e.g.
938 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
939 if (NoGap && LastReg && LastReg != Reg-1)
948 if (Regs.size() > 1 || LdrOpc == 0) {
949 MachineInstrBuilder MIB =
950 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
952 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
953 MIB.addReg(Regs[i], getDefRegState(true));
955 MIB.copyImplicitOps(&*MI);
956 MI->eraseFromParent();
959 } else if (Regs.size() == 1) {
960 // If we adjusted the reg to PC from LR above, switch it back here. We
961 // only do that for LDM.
962 if (Regs[0] == ARM::PC)
964 MachineInstrBuilder MIB =
965 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
966 .addReg(ARM::SP, RegState::Define)
968 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
969 // that refactoring is complete (eventually).
970 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
972 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
979 // Put any subsequent vpop instructions after this one: they will refer to
980 // higher register numbers so need to be popped afterwards.
985 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
986 /// starting from d8. Also insert stack realignment code and leave the stack
987 /// pointer pointing to the d8 spill slot.
988 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
989 MachineBasicBlock::iterator MI,
990 unsigned NumAlignedDPRCS2Regs,
991 const std::vector<CalleeSavedInfo> &CSI,
992 const TargetRegisterInfo *TRI) {
993 MachineFunction &MF = *MBB.getParent();
994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
995 DebugLoc DL = MI->getDebugLoc();
996 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
997 MachineFrameInfo &MFI = *MF.getFrameInfo();
999 // Mark the D-register spill slots as properly aligned. Since MFI computes
1000 // stack slot layout backwards, this can actually mean that the d-reg stack
1001 // slot offsets can be wrong. The offset for d8 will always be correct.
1002 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1003 unsigned DNum = CSI[i].getReg() - ARM::D8;
1006 int FI = CSI[i].getFrameIdx();
1007 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1008 // registers will be 8-byte aligned.
1009 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1011 // The stack slot for D8 needs to be maximally aligned because this is
1012 // actually the point where we align the stack pointer. MachineFrameInfo
1013 // computes all offsets relative to the incoming stack pointer which is a
1014 // bit weird when realigning the stack. Any extra padding for this
1015 // over-alignment is not realized because the code inserted below adjusts
1016 // the stack pointer by numregs * 8 before aligning the stack pointer.
1018 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1021 // Move the stack pointer to the d8 spill slot, and align it at the same
1022 // time. Leave the stack slot address in the scratch register r4.
1024 // sub r4, sp, #numregs * 8
1025 // bic r4, r4, #align - 1
1028 bool isThumb = AFI->isThumbFunction();
1029 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1030 AFI->setShouldRestoreSPFromFP(true);
1032 // sub r4, sp, #numregs * 8
1033 // The immediate is <= 64, so it doesn't need any special encoding.
1034 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1035 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1037 .addImm(8 * NumAlignedDPRCS2Regs)));
1039 // bic r4, r4, #align-1
1040 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1041 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1042 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1043 .addReg(ARM::R4, RegState::Kill)
1044 .addImm(MaxAlign - 1)));
1047 // The stack pointer must be adjusted before spilling anything, otherwise
1048 // the stack slots could be clobbered by an interrupt handler.
1049 // Leave r4 live, it is used below.
1050 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1051 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1053 MIB = AddDefaultPred(MIB);
1057 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1058 // r4 holds the stack slot address.
1059 unsigned NextReg = ARM::D8;
1061 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1062 // The writeback is only needed when emitting two vst1.64 instructions.
1063 if (NumAlignedDPRCS2Regs >= 6) {
1064 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1065 &ARM::QQPRRegClass);
1066 MBB.addLiveIn(SupReg);
1067 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1069 .addReg(ARM::R4, RegState::Kill).addImm(16)
1071 .addReg(SupReg, RegState::ImplicitKill));
1073 NumAlignedDPRCS2Regs -= 4;
1076 // We won't modify r4 beyond this point. It currently points to the next
1077 // register to be spilled.
1078 unsigned R4BaseReg = NextReg;
1080 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1081 if (NumAlignedDPRCS2Regs >= 4) {
1082 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1083 &ARM::QQPRRegClass);
1084 MBB.addLiveIn(SupReg);
1085 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1086 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1087 .addReg(SupReg, RegState::ImplicitKill));
1089 NumAlignedDPRCS2Regs -= 4;
1092 // 16-byte aligned vst1.64 with 2 d-regs.
1093 if (NumAlignedDPRCS2Regs >= 2) {
1094 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1096 MBB.addLiveIn(SupReg);
1097 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1098 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1100 NumAlignedDPRCS2Regs -= 2;
1103 // Finally, use a vanilla vstr.64 for the odd last register.
1104 if (NumAlignedDPRCS2Regs) {
1105 MBB.addLiveIn(NextReg);
1106 // vstr.64 uses addrmode5 which has an offset scale of 4.
1107 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1109 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1112 // The last spill instruction inserted should kill the scratch register r4.
1113 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1116 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1117 /// iterator to the following instruction.
1118 static MachineBasicBlock::iterator
1119 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1120 unsigned NumAlignedDPRCS2Regs) {
1121 // sub r4, sp, #numregs * 8
1122 // bic r4, r4, #align - 1
1125 assert(MI->mayStore() && "Expecting spill instruction");
1127 // These switches all fall through.
1128 switch(NumAlignedDPRCS2Regs) {
1131 assert(MI->mayStore() && "Expecting spill instruction");
1134 assert(MI->mayStore() && "Expecting spill instruction");
1138 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1144 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1145 /// starting from d8. These instructions are assumed to execute while the
1146 /// stack is still aligned, unlike the code inserted by emitPopInst.
1147 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1148 MachineBasicBlock::iterator MI,
1149 unsigned NumAlignedDPRCS2Regs,
1150 const std::vector<CalleeSavedInfo> &CSI,
1151 const TargetRegisterInfo *TRI) {
1152 MachineFunction &MF = *MBB.getParent();
1153 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1154 DebugLoc DL = MI->getDebugLoc();
1155 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1157 // Find the frame index assigned to d8.
1159 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1160 if (CSI[i].getReg() == ARM::D8) {
1161 D8SpillFI = CSI[i].getFrameIdx();
1165 // Materialize the address of the d8 spill slot into the scratch register r4.
1166 // This can be fairly complicated if the stack frame is large, so just use
1167 // the normal frame index elimination mechanism to do it. This code runs as
1168 // the initial part of the epilog where the stack and base pointers haven't
1169 // been changed yet.
1170 bool isThumb = AFI->isThumbFunction();
1171 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1173 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1174 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1175 .addFrameIndex(D8SpillFI).addImm(0)));
1177 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1178 unsigned NextReg = ARM::D8;
1180 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1181 if (NumAlignedDPRCS2Regs >= 6) {
1182 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1183 &ARM::QQPRRegClass);
1184 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1185 .addReg(ARM::R4, RegState::Define)
1186 .addReg(ARM::R4, RegState::Kill).addImm(16)
1187 .addReg(SupReg, RegState::ImplicitDefine));
1189 NumAlignedDPRCS2Regs -= 4;
1192 // We won't modify r4 beyond this point. It currently points to the next
1193 // register to be spilled.
1194 unsigned R4BaseReg = NextReg;
1196 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1197 if (NumAlignedDPRCS2Regs >= 4) {
1198 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1199 &ARM::QQPRRegClass);
1200 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1201 .addReg(ARM::R4).addImm(16)
1202 .addReg(SupReg, RegState::ImplicitDefine));
1204 NumAlignedDPRCS2Regs -= 4;
1207 // 16-byte aligned vld1.64 with 2 d-regs.
1208 if (NumAlignedDPRCS2Regs >= 2) {
1209 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1211 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1212 .addReg(ARM::R4).addImm(16));
1214 NumAlignedDPRCS2Regs -= 2;
1217 // Finally, use a vanilla vldr.64 for the remaining odd register.
1218 if (NumAlignedDPRCS2Regs)
1219 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1220 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1222 // Last store kills r4.
1223 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1226 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1227 MachineBasicBlock::iterator MI,
1228 const std::vector<CalleeSavedInfo> &CSI,
1229 const TargetRegisterInfo *TRI) const {
1233 MachineFunction &MF = *MBB.getParent();
1234 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1236 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1237 unsigned PushOneOpc = AFI->isThumbFunction() ?
1238 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1239 unsigned FltOpc = ARM::VSTMDDB_UPD;
1240 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1241 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1242 MachineInstr::FrameSetup);
1243 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1244 MachineInstr::FrameSetup);
1245 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1246 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1248 // The code above does not insert spill code for the aligned DPRCS2 registers.
1249 // The stack realignment code will be inserted between the push instructions
1250 // and these spills.
1251 if (NumAlignedDPRCS2Regs)
1252 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1257 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1258 MachineBasicBlock::iterator MI,
1259 const std::vector<CalleeSavedInfo> &CSI,
1260 const TargetRegisterInfo *TRI) const {
1264 MachineFunction &MF = *MBB.getParent();
1265 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1266 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1267 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1269 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1270 // registers. Do that here instead.
1271 if (NumAlignedDPRCS2Regs)
1272 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1274 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1275 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1276 unsigned FltOpc = ARM::VLDMDIA_UPD;
1277 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1278 NumAlignedDPRCS2Regs);
1279 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1280 &isARMArea2Register, 0);
1281 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1282 &isARMArea1Register, 0);
1287 // FIXME: Make generic?
1288 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1289 const ARMBaseInstrInfo &TII) {
1290 unsigned FnSize = 0;
1291 for (auto &MBB : MF) {
1292 for (auto &MI : MBB)
1293 FnSize += TII.GetInstSizeInBytes(&MI);
1298 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1299 /// frames and return the stack size limit beyond which some of these
1300 /// instructions will require a scratch register during their expansion later.
1301 // FIXME: Move to TII?
1302 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1303 const TargetFrameLowering *TFI) {
1304 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1305 unsigned Limit = (1 << 12) - 1;
1306 for (auto &MBB : MF) {
1307 for (auto &MI : MBB) {
1308 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1309 if (!MI.getOperand(i).isFI())
1312 // When using ADDri to get the address of a stack object, 255 is the
1313 // largest offset guaranteed to fit in the immediate offset.
1314 if (MI.getOpcode() == ARM::ADDri) {
1315 Limit = std::min(Limit, (1U << 8) - 1);
1319 // Otherwise check the addressing mode.
1320 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1321 case ARMII::AddrMode3:
1322 case ARMII::AddrModeT2_i8:
1323 Limit = std::min(Limit, (1U << 8) - 1);
1325 case ARMII::AddrMode5:
1326 case ARMII::AddrModeT2_i8s4:
1327 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1329 case ARMII::AddrModeT2_i12:
1330 // i12 supports only positive offset so these will be converted to
1331 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1332 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1333 Limit = std::min(Limit, (1U << 8) - 1);
1335 case ARMII::AddrMode4:
1336 case ARMII::AddrMode6:
1337 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1338 // immediate offset for stack references.
1343 break; // At most one FI per instruction
1351 // In functions that realign the stack, it can be an advantage to spill the
1352 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1353 // instructions take alignment hints that can improve performance.
1355 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1356 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1357 if (!SpillAlignedNEONRegs)
1360 // Naked functions don't spill callee-saved registers.
1361 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1365 // We are planning to use NEON instructions vst1 / vld1.
1366 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1369 // Don't bother if the default stack alignment is sufficiently high.
1372 ->getFrameLowering()
1373 ->getStackAlignment() >= 8)
1376 // Aligned spills require stack realignment.
1377 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1378 MF.getSubtarget().getRegisterInfo());
1379 if (!RegInfo->canRealignStack(MF))
1382 // We always spill contiguous d-registers starting from d8. Count how many
1383 // needs spilling. The register allocator will almost always use the
1384 // callee-saved registers in order, but it can happen that there are holes in
1385 // the range. Registers above the hole will be spilled to the standard DPRCS
1387 MachineRegisterInfo &MRI = MF.getRegInfo();
1388 unsigned NumSpills = 0;
1389 for (; NumSpills < 8; ++NumSpills)
1390 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1393 // Don't do this for just one d-register. It's not worth it.
1397 // Spill the first NumSpills D-registers after realigning the stack.
1398 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1400 // A scratch register is required for the vst1 / vld1 instructions.
1401 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1405 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1406 RegScavenger *RS) const {
1407 // This tells PEI to spill the FP as if it is any other callee-save register
1408 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1409 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1410 // to combine multiple loads / stores.
1411 bool CanEliminateFrame = true;
1412 bool CS1Spilled = false;
1413 bool LRSpilled = false;
1414 unsigned NumGPRSpills = 0;
1415 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1416 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1417 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1418 MF.getSubtarget().getRegisterInfo());
1419 const ARMBaseInstrInfo &TII =
1420 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1421 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1422 MachineFrameInfo *MFI = MF.getFrameInfo();
1423 MachineRegisterInfo &MRI = MF.getRegInfo();
1424 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1426 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1427 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1428 // since it's not always possible to restore sp from fp in a single
1430 // FIXME: It will be better just to find spare register here.
1431 if (AFI->isThumb2Function() &&
1432 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1433 MRI.setPhysRegUsed(ARM::R4);
1435 if (AFI->isThumb1OnlyFunction()) {
1436 // Spill LR if Thumb1 function uses variable length argument lists.
1437 if (AFI->getArgRegsSaveSize() > 0)
1438 MRI.setPhysRegUsed(ARM::LR);
1440 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1441 // for sure what the stack size will be, but for this, an estimate is good
1442 // enough. If there anything changes it, it'll be a spill, which implies
1443 // we've used all the registers and so R4 is already used, so not marking
1444 // it here will be OK.
1445 // FIXME: It will be better just to find spare register here.
1446 unsigned StackSize = MFI->estimateStackSize(MF);
1447 if (MFI->hasVarSizedObjects() || StackSize > 508)
1448 MRI.setPhysRegUsed(ARM::R4);
1451 // See if we can spill vector registers to aligned stack.
1452 checkNumAlignedDPRCS2Regs(MF);
1454 // Spill the BasePtr if it's used.
1455 if (RegInfo->hasBasePointer(MF))
1456 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1458 // Don't spill FP if the frame can be eliminated. This is determined
1459 // by scanning the callee-save registers to see if any is used.
1460 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1461 for (unsigned i = 0; CSRegs[i]; ++i) {
1462 unsigned Reg = CSRegs[i];
1463 bool Spilled = false;
1464 if (MRI.isPhysRegUsed(Reg)) {
1466 CanEliminateFrame = false;
1469 if (!ARM::GPRRegClass.contains(Reg))
1475 if (!STI.isTargetDarwin()) {
1482 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1487 case ARM::R0: case ARM::R1:
1488 case ARM::R2: case ARM::R3:
1489 case ARM::R4: case ARM::R5:
1490 case ARM::R6: case ARM::R7:
1497 if (!STI.isTargetDarwin()) {
1498 UnspilledCS1GPRs.push_back(Reg);
1503 case ARM::R0: case ARM::R1:
1504 case ARM::R2: case ARM::R3:
1505 case ARM::R4: case ARM::R5:
1506 case ARM::R6: case ARM::R7:
1508 UnspilledCS1GPRs.push_back(Reg);
1511 UnspilledCS2GPRs.push_back(Reg);
1517 bool ForceLRSpill = false;
1518 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1519 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1520 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1521 // use of BL to implement far jump. If it turns out that it's not needed
1522 // then the branch fix up path will undo it.
1523 if (FnSize >= (1 << 11)) {
1524 CanEliminateFrame = false;
1525 ForceLRSpill = true;
1529 // If any of the stack slot references may be out of range of an immediate
1530 // offset, make sure a register (or a spill slot) is available for the
1531 // register scavenger. Note that if we're indexing off the frame pointer, the
1532 // effective stack size is 4 bytes larger since the FP points to the stack
1533 // slot of the previous FP. Also, if we have variable sized objects in the
1534 // function, stack slot references will often be negative, and some of
1535 // our instructions are positive-offset only, so conservatively consider
1536 // that case to want a spill slot (or register) as well. Similarly, if
1537 // the function adjusts the stack pointer during execution and the
1538 // adjustments aren't already part of our stack size estimate, our offset
1539 // calculations may be off, so be conservative.
1540 // FIXME: We could add logic to be more precise about negative offsets
1541 // and which instructions will need a scratch register for them. Is it
1542 // worth the effort and added fragility?
1545 (MFI->estimateStackSize(MF) +
1546 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1547 estimateRSStackSizeLimit(MF, this)))
1548 || MFI->hasVarSizedObjects()
1549 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1551 bool ExtraCSSpill = false;
1552 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1553 AFI->setHasStackFrame(true);
1555 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1556 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1557 if (!LRSpilled && CS1Spilled) {
1558 MRI.setPhysRegUsed(ARM::LR);
1560 SmallVectorImpl<unsigned>::iterator LRPos;
1561 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1563 if (LRPos != UnspilledCS1GPRs.end())
1564 UnspilledCS1GPRs.erase(LRPos);
1566 ForceLRSpill = false;
1567 ExtraCSSpill = true;
1571 MRI.setPhysRegUsed(FramePtr);
1572 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1574 if (FPPos != UnspilledCS1GPRs.end())
1575 UnspilledCS1GPRs.erase(FPPos);
1579 // If stack and double are 8-byte aligned and we are spilling an odd number
1580 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1581 // the integer and double callee save areas.
1582 unsigned TargetAlign = getStackAlignment();
1583 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1584 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1585 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1586 unsigned Reg = UnspilledCS1GPRs[i];
1587 // Don't spill high register if the function is thumb1
1588 if (!AFI->isThumb1OnlyFunction() ||
1589 isARMLowRegister(Reg) || Reg == ARM::LR) {
1590 MRI.setPhysRegUsed(Reg);
1591 if (!MRI.isReserved(Reg))
1592 ExtraCSSpill = true;
1596 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1597 unsigned Reg = UnspilledCS2GPRs.front();
1598 MRI.setPhysRegUsed(Reg);
1599 if (!MRI.isReserved(Reg))
1600 ExtraCSSpill = true;
1604 // Estimate if we might need to scavenge a register at some point in order
1605 // to materialize a stack offset. If so, either spill one additional
1606 // callee-saved register or reserve a special spill slot to facilitate
1607 // register scavenging. Thumb1 needs a spill slot for stack pointer
1608 // adjustments also, even when the frame itself is small.
1609 if (BigStack && !ExtraCSSpill) {
1610 // If any non-reserved CS register isn't spilled, just spill one or two
1611 // extra. That should take care of it!
1612 unsigned NumExtras = TargetAlign / 4;
1613 SmallVector<unsigned, 2> Extras;
1614 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1615 unsigned Reg = UnspilledCS1GPRs.back();
1616 UnspilledCS1GPRs.pop_back();
1617 if (!MRI.isReserved(Reg) &&
1618 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1620 Extras.push_back(Reg);
1624 // For non-Thumb1 functions, also check for hi-reg CS registers
1625 if (!AFI->isThumb1OnlyFunction()) {
1626 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1627 unsigned Reg = UnspilledCS2GPRs.back();
1628 UnspilledCS2GPRs.pop_back();
1629 if (!MRI.isReserved(Reg)) {
1630 Extras.push_back(Reg);
1635 if (Extras.size() && NumExtras == 0) {
1636 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1637 MRI.setPhysRegUsed(Extras[i]);
1639 } else if (!AFI->isThumb1OnlyFunction()) {
1640 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1641 // closest to SP or frame pointer.
1642 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1643 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1651 MRI.setPhysRegUsed(ARM::LR);
1652 AFI->setLRIsSpilledForFarJump(true);
1657 void ARMFrameLowering::
1658 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1659 MachineBasicBlock::iterator I) const {
1660 const ARMBaseInstrInfo &TII =
1661 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1662 if (!hasReservedCallFrame(MF)) {
1663 // If we have alloca, convert as follows:
1664 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1665 // ADJCALLSTACKUP -> add, sp, sp, amount
1666 MachineInstr *Old = I;
1667 DebugLoc dl = Old->getDebugLoc();
1668 unsigned Amount = Old->getOperand(0).getImm();
1670 // We need to keep the stack aligned properly. To do this, we round the
1671 // amount of space needed for the outgoing arguments up to the next
1672 // alignment boundary.
1673 unsigned Align = getStackAlignment();
1674 Amount = (Amount+Align-1)/Align*Align;
1676 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1677 assert(!AFI->isThumb1OnlyFunction() &&
1678 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1679 bool isARM = !AFI->isThumbFunction();
1681 // Replace the pseudo instruction with a new instruction...
1682 unsigned Opc = Old->getOpcode();
1683 int PIdx = Old->findFirstPredOperandIdx();
1684 ARMCC::CondCodes Pred = (PIdx == -1)
1685 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1686 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1687 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1688 unsigned PredReg = Old->getOperand(2).getReg();
1689 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1692 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1693 unsigned PredReg = Old->getOperand(3).getReg();
1694 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1695 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1703 /// Get the minimum constant for ARM that is greater than or equal to the
1704 /// argument. In ARM, constants can have any value that can be produced by
1705 /// rotating an 8-bit value to the right by an even number of bits within a
1707 static uint32_t alignToARMConstant(uint32_t Value) {
1708 unsigned Shifted = 0;
1713 while (!(Value & 0xC0000000)) {
1718 bool Carry = (Value & 0x00FFFFFF);
1719 Value = ((Value & 0xFF000000) >> 24) + Carry;
1721 if (Value & 0x0000100)
1722 Value = Value & 0x000001FC;
1725 Value = Value >> (Shifted - 24);
1727 Value = Value << (24 - Shifted);
1732 // The stack limit in the TCB is set to this many bytes above the actual
1734 static const uint64_t kSplitStackAvailable = 256;
1736 // Adjust the function prologue to enable split stacks. This currently only
1737 // supports android and linux.
1739 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1740 // must be well defined in order to allow for consistent implementations of the
1741 // __morestack helper function. The ABI is also not a normal ABI in that it
1742 // doesn't follow the normal calling conventions because this allows the
1743 // prologue of each function to be optimized further.
1745 // Currently, the ABI looks like (when calling __morestack)
1747 // * r4 holds the minimum stack size requested for this function call
1748 // * r5 holds the stack size of the arguments to the function
1749 // * the beginning of the function is 3 instructions after the call to
1752 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1753 // place the arguments on to the new stack, and the 3-instruction knowledge to
1754 // jump directly to the body of the function when working on the new stack.
1756 // An old (and possibly no longer compatible) implementation of __morestack for
1757 // ARM can be found at [1].
1759 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1760 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1763 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1764 bool Thumb = ST->isThumb();
1766 // Sadly, this currently doesn't support varargs, platforms other than
1767 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1768 if (MF.getFunction()->isVarArg())
1769 report_fatal_error("Segmented stacks do not support vararg functions.");
1770 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1771 report_fatal_error("Segmented stacks not supported on this platform.");
1773 MachineBasicBlock &prologueMBB = MF.front();
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 MachineModuleInfo &MMI = MF.getMMI();
1776 MCContext &Context = MMI.getContext();
1777 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1778 const ARMBaseInstrInfo &TII =
1779 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1780 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1783 uint64_t StackSize = MFI->getStackSize();
1785 // Do not generate a prologue for functions with a stack of size zero
1789 // Use R4 and R5 as scratch registers.
1790 // We save R4 and R5 before use and restore them before leaving the function.
1791 unsigned ScratchReg0 = ARM::R4;
1792 unsigned ScratchReg1 = ARM::R5;
1793 uint64_t AlignedStackSize;
1795 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1796 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1797 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1798 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1799 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1801 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1802 e = prologueMBB.livein_end();
1804 AllocMBB->addLiveIn(*i);
1805 GetMBB->addLiveIn(*i);
1806 McrMBB->addLiveIn(*i);
1807 PrevStackMBB->addLiveIn(*i);
1808 PostStackMBB->addLiveIn(*i);
1811 MF.push_front(PostStackMBB);
1812 MF.push_front(AllocMBB);
1813 MF.push_front(GetMBB);
1814 MF.push_front(McrMBB);
1815 MF.push_front(PrevStackMBB);
1817 // The required stack size that is aligned to ARM constant criterion.
1818 AlignedStackSize = alignToARMConstant(StackSize);
1820 // When the frame size is less than 256 we just compare the stack
1821 // boundary directly to the value of the stack pointer, per gcc.
1822 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1824 // We will use two of the callee save registers as scratch registers so we
1825 // need to save those registers onto the stack.
1826 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1827 // requested and arguments for __morestack().
1828 // SR0: Scratch Register #0
1829 // SR1: Scratch Register #1
1832 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1833 .addReg(ScratchReg0).addReg(ScratchReg1);
1835 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1836 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1837 .addReg(ScratchReg0).addReg(ScratchReg1);
1840 // Emit the relevant DWARF information about the change in stack pointer as
1841 // well as where to find both r4 and r5 (the callee-save registers)
1843 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1844 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1845 .addCFIIndex(CFIIndex);
1846 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1847 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1848 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1849 .addCFIIndex(CFIIndex);
1850 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1851 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1852 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1853 .addCFIIndex(CFIIndex);
1857 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1859 } else if (CompareStackPointer) {
1860 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1861 .addReg(ARM::SP)).addReg(0);
1864 // sub SR1, sp, #StackSize
1865 if (!CompareStackPointer && Thumb) {
1867 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1868 .addReg(ScratchReg1).addImm(AlignedStackSize));
1869 } else if (!CompareStackPointer) {
1870 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1871 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1874 if (Thumb && ST->isThumb1Only()) {
1875 unsigned PCLabelId = ARMFI->createPICLabelUId();
1876 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1877 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1878 MachineConstantPool *MCP = MF.getConstantPool();
1879 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1881 // ldr SR0, [pc, offset(STACK_LIMIT)]
1882 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1883 .addConstantPoolIndex(CPI));
1886 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1887 .addReg(ScratchReg0).addImm(0));
1889 // Get TLS base address from the coprocessor
1890 // mrc p15, #0, SR0, c13, c0, #3
1891 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1898 // Use the last tls slot on android and a private field of the TCP on linux.
1899 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1900 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1902 // Get the stack limit from the right offset
1903 // ldr SR0, [sr0, #4 * TlsOffset]
1904 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1905 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1908 // Compare stack limit with stack size requested.
1910 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1911 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1912 .addReg(ScratchReg0)
1913 .addReg(ScratchReg1));
1915 // This jump is taken if StackLimit < SP - stack required.
1916 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1917 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1922 // Calling __morestack(StackSize, Size of stack arguments).
1923 // __morestack knows that the stack size requested is in SR0(r4)
1924 // and amount size of stack arguments is in SR1(r5).
1926 // Pass first argument for the __morestack by Scratch Register #0.
1927 // The amount size of stack required
1929 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1930 ScratchReg0)).addImm(AlignedStackSize));
1932 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1933 .addImm(AlignedStackSize)).addReg(0);
1935 // Pass second argument for the __morestack by Scratch Register #1.
1936 // The amount size of stack consumed to save function arguments.
1939 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1940 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1942 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1943 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1947 // push {lr} - Save return address of this function.
1949 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1952 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1953 .addReg(ARM::SP, RegState::Define)
1958 // Emit the DWARF info about the change in stack as well as where to find the
1959 // previous link register
1961 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1962 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1963 .addCFIIndex(CFIIndex);
1964 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1965 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1966 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1967 .addCFIIndex(CFIIndex);
1969 // Call __morestack().
1971 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1972 .addExternalSymbol("__morestack");
1974 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1975 .addExternalSymbol("__morestack");
1978 // pop {lr} - Restore return address of this original function.
1980 if (ST->isThumb1Only()) {
1981 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1982 .addReg(ScratchReg0);
1983 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1984 .addReg(ScratchReg0));
1986 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1987 .addReg(ARM::LR, RegState::Define)
1988 .addReg(ARM::SP, RegState::Define)
1993 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1994 .addReg(ARM::SP, RegState::Define)
1999 // Restore SR0 and SR1 in case of __morestack() was called.
2000 // __morestack() will skip PostStackMBB block so we need to restore
2001 // scratch registers from here.
2004 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2005 .addReg(ScratchReg0)
2006 .addReg(ScratchReg1);
2008 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2009 .addReg(ARM::SP, RegState::Define)
2011 .addReg(ScratchReg0)
2012 .addReg(ScratchReg1);
2015 // Update the CFA offset now that we've popped
2016 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2017 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2018 .addCFIIndex(CFIIndex);
2020 // bx lr - Return from this function.
2021 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2022 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2024 // Restore SR0 and SR1 in case of __morestack() was not called.
2027 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2028 .addReg(ScratchReg0)
2029 .addReg(ScratchReg1);
2031 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2032 .addReg(ARM::SP, RegState::Define)
2034 .addReg(ScratchReg0)
2035 .addReg(ScratchReg1);
2038 // Update the CFA offset now that we've popped
2039 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2040 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2041 .addCFIIndex(CFIIndex);
2043 // Tell debuggers that r4 and r5 are now the same as they were in the
2044 // previous function, that they're the "Same Value".
2045 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2046 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2047 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2048 .addCFIIndex(CFIIndex);
2049 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2050 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2051 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2052 .addCFIIndex(CFIIndex);
2054 // Organizing MBB lists
2055 PostStackMBB->addSuccessor(&prologueMBB);
2057 AllocMBB->addSuccessor(PostStackMBB);
2059 GetMBB->addSuccessor(PostStackMBB);
2060 GetMBB->addSuccessor(AllocMBB);
2062 McrMBB->addSuccessor(GetMBB);
2064 PrevStackMBB->addSuccessor(McrMBB);