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 "ARMMachineFunctionInfo.h"
18 #include "MCTargetDesc/ARMAddressingModes.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetOptions.h"
34 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
35 cl::desc("Align ARM NEON spills in prolog and epilog"));
37 static MachineBasicBlock::iterator
38 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
39 unsigned NumAlignedDPRCS2Regs);
41 /// hasFP - Return true if the specified function should have a dedicated frame
42 /// pointer register. This is true if the function has variable sized allocas
43 /// or if frame pointer elimination is disabled.
44 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
45 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
47 // iOS requires FP not to be clobbered for backtracing purpose.
48 if (STI.isTargetIOS())
51 const MachineFrameInfo *MFI = MF.getFrameInfo();
52 // Always eliminate non-leaf frame pointers.
53 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
55 RegInfo->needsStackRealignment(MF) ||
56 MFI->hasVarSizedObjects() ||
57 MFI->isFrameAddressTaken());
60 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
61 /// not required, we reserve argument space for call sites in the function
62 /// immediately on entry to the current function. This eliminates the need for
63 /// add/sub sp brackets around call sites. Returns true if the call frame is
64 /// included as part of the stack frame.
65 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
66 const MachineFrameInfo *FFI = MF.getFrameInfo();
67 unsigned CFSize = FFI->getMaxCallFrameSize();
68 // It's not always a good idea to include the call frame as part of the
69 // stack frame. ARM (especially Thumb) has small immediate offset to
70 // address the stack frame. So a large call frame can cause poor codegen
71 // and may even makes it impossible to scavenge a register.
72 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
75 return !MF.getFrameInfo()->hasVarSizedObjects();
78 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
79 /// call frame pseudos can be simplified. Unlike most targets, having a FP
80 /// is not sufficient here since we still may reference some objects via SP
81 /// even when FP is available in Thumb2 mode.
83 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
84 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
87 static bool isCSRestore(MachineInstr *MI,
88 const ARMBaseInstrInfo &TII,
89 const uint16_t *CSRegs) {
90 // Integer spill area is handled with "pop".
91 if (isPopOpcode(MI->getOpcode())) {
92 // The first two operands are predicates. The last two are
93 // imp-def and imp-use of SP. Check everything in between.
94 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
95 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
99 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
100 MI->getOpcode() == ARM::LDR_POST_REG ||
101 MI->getOpcode() == ARM::t2LDR_POST) &&
102 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
103 MI->getOperand(1).getReg() == ARM::SP)
109 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
110 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
111 const ARMBaseInstrInfo &TII, unsigned DestReg,
112 unsigned SrcReg, int NumBytes,
113 unsigned MIFlags = MachineInstr::NoFlags,
114 ARMCC::CondCodes Pred = ARMCC::AL,
115 unsigned PredReg = 0) {
117 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
118 Pred, PredReg, TII, MIFlags);
120 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
121 Pred, PredReg, TII, MIFlags);
124 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
125 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
126 const ARMBaseInstrInfo &TII, int NumBytes,
127 unsigned MIFlags = MachineInstr::NoFlags,
128 ARMCC::CondCodes Pred = ARMCC::AL,
129 unsigned PredReg = 0) {
130 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
131 MIFlags, Pred, PredReg);
134 static int sizeOfSPAdjustment(const MachineInstr *MI) {
135 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
137 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
138 // pred) so the list starts at 4.
139 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
144 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
145 MachineBasicBlock &MBB = MF.front();
146 MachineBasicBlock::iterator MBBI = MBB.begin();
147 MachineFrameInfo *MFI = MF.getFrameInfo();
148 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
149 MachineModuleInfo &MMI = MF.getMMI();
150 MCContext &Context = MMI.getContext();
151 const MCRegisterInfo *MRI = Context.getRegisterInfo();
152 const ARMBaseRegisterInfo *RegInfo =
153 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
154 const ARMBaseInstrInfo &TII =
155 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
156 assert(!AFI->isThumb1OnlyFunction() &&
157 "This emitPrologue does not support Thumb1!");
158 bool isARM = !AFI->isThumbFunction();
159 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
160 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
161 unsigned NumBytes = MFI->getStackSize();
162 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
163 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
164 unsigned FramePtr = RegInfo->getFrameRegister(MF);
167 // Determine the sizes of each callee-save spill areas and record which frame
168 // belongs to which callee-save spill areas.
169 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
170 int FramePtrSpillFI = 0;
173 // All calls are tail calls in GHC calling conv, and functions have no
174 // prologue/epilogue.
175 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
178 // Allocate the vararg register save area.
179 if (ArgRegsSaveSize) {
180 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
181 MachineInstr::FrameSetup);
182 MCSymbol *SPLabel = Context.CreateTempSymbol();
183 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
185 CFAOffset -= ArgRegsSaveSize;
187 MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
190 if (!AFI->hasStackFrame()) {
191 if (NumBytes - ArgRegsSaveSize != 0) {
192 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
193 MachineInstr::FrameSetup);
194 MCSymbol *SPLabel = Context.CreateTempSymbol();
195 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
197 CFAOffset -= NumBytes - ArgRegsSaveSize;
198 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(SPLabel,
204 // Determine spill area sizes.
205 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
206 unsigned Reg = CSI[i].getReg();
207 int FI = CSI[i].getFrameIdx();
214 if (STI.isTargetMachO()) {
229 FramePtrSpillFI = FI;
233 // This is a DPR. Exclude the aligned DPRCS2 spills.
236 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
242 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
245 GPRCS1Push = LastPush = MBBI++;
247 // Determine starting offsets of spill areas.
248 bool HasFP = hasFP(MF);
249 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
250 + GPRCS2Size + DPRCSSize);
251 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
252 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
253 int FramePtrOffsetInPush = 0;
255 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
256 + GPRCS1Size + ArgRegsSaveSize;
257 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
260 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
261 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
262 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
266 GPRCS2Push = LastPush = MBBI++;
271 // Since vpush register list cannot have gaps, there may be multiple vpush
272 // instructions in the prologue.
273 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
277 // Move past the aligned DPRCS2 area.
278 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
279 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
280 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
281 // leaves the stack pointer pointing to the DPRCS2 area.
283 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
284 NumBytes += MFI->getObjectOffset(D8SpillFI);
286 NumBytes = DPRCSOffset;
288 unsigned adjustedGPRCS1Size = GPRCS1Size;
290 // Adjust SP after all the callee-save spills.
291 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
292 if (LastPush == GPRCS1Push) {
293 FramePtrOffsetInPush += NumBytes;
294 adjustedGPRCS1Size += NumBytes;
298 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
299 MachineInstr::FrameSetup);
302 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
303 // Note it's not safe to do this in Thumb2 mode because it would have
304 // taken two instructions:
307 // If an interrupt is taken between the two instructions, then sp is in
308 // an inconsistent state (pointing to the middle of callee-saved area).
309 // The interrupt handler can end up clobbering the registers.
310 AFI->setShouldRestoreSPFromFP(true);
313 if (adjustedGPRCS1Size > 0) {
314 MCSymbol *SPLabel = Context.CreateTempSymbol();
315 BuildMI(MBB, ++GPRCS1Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
317 CFAOffset -= adjustedGPRCS1Size;
319 MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
320 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
321 E = CSI.end(); I != E; ++I) {
322 unsigned Reg = I->getReg();
323 int FI = I->getFrameIdx();
330 if (STI.isTargetMachO())
342 MMI.addFrameInst(MCCFIInstruction::createOffset(SPLabel,
343 MRI->getDwarfRegNum(Reg, true),
344 MFI->getObjectOffset(FI)));
350 // Set FP to point to the stack slot that contains the previous FP.
351 // For iOS, FP is R7, which has now been stored in spill area 1.
352 // Otherwise, if this is not iOS, all the callee-saved registers go
353 // into spill area 1, including the FP in R11. In either case, it
354 // is in area one and the adjustment needs to take place just after
357 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
358 FramePtr, ARM::SP, FramePtrOffsetInPush,
359 MachineInstr::FrameSetup);
360 MCSymbol *SPLabel = Context.CreateTempSymbol();
361 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
363 if (FramePtrOffsetInPush) {
364 CFAOffset += FramePtrOffsetInPush;
366 MCCFIInstruction::createDefCfa(SPLabel,
367 MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
370 MCCFIInstruction::createDefCfaRegister(SPLabel,
371 MRI->getDwarfRegNum(FramePtr, true)));
374 if (GPRCS2Size > 0) {
375 MCSymbol *SPLabel = Context.CreateTempSymbol();
376 BuildMI(MBB, ++GPRCS2Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
379 CFAOffset -= GPRCS2Size;
381 MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
383 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
384 E = CSI.end(); I != E; ++I) {
385 unsigned Reg = I->getReg();
386 int FI = I->getFrameIdx();
393 if (STI.isTargetMachO()) {
394 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
395 unsigned Offset = MFI->getObjectOffset(FI);
397 MCCFIInstruction::createOffset(SPLabel, DwarfReg, Offset));
405 // Since vpush register list cannot have gaps, there may be multiple vpush
406 // instructions in the prologue.
407 MCSymbol *SPLabel = NULL;
409 MachineBasicBlock::iterator Push = DPRCSPush++;
411 SPLabel = Context.CreateTempSymbol();
412 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::PROLOG_LABEL))
414 CFAOffset -= sizeOfSPAdjustment(Push);;
416 MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
418 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
421 SPLabel = Context.CreateTempSymbol();
422 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::PROLOG_LABEL))
425 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
426 E = CSI.end(); I != E; ++I) {
427 unsigned Reg = I->getReg();
428 int FI = I->getFrameIdx();
429 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
430 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
431 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
432 unsigned Offset = MFI->getObjectOffset(FI);
433 MMI.addFrameInst(MCCFIInstruction::createOffset(SPLabel, DwarfReg,
441 MCSymbol *SPLabel = Context.CreateTempSymbol();
442 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
444 CFAOffset -= NumBytes;
446 MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
450 if (STI.isTargetELF() && hasFP(MF))
451 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
452 AFI->getFramePtrSpillOffset());
454 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
455 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
456 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
458 // If we need dynamic stack realignment, do it here. Be paranoid and make
459 // sure if we also have VLAs, we have a base pointer for frame access.
460 // If aligned NEON registers were spilled, the stack has already been
462 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
463 unsigned MaxAlign = MFI->getMaxAlignment();
464 assert (!AFI->isThumb1OnlyFunction());
465 if (!AFI->isThumbFunction()) {
466 // Emit bic sp, sp, MaxAlign
467 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
468 TII.get(ARM::BICri), ARM::SP)
469 .addReg(ARM::SP, RegState::Kill)
470 .addImm(MaxAlign-1)));
472 // We cannot use sp as source/dest register here, thus we're emitting the
473 // following sequence:
475 // bic r4, r4, MaxAlign
477 // FIXME: It will be better just to find spare register here.
478 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
479 .addReg(ARM::SP, RegState::Kill));
480 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
481 TII.get(ARM::t2BICri), ARM::R4)
482 .addReg(ARM::R4, RegState::Kill)
483 .addImm(MaxAlign-1)));
484 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
485 .addReg(ARM::R4, RegState::Kill));
488 AFI->setShouldRestoreSPFromFP(true);
491 // If we need a base pointer, set it up here. It's whatever the value
492 // of the stack pointer is at this point. Any variable size objects
493 // will be allocated after this, so we can still use the base pointer
494 // to reference locals.
495 // FIXME: Clarify FrameSetup flags here.
496 if (RegInfo->hasBasePointer(MF)) {
498 BuildMI(MBB, MBBI, dl,
499 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
501 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
503 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
504 RegInfo->getBaseRegister())
508 // If the frame has variable sized objects then the epilogue must restore
509 // the sp from fp. We can assume there's an FP here since hasFP already
510 // checks for hasVarSizedObjects.
511 if (MFI->hasVarSizedObjects())
512 AFI->setShouldRestoreSPFromFP(true);
515 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
516 MachineBasicBlock &MBB) const {
517 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
518 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
519 unsigned RetOpcode = MBBI->getOpcode();
520 DebugLoc dl = MBBI->getDebugLoc();
521 MachineFrameInfo *MFI = MF.getFrameInfo();
522 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
523 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
524 const ARMBaseInstrInfo &TII =
525 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
526 assert(!AFI->isThumb1OnlyFunction() &&
527 "This emitEpilogue does not support Thumb1!");
528 bool isARM = !AFI->isThumbFunction();
530 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
531 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
532 int NumBytes = (int)MFI->getStackSize();
533 unsigned FramePtr = RegInfo->getFrameRegister(MF);
535 // All calls are tail calls in GHC calling conv, and functions have no
536 // prologue/epilogue.
537 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
540 if (!AFI->hasStackFrame()) {
541 if (NumBytes - ArgRegsSaveSize != 0)
542 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
544 // Unwind MBBI to point to first LDR / VLDRD.
545 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
546 if (MBBI != MBB.begin()) {
549 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
550 if (!isCSRestore(MBBI, TII, CSRegs))
554 // Move SP to start of FP callee save spill area.
555 NumBytes -= (ArgRegsSaveSize +
556 AFI->getGPRCalleeSavedArea1Size() +
557 AFI->getGPRCalleeSavedArea2Size() +
558 AFI->getDPRCalleeSavedAreaSize());
560 // Reset SP based on frame pointer only if the stack frame extends beyond
561 // frame pointer stack slot or target is ELF and the function has FP.
562 if (AFI->shouldRestoreSPFromFP()) {
563 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
566 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
569 // It's not possible to restore SP from FP in a single instruction.
570 // For iOS, this looks like:
573 // This is bad, if an interrupt is taken after the mov, sp is in an
574 // inconsistent state.
575 // Use the first callee-saved register as a scratch register.
576 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
577 "No scratch register to restore SP from FP!");
578 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
580 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
587 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
588 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
590 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
594 } else if (NumBytes &&
595 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
596 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
598 // Increment past our save areas.
599 if (AFI->getDPRCalleeSavedAreaSize()) {
601 // Since vpop register list cannot have gaps, there may be multiple vpop
602 // instructions in the epilogue.
603 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
606 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
607 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
610 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
611 // Tail call return: adjust the stack pointer and jump to callee.
612 MBBI = MBB.getLastNonDebugInstr();
613 MachineOperand &JumpTarget = MBBI->getOperand(0);
615 // Jump to label or value in register.
616 if (RetOpcode == ARM::TCRETURNdi) {
617 unsigned TCOpcode = STI.isThumb() ?
618 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
620 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
621 if (JumpTarget.isGlobal())
622 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
623 JumpTarget.getTargetFlags());
625 assert(JumpTarget.isSymbol());
626 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
627 JumpTarget.getTargetFlags());
630 // Add the default predicate in Thumb mode.
631 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
632 } else if (RetOpcode == ARM::TCRETURNri) {
633 BuildMI(MBB, MBBI, dl,
634 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
635 addReg(JumpTarget.getReg(), RegState::Kill);
638 MachineInstr *NewMI = std::prev(MBBI);
639 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
640 NewMI->addOperand(MBBI->getOperand(i));
642 // Delete the pseudo instruction TCRETURN.
648 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
651 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
652 /// debug info. It's the same as what we use for resolving the code-gen
653 /// references for now. FIXME: This can go wrong when references are
654 /// SP-relative and simple call frames aren't used.
656 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
657 unsigned &FrameReg) const {
658 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
662 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
663 int FI, unsigned &FrameReg,
665 const MachineFrameInfo *MFI = MF.getFrameInfo();
666 const ARMBaseRegisterInfo *RegInfo =
667 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
668 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
669 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
670 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
671 bool isFixed = MFI->isFixedObjectIndex(FI);
676 // SP can move around if there are allocas. We may also lose track of SP
677 // when emergency spilling inside a non-reserved call frame setup.
678 bool hasMovingSP = !hasReservedCallFrame(MF);
680 // When dynamically realigning the stack, use the frame pointer for
681 // parameters, and the stack/base pointer for locals.
682 if (RegInfo->needsStackRealignment(MF)) {
683 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
685 FrameReg = RegInfo->getFrameRegister(MF);
687 } else if (hasMovingSP) {
688 assert(RegInfo->hasBasePointer(MF) &&
689 "VLAs and dynamic stack alignment, but missing base pointer!");
690 FrameReg = RegInfo->getBaseRegister();
695 // If there is a frame pointer, use it when we can.
696 if (hasFP(MF) && AFI->hasStackFrame()) {
697 // Use frame pointer to reference fixed objects. Use it for locals if
698 // there are VLAs (and thus the SP isn't reliable as a base).
699 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
700 FrameReg = RegInfo->getFrameRegister(MF);
702 } else if (hasMovingSP) {
703 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
704 if (AFI->isThumb2Function()) {
705 // Try to use the frame pointer if we can, else use the base pointer
706 // since it's available. This is handy for the emergency spill slot, in
708 if (FPOffset >= -255 && FPOffset < 0) {
709 FrameReg = RegInfo->getFrameRegister(MF);
713 } else if (AFI->isThumb2Function()) {
714 // Use add <rd>, sp, #<imm8>
715 // ldr <rd>, [sp, #<imm8>]
716 // if at all possible to save space.
717 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
719 // In Thumb2 mode, the negative offset is very limited. Try to avoid
720 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
721 if (FPOffset >= -255 && FPOffset < 0) {
722 FrameReg = RegInfo->getFrameRegister(MF);
725 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
726 // Otherwise, use SP or FP, whichever is closer to the stack slot.
727 FrameReg = RegInfo->getFrameRegister(MF);
731 // Use the base pointer if we have one.
732 if (RegInfo->hasBasePointer(MF))
733 FrameReg = RegInfo->getBaseRegister();
737 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
740 return getFrameIndexReference(MF, FI, FrameReg);
743 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
744 MachineBasicBlock::iterator MI,
745 const std::vector<CalleeSavedInfo> &CSI,
746 unsigned StmOpc, unsigned StrOpc,
748 bool(*Func)(unsigned, bool),
749 unsigned NumAlignedDPRCS2Regs,
750 unsigned MIFlags) const {
751 MachineFunction &MF = *MBB.getParent();
752 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
755 if (MI != MBB.end()) DL = MI->getDebugLoc();
757 SmallVector<std::pair<unsigned,bool>, 4> Regs;
758 unsigned i = CSI.size();
760 unsigned LastReg = 0;
761 for (; i != 0; --i) {
762 unsigned Reg = CSI[i-1].getReg();
763 if (!(Func)(Reg, STI.isTargetMachO())) continue;
765 // D-registers in the aligned area DPRCS2 are NOT spilled here.
766 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
769 // Add the callee-saved register as live-in unless it's LR and
770 // @llvm.returnaddress is called. If LR is returned for
771 // @llvm.returnaddress then it's already added to the function and
772 // entry block live-in sets.
774 if (Reg == ARM::LR) {
775 if (MF.getFrameInfo()->isReturnAddressTaken() &&
776 MF.getRegInfo().isLiveIn(Reg))
783 // If NoGap is true, push consecutive registers and then leave the rest
784 // for other instructions. e.g.
785 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
786 if (NoGap && LastReg && LastReg != Reg-1)
789 Regs.push_back(std::make_pair(Reg, isKill));
794 if (Regs.size() > 1 || StrOpc== 0) {
795 MachineInstrBuilder MIB =
796 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
797 .addReg(ARM::SP).setMIFlags(MIFlags));
798 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
799 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
800 } else if (Regs.size() == 1) {
801 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
803 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
804 .addReg(ARM::SP).setMIFlags(MIFlags)
812 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
813 MachineBasicBlock::iterator MI,
814 const std::vector<CalleeSavedInfo> &CSI,
815 unsigned LdmOpc, unsigned LdrOpc,
816 bool isVarArg, bool NoGap,
817 bool(*Func)(unsigned, bool),
818 unsigned NumAlignedDPRCS2Regs) const {
819 MachineFunction &MF = *MBB.getParent();
820 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
821 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
822 DebugLoc DL = MI->getDebugLoc();
823 unsigned RetOpcode = MI->getOpcode();
824 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
825 RetOpcode == ARM::TCRETURNri);
827 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
829 SmallVector<unsigned, 4> Regs;
830 unsigned i = CSI.size();
832 unsigned LastReg = 0;
833 bool DeleteRet = false;
834 for (; i != 0; --i) {
835 unsigned Reg = CSI[i-1].getReg();
836 if (!(Func)(Reg, STI.isTargetMachO())) continue;
838 // The aligned reloads from area DPRCS2 are not inserted here.
839 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
842 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
845 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
846 // Fold the return instruction into the LDM.
850 // If NoGap is true, pop consecutive registers and then leave the rest
851 // for other instructions. e.g.
852 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
853 if (NoGap && LastReg && LastReg != Reg-1)
862 if (Regs.size() > 1 || LdrOpc == 0) {
863 MachineInstrBuilder MIB =
864 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
866 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
867 MIB.addReg(Regs[i], getDefRegState(true));
869 MIB.copyImplicitOps(&*MI);
870 MI->eraseFromParent();
873 } else if (Regs.size() == 1) {
874 // If we adjusted the reg to PC from LR above, switch it back here. We
875 // only do that for LDM.
876 if (Regs[0] == ARM::PC)
878 MachineInstrBuilder MIB =
879 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
880 .addReg(ARM::SP, RegState::Define)
882 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
883 // that refactoring is complete (eventually).
884 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
886 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
895 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
896 /// starting from d8. Also insert stack realignment code and leave the stack
897 /// pointer pointing to the d8 spill slot.
898 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
899 MachineBasicBlock::iterator MI,
900 unsigned NumAlignedDPRCS2Regs,
901 const std::vector<CalleeSavedInfo> &CSI,
902 const TargetRegisterInfo *TRI) {
903 MachineFunction &MF = *MBB.getParent();
904 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
905 DebugLoc DL = MI->getDebugLoc();
906 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
907 MachineFrameInfo &MFI = *MF.getFrameInfo();
909 // Mark the D-register spill slots as properly aligned. Since MFI computes
910 // stack slot layout backwards, this can actually mean that the d-reg stack
911 // slot offsets can be wrong. The offset for d8 will always be correct.
912 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
913 unsigned DNum = CSI[i].getReg() - ARM::D8;
916 int FI = CSI[i].getFrameIdx();
917 // The even-numbered registers will be 16-byte aligned, the odd-numbered
918 // registers will be 8-byte aligned.
919 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
921 // The stack slot for D8 needs to be maximally aligned because this is
922 // actually the point where we align the stack pointer. MachineFrameInfo
923 // computes all offsets relative to the incoming stack pointer which is a
924 // bit weird when realigning the stack. Any extra padding for this
925 // over-alignment is not realized because the code inserted below adjusts
926 // the stack pointer by numregs * 8 before aligning the stack pointer.
928 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
931 // Move the stack pointer to the d8 spill slot, and align it at the same
932 // time. Leave the stack slot address in the scratch register r4.
934 // sub r4, sp, #numregs * 8
935 // bic r4, r4, #align - 1
938 bool isThumb = AFI->isThumbFunction();
939 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
940 AFI->setShouldRestoreSPFromFP(true);
942 // sub r4, sp, #numregs * 8
943 // The immediate is <= 64, so it doesn't need any special encoding.
944 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
945 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
947 .addImm(8 * NumAlignedDPRCS2Regs)));
949 // bic r4, r4, #align-1
950 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
951 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
952 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
953 .addReg(ARM::R4, RegState::Kill)
954 .addImm(MaxAlign - 1)));
957 // The stack pointer must be adjusted before spilling anything, otherwise
958 // the stack slots could be clobbered by an interrupt handler.
959 // Leave r4 live, it is used below.
960 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
961 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
963 MIB = AddDefaultPred(MIB);
967 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
968 // r4 holds the stack slot address.
969 unsigned NextReg = ARM::D8;
971 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
972 // The writeback is only needed when emitting two vst1.64 instructions.
973 if (NumAlignedDPRCS2Regs >= 6) {
974 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
976 MBB.addLiveIn(SupReg);
977 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
979 .addReg(ARM::R4, RegState::Kill).addImm(16)
981 .addReg(SupReg, RegState::ImplicitKill));
983 NumAlignedDPRCS2Regs -= 4;
986 // We won't modify r4 beyond this point. It currently points to the next
987 // register to be spilled.
988 unsigned R4BaseReg = NextReg;
990 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
991 if (NumAlignedDPRCS2Regs >= 4) {
992 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
994 MBB.addLiveIn(SupReg);
995 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
996 .addReg(ARM::R4).addImm(16).addReg(NextReg)
997 .addReg(SupReg, RegState::ImplicitKill));
999 NumAlignedDPRCS2Regs -= 4;
1002 // 16-byte aligned vst1.64 with 2 d-regs.
1003 if (NumAlignedDPRCS2Regs >= 2) {
1004 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1006 MBB.addLiveIn(SupReg);
1007 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1008 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1010 NumAlignedDPRCS2Regs -= 2;
1013 // Finally, use a vanilla vstr.64 for the odd last register.
1014 if (NumAlignedDPRCS2Regs) {
1015 MBB.addLiveIn(NextReg);
1016 // vstr.64 uses addrmode5 which has an offset scale of 4.
1017 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1019 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1022 // The last spill instruction inserted should kill the scratch register r4.
1023 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1026 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1027 /// iterator to the following instruction.
1028 static MachineBasicBlock::iterator
1029 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1030 unsigned NumAlignedDPRCS2Regs) {
1031 // sub r4, sp, #numregs * 8
1032 // bic r4, r4, #align - 1
1035 assert(MI->mayStore() && "Expecting spill instruction");
1037 // These switches all fall through.
1038 switch(NumAlignedDPRCS2Regs) {
1041 assert(MI->mayStore() && "Expecting spill instruction");
1044 assert(MI->mayStore() && "Expecting spill instruction");
1048 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1054 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1055 /// starting from d8. These instructions are assumed to execute while the
1056 /// stack is still aligned, unlike the code inserted by emitPopInst.
1057 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1058 MachineBasicBlock::iterator MI,
1059 unsigned NumAlignedDPRCS2Regs,
1060 const std::vector<CalleeSavedInfo> &CSI,
1061 const TargetRegisterInfo *TRI) {
1062 MachineFunction &MF = *MBB.getParent();
1063 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1064 DebugLoc DL = MI->getDebugLoc();
1065 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1067 // Find the frame index assigned to d8.
1069 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1070 if (CSI[i].getReg() == ARM::D8) {
1071 D8SpillFI = CSI[i].getFrameIdx();
1075 // Materialize the address of the d8 spill slot into the scratch register r4.
1076 // This can be fairly complicated if the stack frame is large, so just use
1077 // the normal frame index elimination mechanism to do it. This code runs as
1078 // the initial part of the epilog where the stack and base pointers haven't
1079 // been changed yet.
1080 bool isThumb = AFI->isThumbFunction();
1081 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1083 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1084 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1085 .addFrameIndex(D8SpillFI).addImm(0)));
1087 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1088 unsigned NextReg = ARM::D8;
1090 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1091 if (NumAlignedDPRCS2Regs >= 6) {
1092 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1093 &ARM::QQPRRegClass);
1094 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1095 .addReg(ARM::R4, RegState::Define)
1096 .addReg(ARM::R4, RegState::Kill).addImm(16)
1097 .addReg(SupReg, RegState::ImplicitDefine));
1099 NumAlignedDPRCS2Regs -= 4;
1102 // We won't modify r4 beyond this point. It currently points to the next
1103 // register to be spilled.
1104 unsigned R4BaseReg = NextReg;
1106 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1107 if (NumAlignedDPRCS2Regs >= 4) {
1108 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1109 &ARM::QQPRRegClass);
1110 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1111 .addReg(ARM::R4).addImm(16)
1112 .addReg(SupReg, RegState::ImplicitDefine));
1114 NumAlignedDPRCS2Regs -= 4;
1117 // 16-byte aligned vld1.64 with 2 d-regs.
1118 if (NumAlignedDPRCS2Regs >= 2) {
1119 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1121 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1122 .addReg(ARM::R4).addImm(16));
1124 NumAlignedDPRCS2Regs -= 2;
1127 // Finally, use a vanilla vldr.64 for the remaining odd register.
1128 if (NumAlignedDPRCS2Regs)
1129 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1130 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1132 // Last store kills r4.
1133 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1136 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1137 MachineBasicBlock::iterator MI,
1138 const std::vector<CalleeSavedInfo> &CSI,
1139 const TargetRegisterInfo *TRI) const {
1143 MachineFunction &MF = *MBB.getParent();
1144 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1146 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1147 unsigned PushOneOpc = AFI->isThumbFunction() ?
1148 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1149 unsigned FltOpc = ARM::VSTMDDB_UPD;
1150 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1151 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1152 MachineInstr::FrameSetup);
1153 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1154 MachineInstr::FrameSetup);
1155 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1156 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1158 // The code above does not insert spill code for the aligned DPRCS2 registers.
1159 // The stack realignment code will be inserted between the push instructions
1160 // and these spills.
1161 if (NumAlignedDPRCS2Regs)
1162 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1167 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1168 MachineBasicBlock::iterator MI,
1169 const std::vector<CalleeSavedInfo> &CSI,
1170 const TargetRegisterInfo *TRI) const {
1174 MachineFunction &MF = *MBB.getParent();
1175 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1176 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1177 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1179 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1180 // registers. Do that here instead.
1181 if (NumAlignedDPRCS2Regs)
1182 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1184 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1185 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1186 unsigned FltOpc = ARM::VLDMDIA_UPD;
1187 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1188 NumAlignedDPRCS2Regs);
1189 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1190 &isARMArea2Register, 0);
1191 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1192 &isARMArea1Register, 0);
1197 // FIXME: Make generic?
1198 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1199 const ARMBaseInstrInfo &TII) {
1200 unsigned FnSize = 0;
1201 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1202 MBBI != E; ++MBBI) {
1203 const MachineBasicBlock &MBB = *MBBI;
1204 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1206 FnSize += TII.GetInstSizeInBytes(I);
1211 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1212 /// frames and return the stack size limit beyond which some of these
1213 /// instructions will require a scratch register during their expansion later.
1214 // FIXME: Move to TII?
1215 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1216 const TargetFrameLowering *TFI) {
1217 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1218 unsigned Limit = (1 << 12) - 1;
1219 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1220 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1222 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1223 if (!I->getOperand(i).isFI()) continue;
1225 // When using ADDri to get the address of a stack object, 255 is the
1226 // largest offset guaranteed to fit in the immediate offset.
1227 if (I->getOpcode() == ARM::ADDri) {
1228 Limit = std::min(Limit, (1U << 8) - 1);
1232 // Otherwise check the addressing mode.
1233 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1234 case ARMII::AddrMode3:
1235 case ARMII::AddrModeT2_i8:
1236 Limit = std::min(Limit, (1U << 8) - 1);
1238 case ARMII::AddrMode5:
1239 case ARMII::AddrModeT2_i8s4:
1240 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1242 case ARMII::AddrModeT2_i12:
1243 // i12 supports only positive offset so these will be converted to
1244 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1245 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1246 Limit = std::min(Limit, (1U << 8) - 1);
1248 case ARMII::AddrMode4:
1249 case ARMII::AddrMode6:
1250 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1251 // immediate offset for stack references.
1256 break; // At most one FI per instruction
1264 // In functions that realign the stack, it can be an advantage to spill the
1265 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1266 // instructions take alignment hints that can improve performance.
1268 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1269 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1270 if (!SpillAlignedNEONRegs)
1273 // Naked functions don't spill callee-saved registers.
1274 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1278 // We are planning to use NEON instructions vst1 / vld1.
1279 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1282 // Don't bother if the default stack alignment is sufficiently high.
1283 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1286 // Aligned spills require stack realignment.
1287 const ARMBaseRegisterInfo *RegInfo =
1288 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1289 if (!RegInfo->canRealignStack(MF))
1292 // We always spill contiguous d-registers starting from d8. Count how many
1293 // needs spilling. The register allocator will almost always use the
1294 // callee-saved registers in order, but it can happen that there are holes in
1295 // the range. Registers above the hole will be spilled to the standard DPRCS
1297 MachineRegisterInfo &MRI = MF.getRegInfo();
1298 unsigned NumSpills = 0;
1299 for (; NumSpills < 8; ++NumSpills)
1300 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1303 // Don't do this for just one d-register. It's not worth it.
1307 // Spill the first NumSpills D-registers after realigning the stack.
1308 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1310 // A scratch register is required for the vst1 / vld1 instructions.
1311 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1315 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1316 RegScavenger *RS) const {
1317 // This tells PEI to spill the FP as if it is any other callee-save register
1318 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1319 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1320 // to combine multiple loads / stores.
1321 bool CanEliminateFrame = true;
1322 bool CS1Spilled = false;
1323 bool LRSpilled = false;
1324 unsigned NumGPRSpills = 0;
1325 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1326 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1327 const ARMBaseRegisterInfo *RegInfo =
1328 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1329 const ARMBaseInstrInfo &TII =
1330 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1331 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1332 MachineFrameInfo *MFI = MF.getFrameInfo();
1333 MachineRegisterInfo &MRI = MF.getRegInfo();
1334 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1336 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1337 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1338 // since it's not always possible to restore sp from fp in a single
1340 // FIXME: It will be better just to find spare register here.
1341 if (AFI->isThumb2Function() &&
1342 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1343 MRI.setPhysRegUsed(ARM::R4);
1345 if (AFI->isThumb1OnlyFunction()) {
1346 // Spill LR if Thumb1 function uses variable length argument lists.
1347 if (AFI->getArgRegsSaveSize() > 0)
1348 MRI.setPhysRegUsed(ARM::LR);
1350 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1351 // for sure what the stack size will be, but for this, an estimate is good
1352 // enough. If there anything changes it, it'll be a spill, which implies
1353 // we've used all the registers and so R4 is already used, so not marking
1354 // it here will be OK.
1355 // FIXME: It will be better just to find spare register here.
1356 unsigned StackSize = MFI->estimateStackSize(MF);
1357 if (MFI->hasVarSizedObjects() || StackSize > 508)
1358 MRI.setPhysRegUsed(ARM::R4);
1361 // See if we can spill vector registers to aligned stack.
1362 checkNumAlignedDPRCS2Regs(MF);
1364 // Spill the BasePtr if it's used.
1365 if (RegInfo->hasBasePointer(MF))
1366 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1368 // Don't spill FP if the frame can be eliminated. This is determined
1369 // by scanning the callee-save registers to see if any is used.
1370 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1371 for (unsigned i = 0; CSRegs[i]; ++i) {
1372 unsigned Reg = CSRegs[i];
1373 bool Spilled = false;
1374 if (MRI.isPhysRegUsed(Reg)) {
1376 CanEliminateFrame = false;
1379 if (!ARM::GPRRegClass.contains(Reg))
1385 if (!STI.isTargetMachO()) {
1392 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1397 case ARM::R0: case ARM::R1:
1398 case ARM::R2: case ARM::R3:
1399 case ARM::R4: case ARM::R5:
1400 case ARM::R6: case ARM::R7:
1407 if (!STI.isTargetMachO()) {
1408 UnspilledCS1GPRs.push_back(Reg);
1413 case ARM::R0: case ARM::R1:
1414 case ARM::R2: case ARM::R3:
1415 case ARM::R4: case ARM::R5:
1416 case ARM::R6: case ARM::R7:
1418 UnspilledCS1GPRs.push_back(Reg);
1421 UnspilledCS2GPRs.push_back(Reg);
1427 bool ForceLRSpill = false;
1428 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1429 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1430 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1431 // use of BL to implement far jump. If it turns out that it's not needed
1432 // then the branch fix up path will undo it.
1433 if (FnSize >= (1 << 11)) {
1434 CanEliminateFrame = false;
1435 ForceLRSpill = true;
1439 // If any of the stack slot references may be out of range of an immediate
1440 // offset, make sure a register (or a spill slot) is available for the
1441 // register scavenger. Note that if we're indexing off the frame pointer, the
1442 // effective stack size is 4 bytes larger since the FP points to the stack
1443 // slot of the previous FP. Also, if we have variable sized objects in the
1444 // function, stack slot references will often be negative, and some of
1445 // our instructions are positive-offset only, so conservatively consider
1446 // that case to want a spill slot (or register) as well. Similarly, if
1447 // the function adjusts the stack pointer during execution and the
1448 // adjustments aren't already part of our stack size estimate, our offset
1449 // calculations may be off, so be conservative.
1450 // FIXME: We could add logic to be more precise about negative offsets
1451 // and which instructions will need a scratch register for them. Is it
1452 // worth the effort and added fragility?
1455 (MFI->estimateStackSize(MF) +
1456 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1457 estimateRSStackSizeLimit(MF, this)))
1458 || MFI->hasVarSizedObjects()
1459 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1461 bool ExtraCSSpill = false;
1462 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1463 AFI->setHasStackFrame(true);
1465 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1466 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1467 if (!LRSpilled && CS1Spilled) {
1468 MRI.setPhysRegUsed(ARM::LR);
1470 SmallVectorImpl<unsigned>::iterator LRPos;
1471 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1473 if (LRPos != UnspilledCS1GPRs.end())
1474 UnspilledCS1GPRs.erase(LRPos);
1476 ForceLRSpill = false;
1477 ExtraCSSpill = true;
1481 MRI.setPhysRegUsed(FramePtr);
1485 // If stack and double are 8-byte aligned and we are spilling an odd number
1486 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1487 // the integer and double callee save areas.
1488 unsigned TargetAlign = getStackAlignment();
1489 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1490 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1491 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1492 unsigned Reg = UnspilledCS1GPRs[i];
1493 // Don't spill high register if the function is thumb1
1494 if (!AFI->isThumb1OnlyFunction() ||
1495 isARMLowRegister(Reg) || Reg == ARM::LR) {
1496 MRI.setPhysRegUsed(Reg);
1497 if (!MRI.isReserved(Reg))
1498 ExtraCSSpill = true;
1502 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1503 unsigned Reg = UnspilledCS2GPRs.front();
1504 MRI.setPhysRegUsed(Reg);
1505 if (!MRI.isReserved(Reg))
1506 ExtraCSSpill = true;
1510 // Estimate if we might need to scavenge a register at some point in order
1511 // to materialize a stack offset. If so, either spill one additional
1512 // callee-saved register or reserve a special spill slot to facilitate
1513 // register scavenging. Thumb1 needs a spill slot for stack pointer
1514 // adjustments also, even when the frame itself is small.
1515 if (BigStack && !ExtraCSSpill) {
1516 // If any non-reserved CS register isn't spilled, just spill one or two
1517 // extra. That should take care of it!
1518 unsigned NumExtras = TargetAlign / 4;
1519 SmallVector<unsigned, 2> Extras;
1520 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1521 unsigned Reg = UnspilledCS1GPRs.back();
1522 UnspilledCS1GPRs.pop_back();
1523 if (!MRI.isReserved(Reg) &&
1524 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1526 Extras.push_back(Reg);
1530 // For non-Thumb1 functions, also check for hi-reg CS registers
1531 if (!AFI->isThumb1OnlyFunction()) {
1532 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1533 unsigned Reg = UnspilledCS2GPRs.back();
1534 UnspilledCS2GPRs.pop_back();
1535 if (!MRI.isReserved(Reg)) {
1536 Extras.push_back(Reg);
1541 if (Extras.size() && NumExtras == 0) {
1542 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1543 MRI.setPhysRegUsed(Extras[i]);
1545 } else if (!AFI->isThumb1OnlyFunction()) {
1546 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1547 // closest to SP or frame pointer.
1548 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1549 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1557 MRI.setPhysRegUsed(ARM::LR);
1558 AFI->setLRIsSpilledForFarJump(true);
1563 void ARMFrameLowering::
1564 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1565 MachineBasicBlock::iterator I) const {
1566 const ARMBaseInstrInfo &TII =
1567 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1568 if (!hasReservedCallFrame(MF)) {
1569 // If we have alloca, convert as follows:
1570 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1571 // ADJCALLSTACKUP -> add, sp, sp, amount
1572 MachineInstr *Old = I;
1573 DebugLoc dl = Old->getDebugLoc();
1574 unsigned Amount = Old->getOperand(0).getImm();
1576 // We need to keep the stack aligned properly. To do this, we round the
1577 // amount of space needed for the outgoing arguments up to the next
1578 // alignment boundary.
1579 unsigned Align = getStackAlignment();
1580 Amount = (Amount+Align-1)/Align*Align;
1582 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1583 assert(!AFI->isThumb1OnlyFunction() &&
1584 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1585 bool isARM = !AFI->isThumbFunction();
1587 // Replace the pseudo instruction with a new instruction...
1588 unsigned Opc = Old->getOpcode();
1589 int PIdx = Old->findFirstPredOperandIdx();
1590 ARMCC::CondCodes Pred = (PIdx == -1)
1591 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1592 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1593 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1594 unsigned PredReg = Old->getOperand(2).getReg();
1595 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1598 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1599 unsigned PredReg = Old->getOperand(3).getReg();
1600 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1601 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,