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 /// hasFP - Return true if the specified function should have a dedicated frame
43 /// pointer register. This is true if the function has variable sized allocas
44 /// or if frame pointer elimination is disabled.
45 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
46 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
48 // iOS requires FP not to be clobbered for backtracing purpose.
49 if (STI.isTargetIOS())
52 const MachineFrameInfo *MFI = MF.getFrameInfo();
53 // Always eliminate non-leaf frame pointers.
54 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
56 RegInfo->needsStackRealignment(MF) ||
57 MFI->hasVarSizedObjects() ||
58 MFI->isFrameAddressTaken());
61 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
62 /// not required, we reserve argument space for call sites in the function
63 /// immediately on entry to the current function. This eliminates the need for
64 /// add/sub sp brackets around call sites. Returns true if the call frame is
65 /// included as part of the stack frame.
66 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
67 const MachineFrameInfo *FFI = MF.getFrameInfo();
68 unsigned CFSize = FFI->getMaxCallFrameSize();
69 // It's not always a good idea to include the call frame as part of the
70 // stack frame. ARM (especially Thumb) has small immediate offset to
71 // address the stack frame. So a large call frame can cause poor codegen
72 // and may even makes it impossible to scavenge a register.
73 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
76 return !MF.getFrameInfo()->hasVarSizedObjects();
79 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
80 /// call frame pseudos can be simplified. Unlike most targets, having a FP
81 /// is not sufficient here since we still may reference some objects via SP
82 /// even when FP is available in Thumb2 mode.
84 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
85 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
88 static bool isCSRestore(MachineInstr *MI,
89 const ARMBaseInstrInfo &TII,
90 const MCPhysReg *CSRegs) {
91 // Integer spill area is handled with "pop".
92 if (isPopOpcode(MI->getOpcode())) {
93 // The first two operands are predicates. The last two are
94 // imp-def and imp-use of SP. Check everything in between.
95 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
96 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
100 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
101 MI->getOpcode() == ARM::LDR_POST_REG ||
102 MI->getOpcode() == ARM::t2LDR_POST) &&
103 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
104 MI->getOperand(1).getReg() == ARM::SP)
110 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
112 const ARMBaseInstrInfo &TII, unsigned DestReg,
113 unsigned SrcReg, int NumBytes,
114 unsigned MIFlags = MachineInstr::NoFlags,
115 ARMCC::CondCodes Pred = ARMCC::AL,
116 unsigned PredReg = 0) {
118 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
119 Pred, PredReg, TII, MIFlags);
121 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
122 Pred, PredReg, TII, MIFlags);
125 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
127 const ARMBaseInstrInfo &TII, int NumBytes,
128 unsigned MIFlags = MachineInstr::NoFlags,
129 ARMCC::CondCodes Pred = ARMCC::AL,
130 unsigned PredReg = 0) {
131 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
132 MIFlags, Pred, PredReg);
135 static int sizeOfSPAdjustment(const MachineInstr *MI) {
136 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
138 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
139 // pred) so the list starts at 4.
140 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
145 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
146 size_t StackSizeInBytes) {
147 const MachineFrameInfo *MFI = MF.getFrameInfo();
148 if (MFI->getStackProtectorIndex() > 0)
149 return StackSizeInBytes >= 4080;
150 return StackSizeInBytes >= 4096;
153 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
154 MachineBasicBlock &MBB = MF.front();
155 MachineBasicBlock::iterator MBBI = MBB.begin();
156 MachineFrameInfo *MFI = MF.getFrameInfo();
157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
158 MachineModuleInfo &MMI = MF.getMMI();
159 MCContext &Context = MMI.getContext();
160 const TargetMachine &TM = MF.getTarget();
161 const MCRegisterInfo *MRI = Context.getRegisterInfo();
162 const ARMBaseRegisterInfo *RegInfo =
163 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
164 const ARMBaseInstrInfo &TII =
165 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
166 assert(!AFI->isThumb1OnlyFunction() &&
167 "This emitPrologue does not support Thumb1!");
168 bool isARM = !AFI->isThumbFunction();
169 unsigned Align = TM.getFrameLowering()->getStackAlignment();
170 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
171 unsigned NumBytes = MFI->getStackSize();
172 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
173 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
174 unsigned FramePtr = RegInfo->getFrameRegister(MF);
177 // Determine the sizes of each callee-save spill areas and record which frame
178 // belongs to which callee-save spill areas.
179 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
180 int FramePtrSpillFI = 0;
183 // All calls are tail calls in GHC calling conv, and functions have no
184 // prologue/epilogue.
185 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
188 // Allocate the vararg register save area.
189 if (ArgRegsSaveSize) {
190 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
191 MachineInstr::FrameSetup);
192 CFAOffset -= ArgRegsSaveSize;
193 unsigned CFIIndex = MMI.addFrameInst(
194 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
195 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
196 .addCFIIndex(CFIIndex);
199 if (!AFI->hasStackFrame() &&
200 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
201 if (NumBytes - ArgRegsSaveSize != 0) {
202 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
203 MachineInstr::FrameSetup);
204 CFAOffset -= NumBytes - ArgRegsSaveSize;
205 unsigned CFIIndex = MMI.addFrameInst(
206 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
207 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
208 .addCFIIndex(CFIIndex);
213 // Determine spill area sizes.
214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
215 unsigned Reg = CSI[i].getReg();
216 int FI = CSI[i].getFrameIdx();
223 if (STI.isTargetDarwin()) {
238 FramePtrSpillFI = FI;
242 // This is a DPR. Exclude the aligned DPRCS2 spills.
245 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
251 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
254 GPRCS1Push = LastPush = MBBI++;
256 // Determine starting offsets of spill areas.
257 bool HasFP = hasFP(MF);
258 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
259 + GPRCS2Size + DPRCSSize);
260 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
261 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
262 int FramePtrOffsetInPush = 0;
264 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
265 + GPRCS1Size + ArgRegsSaveSize;
266 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
269 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
270 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
271 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
275 GPRCS2Push = LastPush = MBBI++;
280 // Since vpush register list cannot have gaps, there may be multiple vpush
281 // instructions in the prologue.
282 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
286 // Move past the aligned DPRCS2 area.
287 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
288 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
289 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
290 // leaves the stack pointer pointing to the DPRCS2 area.
292 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
293 NumBytes += MFI->getObjectOffset(D8SpillFI);
295 NumBytes = DPRCSOffset;
297 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
298 uint32_t NumWords = NumBytes >> 2;
300 if (NumWords < 65536)
301 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
303 .setMIFlags(MachineInstr::FrameSetup));
305 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
307 .setMIFlags(MachineInstr::FrameSetup);
309 switch (TM.getCodeModel()) {
310 case CodeModel::Small:
311 case CodeModel::Medium:
312 case CodeModel::Default:
313 case CodeModel::Kernel:
314 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
315 .addImm((unsigned)ARMCC::AL).addReg(0)
316 .addExternalSymbol("__chkstk")
317 .addReg(ARM::R4, RegState::Implicit)
318 .setMIFlags(MachineInstr::FrameSetup);
320 case CodeModel::Large:
321 case CodeModel::JITDefault:
322 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
323 .addExternalSymbol("__chkstk")
324 .setMIFlags(MachineInstr::FrameSetup);
326 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
327 .addImm((unsigned)ARMCC::AL).addReg(0)
328 .addReg(ARM::R12, RegState::Kill)
329 .addReg(ARM::R4, RegState::Implicit)
330 .setMIFlags(MachineInstr::FrameSetup);
334 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
336 .addReg(ARM::SP, RegState::Define)
337 .addReg(ARM::R4, RegState::Kill)
338 .setMIFlags(MachineInstr::FrameSetup)));
342 unsigned adjustedGPRCS1Size = GPRCS1Size;
344 // Adjust SP after all the callee-save spills.
345 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
346 if (LastPush == GPRCS1Push) {
347 FramePtrOffsetInPush += NumBytes;
348 adjustedGPRCS1Size += NumBytes;
352 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
353 MachineInstr::FrameSetup);
356 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
357 // Note it's not safe to do this in Thumb2 mode because it would have
358 // taken two instructions:
361 // If an interrupt is taken between the two instructions, then sp is in
362 // an inconsistent state (pointing to the middle of callee-saved area).
363 // The interrupt handler can end up clobbering the registers.
364 AFI->setShouldRestoreSPFromFP(true);
367 if (adjustedGPRCS1Size > 0) {
368 CFAOffset -= adjustedGPRCS1Size;
369 unsigned CFIIndex = MMI.addFrameInst(
370 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
371 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
372 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
373 .addCFIIndex(CFIIndex);
374 for (const auto &Entry : CSI) {
375 unsigned Reg = Entry.getReg();
376 int FI = Entry.getFrameIdx();
383 if (STI.isTargetDarwin())
395 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
396 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
397 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
398 .addCFIIndex(CFIIndex);
404 // Set FP to point to the stack slot that contains the previous FP.
405 // For iOS, FP is R7, which has now been stored in spill area 1.
406 // Otherwise, if this is not iOS, all the callee-saved registers go
407 // into spill area 1, including the FP in R11. In either case, it
408 // is in area one and the adjustment needs to take place just after
411 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
412 FramePtr, ARM::SP, FramePtrOffsetInPush,
413 MachineInstr::FrameSetup);
414 if (FramePtrOffsetInPush) {
415 CFAOffset += FramePtrOffsetInPush;
416 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
417 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
418 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
419 .addCFIIndex(CFIIndex);
423 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
424 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
425 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
426 .addCFIIndex(CFIIndex);
430 if (GPRCS2Size > 0) {
431 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
433 CFAOffset -= GPRCS2Size;
434 unsigned CFIIndex = MMI.addFrameInst(
435 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
436 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
437 .addCFIIndex(CFIIndex);
439 for (const auto &Entry : CSI) {
440 unsigned Reg = Entry.getReg();
441 int FI = Entry.getFrameIdx();
448 if (STI.isTargetDarwin()) {
449 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
450 unsigned Offset = MFI->getObjectOffset(FI);
451 unsigned CFIIndex = MMI.addFrameInst(
452 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
453 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
454 .addCFIIndex(CFIIndex);
462 // Since vpush register list cannot have gaps, there may be multiple vpush
463 // instructions in the prologue.
465 MachineBasicBlock::iterator Push = DPRCSPush++;
467 CFAOffset -= sizeOfSPAdjustment(Push);
468 unsigned CFIIndex = MMI.addFrameInst(
469 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
470 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
471 .addCFIIndex(CFIIndex);
473 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
475 for (const auto &Entry : CSI) {
476 unsigned Reg = Entry.getReg();
477 int FI = Entry.getFrameIdx();
478 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
479 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
480 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
481 unsigned Offset = MFI->getObjectOffset(FI);
482 unsigned CFIIndex = MMI.addFrameInst(
483 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
484 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
485 .addCFIIndex(CFIIndex);
492 CFAOffset -= NumBytes;
493 unsigned CFIIndex = MMI.addFrameInst(
494 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
495 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
496 .addCFIIndex(CFIIndex);
500 if (STI.isTargetELF() && hasFP(MF))
501 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
502 AFI->getFramePtrSpillOffset());
504 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
505 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
506 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
508 // If we need dynamic stack realignment, do it here. Be paranoid and make
509 // sure if we also have VLAs, we have a base pointer for frame access.
510 // If aligned NEON registers were spilled, the stack has already been
512 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
513 unsigned MaxAlign = MFI->getMaxAlignment();
514 assert (!AFI->isThumb1OnlyFunction());
515 if (!AFI->isThumbFunction()) {
516 // Emit bic sp, sp, MaxAlign
517 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
518 TII.get(ARM::BICri), ARM::SP)
519 .addReg(ARM::SP, RegState::Kill)
520 .addImm(MaxAlign-1)));
522 // We cannot use sp as source/dest register here, thus we're emitting the
523 // following sequence:
525 // bic r4, r4, MaxAlign
527 // FIXME: It will be better just to find spare register here.
528 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
529 .addReg(ARM::SP, RegState::Kill));
530 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
531 TII.get(ARM::t2BICri), ARM::R4)
532 .addReg(ARM::R4, RegState::Kill)
533 .addImm(MaxAlign-1)));
534 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
535 .addReg(ARM::R4, RegState::Kill));
538 AFI->setShouldRestoreSPFromFP(true);
541 // If we need a base pointer, set it up here. It's whatever the value
542 // of the stack pointer is at this point. Any variable size objects
543 // will be allocated after this, so we can still use the base pointer
544 // to reference locals.
545 // FIXME: Clarify FrameSetup flags here.
546 if (RegInfo->hasBasePointer(MF)) {
548 BuildMI(MBB, MBBI, dl,
549 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
551 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
553 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
554 RegInfo->getBaseRegister())
558 // If the frame has variable sized objects then the epilogue must restore
559 // the sp from fp. We can assume there's an FP here since hasFP already
560 // checks for hasVarSizedObjects.
561 if (MFI->hasVarSizedObjects())
562 AFI->setShouldRestoreSPFromFP(true);
565 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
566 MachineBasicBlock &MBB) const {
567 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
568 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
569 unsigned RetOpcode = MBBI->getOpcode();
570 DebugLoc dl = MBBI->getDebugLoc();
571 MachineFrameInfo *MFI = MF.getFrameInfo();
572 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
573 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
574 const ARMBaseInstrInfo &TII =
575 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
576 assert(!AFI->isThumb1OnlyFunction() &&
577 "This emitEpilogue does not support Thumb1!");
578 bool isARM = !AFI->isThumbFunction();
580 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
581 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
582 int NumBytes = (int)MFI->getStackSize();
583 unsigned FramePtr = RegInfo->getFrameRegister(MF);
585 // All calls are tail calls in GHC calling conv, and functions have no
586 // prologue/epilogue.
587 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
590 if (!AFI->hasStackFrame()) {
591 if (NumBytes - ArgRegsSaveSize != 0)
592 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
594 // Unwind MBBI to point to first LDR / VLDRD.
595 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
596 if (MBBI != MBB.begin()) {
599 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
600 if (!isCSRestore(MBBI, TII, CSRegs))
604 // Move SP to start of FP callee save spill area.
605 NumBytes -= (ArgRegsSaveSize +
606 AFI->getGPRCalleeSavedArea1Size() +
607 AFI->getGPRCalleeSavedArea2Size() +
608 AFI->getDPRCalleeSavedAreaSize());
610 // Reset SP based on frame pointer only if the stack frame extends beyond
611 // frame pointer stack slot or target is ELF and the function has FP.
612 if (AFI->shouldRestoreSPFromFP()) {
613 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
616 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
619 // It's not possible to restore SP from FP in a single instruction.
620 // For iOS, this looks like:
623 // This is bad, if an interrupt is taken after the mov, sp is in an
624 // inconsistent state.
625 // Use the first callee-saved register as a scratch register.
626 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
627 "No scratch register to restore SP from FP!");
628 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
630 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
637 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
638 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
640 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
644 } else if (NumBytes &&
645 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
646 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
648 // Increment past our save areas.
649 if (AFI->getDPRCalleeSavedAreaSize()) {
651 // Since vpop register list cannot have gaps, there may be multiple vpop
652 // instructions in the epilogue.
653 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
656 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
657 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
660 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
661 // Tail call return: adjust the stack pointer and jump to callee.
662 MBBI = MBB.getLastNonDebugInstr();
663 MachineOperand &JumpTarget = MBBI->getOperand(0);
665 // Jump to label or value in register.
666 if (RetOpcode == ARM::TCRETURNdi) {
667 unsigned TCOpcode = STI.isThumb() ?
668 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
670 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
671 if (JumpTarget.isGlobal())
672 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
673 JumpTarget.getTargetFlags());
675 assert(JumpTarget.isSymbol());
676 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
677 JumpTarget.getTargetFlags());
680 // Add the default predicate in Thumb mode.
681 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
682 } else if (RetOpcode == ARM::TCRETURNri) {
683 BuildMI(MBB, MBBI, dl,
684 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
685 addReg(JumpTarget.getReg(), RegState::Kill);
688 MachineInstr *NewMI = std::prev(MBBI);
689 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
690 NewMI->addOperand(MBBI->getOperand(i));
692 // Delete the pseudo instruction TCRETURN.
698 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
701 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
702 /// debug info. It's the same as what we use for resolving the code-gen
703 /// references for now. FIXME: This can go wrong when references are
704 /// SP-relative and simple call frames aren't used.
706 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
707 unsigned &FrameReg) const {
708 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
712 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
713 int FI, unsigned &FrameReg,
715 const MachineFrameInfo *MFI = MF.getFrameInfo();
716 const ARMBaseRegisterInfo *RegInfo =
717 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
718 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
719 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
720 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
721 bool isFixed = MFI->isFixedObjectIndex(FI);
726 // SP can move around if there are allocas. We may also lose track of SP
727 // when emergency spilling inside a non-reserved call frame setup.
728 bool hasMovingSP = !hasReservedCallFrame(MF);
730 // When dynamically realigning the stack, use the frame pointer for
731 // parameters, and the stack/base pointer for locals.
732 if (RegInfo->needsStackRealignment(MF)) {
733 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
735 FrameReg = RegInfo->getFrameRegister(MF);
737 } else if (hasMovingSP) {
738 assert(RegInfo->hasBasePointer(MF) &&
739 "VLAs and dynamic stack alignment, but missing base pointer!");
740 FrameReg = RegInfo->getBaseRegister();
745 // If there is a frame pointer, use it when we can.
746 if (hasFP(MF) && AFI->hasStackFrame()) {
747 // Use frame pointer to reference fixed objects. Use it for locals if
748 // there are VLAs (and thus the SP isn't reliable as a base).
749 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
750 FrameReg = RegInfo->getFrameRegister(MF);
752 } else if (hasMovingSP) {
753 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
754 if (AFI->isThumb2Function()) {
755 // Try to use the frame pointer if we can, else use the base pointer
756 // since it's available. This is handy for the emergency spill slot, in
758 if (FPOffset >= -255 && FPOffset < 0) {
759 FrameReg = RegInfo->getFrameRegister(MF);
763 } else if (AFI->isThumb2Function()) {
764 // Use add <rd>, sp, #<imm8>
765 // ldr <rd>, [sp, #<imm8>]
766 // if at all possible to save space.
767 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
769 // In Thumb2 mode, the negative offset is very limited. Try to avoid
770 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
771 if (FPOffset >= -255 && FPOffset < 0) {
772 FrameReg = RegInfo->getFrameRegister(MF);
775 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
776 // Otherwise, use SP or FP, whichever is closer to the stack slot.
777 FrameReg = RegInfo->getFrameRegister(MF);
781 // Use the base pointer if we have one.
782 if (RegInfo->hasBasePointer(MF))
783 FrameReg = RegInfo->getBaseRegister();
787 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
790 return getFrameIndexReference(MF, FI, FrameReg);
793 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
794 MachineBasicBlock::iterator MI,
795 const std::vector<CalleeSavedInfo> &CSI,
796 unsigned StmOpc, unsigned StrOpc,
798 bool(*Func)(unsigned, bool),
799 unsigned NumAlignedDPRCS2Regs,
800 unsigned MIFlags) const {
801 MachineFunction &MF = *MBB.getParent();
802 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
805 if (MI != MBB.end()) DL = MI->getDebugLoc();
807 SmallVector<std::pair<unsigned,bool>, 4> Regs;
808 unsigned i = CSI.size();
810 unsigned LastReg = 0;
811 for (; i != 0; --i) {
812 unsigned Reg = CSI[i-1].getReg();
813 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
815 // D-registers in the aligned area DPRCS2 are NOT spilled here.
816 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
819 // Add the callee-saved register as live-in unless it's LR and
820 // @llvm.returnaddress is called. If LR is returned for
821 // @llvm.returnaddress then it's already added to the function and
822 // entry block live-in sets.
824 if (Reg == ARM::LR) {
825 if (MF.getFrameInfo()->isReturnAddressTaken() &&
826 MF.getRegInfo().isLiveIn(Reg))
833 // If NoGap is true, push consecutive registers and then leave the rest
834 // for other instructions. e.g.
835 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
836 if (NoGap && LastReg && LastReg != Reg-1)
839 Regs.push_back(std::make_pair(Reg, isKill));
844 if (Regs.size() > 1 || StrOpc== 0) {
845 MachineInstrBuilder MIB =
846 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
847 .addReg(ARM::SP).setMIFlags(MIFlags));
848 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
849 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
850 } else if (Regs.size() == 1) {
851 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
853 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
854 .addReg(ARM::SP).setMIFlags(MIFlags)
860 // Put any subsequent vpush instructions before this one: they will refer to
861 // higher register numbers so need to be pushed first in order to preserve
867 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
868 MachineBasicBlock::iterator MI,
869 const std::vector<CalleeSavedInfo> &CSI,
870 unsigned LdmOpc, unsigned LdrOpc,
871 bool isVarArg, bool NoGap,
872 bool(*Func)(unsigned, bool),
873 unsigned NumAlignedDPRCS2Regs) const {
874 MachineFunction &MF = *MBB.getParent();
875 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
876 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
877 DebugLoc DL = MI->getDebugLoc();
878 unsigned RetOpcode = MI->getOpcode();
879 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
880 RetOpcode == ARM::TCRETURNri);
882 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
884 SmallVector<unsigned, 4> Regs;
885 unsigned i = CSI.size();
887 unsigned LastReg = 0;
888 bool DeleteRet = false;
889 for (; i != 0; --i) {
890 unsigned Reg = CSI[i-1].getReg();
891 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
893 // The aligned reloads from area DPRCS2 are not inserted here.
894 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
897 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
900 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
901 // Fold the return instruction into the LDM.
905 // If NoGap is true, pop consecutive registers and then leave the rest
906 // for other instructions. e.g.
907 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
908 if (NoGap && LastReg && LastReg != Reg-1)
917 if (Regs.size() > 1 || LdrOpc == 0) {
918 MachineInstrBuilder MIB =
919 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
921 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
922 MIB.addReg(Regs[i], getDefRegState(true));
924 MIB.copyImplicitOps(&*MI);
925 MI->eraseFromParent();
928 } else if (Regs.size() == 1) {
929 // If we adjusted the reg to PC from LR above, switch it back here. We
930 // only do that for LDM.
931 if (Regs[0] == ARM::PC)
933 MachineInstrBuilder MIB =
934 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
935 .addReg(ARM::SP, RegState::Define)
937 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
938 // that refactoring is complete (eventually).
939 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
941 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
948 // Put any subsequent vpop instructions after this one: they will refer to
949 // higher register numbers so need to be popped afterwards.
954 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
955 /// starting from d8. Also insert stack realignment code and leave the stack
956 /// pointer pointing to the d8 spill slot.
957 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
958 MachineBasicBlock::iterator MI,
959 unsigned NumAlignedDPRCS2Regs,
960 const std::vector<CalleeSavedInfo> &CSI,
961 const TargetRegisterInfo *TRI) {
962 MachineFunction &MF = *MBB.getParent();
963 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
964 DebugLoc DL = MI->getDebugLoc();
965 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
966 MachineFrameInfo &MFI = *MF.getFrameInfo();
968 // Mark the D-register spill slots as properly aligned. Since MFI computes
969 // stack slot layout backwards, this can actually mean that the d-reg stack
970 // slot offsets can be wrong. The offset for d8 will always be correct.
971 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
972 unsigned DNum = CSI[i].getReg() - ARM::D8;
975 int FI = CSI[i].getFrameIdx();
976 // The even-numbered registers will be 16-byte aligned, the odd-numbered
977 // registers will be 8-byte aligned.
978 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
980 // The stack slot for D8 needs to be maximally aligned because this is
981 // actually the point where we align the stack pointer. MachineFrameInfo
982 // computes all offsets relative to the incoming stack pointer which is a
983 // bit weird when realigning the stack. Any extra padding for this
984 // over-alignment is not realized because the code inserted below adjusts
985 // the stack pointer by numregs * 8 before aligning the stack pointer.
987 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
990 // Move the stack pointer to the d8 spill slot, and align it at the same
991 // time. Leave the stack slot address in the scratch register r4.
993 // sub r4, sp, #numregs * 8
994 // bic r4, r4, #align - 1
997 bool isThumb = AFI->isThumbFunction();
998 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
999 AFI->setShouldRestoreSPFromFP(true);
1001 // sub r4, sp, #numregs * 8
1002 // The immediate is <= 64, so it doesn't need any special encoding.
1003 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1004 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1006 .addImm(8 * NumAlignedDPRCS2Regs)));
1008 // bic r4, r4, #align-1
1009 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1010 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1011 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1012 .addReg(ARM::R4, RegState::Kill)
1013 .addImm(MaxAlign - 1)));
1016 // The stack pointer must be adjusted before spilling anything, otherwise
1017 // the stack slots could be clobbered by an interrupt handler.
1018 // Leave r4 live, it is used below.
1019 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1020 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1022 MIB = AddDefaultPred(MIB);
1026 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1027 // r4 holds the stack slot address.
1028 unsigned NextReg = ARM::D8;
1030 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1031 // The writeback is only needed when emitting two vst1.64 instructions.
1032 if (NumAlignedDPRCS2Regs >= 6) {
1033 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1034 &ARM::QQPRRegClass);
1035 MBB.addLiveIn(SupReg);
1036 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1038 .addReg(ARM::R4, RegState::Kill).addImm(16)
1040 .addReg(SupReg, RegState::ImplicitKill));
1042 NumAlignedDPRCS2Regs -= 4;
1045 // We won't modify r4 beyond this point. It currently points to the next
1046 // register to be spilled.
1047 unsigned R4BaseReg = NextReg;
1049 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1050 if (NumAlignedDPRCS2Regs >= 4) {
1051 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1052 &ARM::QQPRRegClass);
1053 MBB.addLiveIn(SupReg);
1054 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1055 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1056 .addReg(SupReg, RegState::ImplicitKill));
1058 NumAlignedDPRCS2Regs -= 4;
1061 // 16-byte aligned vst1.64 with 2 d-regs.
1062 if (NumAlignedDPRCS2Regs >= 2) {
1063 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1065 MBB.addLiveIn(SupReg);
1066 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1067 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1069 NumAlignedDPRCS2Regs -= 2;
1072 // Finally, use a vanilla vstr.64 for the odd last register.
1073 if (NumAlignedDPRCS2Regs) {
1074 MBB.addLiveIn(NextReg);
1075 // vstr.64 uses addrmode5 which has an offset scale of 4.
1076 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1078 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1081 // The last spill instruction inserted should kill the scratch register r4.
1082 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1085 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1086 /// iterator to the following instruction.
1087 static MachineBasicBlock::iterator
1088 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1089 unsigned NumAlignedDPRCS2Regs) {
1090 // sub r4, sp, #numregs * 8
1091 // bic r4, r4, #align - 1
1094 assert(MI->mayStore() && "Expecting spill instruction");
1096 // These switches all fall through.
1097 switch(NumAlignedDPRCS2Regs) {
1100 assert(MI->mayStore() && "Expecting spill instruction");
1103 assert(MI->mayStore() && "Expecting spill instruction");
1107 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1113 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1114 /// starting from d8. These instructions are assumed to execute while the
1115 /// stack is still aligned, unlike the code inserted by emitPopInst.
1116 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1117 MachineBasicBlock::iterator MI,
1118 unsigned NumAlignedDPRCS2Regs,
1119 const std::vector<CalleeSavedInfo> &CSI,
1120 const TargetRegisterInfo *TRI) {
1121 MachineFunction &MF = *MBB.getParent();
1122 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1123 DebugLoc DL = MI->getDebugLoc();
1124 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1126 // Find the frame index assigned to d8.
1128 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1129 if (CSI[i].getReg() == ARM::D8) {
1130 D8SpillFI = CSI[i].getFrameIdx();
1134 // Materialize the address of the d8 spill slot into the scratch register r4.
1135 // This can be fairly complicated if the stack frame is large, so just use
1136 // the normal frame index elimination mechanism to do it. This code runs as
1137 // the initial part of the epilog where the stack and base pointers haven't
1138 // been changed yet.
1139 bool isThumb = AFI->isThumbFunction();
1140 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1142 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1143 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1144 .addFrameIndex(D8SpillFI).addImm(0)));
1146 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1147 unsigned NextReg = ARM::D8;
1149 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1150 if (NumAlignedDPRCS2Regs >= 6) {
1151 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1152 &ARM::QQPRRegClass);
1153 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1154 .addReg(ARM::R4, RegState::Define)
1155 .addReg(ARM::R4, RegState::Kill).addImm(16)
1156 .addReg(SupReg, RegState::ImplicitDefine));
1158 NumAlignedDPRCS2Regs -= 4;
1161 // We won't modify r4 beyond this point. It currently points to the next
1162 // register to be spilled.
1163 unsigned R4BaseReg = NextReg;
1165 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1166 if (NumAlignedDPRCS2Regs >= 4) {
1167 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1168 &ARM::QQPRRegClass);
1169 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1170 .addReg(ARM::R4).addImm(16)
1171 .addReg(SupReg, RegState::ImplicitDefine));
1173 NumAlignedDPRCS2Regs -= 4;
1176 // 16-byte aligned vld1.64 with 2 d-regs.
1177 if (NumAlignedDPRCS2Regs >= 2) {
1178 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1180 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1181 .addReg(ARM::R4).addImm(16));
1183 NumAlignedDPRCS2Regs -= 2;
1186 // Finally, use a vanilla vldr.64 for the remaining odd register.
1187 if (NumAlignedDPRCS2Regs)
1188 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1189 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1191 // Last store kills r4.
1192 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1195 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1196 MachineBasicBlock::iterator MI,
1197 const std::vector<CalleeSavedInfo> &CSI,
1198 const TargetRegisterInfo *TRI) const {
1202 MachineFunction &MF = *MBB.getParent();
1203 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1205 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1206 unsigned PushOneOpc = AFI->isThumbFunction() ?
1207 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1208 unsigned FltOpc = ARM::VSTMDDB_UPD;
1209 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1210 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1211 MachineInstr::FrameSetup);
1212 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1213 MachineInstr::FrameSetup);
1214 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1215 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1217 // The code above does not insert spill code for the aligned DPRCS2 registers.
1218 // The stack realignment code will be inserted between the push instructions
1219 // and these spills.
1220 if (NumAlignedDPRCS2Regs)
1221 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1226 bool ARMFrameLowering::restoreCalleeSavedRegisters(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>();
1235 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1236 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1238 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1239 // registers. Do that here instead.
1240 if (NumAlignedDPRCS2Regs)
1241 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1243 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1244 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1245 unsigned FltOpc = ARM::VLDMDIA_UPD;
1246 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1247 NumAlignedDPRCS2Regs);
1248 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1249 &isARMArea2Register, 0);
1250 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1251 &isARMArea1Register, 0);
1256 // FIXME: Make generic?
1257 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1258 const ARMBaseInstrInfo &TII) {
1259 unsigned FnSize = 0;
1260 for (auto &MBB : MF) {
1261 for (auto &MI : MBB)
1262 FnSize += TII.GetInstSizeInBytes(&MI);
1267 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1268 /// frames and return the stack size limit beyond which some of these
1269 /// instructions will require a scratch register during their expansion later.
1270 // FIXME: Move to TII?
1271 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1272 const TargetFrameLowering *TFI) {
1273 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1274 unsigned Limit = (1 << 12) - 1;
1275 for (auto &MBB : MF) {
1276 for (auto &MI : MBB) {
1277 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1278 if (!MI.getOperand(i).isFI())
1281 // When using ADDri to get the address of a stack object, 255 is the
1282 // largest offset guaranteed to fit in the immediate offset.
1283 if (MI.getOpcode() == ARM::ADDri) {
1284 Limit = std::min(Limit, (1U << 8) - 1);
1288 // Otherwise check the addressing mode.
1289 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1290 case ARMII::AddrMode3:
1291 case ARMII::AddrModeT2_i8:
1292 Limit = std::min(Limit, (1U << 8) - 1);
1294 case ARMII::AddrMode5:
1295 case ARMII::AddrModeT2_i8s4:
1296 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1298 case ARMII::AddrModeT2_i12:
1299 // i12 supports only positive offset so these will be converted to
1300 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1301 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1302 Limit = std::min(Limit, (1U << 8) - 1);
1304 case ARMII::AddrMode4:
1305 case ARMII::AddrMode6:
1306 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1307 // immediate offset for stack references.
1312 break; // At most one FI per instruction
1320 // In functions that realign the stack, it can be an advantage to spill the
1321 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1322 // instructions take alignment hints that can improve performance.
1324 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1325 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1326 if (!SpillAlignedNEONRegs)
1329 // Naked functions don't spill callee-saved registers.
1330 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1334 // We are planning to use NEON instructions vst1 / vld1.
1335 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1338 // Don't bother if the default stack alignment is sufficiently high.
1339 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1342 // Aligned spills require stack realignment.
1343 const ARMBaseRegisterInfo *RegInfo =
1344 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1345 if (!RegInfo->canRealignStack(MF))
1348 // We always spill contiguous d-registers starting from d8. Count how many
1349 // needs spilling. The register allocator will almost always use the
1350 // callee-saved registers in order, but it can happen that there are holes in
1351 // the range. Registers above the hole will be spilled to the standard DPRCS
1353 MachineRegisterInfo &MRI = MF.getRegInfo();
1354 unsigned NumSpills = 0;
1355 for (; NumSpills < 8; ++NumSpills)
1356 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1359 // Don't do this for just one d-register. It's not worth it.
1363 // Spill the first NumSpills D-registers after realigning the stack.
1364 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1366 // A scratch register is required for the vst1 / vld1 instructions.
1367 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1371 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1372 RegScavenger *RS) const {
1373 // This tells PEI to spill the FP as if it is any other callee-save register
1374 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1375 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1376 // to combine multiple loads / stores.
1377 bool CanEliminateFrame = true;
1378 bool CS1Spilled = false;
1379 bool LRSpilled = false;
1380 unsigned NumGPRSpills = 0;
1381 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1382 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1383 const ARMBaseRegisterInfo *RegInfo =
1384 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1385 const ARMBaseInstrInfo &TII =
1386 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1387 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1388 MachineFrameInfo *MFI = MF.getFrameInfo();
1389 MachineRegisterInfo &MRI = MF.getRegInfo();
1390 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1392 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1393 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1394 // since it's not always possible to restore sp from fp in a single
1396 // FIXME: It will be better just to find spare register here.
1397 if (AFI->isThumb2Function() &&
1398 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1399 MRI.setPhysRegUsed(ARM::R4);
1401 if (AFI->isThumb1OnlyFunction()) {
1402 // Spill LR if Thumb1 function uses variable length argument lists.
1403 if (AFI->getArgRegsSaveSize() > 0)
1404 MRI.setPhysRegUsed(ARM::LR);
1406 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1407 // for sure what the stack size will be, but for this, an estimate is good
1408 // enough. If there anything changes it, it'll be a spill, which implies
1409 // we've used all the registers and so R4 is already used, so not marking
1410 // it here will be OK.
1411 // FIXME: It will be better just to find spare register here.
1412 unsigned StackSize = MFI->estimateStackSize(MF);
1413 if (MFI->hasVarSizedObjects() || StackSize > 508)
1414 MRI.setPhysRegUsed(ARM::R4);
1417 // See if we can spill vector registers to aligned stack.
1418 checkNumAlignedDPRCS2Regs(MF);
1420 // Spill the BasePtr if it's used.
1421 if (RegInfo->hasBasePointer(MF))
1422 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1424 // Don't spill FP if the frame can be eliminated. This is determined
1425 // by scanning the callee-save registers to see if any is used.
1426 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1427 for (unsigned i = 0; CSRegs[i]; ++i) {
1428 unsigned Reg = CSRegs[i];
1429 bool Spilled = false;
1430 if (MRI.isPhysRegUsed(Reg)) {
1432 CanEliminateFrame = false;
1435 if (!ARM::GPRRegClass.contains(Reg))
1441 if (!STI.isTargetDarwin()) {
1448 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1453 case ARM::R0: case ARM::R1:
1454 case ARM::R2: case ARM::R3:
1455 case ARM::R4: case ARM::R5:
1456 case ARM::R6: case ARM::R7:
1463 if (!STI.isTargetDarwin()) {
1464 UnspilledCS1GPRs.push_back(Reg);
1469 case ARM::R0: case ARM::R1:
1470 case ARM::R2: case ARM::R3:
1471 case ARM::R4: case ARM::R5:
1472 case ARM::R6: case ARM::R7:
1474 UnspilledCS1GPRs.push_back(Reg);
1477 UnspilledCS2GPRs.push_back(Reg);
1483 bool ForceLRSpill = false;
1484 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1485 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1486 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1487 // use of BL to implement far jump. If it turns out that it's not needed
1488 // then the branch fix up path will undo it.
1489 if (FnSize >= (1 << 11)) {
1490 CanEliminateFrame = false;
1491 ForceLRSpill = true;
1495 // If any of the stack slot references may be out of range of an immediate
1496 // offset, make sure a register (or a spill slot) is available for the
1497 // register scavenger. Note that if we're indexing off the frame pointer, the
1498 // effective stack size is 4 bytes larger since the FP points to the stack
1499 // slot of the previous FP. Also, if we have variable sized objects in the
1500 // function, stack slot references will often be negative, and some of
1501 // our instructions are positive-offset only, so conservatively consider
1502 // that case to want a spill slot (or register) as well. Similarly, if
1503 // the function adjusts the stack pointer during execution and the
1504 // adjustments aren't already part of our stack size estimate, our offset
1505 // calculations may be off, so be conservative.
1506 // FIXME: We could add logic to be more precise about negative offsets
1507 // and which instructions will need a scratch register for them. Is it
1508 // worth the effort and added fragility?
1511 (MFI->estimateStackSize(MF) +
1512 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1513 estimateRSStackSizeLimit(MF, this)))
1514 || MFI->hasVarSizedObjects()
1515 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1517 bool ExtraCSSpill = false;
1518 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1519 AFI->setHasStackFrame(true);
1521 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1522 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1523 if (!LRSpilled && CS1Spilled) {
1524 MRI.setPhysRegUsed(ARM::LR);
1526 SmallVectorImpl<unsigned>::iterator LRPos;
1527 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1529 if (LRPos != UnspilledCS1GPRs.end())
1530 UnspilledCS1GPRs.erase(LRPos);
1532 ForceLRSpill = false;
1533 ExtraCSSpill = true;
1537 MRI.setPhysRegUsed(FramePtr);
1538 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1540 if (FPPos != UnspilledCS1GPRs.end())
1541 UnspilledCS1GPRs.erase(FPPos);
1545 // If stack and double are 8-byte aligned and we are spilling an odd number
1546 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1547 // the integer and double callee save areas.
1548 unsigned TargetAlign = getStackAlignment();
1549 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1550 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1551 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1552 unsigned Reg = UnspilledCS1GPRs[i];
1553 // Don't spill high register if the function is thumb1
1554 if (!AFI->isThumb1OnlyFunction() ||
1555 isARMLowRegister(Reg) || Reg == ARM::LR) {
1556 MRI.setPhysRegUsed(Reg);
1557 if (!MRI.isReserved(Reg))
1558 ExtraCSSpill = true;
1562 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1563 unsigned Reg = UnspilledCS2GPRs.front();
1564 MRI.setPhysRegUsed(Reg);
1565 if (!MRI.isReserved(Reg))
1566 ExtraCSSpill = true;
1570 // Estimate if we might need to scavenge a register at some point in order
1571 // to materialize a stack offset. If so, either spill one additional
1572 // callee-saved register or reserve a special spill slot to facilitate
1573 // register scavenging. Thumb1 needs a spill slot for stack pointer
1574 // adjustments also, even when the frame itself is small.
1575 if (BigStack && !ExtraCSSpill) {
1576 // If any non-reserved CS register isn't spilled, just spill one or two
1577 // extra. That should take care of it!
1578 unsigned NumExtras = TargetAlign / 4;
1579 SmallVector<unsigned, 2> Extras;
1580 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1581 unsigned Reg = UnspilledCS1GPRs.back();
1582 UnspilledCS1GPRs.pop_back();
1583 if (!MRI.isReserved(Reg) &&
1584 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1586 Extras.push_back(Reg);
1590 // For non-Thumb1 functions, also check for hi-reg CS registers
1591 if (!AFI->isThumb1OnlyFunction()) {
1592 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1593 unsigned Reg = UnspilledCS2GPRs.back();
1594 UnspilledCS2GPRs.pop_back();
1595 if (!MRI.isReserved(Reg)) {
1596 Extras.push_back(Reg);
1601 if (Extras.size() && NumExtras == 0) {
1602 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1603 MRI.setPhysRegUsed(Extras[i]);
1605 } else if (!AFI->isThumb1OnlyFunction()) {
1606 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1607 // closest to SP or frame pointer.
1608 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1609 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1617 MRI.setPhysRegUsed(ARM::LR);
1618 AFI->setLRIsSpilledForFarJump(true);
1623 void ARMFrameLowering::
1624 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1625 MachineBasicBlock::iterator I) const {
1626 const ARMBaseInstrInfo &TII =
1627 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1628 if (!hasReservedCallFrame(MF)) {
1629 // If we have alloca, convert as follows:
1630 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1631 // ADJCALLSTACKUP -> add, sp, sp, amount
1632 MachineInstr *Old = I;
1633 DebugLoc dl = Old->getDebugLoc();
1634 unsigned Amount = Old->getOperand(0).getImm();
1636 // We need to keep the stack aligned properly. To do this, we round the
1637 // amount of space needed for the outgoing arguments up to the next
1638 // alignment boundary.
1639 unsigned Align = getStackAlignment();
1640 Amount = (Amount+Align-1)/Align*Align;
1642 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1643 assert(!AFI->isThumb1OnlyFunction() &&
1644 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1645 bool isARM = !AFI->isThumbFunction();
1647 // Replace the pseudo instruction with a new instruction...
1648 unsigned Opc = Old->getOpcode();
1649 int PIdx = Old->findFirstPredOperandIdx();
1650 ARMCC::CondCodes Pred = (PIdx == -1)
1651 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1652 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1653 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1654 unsigned PredReg = Old->getOperand(2).getReg();
1655 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1658 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1659 unsigned PredReg = Old->getOperand(3).getReg();
1660 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1661 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1669 /// Get the minimum constant for ARM that is greater than or equal to the
1670 /// argument. In ARM, constants can have any value that can be produced by
1671 /// rotating an 8-bit value to the right by an even number of bits within a
1673 static uint32_t alignToARMConstant(uint32_t Value) {
1674 unsigned Shifted = 0;
1679 while (!(Value & 0xC0000000)) {
1684 bool Carry = (Value & 0x00FFFFFF);
1685 Value = ((Value & 0xFF000000) >> 24) + Carry;
1687 if (Value & 0x0000100)
1688 Value = Value & 0x000001FC;
1691 Value = Value >> (Shifted - 24);
1693 Value = Value << (24 - Shifted);
1698 // The stack limit in the TCB is set to this many bytes above the actual
1700 static const uint64_t kSplitStackAvailable = 256;
1702 // Adjust the function prologue to enable split stacks. This currently only
1703 // supports android and linux.
1705 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1706 // must be well defined in order to allow for consistent implementations of the
1707 // __morestack helper function. The ABI is also not a normal ABI in that it
1708 // doesn't follow the normal calling conventions because this allows the
1709 // prologue of each function to be optimized further.
1711 // Currently, the ABI looks like (when calling __morestack)
1713 // * r4 holds the minimum stack size requested for this function call
1714 // * r5 holds the stack size of the arguments to the function
1715 // * the beginning of the function is 3 instructions after the call to
1718 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1719 // place the arguments on to the new stack, and the 3-instruction knowledge to
1720 // jump directly to the body of the function when working on the new stack.
1722 // An old (and possibly no longer compatible) implementation of __morestack for
1723 // ARM can be found at [1].
1725 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1726 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1729 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1730 bool Thumb = ST->isThumb();
1732 // Sadly, this currently doesn't support varargs, platforms other than
1733 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1734 if (MF.getFunction()->isVarArg())
1735 report_fatal_error("Segmented stacks do not support vararg functions.");
1736 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1737 report_fatal_error("Segmented stacks not supported on this platform.");
1739 MachineBasicBlock &prologueMBB = MF.front();
1740 MachineFrameInfo *MFI = MF.getFrameInfo();
1741 MachineModuleInfo &MMI = MF.getMMI();
1742 MCContext &Context = MMI.getContext();
1743 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1744 const ARMBaseInstrInfo &TII =
1745 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1746 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1749 uint64_t StackSize = MFI->getStackSize();
1751 // Do not generate a prologue for functions with a stack of size zero
1755 // Use R4 and R5 as scratch registers.
1756 // We save R4 and R5 before use and restore them before leaving the function.
1757 unsigned ScratchReg0 = ARM::R4;
1758 unsigned ScratchReg1 = ARM::R5;
1759 uint64_t AlignedStackSize;
1761 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1762 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1763 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1764 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1765 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1767 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1768 e = prologueMBB.livein_end();
1770 AllocMBB->addLiveIn(*i);
1771 GetMBB->addLiveIn(*i);
1772 McrMBB->addLiveIn(*i);
1773 PrevStackMBB->addLiveIn(*i);
1774 PostStackMBB->addLiveIn(*i);
1777 MF.push_front(PostStackMBB);
1778 MF.push_front(AllocMBB);
1779 MF.push_front(GetMBB);
1780 MF.push_front(McrMBB);
1781 MF.push_front(PrevStackMBB);
1783 // The required stack size that is aligned to ARM constant criterion.
1784 AlignedStackSize = alignToARMConstant(StackSize);
1786 // When the frame size is less than 256 we just compare the stack
1787 // boundary directly to the value of the stack pointer, per gcc.
1788 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1790 // We will use two of the callee save registers as scratch registers so we
1791 // need to save those registers onto the stack.
1792 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1793 // requested and arguments for __morestack().
1794 // SR0: Scratch Register #0
1795 // SR1: Scratch Register #1
1798 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1799 .addReg(ScratchReg0).addReg(ScratchReg1);
1801 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1802 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1803 .addReg(ScratchReg0).addReg(ScratchReg1);
1806 // Emit the relevant DWARF information about the change in stack pointer as
1807 // well as where to find both r4 and r5 (the callee-save registers)
1809 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1810 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1811 .addCFIIndex(CFIIndex);
1812 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1813 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1814 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1815 .addCFIIndex(CFIIndex);
1816 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1817 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1818 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1819 .addCFIIndex(CFIIndex);
1823 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1825 } else if (CompareStackPointer) {
1826 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1827 .addReg(ARM::SP)).addReg(0);
1830 // sub SR1, sp, #StackSize
1831 if (!CompareStackPointer && Thumb) {
1833 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1834 .addReg(ScratchReg1).addImm(AlignedStackSize));
1835 } else if (!CompareStackPointer) {
1836 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1837 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1840 if (Thumb && ST->isThumb1Only()) {
1841 unsigned PCLabelId = ARMFI->createPICLabelUId();
1842 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1843 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1844 MachineConstantPool *MCP = MF.getConstantPool();
1845 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1847 // ldr SR0, [pc, offset(STACK_LIMIT)]
1848 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1849 .addConstantPoolIndex(CPI));
1852 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1853 .addReg(ScratchReg0).addImm(0));
1855 // Get TLS base address from the coprocessor
1856 // mrc p15, #0, SR0, c13, c0, #3
1857 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1864 // Use the last tls slot on android and a private field of the TCP on linux.
1865 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1866 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1868 // Get the stack limit from the right offset
1869 // ldr SR0, [sr0, #4 * TlsOffset]
1870 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1871 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1874 // Compare stack limit with stack size requested.
1876 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1877 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1878 .addReg(ScratchReg0)
1879 .addReg(ScratchReg1));
1881 // This jump is taken if StackLimit < SP - stack required.
1882 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1883 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1888 // Calling __morestack(StackSize, Size of stack arguments).
1889 // __morestack knows that the stack size requested is in SR0(r4)
1890 // and amount size of stack arguments is in SR1(r5).
1892 // Pass first argument for the __morestack by Scratch Register #0.
1893 // The amount size of stack required
1895 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1896 ScratchReg0)).addImm(AlignedStackSize));
1898 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1899 .addImm(AlignedStackSize)).addReg(0);
1901 // Pass second argument for the __morestack by Scratch Register #1.
1902 // The amount size of stack consumed to save function arguments.
1905 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1906 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1908 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1909 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1913 // push {lr} - Save return address of this function.
1915 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1918 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1919 .addReg(ARM::SP, RegState::Define)
1924 // Emit the DWARF info about the change in stack as well as where to find the
1925 // previous link register
1927 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1928 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1929 .addCFIIndex(CFIIndex);
1930 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1931 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1932 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1933 .addCFIIndex(CFIIndex);
1935 // Call __morestack().
1937 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1938 .addExternalSymbol("__morestack");
1940 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1941 .addExternalSymbol("__morestack");
1944 // pop {lr} - Restore return address of this original function.
1946 if (ST->isThumb1Only()) {
1947 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1948 .addReg(ScratchReg0);
1949 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1950 .addReg(ScratchReg0));
1952 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1953 .addReg(ARM::LR, RegState::Define)
1954 .addReg(ARM::SP, RegState::Define)
1959 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1960 .addReg(ARM::SP, RegState::Define)
1965 // Restore SR0 and SR1 in case of __morestack() was called.
1966 // __morestack() will skip PostStackMBB block so we need to restore
1967 // scratch registers from here.
1970 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1971 .addReg(ScratchReg0)
1972 .addReg(ScratchReg1);
1974 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1975 .addReg(ARM::SP, RegState::Define)
1977 .addReg(ScratchReg0)
1978 .addReg(ScratchReg1);
1981 // Update the CFA offset now that we've popped
1982 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1983 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1984 .addCFIIndex(CFIIndex);
1986 // bx lr - Return from this function.
1987 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1988 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
1990 // Restore SR0 and SR1 in case of __morestack() was not called.
1993 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
1994 .addReg(ScratchReg0)
1995 .addReg(ScratchReg1);
1997 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
1998 .addReg(ARM::SP, RegState::Define)
2000 .addReg(ScratchReg0)
2001 .addReg(ScratchReg1);
2004 // Update the CFA offset now that we've popped
2005 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2006 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2007 .addCFIIndex(CFIIndex);
2009 // Tell debuggers that r4 and r5 are now the same as they were in the
2010 // previous function, that they're the "Same Value".
2011 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2012 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2013 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2014 .addCFIIndex(CFIIndex);
2015 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2016 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2017 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2018 .addCFIIndex(CFIIndex);
2020 // Organizing MBB lists
2021 PostStackMBB->addSuccessor(&prologueMBB);
2023 AllocMBB->addSuccessor(PostStackMBB);
2025 GetMBB->addSuccessor(PostStackMBB);
2026 GetMBB->addSuccessor(AllocMBB);
2028 McrMBB->addSuccessor(GetMBB);
2030 PrevStackMBB->addSuccessor(McrMBB);