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)
809 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
810 MachineBasicBlock::iterator MI,
811 const std::vector<CalleeSavedInfo> &CSI,
812 unsigned LdmOpc, unsigned LdrOpc,
813 bool isVarArg, bool NoGap,
814 bool(*Func)(unsigned, bool),
815 unsigned NumAlignedDPRCS2Regs) const {
816 MachineFunction &MF = *MBB.getParent();
817 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
818 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
819 DebugLoc DL = MI->getDebugLoc();
820 unsigned RetOpcode = MI->getOpcode();
821 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
822 RetOpcode == ARM::TCRETURNri);
824 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
826 SmallVector<unsigned, 4> Regs;
827 unsigned i = CSI.size();
829 unsigned LastReg = 0;
830 bool DeleteRet = false;
831 for (; i != 0; --i) {
832 unsigned Reg = CSI[i-1].getReg();
833 if (!(Func)(Reg, STI.isTargetMachO())) continue;
835 // The aligned reloads from area DPRCS2 are not inserted here.
836 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
839 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
842 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
843 // Fold the return instruction into the LDM.
847 // If NoGap is true, pop consecutive registers and then leave the rest
848 // for other instructions. e.g.
849 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
850 if (NoGap && LastReg && LastReg != Reg-1)
859 if (Regs.size() > 1 || LdrOpc == 0) {
860 MachineInstrBuilder MIB =
861 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
863 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
864 MIB.addReg(Regs[i], getDefRegState(true));
866 MIB.copyImplicitOps(&*MI);
867 MI->eraseFromParent();
870 } else if (Regs.size() == 1) {
871 // If we adjusted the reg to PC from LR above, switch it back here. We
872 // only do that for LDM.
873 if (Regs[0] == ARM::PC)
875 MachineInstrBuilder MIB =
876 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
877 .addReg(ARM::SP, RegState::Define)
879 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
880 // that refactoring is complete (eventually).
881 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
883 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
892 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
893 /// starting from d8. Also insert stack realignment code and leave the stack
894 /// pointer pointing to the d8 spill slot.
895 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
896 MachineBasicBlock::iterator MI,
897 unsigned NumAlignedDPRCS2Regs,
898 const std::vector<CalleeSavedInfo> &CSI,
899 const TargetRegisterInfo *TRI) {
900 MachineFunction &MF = *MBB.getParent();
901 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
902 DebugLoc DL = MI->getDebugLoc();
903 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
904 MachineFrameInfo &MFI = *MF.getFrameInfo();
906 // Mark the D-register spill slots as properly aligned. Since MFI computes
907 // stack slot layout backwards, this can actually mean that the d-reg stack
908 // slot offsets can be wrong. The offset for d8 will always be correct.
909 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
910 unsigned DNum = CSI[i].getReg() - ARM::D8;
913 int FI = CSI[i].getFrameIdx();
914 // The even-numbered registers will be 16-byte aligned, the odd-numbered
915 // registers will be 8-byte aligned.
916 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
918 // The stack slot for D8 needs to be maximally aligned because this is
919 // actually the point where we align the stack pointer. MachineFrameInfo
920 // computes all offsets relative to the incoming stack pointer which is a
921 // bit weird when realigning the stack. Any extra padding for this
922 // over-alignment is not realized because the code inserted below adjusts
923 // the stack pointer by numregs * 8 before aligning the stack pointer.
925 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
928 // Move the stack pointer to the d8 spill slot, and align it at the same
929 // time. Leave the stack slot address in the scratch register r4.
931 // sub r4, sp, #numregs * 8
932 // bic r4, r4, #align - 1
935 bool isThumb = AFI->isThumbFunction();
936 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
937 AFI->setShouldRestoreSPFromFP(true);
939 // sub r4, sp, #numregs * 8
940 // The immediate is <= 64, so it doesn't need any special encoding.
941 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
942 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
944 .addImm(8 * NumAlignedDPRCS2Regs)));
946 // bic r4, r4, #align-1
947 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
948 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
949 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
950 .addReg(ARM::R4, RegState::Kill)
951 .addImm(MaxAlign - 1)));
954 // The stack pointer must be adjusted before spilling anything, otherwise
955 // the stack slots could be clobbered by an interrupt handler.
956 // Leave r4 live, it is used below.
957 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
958 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
960 MIB = AddDefaultPred(MIB);
964 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
965 // r4 holds the stack slot address.
966 unsigned NextReg = ARM::D8;
968 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
969 // The writeback is only needed when emitting two vst1.64 instructions.
970 if (NumAlignedDPRCS2Regs >= 6) {
971 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
973 MBB.addLiveIn(SupReg);
974 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
976 .addReg(ARM::R4, RegState::Kill).addImm(16)
978 .addReg(SupReg, RegState::ImplicitKill));
980 NumAlignedDPRCS2Regs -= 4;
983 // We won't modify r4 beyond this point. It currently points to the next
984 // register to be spilled.
985 unsigned R4BaseReg = NextReg;
987 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
988 if (NumAlignedDPRCS2Regs >= 4) {
989 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
991 MBB.addLiveIn(SupReg);
992 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
993 .addReg(ARM::R4).addImm(16).addReg(NextReg)
994 .addReg(SupReg, RegState::ImplicitKill));
996 NumAlignedDPRCS2Regs -= 4;
999 // 16-byte aligned vst1.64 with 2 d-regs.
1000 if (NumAlignedDPRCS2Regs >= 2) {
1001 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1003 MBB.addLiveIn(SupReg);
1004 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1005 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1007 NumAlignedDPRCS2Regs -= 2;
1010 // Finally, use a vanilla vstr.64 for the odd last register.
1011 if (NumAlignedDPRCS2Regs) {
1012 MBB.addLiveIn(NextReg);
1013 // vstr.64 uses addrmode5 which has an offset scale of 4.
1014 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1016 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1019 // The last spill instruction inserted should kill the scratch register r4.
1020 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1023 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1024 /// iterator to the following instruction.
1025 static MachineBasicBlock::iterator
1026 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1027 unsigned NumAlignedDPRCS2Regs) {
1028 // sub r4, sp, #numregs * 8
1029 // bic r4, r4, #align - 1
1032 assert(MI->mayStore() && "Expecting spill instruction");
1034 // These switches all fall through.
1035 switch(NumAlignedDPRCS2Regs) {
1038 assert(MI->mayStore() && "Expecting spill instruction");
1041 assert(MI->mayStore() && "Expecting spill instruction");
1045 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1051 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1052 /// starting from d8. These instructions are assumed to execute while the
1053 /// stack is still aligned, unlike the code inserted by emitPopInst.
1054 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1055 MachineBasicBlock::iterator MI,
1056 unsigned NumAlignedDPRCS2Regs,
1057 const std::vector<CalleeSavedInfo> &CSI,
1058 const TargetRegisterInfo *TRI) {
1059 MachineFunction &MF = *MBB.getParent();
1060 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1061 DebugLoc DL = MI->getDebugLoc();
1062 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1064 // Find the frame index assigned to d8.
1066 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1067 if (CSI[i].getReg() == ARM::D8) {
1068 D8SpillFI = CSI[i].getFrameIdx();
1072 // Materialize the address of the d8 spill slot into the scratch register r4.
1073 // This can be fairly complicated if the stack frame is large, so just use
1074 // the normal frame index elimination mechanism to do it. This code runs as
1075 // the initial part of the epilog where the stack and base pointers haven't
1076 // been changed yet.
1077 bool isThumb = AFI->isThumbFunction();
1078 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1080 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1081 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1082 .addFrameIndex(D8SpillFI).addImm(0)));
1084 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1085 unsigned NextReg = ARM::D8;
1087 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1088 if (NumAlignedDPRCS2Regs >= 6) {
1089 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1090 &ARM::QQPRRegClass);
1091 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1092 .addReg(ARM::R4, RegState::Define)
1093 .addReg(ARM::R4, RegState::Kill).addImm(16)
1094 .addReg(SupReg, RegState::ImplicitDefine));
1096 NumAlignedDPRCS2Regs -= 4;
1099 // We won't modify r4 beyond this point. It currently points to the next
1100 // register to be spilled.
1101 unsigned R4BaseReg = NextReg;
1103 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1104 if (NumAlignedDPRCS2Regs >= 4) {
1105 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1106 &ARM::QQPRRegClass);
1107 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1108 .addReg(ARM::R4).addImm(16)
1109 .addReg(SupReg, RegState::ImplicitDefine));
1111 NumAlignedDPRCS2Regs -= 4;
1114 // 16-byte aligned vld1.64 with 2 d-regs.
1115 if (NumAlignedDPRCS2Regs >= 2) {
1116 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1118 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1119 .addReg(ARM::R4).addImm(16));
1121 NumAlignedDPRCS2Regs -= 2;
1124 // Finally, use a vanilla vldr.64 for the remaining odd register.
1125 if (NumAlignedDPRCS2Regs)
1126 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1127 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1129 // Last store kills r4.
1130 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1133 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1134 MachineBasicBlock::iterator MI,
1135 const std::vector<CalleeSavedInfo> &CSI,
1136 const TargetRegisterInfo *TRI) const {
1140 MachineFunction &MF = *MBB.getParent();
1141 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1143 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1144 unsigned PushOneOpc = AFI->isThumbFunction() ?
1145 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1146 unsigned FltOpc = ARM::VSTMDDB_UPD;
1147 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1148 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1149 MachineInstr::FrameSetup);
1150 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1151 MachineInstr::FrameSetup);
1152 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1153 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1155 // The code above does not insert spill code for the aligned DPRCS2 registers.
1156 // The stack realignment code will be inserted between the push instructions
1157 // and these spills.
1158 if (NumAlignedDPRCS2Regs)
1159 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1164 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1165 MachineBasicBlock::iterator MI,
1166 const std::vector<CalleeSavedInfo> &CSI,
1167 const TargetRegisterInfo *TRI) const {
1171 MachineFunction &MF = *MBB.getParent();
1172 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1173 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1174 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1176 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1177 // registers. Do that here instead.
1178 if (NumAlignedDPRCS2Regs)
1179 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1181 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1182 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1183 unsigned FltOpc = ARM::VLDMDIA_UPD;
1184 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1185 NumAlignedDPRCS2Regs);
1186 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1187 &isARMArea2Register, 0);
1188 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1189 &isARMArea1Register, 0);
1194 // FIXME: Make generic?
1195 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1196 const ARMBaseInstrInfo &TII) {
1197 unsigned FnSize = 0;
1198 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1199 MBBI != E; ++MBBI) {
1200 const MachineBasicBlock &MBB = *MBBI;
1201 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1203 FnSize += TII.GetInstSizeInBytes(I);
1208 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1209 /// frames and return the stack size limit beyond which some of these
1210 /// instructions will require a scratch register during their expansion later.
1211 // FIXME: Move to TII?
1212 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1213 const TargetFrameLowering *TFI) {
1214 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1215 unsigned Limit = (1 << 12) - 1;
1216 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1217 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1219 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1220 if (!I->getOperand(i).isFI()) continue;
1222 // When using ADDri to get the address of a stack object, 255 is the
1223 // largest offset guaranteed to fit in the immediate offset.
1224 if (I->getOpcode() == ARM::ADDri) {
1225 Limit = std::min(Limit, (1U << 8) - 1);
1229 // Otherwise check the addressing mode.
1230 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1231 case ARMII::AddrMode3:
1232 case ARMII::AddrModeT2_i8:
1233 Limit = std::min(Limit, (1U << 8) - 1);
1235 case ARMII::AddrMode5:
1236 case ARMII::AddrModeT2_i8s4:
1237 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1239 case ARMII::AddrModeT2_i12:
1240 // i12 supports only positive offset so these will be converted to
1241 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1242 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1243 Limit = std::min(Limit, (1U << 8) - 1);
1245 case ARMII::AddrMode4:
1246 case ARMII::AddrMode6:
1247 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1248 // immediate offset for stack references.
1253 break; // At most one FI per instruction
1261 // In functions that realign the stack, it can be an advantage to spill the
1262 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1263 // instructions take alignment hints that can improve performance.
1265 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1266 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1267 if (!SpillAlignedNEONRegs)
1270 // Naked functions don't spill callee-saved registers.
1271 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1275 // We are planning to use NEON instructions vst1 / vld1.
1276 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1279 // Don't bother if the default stack alignment is sufficiently high.
1280 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1283 // Aligned spills require stack realignment.
1284 const ARMBaseRegisterInfo *RegInfo =
1285 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1286 if (!RegInfo->canRealignStack(MF))
1289 // We always spill contiguous d-registers starting from d8. Count how many
1290 // needs spilling. The register allocator will almost always use the
1291 // callee-saved registers in order, but it can happen that there are holes in
1292 // the range. Registers above the hole will be spilled to the standard DPRCS
1294 MachineRegisterInfo &MRI = MF.getRegInfo();
1295 unsigned NumSpills = 0;
1296 for (; NumSpills < 8; ++NumSpills)
1297 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1300 // Don't do this for just one d-register. It's not worth it.
1304 // Spill the first NumSpills D-registers after realigning the stack.
1305 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1307 // A scratch register is required for the vst1 / vld1 instructions.
1308 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1312 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1313 RegScavenger *RS) const {
1314 // This tells PEI to spill the FP as if it is any other callee-save register
1315 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1316 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1317 // to combine multiple loads / stores.
1318 bool CanEliminateFrame = true;
1319 bool CS1Spilled = false;
1320 bool LRSpilled = false;
1321 unsigned NumGPRSpills = 0;
1322 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1323 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1324 const ARMBaseRegisterInfo *RegInfo =
1325 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1326 const ARMBaseInstrInfo &TII =
1327 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1328 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1329 MachineFrameInfo *MFI = MF.getFrameInfo();
1330 MachineRegisterInfo &MRI = MF.getRegInfo();
1331 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1333 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1334 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1335 // since it's not always possible to restore sp from fp in a single
1337 // FIXME: It will be better just to find spare register here.
1338 if (AFI->isThumb2Function() &&
1339 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1340 MRI.setPhysRegUsed(ARM::R4);
1342 if (AFI->isThumb1OnlyFunction()) {
1343 // Spill LR if Thumb1 function uses variable length argument lists.
1344 if (AFI->getArgRegsSaveSize() > 0)
1345 MRI.setPhysRegUsed(ARM::LR);
1347 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1348 // for sure what the stack size will be, but for this, an estimate is good
1349 // enough. If there anything changes it, it'll be a spill, which implies
1350 // we've used all the registers and so R4 is already used, so not marking
1351 // it here will be OK.
1352 // FIXME: It will be better just to find spare register here.
1353 unsigned StackSize = MFI->estimateStackSize(MF);
1354 if (MFI->hasVarSizedObjects() || StackSize > 508)
1355 MRI.setPhysRegUsed(ARM::R4);
1358 // See if we can spill vector registers to aligned stack.
1359 checkNumAlignedDPRCS2Regs(MF);
1361 // Spill the BasePtr if it's used.
1362 if (RegInfo->hasBasePointer(MF))
1363 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1365 // Don't spill FP if the frame can be eliminated. This is determined
1366 // by scanning the callee-save registers to see if any is used.
1367 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1368 for (unsigned i = 0; CSRegs[i]; ++i) {
1369 unsigned Reg = CSRegs[i];
1370 bool Spilled = false;
1371 if (MRI.isPhysRegUsed(Reg)) {
1373 CanEliminateFrame = false;
1376 if (!ARM::GPRRegClass.contains(Reg))
1382 if (!STI.isTargetMachO()) {
1389 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1394 case ARM::R0: case ARM::R1:
1395 case ARM::R2: case ARM::R3:
1396 case ARM::R4: case ARM::R5:
1397 case ARM::R6: case ARM::R7:
1404 if (!STI.isTargetMachO()) {
1405 UnspilledCS1GPRs.push_back(Reg);
1410 case ARM::R0: case ARM::R1:
1411 case ARM::R2: case ARM::R3:
1412 case ARM::R4: case ARM::R5:
1413 case ARM::R6: case ARM::R7:
1415 UnspilledCS1GPRs.push_back(Reg);
1418 UnspilledCS2GPRs.push_back(Reg);
1424 bool ForceLRSpill = false;
1425 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1426 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1427 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1428 // use of BL to implement far jump. If it turns out that it's not needed
1429 // then the branch fix up path will undo it.
1430 if (FnSize >= (1 << 11)) {
1431 CanEliminateFrame = false;
1432 ForceLRSpill = true;
1436 // If any of the stack slot references may be out of range of an immediate
1437 // offset, make sure a register (or a spill slot) is available for the
1438 // register scavenger. Note that if we're indexing off the frame pointer, the
1439 // effective stack size is 4 bytes larger since the FP points to the stack
1440 // slot of the previous FP. Also, if we have variable sized objects in the
1441 // function, stack slot references will often be negative, and some of
1442 // our instructions are positive-offset only, so conservatively consider
1443 // that case to want a spill slot (or register) as well. Similarly, if
1444 // the function adjusts the stack pointer during execution and the
1445 // adjustments aren't already part of our stack size estimate, our offset
1446 // calculations may be off, so be conservative.
1447 // FIXME: We could add logic to be more precise about negative offsets
1448 // and which instructions will need a scratch register for them. Is it
1449 // worth the effort and added fragility?
1452 (MFI->estimateStackSize(MF) +
1453 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1454 estimateRSStackSizeLimit(MF, this)))
1455 || MFI->hasVarSizedObjects()
1456 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1458 bool ExtraCSSpill = false;
1459 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1460 AFI->setHasStackFrame(true);
1462 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1463 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1464 if (!LRSpilled && CS1Spilled) {
1465 MRI.setPhysRegUsed(ARM::LR);
1467 SmallVectorImpl<unsigned>::iterator LRPos;
1468 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1470 if (LRPos != UnspilledCS1GPRs.end())
1471 UnspilledCS1GPRs.erase(LRPos);
1473 ForceLRSpill = false;
1474 ExtraCSSpill = true;
1478 MRI.setPhysRegUsed(FramePtr);
1482 // If stack and double are 8-byte aligned and we are spilling an odd number
1483 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1484 // the integer and double callee save areas.
1485 unsigned TargetAlign = getStackAlignment();
1486 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1487 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1488 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1489 unsigned Reg = UnspilledCS1GPRs[i];
1490 // Don't spill high register if the function is thumb1
1491 if (!AFI->isThumb1OnlyFunction() ||
1492 isARMLowRegister(Reg) || Reg == ARM::LR) {
1493 MRI.setPhysRegUsed(Reg);
1494 if (!MRI.isReserved(Reg))
1495 ExtraCSSpill = true;
1499 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1500 unsigned Reg = UnspilledCS2GPRs.front();
1501 MRI.setPhysRegUsed(Reg);
1502 if (!MRI.isReserved(Reg))
1503 ExtraCSSpill = true;
1507 // Estimate if we might need to scavenge a register at some point in order
1508 // to materialize a stack offset. If so, either spill one additional
1509 // callee-saved register or reserve a special spill slot to facilitate
1510 // register scavenging. Thumb1 needs a spill slot for stack pointer
1511 // adjustments also, even when the frame itself is small.
1512 if (BigStack && !ExtraCSSpill) {
1513 // If any non-reserved CS register isn't spilled, just spill one or two
1514 // extra. That should take care of it!
1515 unsigned NumExtras = TargetAlign / 4;
1516 SmallVector<unsigned, 2> Extras;
1517 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1518 unsigned Reg = UnspilledCS1GPRs.back();
1519 UnspilledCS1GPRs.pop_back();
1520 if (!MRI.isReserved(Reg) &&
1521 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1523 Extras.push_back(Reg);
1527 // For non-Thumb1 functions, also check for hi-reg CS registers
1528 if (!AFI->isThumb1OnlyFunction()) {
1529 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1530 unsigned Reg = UnspilledCS2GPRs.back();
1531 UnspilledCS2GPRs.pop_back();
1532 if (!MRI.isReserved(Reg)) {
1533 Extras.push_back(Reg);
1538 if (Extras.size() && NumExtras == 0) {
1539 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1540 MRI.setPhysRegUsed(Extras[i]);
1542 } else if (!AFI->isThumb1OnlyFunction()) {
1543 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1544 // closest to SP or frame pointer.
1545 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1546 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1554 MRI.setPhysRegUsed(ARM::LR);
1555 AFI->setLRIsSpilledForFarJump(true);
1560 void ARMFrameLowering::
1561 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1562 MachineBasicBlock::iterator I) const {
1563 const ARMBaseInstrInfo &TII =
1564 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1565 if (!hasReservedCallFrame(MF)) {
1566 // If we have alloca, convert as follows:
1567 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1568 // ADJCALLSTACKUP -> add, sp, sp, amount
1569 MachineInstr *Old = I;
1570 DebugLoc dl = Old->getDebugLoc();
1571 unsigned Amount = Old->getOperand(0).getImm();
1573 // We need to keep the stack aligned properly. To do this, we round the
1574 // amount of space needed for the outgoing arguments up to the next
1575 // alignment boundary.
1576 unsigned Align = getStackAlignment();
1577 Amount = (Amount+Align-1)/Align*Align;
1579 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1580 assert(!AFI->isThumb1OnlyFunction() &&
1581 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1582 bool isARM = !AFI->isThumbFunction();
1584 // Replace the pseudo instruction with a new instruction...
1585 unsigned Opc = Old->getOpcode();
1586 int PIdx = Old->findFirstPredOperandIdx();
1587 ARMCC::CondCodes Pred = (PIdx == -1)
1588 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1589 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1590 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1591 unsigned PredReg = Old->getOperand(2).getReg();
1592 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1595 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1596 unsigned PredReg = Old->getOperand(3).getReg();
1597 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1598 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,