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 CFAOffset -= ArgRegsSaveSize;
183 unsigned CFIIndex = MMI.addFrameInst(
184 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
185 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
186 .addCFIIndex(CFIIndex);
189 if (!AFI->hasStackFrame()) {
190 if (NumBytes - ArgRegsSaveSize != 0) {
191 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
192 MachineInstr::FrameSetup);
193 CFAOffset -= NumBytes - ArgRegsSaveSize;
194 unsigned CFIIndex = MMI.addFrameInst(
195 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
196 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
197 .addCFIIndex(CFIIndex);
202 // Determine spill area sizes.
203 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
204 unsigned Reg = CSI[i].getReg();
205 int FI = CSI[i].getFrameIdx();
212 if (STI.isTargetMachO()) {
227 FramePtrSpillFI = FI;
231 // This is a DPR. Exclude the aligned DPRCS2 spills.
234 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
240 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
243 GPRCS1Push = LastPush = MBBI++;
245 // Determine starting offsets of spill areas.
246 bool HasFP = hasFP(MF);
247 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
248 + GPRCS2Size + DPRCSSize);
249 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
250 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
251 int FramePtrOffsetInPush = 0;
253 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
254 + GPRCS1Size + ArgRegsSaveSize;
255 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
258 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
259 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
260 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
264 GPRCS2Push = LastPush = MBBI++;
269 // Since vpush register list cannot have gaps, there may be multiple vpush
270 // instructions in the prologue.
271 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
275 // Move past the aligned DPRCS2 area.
276 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
277 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
278 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
279 // leaves the stack pointer pointing to the DPRCS2 area.
281 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
282 NumBytes += MFI->getObjectOffset(D8SpillFI);
284 NumBytes = DPRCSOffset;
286 unsigned adjustedGPRCS1Size = GPRCS1Size;
288 // Adjust SP after all the callee-save spills.
289 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
290 if (LastPush == GPRCS1Push) {
291 FramePtrOffsetInPush += NumBytes;
292 adjustedGPRCS1Size += NumBytes;
296 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
297 MachineInstr::FrameSetup);
300 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
301 // Note it's not safe to do this in Thumb2 mode because it would have
302 // taken two instructions:
305 // If an interrupt is taken between the two instructions, then sp is in
306 // an inconsistent state (pointing to the middle of callee-saved area).
307 // The interrupt handler can end up clobbering the registers.
308 AFI->setShouldRestoreSPFromFP(true);
311 if (adjustedGPRCS1Size > 0) {
312 CFAOffset -= adjustedGPRCS1Size;
313 unsigned CFIIndex = MMI.addFrameInst(
314 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
315 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
316 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
317 .addCFIIndex(CFIIndex);
318 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
319 E = CSI.end(); I != E; ++I) {
320 unsigned Reg = I->getReg();
321 int FI = I->getFrameIdx();
328 if (STI.isTargetMachO())
340 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
341 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
342 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
343 .addCFIIndex(CFIIndex);
349 // Set FP to point to the stack slot that contains the previous FP.
350 // For iOS, FP is R7, which has now been stored in spill area 1.
351 // Otherwise, if this is not iOS, all the callee-saved registers go
352 // into spill area 1, including the FP in R11. In either case, it
353 // is in area one and the adjustment needs to take place just after
356 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
357 FramePtr, ARM::SP, FramePtrOffsetInPush,
358 MachineInstr::FrameSetup);
359 if (FramePtrOffsetInPush) {
360 CFAOffset += FramePtrOffsetInPush;
361 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
362 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
363 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
364 .addCFIIndex(CFIIndex);
368 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
369 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
370 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
371 .addCFIIndex(CFIIndex);
375 if (GPRCS2Size > 0) {
376 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
378 CFAOffset -= GPRCS2Size;
379 unsigned CFIIndex = MMI.addFrameInst(
380 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
381 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
382 .addCFIIndex(CFIIndex);
384 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
385 E = CSI.end(); I != E; ++I) {
386 unsigned Reg = I->getReg();
387 int FI = I->getFrameIdx();
394 if (STI.isTargetMachO()) {
395 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
396 unsigned Offset = MFI->getObjectOffset(FI);
397 unsigned CFIIndex = MMI.addFrameInst(
398 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
399 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
400 .addCFIIndex(CFIIndex);
408 // Since vpush register list cannot have gaps, there may be multiple vpush
409 // instructions in the prologue.
411 MachineBasicBlock::iterator Push = DPRCSPush++;
413 CFAOffset -= sizeOfSPAdjustment(Push);;
414 unsigned CFIIndex = MMI.addFrameInst(
415 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
416 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
417 .addCFIIndex(CFIIndex);
419 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
421 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
422 E = CSI.end(); I != E; ++I) {
423 unsigned Reg = I->getReg();
424 int FI = I->getFrameIdx();
425 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
426 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
427 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
428 unsigned Offset = MFI->getObjectOffset(FI);
429 unsigned CFIIndex = MMI.addFrameInst(
430 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
431 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
432 .addCFIIndex(CFIIndex);
439 CFAOffset -= NumBytes;
440 unsigned CFIIndex = MMI.addFrameInst(
441 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
442 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
443 .addCFIIndex(CFIIndex);
447 if (STI.isTargetELF() && hasFP(MF))
448 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
449 AFI->getFramePtrSpillOffset());
451 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
452 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
453 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
455 // If we need dynamic stack realignment, do it here. Be paranoid and make
456 // sure if we also have VLAs, we have a base pointer for frame access.
457 // If aligned NEON registers were spilled, the stack has already been
459 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
460 unsigned MaxAlign = MFI->getMaxAlignment();
461 assert (!AFI->isThumb1OnlyFunction());
462 if (!AFI->isThumbFunction()) {
463 // Emit bic sp, sp, MaxAlign
464 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
465 TII.get(ARM::BICri), ARM::SP)
466 .addReg(ARM::SP, RegState::Kill)
467 .addImm(MaxAlign-1)));
469 // We cannot use sp as source/dest register here, thus we're emitting the
470 // following sequence:
472 // bic r4, r4, MaxAlign
474 // FIXME: It will be better just to find spare register here.
475 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
476 .addReg(ARM::SP, RegState::Kill));
477 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
478 TII.get(ARM::t2BICri), ARM::R4)
479 .addReg(ARM::R4, RegState::Kill)
480 .addImm(MaxAlign-1)));
481 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
482 .addReg(ARM::R4, RegState::Kill));
485 AFI->setShouldRestoreSPFromFP(true);
488 // If we need a base pointer, set it up here. It's whatever the value
489 // of the stack pointer is at this point. Any variable size objects
490 // will be allocated after this, so we can still use the base pointer
491 // to reference locals.
492 // FIXME: Clarify FrameSetup flags here.
493 if (RegInfo->hasBasePointer(MF)) {
495 BuildMI(MBB, MBBI, dl,
496 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
498 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
500 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
501 RegInfo->getBaseRegister())
505 // If the frame has variable sized objects then the epilogue must restore
506 // the sp from fp. We can assume there's an FP here since hasFP already
507 // checks for hasVarSizedObjects.
508 if (MFI->hasVarSizedObjects())
509 AFI->setShouldRestoreSPFromFP(true);
512 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
513 MachineBasicBlock &MBB) const {
514 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
515 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
516 unsigned RetOpcode = MBBI->getOpcode();
517 DebugLoc dl = MBBI->getDebugLoc();
518 MachineFrameInfo *MFI = MF.getFrameInfo();
519 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
520 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
521 const ARMBaseInstrInfo &TII =
522 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
523 assert(!AFI->isThumb1OnlyFunction() &&
524 "This emitEpilogue does not support Thumb1!");
525 bool isARM = !AFI->isThumbFunction();
527 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
528 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
529 int NumBytes = (int)MFI->getStackSize();
530 unsigned FramePtr = RegInfo->getFrameRegister(MF);
532 // All calls are tail calls in GHC calling conv, and functions have no
533 // prologue/epilogue.
534 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
537 if (!AFI->hasStackFrame()) {
538 if (NumBytes - ArgRegsSaveSize != 0)
539 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
541 // Unwind MBBI to point to first LDR / VLDRD.
542 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
543 if (MBBI != MBB.begin()) {
546 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
547 if (!isCSRestore(MBBI, TII, CSRegs))
551 // Move SP to start of FP callee save spill area.
552 NumBytes -= (ArgRegsSaveSize +
553 AFI->getGPRCalleeSavedArea1Size() +
554 AFI->getGPRCalleeSavedArea2Size() +
555 AFI->getDPRCalleeSavedAreaSize());
557 // Reset SP based on frame pointer only if the stack frame extends beyond
558 // frame pointer stack slot or target is ELF and the function has FP.
559 if (AFI->shouldRestoreSPFromFP()) {
560 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
563 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
566 // It's not possible to restore SP from FP in a single instruction.
567 // For iOS, this looks like:
570 // This is bad, if an interrupt is taken after the mov, sp is in an
571 // inconsistent state.
572 // Use the first callee-saved register as a scratch register.
573 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
574 "No scratch register to restore SP from FP!");
575 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
577 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
584 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
585 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
587 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
591 } else if (NumBytes &&
592 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
593 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
595 // Increment past our save areas.
596 if (AFI->getDPRCalleeSavedAreaSize()) {
598 // Since vpop register list cannot have gaps, there may be multiple vpop
599 // instructions in the epilogue.
600 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
603 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
604 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
607 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
608 // Tail call return: adjust the stack pointer and jump to callee.
609 MBBI = MBB.getLastNonDebugInstr();
610 MachineOperand &JumpTarget = MBBI->getOperand(0);
612 // Jump to label or value in register.
613 if (RetOpcode == ARM::TCRETURNdi) {
614 unsigned TCOpcode = STI.isThumb() ?
615 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
617 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
618 if (JumpTarget.isGlobal())
619 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
620 JumpTarget.getTargetFlags());
622 assert(JumpTarget.isSymbol());
623 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
624 JumpTarget.getTargetFlags());
627 // Add the default predicate in Thumb mode.
628 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
629 } else if (RetOpcode == ARM::TCRETURNri) {
630 BuildMI(MBB, MBBI, dl,
631 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
632 addReg(JumpTarget.getReg(), RegState::Kill);
635 MachineInstr *NewMI = std::prev(MBBI);
636 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
637 NewMI->addOperand(MBBI->getOperand(i));
639 // Delete the pseudo instruction TCRETURN.
645 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
648 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
649 /// debug info. It's the same as what we use for resolving the code-gen
650 /// references for now. FIXME: This can go wrong when references are
651 /// SP-relative and simple call frames aren't used.
653 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
654 unsigned &FrameReg) const {
655 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
659 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
660 int FI, unsigned &FrameReg,
662 const MachineFrameInfo *MFI = MF.getFrameInfo();
663 const ARMBaseRegisterInfo *RegInfo =
664 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
665 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
666 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
667 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
668 bool isFixed = MFI->isFixedObjectIndex(FI);
673 // SP can move around if there are allocas. We may also lose track of SP
674 // when emergency spilling inside a non-reserved call frame setup.
675 bool hasMovingSP = !hasReservedCallFrame(MF);
677 // When dynamically realigning the stack, use the frame pointer for
678 // parameters, and the stack/base pointer for locals.
679 if (RegInfo->needsStackRealignment(MF)) {
680 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
682 FrameReg = RegInfo->getFrameRegister(MF);
684 } else if (hasMovingSP) {
685 assert(RegInfo->hasBasePointer(MF) &&
686 "VLAs and dynamic stack alignment, but missing base pointer!");
687 FrameReg = RegInfo->getBaseRegister();
692 // If there is a frame pointer, use it when we can.
693 if (hasFP(MF) && AFI->hasStackFrame()) {
694 // Use frame pointer to reference fixed objects. Use it for locals if
695 // there are VLAs (and thus the SP isn't reliable as a base).
696 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
697 FrameReg = RegInfo->getFrameRegister(MF);
699 } else if (hasMovingSP) {
700 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
701 if (AFI->isThumb2Function()) {
702 // Try to use the frame pointer if we can, else use the base pointer
703 // since it's available. This is handy for the emergency spill slot, in
705 if (FPOffset >= -255 && FPOffset < 0) {
706 FrameReg = RegInfo->getFrameRegister(MF);
710 } else if (AFI->isThumb2Function()) {
711 // Use add <rd>, sp, #<imm8>
712 // ldr <rd>, [sp, #<imm8>]
713 // if at all possible to save space.
714 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
716 // In Thumb2 mode, the negative offset is very limited. Try to avoid
717 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
718 if (FPOffset >= -255 && FPOffset < 0) {
719 FrameReg = RegInfo->getFrameRegister(MF);
722 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
723 // Otherwise, use SP or FP, whichever is closer to the stack slot.
724 FrameReg = RegInfo->getFrameRegister(MF);
728 // Use the base pointer if we have one.
729 if (RegInfo->hasBasePointer(MF))
730 FrameReg = RegInfo->getBaseRegister();
734 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
737 return getFrameIndexReference(MF, FI, FrameReg);
740 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
741 MachineBasicBlock::iterator MI,
742 const std::vector<CalleeSavedInfo> &CSI,
743 unsigned StmOpc, unsigned StrOpc,
745 bool(*Func)(unsigned, bool),
746 unsigned NumAlignedDPRCS2Regs,
747 unsigned MIFlags) const {
748 MachineFunction &MF = *MBB.getParent();
749 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
752 if (MI != MBB.end()) DL = MI->getDebugLoc();
754 SmallVector<std::pair<unsigned,bool>, 4> Regs;
755 unsigned i = CSI.size();
757 unsigned LastReg = 0;
758 for (; i != 0; --i) {
759 unsigned Reg = CSI[i-1].getReg();
760 if (!(Func)(Reg, STI.isTargetMachO())) continue;
762 // D-registers in the aligned area DPRCS2 are NOT spilled here.
763 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
766 // Add the callee-saved register as live-in unless it's LR and
767 // @llvm.returnaddress is called. If LR is returned for
768 // @llvm.returnaddress then it's already added to the function and
769 // entry block live-in sets.
771 if (Reg == ARM::LR) {
772 if (MF.getFrameInfo()->isReturnAddressTaken() &&
773 MF.getRegInfo().isLiveIn(Reg))
780 // If NoGap is true, push consecutive registers and then leave the rest
781 // for other instructions. e.g.
782 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
783 if (NoGap && LastReg && LastReg != Reg-1)
786 Regs.push_back(std::make_pair(Reg, isKill));
791 if (Regs.size() > 1 || StrOpc== 0) {
792 MachineInstrBuilder MIB =
793 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
794 .addReg(ARM::SP).setMIFlags(MIFlags));
795 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
796 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
797 } else if (Regs.size() == 1) {
798 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
800 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
801 .addReg(ARM::SP).setMIFlags(MIFlags)
807 // Put any subsequent vpush instructions before this one: they will refer to
808 // higher register numbers so need to be pushed first in order to preserve
814 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
815 MachineBasicBlock::iterator MI,
816 const std::vector<CalleeSavedInfo> &CSI,
817 unsigned LdmOpc, unsigned LdrOpc,
818 bool isVarArg, bool NoGap,
819 bool(*Func)(unsigned, bool),
820 unsigned NumAlignedDPRCS2Regs) const {
821 MachineFunction &MF = *MBB.getParent();
822 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
824 DebugLoc DL = MI->getDebugLoc();
825 unsigned RetOpcode = MI->getOpcode();
826 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
827 RetOpcode == ARM::TCRETURNri);
829 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
831 SmallVector<unsigned, 4> Regs;
832 unsigned i = CSI.size();
834 unsigned LastReg = 0;
835 bool DeleteRet = false;
836 for (; i != 0; --i) {
837 unsigned Reg = CSI[i-1].getReg();
838 if (!(Func)(Reg, STI.isTargetMachO())) continue;
840 // The aligned reloads from area DPRCS2 are not inserted here.
841 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
844 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
847 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
848 // Fold the return instruction into the LDM.
852 // If NoGap is true, pop consecutive registers and then leave the rest
853 // for other instructions. e.g.
854 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
855 if (NoGap && LastReg && LastReg != Reg-1)
864 if (Regs.size() > 1 || LdrOpc == 0) {
865 MachineInstrBuilder MIB =
866 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
868 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
869 MIB.addReg(Regs[i], getDefRegState(true));
871 MIB.copyImplicitOps(&*MI);
872 MI->eraseFromParent();
875 } else if (Regs.size() == 1) {
876 // If we adjusted the reg to PC from LR above, switch it back here. We
877 // only do that for LDM.
878 if (Regs[0] == ARM::PC)
880 MachineInstrBuilder MIB =
881 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
882 .addReg(ARM::SP, RegState::Define)
884 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
885 // that refactoring is complete (eventually).
886 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
888 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
895 // Put any subsequent vpop instructions after this one: they will refer to
896 // higher register numbers so need to be popped afterwards.
901 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
902 /// starting from d8. Also insert stack realignment code and leave the stack
903 /// pointer pointing to the d8 spill slot.
904 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
905 MachineBasicBlock::iterator MI,
906 unsigned NumAlignedDPRCS2Regs,
907 const std::vector<CalleeSavedInfo> &CSI,
908 const TargetRegisterInfo *TRI) {
909 MachineFunction &MF = *MBB.getParent();
910 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
911 DebugLoc DL = MI->getDebugLoc();
912 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
913 MachineFrameInfo &MFI = *MF.getFrameInfo();
915 // Mark the D-register spill slots as properly aligned. Since MFI computes
916 // stack slot layout backwards, this can actually mean that the d-reg stack
917 // slot offsets can be wrong. The offset for d8 will always be correct.
918 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
919 unsigned DNum = CSI[i].getReg() - ARM::D8;
922 int FI = CSI[i].getFrameIdx();
923 // The even-numbered registers will be 16-byte aligned, the odd-numbered
924 // registers will be 8-byte aligned.
925 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
927 // The stack slot for D8 needs to be maximally aligned because this is
928 // actually the point where we align the stack pointer. MachineFrameInfo
929 // computes all offsets relative to the incoming stack pointer which is a
930 // bit weird when realigning the stack. Any extra padding for this
931 // over-alignment is not realized because the code inserted below adjusts
932 // the stack pointer by numregs * 8 before aligning the stack pointer.
934 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
937 // Move the stack pointer to the d8 spill slot, and align it at the same
938 // time. Leave the stack slot address in the scratch register r4.
940 // sub r4, sp, #numregs * 8
941 // bic r4, r4, #align - 1
944 bool isThumb = AFI->isThumbFunction();
945 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
946 AFI->setShouldRestoreSPFromFP(true);
948 // sub r4, sp, #numregs * 8
949 // The immediate is <= 64, so it doesn't need any special encoding.
950 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
951 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
953 .addImm(8 * NumAlignedDPRCS2Regs)));
955 // bic r4, r4, #align-1
956 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
957 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
958 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
959 .addReg(ARM::R4, RegState::Kill)
960 .addImm(MaxAlign - 1)));
963 // The stack pointer must be adjusted before spilling anything, otherwise
964 // the stack slots could be clobbered by an interrupt handler.
965 // Leave r4 live, it is used below.
966 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
967 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
969 MIB = AddDefaultPred(MIB);
973 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
974 // r4 holds the stack slot address.
975 unsigned NextReg = ARM::D8;
977 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
978 // The writeback is only needed when emitting two vst1.64 instructions.
979 if (NumAlignedDPRCS2Regs >= 6) {
980 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
982 MBB.addLiveIn(SupReg);
983 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
985 .addReg(ARM::R4, RegState::Kill).addImm(16)
987 .addReg(SupReg, RegState::ImplicitKill));
989 NumAlignedDPRCS2Regs -= 4;
992 // We won't modify r4 beyond this point. It currently points to the next
993 // register to be spilled.
994 unsigned R4BaseReg = NextReg;
996 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
997 if (NumAlignedDPRCS2Regs >= 4) {
998 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1000 MBB.addLiveIn(SupReg);
1001 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1002 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1003 .addReg(SupReg, RegState::ImplicitKill));
1005 NumAlignedDPRCS2Regs -= 4;
1008 // 16-byte aligned vst1.64 with 2 d-regs.
1009 if (NumAlignedDPRCS2Regs >= 2) {
1010 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1012 MBB.addLiveIn(SupReg);
1013 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1014 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1016 NumAlignedDPRCS2Regs -= 2;
1019 // Finally, use a vanilla vstr.64 for the odd last register.
1020 if (NumAlignedDPRCS2Regs) {
1021 MBB.addLiveIn(NextReg);
1022 // vstr.64 uses addrmode5 which has an offset scale of 4.
1023 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1025 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1028 // The last spill instruction inserted should kill the scratch register r4.
1029 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1032 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1033 /// iterator to the following instruction.
1034 static MachineBasicBlock::iterator
1035 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1036 unsigned NumAlignedDPRCS2Regs) {
1037 // sub r4, sp, #numregs * 8
1038 // bic r4, r4, #align - 1
1041 assert(MI->mayStore() && "Expecting spill instruction");
1043 // These switches all fall through.
1044 switch(NumAlignedDPRCS2Regs) {
1047 assert(MI->mayStore() && "Expecting spill instruction");
1050 assert(MI->mayStore() && "Expecting spill instruction");
1054 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1060 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1061 /// starting from d8. These instructions are assumed to execute while the
1062 /// stack is still aligned, unlike the code inserted by emitPopInst.
1063 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1064 MachineBasicBlock::iterator MI,
1065 unsigned NumAlignedDPRCS2Regs,
1066 const std::vector<CalleeSavedInfo> &CSI,
1067 const TargetRegisterInfo *TRI) {
1068 MachineFunction &MF = *MBB.getParent();
1069 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1070 DebugLoc DL = MI->getDebugLoc();
1071 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1073 // Find the frame index assigned to d8.
1075 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1076 if (CSI[i].getReg() == ARM::D8) {
1077 D8SpillFI = CSI[i].getFrameIdx();
1081 // Materialize the address of the d8 spill slot into the scratch register r4.
1082 // This can be fairly complicated if the stack frame is large, so just use
1083 // the normal frame index elimination mechanism to do it. This code runs as
1084 // the initial part of the epilog where the stack and base pointers haven't
1085 // been changed yet.
1086 bool isThumb = AFI->isThumbFunction();
1087 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1089 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1090 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1091 .addFrameIndex(D8SpillFI).addImm(0)));
1093 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1094 unsigned NextReg = ARM::D8;
1096 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1097 if (NumAlignedDPRCS2Regs >= 6) {
1098 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1099 &ARM::QQPRRegClass);
1100 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1101 .addReg(ARM::R4, RegState::Define)
1102 .addReg(ARM::R4, RegState::Kill).addImm(16)
1103 .addReg(SupReg, RegState::ImplicitDefine));
1105 NumAlignedDPRCS2Regs -= 4;
1108 // We won't modify r4 beyond this point. It currently points to the next
1109 // register to be spilled.
1110 unsigned R4BaseReg = NextReg;
1112 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1113 if (NumAlignedDPRCS2Regs >= 4) {
1114 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1115 &ARM::QQPRRegClass);
1116 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1117 .addReg(ARM::R4).addImm(16)
1118 .addReg(SupReg, RegState::ImplicitDefine));
1120 NumAlignedDPRCS2Regs -= 4;
1123 // 16-byte aligned vld1.64 with 2 d-regs.
1124 if (NumAlignedDPRCS2Regs >= 2) {
1125 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1127 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1128 .addReg(ARM::R4).addImm(16));
1130 NumAlignedDPRCS2Regs -= 2;
1133 // Finally, use a vanilla vldr.64 for the remaining odd register.
1134 if (NumAlignedDPRCS2Regs)
1135 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1136 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1138 // Last store kills r4.
1139 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1142 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1143 MachineBasicBlock::iterator MI,
1144 const std::vector<CalleeSavedInfo> &CSI,
1145 const TargetRegisterInfo *TRI) const {
1149 MachineFunction &MF = *MBB.getParent();
1150 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1152 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1153 unsigned PushOneOpc = AFI->isThumbFunction() ?
1154 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1155 unsigned FltOpc = ARM::VSTMDDB_UPD;
1156 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1157 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1158 MachineInstr::FrameSetup);
1159 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1160 MachineInstr::FrameSetup);
1161 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1162 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1164 // The code above does not insert spill code for the aligned DPRCS2 registers.
1165 // The stack realignment code will be inserted between the push instructions
1166 // and these spills.
1167 if (NumAlignedDPRCS2Regs)
1168 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1173 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1174 MachineBasicBlock::iterator MI,
1175 const std::vector<CalleeSavedInfo> &CSI,
1176 const TargetRegisterInfo *TRI) const {
1180 MachineFunction &MF = *MBB.getParent();
1181 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1182 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1183 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1185 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1186 // registers. Do that here instead.
1187 if (NumAlignedDPRCS2Regs)
1188 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1190 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1191 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1192 unsigned FltOpc = ARM::VLDMDIA_UPD;
1193 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1194 NumAlignedDPRCS2Regs);
1195 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1196 &isARMArea2Register, 0);
1197 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1198 &isARMArea1Register, 0);
1203 // FIXME: Make generic?
1204 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1205 const ARMBaseInstrInfo &TII) {
1206 unsigned FnSize = 0;
1207 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1208 MBBI != E; ++MBBI) {
1209 const MachineBasicBlock &MBB = *MBBI;
1210 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1212 FnSize += TII.GetInstSizeInBytes(I);
1217 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1218 /// frames and return the stack size limit beyond which some of these
1219 /// instructions will require a scratch register during their expansion later.
1220 // FIXME: Move to TII?
1221 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1222 const TargetFrameLowering *TFI) {
1223 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1224 unsigned Limit = (1 << 12) - 1;
1225 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1226 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1228 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1229 if (!I->getOperand(i).isFI()) continue;
1231 // When using ADDri to get the address of a stack object, 255 is the
1232 // largest offset guaranteed to fit in the immediate offset.
1233 if (I->getOpcode() == ARM::ADDri) {
1234 Limit = std::min(Limit, (1U << 8) - 1);
1238 // Otherwise check the addressing mode.
1239 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1240 case ARMII::AddrMode3:
1241 case ARMII::AddrModeT2_i8:
1242 Limit = std::min(Limit, (1U << 8) - 1);
1244 case ARMII::AddrMode5:
1245 case ARMII::AddrModeT2_i8s4:
1246 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1248 case ARMII::AddrModeT2_i12:
1249 // i12 supports only positive offset so these will be converted to
1250 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1251 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1252 Limit = std::min(Limit, (1U << 8) - 1);
1254 case ARMII::AddrMode4:
1255 case ARMII::AddrMode6:
1256 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1257 // immediate offset for stack references.
1262 break; // At most one FI per instruction
1270 // In functions that realign the stack, it can be an advantage to spill the
1271 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1272 // instructions take alignment hints that can improve performance.
1274 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1275 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1276 if (!SpillAlignedNEONRegs)
1279 // Naked functions don't spill callee-saved registers.
1280 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1284 // We are planning to use NEON instructions vst1 / vld1.
1285 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1288 // Don't bother if the default stack alignment is sufficiently high.
1289 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1292 // Aligned spills require stack realignment.
1293 const ARMBaseRegisterInfo *RegInfo =
1294 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1295 if (!RegInfo->canRealignStack(MF))
1298 // We always spill contiguous d-registers starting from d8. Count how many
1299 // needs spilling. The register allocator will almost always use the
1300 // callee-saved registers in order, but it can happen that there are holes in
1301 // the range. Registers above the hole will be spilled to the standard DPRCS
1303 MachineRegisterInfo &MRI = MF.getRegInfo();
1304 unsigned NumSpills = 0;
1305 for (; NumSpills < 8; ++NumSpills)
1306 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1309 // Don't do this for just one d-register. It's not worth it.
1313 // Spill the first NumSpills D-registers after realigning the stack.
1314 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1316 // A scratch register is required for the vst1 / vld1 instructions.
1317 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1321 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1322 RegScavenger *RS) const {
1323 // This tells PEI to spill the FP as if it is any other callee-save register
1324 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1325 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1326 // to combine multiple loads / stores.
1327 bool CanEliminateFrame = true;
1328 bool CS1Spilled = false;
1329 bool LRSpilled = false;
1330 unsigned NumGPRSpills = 0;
1331 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1332 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1333 const ARMBaseRegisterInfo *RegInfo =
1334 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1335 const ARMBaseInstrInfo &TII =
1336 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1337 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1338 MachineFrameInfo *MFI = MF.getFrameInfo();
1339 MachineRegisterInfo &MRI = MF.getRegInfo();
1340 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1342 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1343 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1344 // since it's not always possible to restore sp from fp in a single
1346 // FIXME: It will be better just to find spare register here.
1347 if (AFI->isThumb2Function() &&
1348 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1349 MRI.setPhysRegUsed(ARM::R4);
1351 if (AFI->isThumb1OnlyFunction()) {
1352 // Spill LR if Thumb1 function uses variable length argument lists.
1353 if (AFI->getArgRegsSaveSize() > 0)
1354 MRI.setPhysRegUsed(ARM::LR);
1356 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1357 // for sure what the stack size will be, but for this, an estimate is good
1358 // enough. If there anything changes it, it'll be a spill, which implies
1359 // we've used all the registers and so R4 is already used, so not marking
1360 // it here will be OK.
1361 // FIXME: It will be better just to find spare register here.
1362 unsigned StackSize = MFI->estimateStackSize(MF);
1363 if (MFI->hasVarSizedObjects() || StackSize > 508)
1364 MRI.setPhysRegUsed(ARM::R4);
1367 // See if we can spill vector registers to aligned stack.
1368 checkNumAlignedDPRCS2Regs(MF);
1370 // Spill the BasePtr if it's used.
1371 if (RegInfo->hasBasePointer(MF))
1372 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1374 // Don't spill FP if the frame can be eliminated. This is determined
1375 // by scanning the callee-save registers to see if any is used.
1376 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1377 for (unsigned i = 0; CSRegs[i]; ++i) {
1378 unsigned Reg = CSRegs[i];
1379 bool Spilled = false;
1380 if (MRI.isPhysRegUsed(Reg)) {
1382 CanEliminateFrame = false;
1385 if (!ARM::GPRRegClass.contains(Reg))
1391 if (!STI.isTargetMachO()) {
1398 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1403 case ARM::R0: case ARM::R1:
1404 case ARM::R2: case ARM::R3:
1405 case ARM::R4: case ARM::R5:
1406 case ARM::R6: case ARM::R7:
1413 if (!STI.isTargetMachO()) {
1414 UnspilledCS1GPRs.push_back(Reg);
1419 case ARM::R0: case ARM::R1:
1420 case ARM::R2: case ARM::R3:
1421 case ARM::R4: case ARM::R5:
1422 case ARM::R6: case ARM::R7:
1424 UnspilledCS1GPRs.push_back(Reg);
1427 UnspilledCS2GPRs.push_back(Reg);
1433 bool ForceLRSpill = false;
1434 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1435 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1436 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1437 // use of BL to implement far jump. If it turns out that it's not needed
1438 // then the branch fix up path will undo it.
1439 if (FnSize >= (1 << 11)) {
1440 CanEliminateFrame = false;
1441 ForceLRSpill = true;
1445 // If any of the stack slot references may be out of range of an immediate
1446 // offset, make sure a register (or a spill slot) is available for the
1447 // register scavenger. Note that if we're indexing off the frame pointer, the
1448 // effective stack size is 4 bytes larger since the FP points to the stack
1449 // slot of the previous FP. Also, if we have variable sized objects in the
1450 // function, stack slot references will often be negative, and some of
1451 // our instructions are positive-offset only, so conservatively consider
1452 // that case to want a spill slot (or register) as well. Similarly, if
1453 // the function adjusts the stack pointer during execution and the
1454 // adjustments aren't already part of our stack size estimate, our offset
1455 // calculations may be off, so be conservative.
1456 // FIXME: We could add logic to be more precise about negative offsets
1457 // and which instructions will need a scratch register for them. Is it
1458 // worth the effort and added fragility?
1461 (MFI->estimateStackSize(MF) +
1462 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1463 estimateRSStackSizeLimit(MF, this)))
1464 || MFI->hasVarSizedObjects()
1465 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1467 bool ExtraCSSpill = false;
1468 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1469 AFI->setHasStackFrame(true);
1471 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1472 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1473 if (!LRSpilled && CS1Spilled) {
1474 MRI.setPhysRegUsed(ARM::LR);
1476 SmallVectorImpl<unsigned>::iterator LRPos;
1477 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1479 if (LRPos != UnspilledCS1GPRs.end())
1480 UnspilledCS1GPRs.erase(LRPos);
1482 ForceLRSpill = false;
1483 ExtraCSSpill = true;
1487 MRI.setPhysRegUsed(FramePtr);
1491 // If stack and double are 8-byte aligned and we are spilling an odd number
1492 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1493 // the integer and double callee save areas.
1494 unsigned TargetAlign = getStackAlignment();
1495 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1496 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1497 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1498 unsigned Reg = UnspilledCS1GPRs[i];
1499 // Don't spill high register if the function is thumb1
1500 if (!AFI->isThumb1OnlyFunction() ||
1501 isARMLowRegister(Reg) || Reg == ARM::LR) {
1502 MRI.setPhysRegUsed(Reg);
1503 if (!MRI.isReserved(Reg))
1504 ExtraCSSpill = true;
1508 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1509 unsigned Reg = UnspilledCS2GPRs.front();
1510 MRI.setPhysRegUsed(Reg);
1511 if (!MRI.isReserved(Reg))
1512 ExtraCSSpill = true;
1516 // Estimate if we might need to scavenge a register at some point in order
1517 // to materialize a stack offset. If so, either spill one additional
1518 // callee-saved register or reserve a special spill slot to facilitate
1519 // register scavenging. Thumb1 needs a spill slot for stack pointer
1520 // adjustments also, even when the frame itself is small.
1521 if (BigStack && !ExtraCSSpill) {
1522 // If any non-reserved CS register isn't spilled, just spill one or two
1523 // extra. That should take care of it!
1524 unsigned NumExtras = TargetAlign / 4;
1525 SmallVector<unsigned, 2> Extras;
1526 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1527 unsigned Reg = UnspilledCS1GPRs.back();
1528 UnspilledCS1GPRs.pop_back();
1529 if (!MRI.isReserved(Reg) &&
1530 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1532 Extras.push_back(Reg);
1536 // For non-Thumb1 functions, also check for hi-reg CS registers
1537 if (!AFI->isThumb1OnlyFunction()) {
1538 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1539 unsigned Reg = UnspilledCS2GPRs.back();
1540 UnspilledCS2GPRs.pop_back();
1541 if (!MRI.isReserved(Reg)) {
1542 Extras.push_back(Reg);
1547 if (Extras.size() && NumExtras == 0) {
1548 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1549 MRI.setPhysRegUsed(Extras[i]);
1551 } else if (!AFI->isThumb1OnlyFunction()) {
1552 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1553 // closest to SP or frame pointer.
1554 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1555 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1563 MRI.setPhysRegUsed(ARM::LR);
1564 AFI->setLRIsSpilledForFarJump(true);
1569 void ARMFrameLowering::
1570 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1571 MachineBasicBlock::iterator I) const {
1572 const ARMBaseInstrInfo &TII =
1573 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1574 if (!hasReservedCallFrame(MF)) {
1575 // If we have alloca, convert as follows:
1576 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1577 // ADJCALLSTACKUP -> add, sp, sp, amount
1578 MachineInstr *Old = I;
1579 DebugLoc dl = Old->getDebugLoc();
1580 unsigned Amount = Old->getOperand(0).getImm();
1582 // We need to keep the stack aligned properly. To do this, we round the
1583 // amount of space needed for the outgoing arguments up to the next
1584 // alignment boundary.
1585 unsigned Align = getStackAlignment();
1586 Amount = (Amount+Align-1)/Align*Align;
1588 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1589 assert(!AFI->isThumb1OnlyFunction() &&
1590 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1591 bool isARM = !AFI->isThumbFunction();
1593 // Replace the pseudo instruction with a new instruction...
1594 unsigned Opc = Old->getOpcode();
1595 int PIdx = Old->findFirstPredOperandIdx();
1596 ARMCC::CondCodes Pred = (PIdx == -1)
1597 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1598 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1599 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1600 unsigned PredReg = Old->getOperand(2).getReg();
1601 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1604 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1605 unsigned PredReg = Old->getOperand(3).getReg();
1606 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1607 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,