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/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Target/TargetOptions.h"
32 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
33 cl::desc("Align ARM NEON spills in prolog and epilog"));
35 static MachineBasicBlock::iterator
36 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
37 unsigned NumAlignedDPRCS2Regs);
39 /// hasFP - Return true if the specified function should have a dedicated frame
40 /// pointer register. This is true if the function has variable sized allocas
41 /// or if frame pointer elimination is disabled.
42 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
43 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
45 // iOS requires FP not to be clobbered for backtracing purpose.
46 if (STI.isTargetIOS())
49 const MachineFrameInfo *MFI = MF.getFrameInfo();
50 // Always eliminate non-leaf frame pointers.
51 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
53 RegInfo->needsStackRealignment(MF) ||
54 MFI->hasVarSizedObjects() ||
55 MFI->isFrameAddressTaken());
58 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
59 /// not required, we reserve argument space for call sites in the function
60 /// immediately on entry to the current function. This eliminates the need for
61 /// add/sub sp brackets around call sites. Returns true if the call frame is
62 /// included as part of the stack frame.
63 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
64 const MachineFrameInfo *FFI = MF.getFrameInfo();
65 unsigned CFSize = FFI->getMaxCallFrameSize();
66 // It's not always a good idea to include the call frame as part of the
67 // stack frame. ARM (especially Thumb) has small immediate offset to
68 // address the stack frame. So a large call frame can cause poor codegen
69 // and may even makes it impossible to scavenge a register.
70 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
73 return !MF.getFrameInfo()->hasVarSizedObjects();
76 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
77 /// call frame pseudos can be simplified. Unlike most targets, having a FP
78 /// is not sufficient here since we still may reference some objects via SP
79 /// even when FP is available in Thumb2 mode.
81 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
82 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
85 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
86 for (unsigned i = 0; CSRegs[i]; ++i)
92 static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
94 const uint16_t *CSRegs) {
95 // Integer spill area is handled with "pop".
96 if (MI->getOpcode() == ARM::LDMIA_RET ||
97 MI->getOpcode() == ARM::t2LDMIA_RET ||
98 MI->getOpcode() == ARM::LDMIA_UPD ||
99 MI->getOpcode() == ARM::t2LDMIA_UPD ||
100 MI->getOpcode() == ARM::VLDMDIA_UPD) {
101 // The first two operands are predicates. The last two are
102 // imp-def and imp-use of SP. Check everything in between.
103 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
104 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
108 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
109 MI->getOpcode() == ARM::LDR_POST_REG ||
110 MI->getOpcode() == ARM::t2LDR_POST) &&
111 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
112 MI->getOperand(1).getReg() == ARM::SP)
119 emitSPUpdate(bool isARM,
120 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
121 DebugLoc dl, const ARMBaseInstrInfo &TII,
122 int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
123 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
125 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
126 Pred, PredReg, TII, MIFlags);
128 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
129 Pred, PredReg, TII, MIFlags);
132 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
133 MachineBasicBlock &MBB = MF.front();
134 MachineBasicBlock::iterator MBBI = MBB.begin();
135 MachineFrameInfo *MFI = MF.getFrameInfo();
136 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
137 const ARMBaseRegisterInfo *RegInfo =
138 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
139 const ARMBaseInstrInfo &TII =
140 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
141 assert(!AFI->isThumb1OnlyFunction() &&
142 "This emitPrologue does not support Thumb1!");
143 bool isARM = !AFI->isThumbFunction();
144 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
145 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
146 unsigned NumBytes = MFI->getStackSize();
147 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
148 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
149 unsigned FramePtr = RegInfo->getFrameRegister(MF);
151 // Determine the sizes of each callee-save spill areas and record which frame
152 // belongs to which callee-save spill areas.
153 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
154 int FramePtrSpillFI = 0;
157 // All calls are tail calls in GHC calling conv, and functions have no
158 // prologue/epilogue.
159 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
162 // Allocate the vararg register save area. This is not counted in NumBytes.
164 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
165 MachineInstr::FrameSetup);
167 if (!AFI->hasStackFrame()) {
169 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
170 MachineInstr::FrameSetup);
174 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
175 unsigned Reg = CSI[i].getReg();
176 int FI = CSI[i].getFrameIdx();
184 FramePtrSpillFI = FI;
185 AFI->addGPRCalleeSavedArea1Frame(FI);
193 FramePtrSpillFI = FI;
194 if (STI.isTargetIOS()) {
195 AFI->addGPRCalleeSavedArea2Frame(FI);
198 AFI->addGPRCalleeSavedArea1Frame(FI);
203 // This is a DPR. Exclude the aligned DPRCS2 spills.
206 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
207 AFI->addDPRCalleeSavedAreaFrame(FI);
214 if (GPRCS1Size > 0) MBBI++;
216 // Set FP to point to the stack slot that contains the previous FP.
217 // For iOS, FP is R7, which has now been stored in spill area 1.
218 // Otherwise, if this is not iOS, all the callee-saved registers go
219 // into spill area 1, including the FP in R11. In either case, it is
220 // now safe to emit this assignment.
221 bool HasFP = hasFP(MF);
223 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
224 MachineInstrBuilder MIB =
225 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
226 .addFrameIndex(FramePtrSpillFI).addImm(0)
227 .setMIFlag(MachineInstr::FrameSetup);
228 AddDefaultCC(AddDefaultPred(MIB));
232 if (GPRCS2Size > 0) MBBI++;
234 // Determine starting offsets of spill areas.
235 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
236 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
237 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
239 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
241 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
242 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
243 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
248 // Since vpush register list cannot have gaps, there may be multiple vpush
249 // instructions in the prologue.
250 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
254 // Move past the aligned DPRCS2 area.
255 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
256 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
257 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
258 // leaves the stack pointer pointing to the DPRCS2 area.
260 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
261 NumBytes += MFI->getObjectOffset(D8SpillFI);
263 NumBytes = DPRCSOffset;
266 // Adjust SP after all the callee-save spills.
267 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
268 MachineInstr::FrameSetup);
270 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
271 // Note it's not safe to do this in Thumb2 mode because it would have
272 // taken two instructions:
275 // If an interrupt is taken between the two instructions, then sp is in
276 // an inconsistent state (pointing to the middle of callee-saved area).
277 // The interrupt handler can end up clobbering the registers.
278 AFI->setShouldRestoreSPFromFP(true);
281 if (STI.isTargetELF() && hasFP(MF))
282 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
283 AFI->getFramePtrSpillOffset());
285 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
286 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
287 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
289 // If we need dynamic stack realignment, do it here. Be paranoid and make
290 // sure if we also have VLAs, we have a base pointer for frame access.
291 // If aligned NEON registers were spilled, the stack has already been
293 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
294 unsigned MaxAlign = MFI->getMaxAlignment();
295 assert (!AFI->isThumb1OnlyFunction());
296 if (!AFI->isThumbFunction()) {
297 // Emit bic sp, sp, MaxAlign
298 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
299 TII.get(ARM::BICri), ARM::SP)
300 .addReg(ARM::SP, RegState::Kill)
301 .addImm(MaxAlign-1)));
303 // We cannot use sp as source/dest register here, thus we're emitting the
304 // following sequence:
306 // bic r4, r4, MaxAlign
308 // FIXME: It will be better just to find spare register here.
309 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
310 .addReg(ARM::SP, RegState::Kill));
311 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
312 TII.get(ARM::t2BICri), ARM::R4)
313 .addReg(ARM::R4, RegState::Kill)
314 .addImm(MaxAlign-1)));
315 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
316 .addReg(ARM::R4, RegState::Kill));
319 AFI->setShouldRestoreSPFromFP(true);
322 // If we need a base pointer, set it up here. It's whatever the value
323 // of the stack pointer is at this point. Any variable size objects
324 // will be allocated after this, so we can still use the base pointer
325 // to reference locals.
326 // FIXME: Clarify FrameSetup flags here.
327 if (RegInfo->hasBasePointer(MF)) {
329 BuildMI(MBB, MBBI, dl,
330 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
332 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
334 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
335 RegInfo->getBaseRegister())
339 // If the frame has variable sized objects then the epilogue must restore
340 // the sp from fp. We can assume there's an FP here since hasFP already
341 // checks for hasVarSizedObjects.
342 if (MFI->hasVarSizedObjects())
343 AFI->setShouldRestoreSPFromFP(true);
346 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
347 MachineBasicBlock &MBB) const {
348 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
349 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
350 unsigned RetOpcode = MBBI->getOpcode();
351 DebugLoc dl = MBBI->getDebugLoc();
352 MachineFrameInfo *MFI = MF.getFrameInfo();
353 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
354 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
355 const ARMBaseInstrInfo &TII =
356 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
357 assert(!AFI->isThumb1OnlyFunction() &&
358 "This emitEpilogue does not support Thumb1!");
359 bool isARM = !AFI->isThumbFunction();
361 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
362 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
363 int NumBytes = (int)MFI->getStackSize();
364 unsigned FramePtr = RegInfo->getFrameRegister(MF);
366 // All calls are tail calls in GHC calling conv, and functions have no
367 // prologue/epilogue.
368 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
371 if (!AFI->hasStackFrame()) {
373 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
375 // Unwind MBBI to point to first LDR / VLDRD.
376 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
377 if (MBBI != MBB.begin()) {
380 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
381 if (!isCSRestore(MBBI, TII, CSRegs))
385 // Move SP to start of FP callee save spill area.
386 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
387 AFI->getGPRCalleeSavedArea2Size() +
388 AFI->getDPRCalleeSavedAreaSize());
390 // Reset SP based on frame pointer only if the stack frame extends beyond
391 // frame pointer stack slot or target is ELF and the function has FP.
392 if (AFI->shouldRestoreSPFromFP()) {
393 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
396 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
399 // It's not possible to restore SP from FP in a single instruction.
400 // For iOS, this looks like:
403 // This is bad, if an interrupt is taken after the mov, sp is in an
404 // inconsistent state.
405 // Use the first callee-saved register as a scratch register.
406 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
407 "No scratch register to restore SP from FP!");
408 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
410 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
417 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
418 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
420 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
425 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
427 // Increment past our save areas.
428 if (AFI->getDPRCalleeSavedAreaSize()) {
430 // Since vpop register list cannot have gaps, there may be multiple vpop
431 // instructions in the epilogue.
432 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
435 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
436 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
439 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
440 // Tail call return: adjust the stack pointer and jump to callee.
441 MBBI = MBB.getLastNonDebugInstr();
442 MachineOperand &JumpTarget = MBBI->getOperand(0);
444 // Jump to label or value in register.
445 if (RetOpcode == ARM::TCRETURNdi) {
446 unsigned TCOpcode = STI.isThumb() ?
447 (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
449 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
450 if (JumpTarget.isGlobal())
451 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
452 JumpTarget.getTargetFlags());
454 assert(JumpTarget.isSymbol());
455 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
456 JumpTarget.getTargetFlags());
459 // Add the default predicate in Thumb mode.
460 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
461 } else if (RetOpcode == ARM::TCRETURNri) {
462 BuildMI(MBB, MBBI, dl,
463 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
464 addReg(JumpTarget.getReg(), RegState::Kill);
467 MachineInstr *NewMI = prior(MBBI);
468 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
469 NewMI->addOperand(MBBI->getOperand(i));
471 // Delete the pseudo instruction TCRETURN.
477 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
480 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
481 /// debug info. It's the same as what we use for resolving the code-gen
482 /// references for now. FIXME: This can go wrong when references are
483 /// SP-relative and simple call frames aren't used.
485 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
486 unsigned &FrameReg) const {
487 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
491 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
492 int FI, unsigned &FrameReg,
494 const MachineFrameInfo *MFI = MF.getFrameInfo();
495 const ARMBaseRegisterInfo *RegInfo =
496 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
497 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
498 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
499 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
500 bool isFixed = MFI->isFixedObjectIndex(FI);
504 if (AFI->isGPRCalleeSavedArea1Frame(FI))
505 return Offset - AFI->getGPRCalleeSavedArea1Offset();
506 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
507 return Offset - AFI->getGPRCalleeSavedArea2Offset();
508 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
509 return Offset - AFI->getDPRCalleeSavedAreaOffset();
511 // SP can move around if there are allocas. We may also lose track of SP
512 // when emergency spilling inside a non-reserved call frame setup.
513 bool hasMovingSP = !hasReservedCallFrame(MF);
515 // When dynamically realigning the stack, use the frame pointer for
516 // parameters, and the stack/base pointer for locals.
517 if (RegInfo->needsStackRealignment(MF)) {
518 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
520 FrameReg = RegInfo->getFrameRegister(MF);
522 } else if (hasMovingSP) {
523 assert(RegInfo->hasBasePointer(MF) &&
524 "VLAs and dynamic stack alignment, but missing base pointer!");
525 FrameReg = RegInfo->getBaseRegister();
530 // If there is a frame pointer, use it when we can.
531 if (hasFP(MF) && AFI->hasStackFrame()) {
532 // Use frame pointer to reference fixed objects. Use it for locals if
533 // there are VLAs (and thus the SP isn't reliable as a base).
534 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
535 FrameReg = RegInfo->getFrameRegister(MF);
537 } else if (hasMovingSP) {
538 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
539 if (AFI->isThumb2Function()) {
540 // Try to use the frame pointer if we can, else use the base pointer
541 // since it's available. This is handy for the emergency spill slot, in
543 if (FPOffset >= -255 && FPOffset < 0) {
544 FrameReg = RegInfo->getFrameRegister(MF);
548 } else if (AFI->isThumb2Function()) {
549 // Use add <rd>, sp, #<imm8>
550 // ldr <rd>, [sp, #<imm8>]
551 // if at all possible to save space.
552 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
554 // In Thumb2 mode, the negative offset is very limited. Try to avoid
555 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
556 if (FPOffset >= -255 && FPOffset < 0) {
557 FrameReg = RegInfo->getFrameRegister(MF);
560 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
561 // Otherwise, use SP or FP, whichever is closer to the stack slot.
562 FrameReg = RegInfo->getFrameRegister(MF);
566 // Use the base pointer if we have one.
567 if (RegInfo->hasBasePointer(MF))
568 FrameReg = RegInfo->getBaseRegister();
572 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
575 return getFrameIndexReference(MF, FI, FrameReg);
578 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
579 MachineBasicBlock::iterator MI,
580 const std::vector<CalleeSavedInfo> &CSI,
581 unsigned StmOpc, unsigned StrOpc,
583 bool(*Func)(unsigned, bool),
584 unsigned NumAlignedDPRCS2Regs,
585 unsigned MIFlags) const {
586 MachineFunction &MF = *MBB.getParent();
587 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
590 if (MI != MBB.end()) DL = MI->getDebugLoc();
592 SmallVector<std::pair<unsigned,bool>, 4> Regs;
593 unsigned i = CSI.size();
595 unsigned LastReg = 0;
596 for (; i != 0; --i) {
597 unsigned Reg = CSI[i-1].getReg();
598 if (!(Func)(Reg, STI.isTargetIOS())) continue;
600 // D-registers in the aligned area DPRCS2 are NOT spilled here.
601 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
604 // Add the callee-saved register as live-in unless it's LR and
605 // @llvm.returnaddress is called. If LR is returned for
606 // @llvm.returnaddress then it's already added to the function and
607 // entry block live-in sets.
609 if (Reg == ARM::LR) {
610 if (MF.getFrameInfo()->isReturnAddressTaken() &&
611 MF.getRegInfo().isLiveIn(Reg))
618 // If NoGap is true, push consecutive registers and then leave the rest
619 // for other instructions. e.g.
620 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
621 if (NoGap && LastReg && LastReg != Reg-1)
624 Regs.push_back(std::make_pair(Reg, isKill));
629 if (Regs.size() > 1 || StrOpc== 0) {
630 MachineInstrBuilder MIB =
631 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
632 .addReg(ARM::SP).setMIFlags(MIFlags));
633 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
634 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
635 } else if (Regs.size() == 1) {
636 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
638 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
639 .addReg(ARM::SP).setMIFlags(MIFlags)
647 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
648 MachineBasicBlock::iterator MI,
649 const std::vector<CalleeSavedInfo> &CSI,
650 unsigned LdmOpc, unsigned LdrOpc,
651 bool isVarArg, bool NoGap,
652 bool(*Func)(unsigned, bool),
653 unsigned NumAlignedDPRCS2Regs) const {
654 MachineFunction &MF = *MBB.getParent();
655 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
656 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
657 DebugLoc DL = MI->getDebugLoc();
658 unsigned RetOpcode = MI->getOpcode();
659 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
660 RetOpcode == ARM::TCRETURNri);
662 SmallVector<unsigned, 4> Regs;
663 unsigned i = CSI.size();
665 unsigned LastReg = 0;
666 bool DeleteRet = false;
667 for (; i != 0; --i) {
668 unsigned Reg = CSI[i-1].getReg();
669 if (!(Func)(Reg, STI.isTargetIOS())) continue;
671 // The aligned reloads from area DPRCS2 are not inserted here.
672 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
675 if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
677 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
678 // Fold the return instruction into the LDM.
682 // If NoGap is true, pop consecutive registers and then leave the rest
683 // for other instructions. e.g.
684 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
685 if (NoGap && LastReg && LastReg != Reg-1)
694 if (Regs.size() > 1 || LdrOpc == 0) {
695 MachineInstrBuilder MIB =
696 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
698 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
699 MIB.addReg(Regs[i], getDefRegState(true));
701 MIB.copyImplicitOps(&*MI);
702 MI->eraseFromParent();
705 } else if (Regs.size() == 1) {
706 // If we adjusted the reg to PC from LR above, switch it back here. We
707 // only do that for LDM.
708 if (Regs[0] == ARM::PC)
710 MachineInstrBuilder MIB =
711 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
712 .addReg(ARM::SP, RegState::Define)
714 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
715 // that refactoring is complete (eventually).
716 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
718 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
727 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
728 /// starting from d8. Also insert stack realignment code and leave the stack
729 /// pointer pointing to the d8 spill slot.
730 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
731 MachineBasicBlock::iterator MI,
732 unsigned NumAlignedDPRCS2Regs,
733 const std::vector<CalleeSavedInfo> &CSI,
734 const TargetRegisterInfo *TRI) {
735 MachineFunction &MF = *MBB.getParent();
736 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
737 DebugLoc DL = MI->getDebugLoc();
738 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
739 MachineFrameInfo &MFI = *MF.getFrameInfo();
741 // Mark the D-register spill slots as properly aligned. Since MFI computes
742 // stack slot layout backwards, this can actually mean that the d-reg stack
743 // slot offsets can be wrong. The offset for d8 will always be correct.
744 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
745 unsigned DNum = CSI[i].getReg() - ARM::D8;
748 int FI = CSI[i].getFrameIdx();
749 // The even-numbered registers will be 16-byte aligned, the odd-numbered
750 // registers will be 8-byte aligned.
751 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
753 // The stack slot for D8 needs to be maximally aligned because this is
754 // actually the point where we align the stack pointer. MachineFrameInfo
755 // computes all offsets relative to the incoming stack pointer which is a
756 // bit weird when realigning the stack. Any extra padding for this
757 // over-alignment is not realized because the code inserted below adjusts
758 // the stack pointer by numregs * 8 before aligning the stack pointer.
760 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
763 // Move the stack pointer to the d8 spill slot, and align it at the same
764 // time. Leave the stack slot address in the scratch register r4.
766 // sub r4, sp, #numregs * 8
767 // bic r4, r4, #align - 1
770 bool isThumb = AFI->isThumbFunction();
771 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
772 AFI->setShouldRestoreSPFromFP(true);
774 // sub r4, sp, #numregs * 8
775 // The immediate is <= 64, so it doesn't need any special encoding.
776 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
777 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
779 .addImm(8 * NumAlignedDPRCS2Regs)));
781 // bic r4, r4, #align-1
782 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
783 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
784 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
785 .addReg(ARM::R4, RegState::Kill)
786 .addImm(MaxAlign - 1)));
789 // The stack pointer must be adjusted before spilling anything, otherwise
790 // the stack slots could be clobbered by an interrupt handler.
791 // Leave r4 live, it is used below.
792 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
793 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
795 MIB = AddDefaultPred(MIB);
799 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
800 // r4 holds the stack slot address.
801 unsigned NextReg = ARM::D8;
803 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
804 // The writeback is only needed when emitting two vst1.64 instructions.
805 if (NumAlignedDPRCS2Regs >= 6) {
806 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
808 MBB.addLiveIn(SupReg);
809 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
811 .addReg(ARM::R4, RegState::Kill).addImm(16)
813 .addReg(SupReg, RegState::ImplicitKill));
815 NumAlignedDPRCS2Regs -= 4;
818 // We won't modify r4 beyond this point. It currently points to the next
819 // register to be spilled.
820 unsigned R4BaseReg = NextReg;
822 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
823 if (NumAlignedDPRCS2Regs >= 4) {
824 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
826 MBB.addLiveIn(SupReg);
827 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
828 .addReg(ARM::R4).addImm(16).addReg(NextReg)
829 .addReg(SupReg, RegState::ImplicitKill));
831 NumAlignedDPRCS2Regs -= 4;
834 // 16-byte aligned vst1.64 with 2 d-regs.
835 if (NumAlignedDPRCS2Regs >= 2) {
836 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
838 MBB.addLiveIn(SupReg);
839 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
840 .addReg(ARM::R4).addImm(16).addReg(SupReg));
842 NumAlignedDPRCS2Regs -= 2;
845 // Finally, use a vanilla vstr.64 for the odd last register.
846 if (NumAlignedDPRCS2Regs) {
847 MBB.addLiveIn(NextReg);
848 // vstr.64 uses addrmode5 which has an offset scale of 4.
849 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
851 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
854 // The last spill instruction inserted should kill the scratch register r4.
855 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
858 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
859 /// iterator to the following instruction.
860 static MachineBasicBlock::iterator
861 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
862 unsigned NumAlignedDPRCS2Regs) {
863 // sub r4, sp, #numregs * 8
864 // bic r4, r4, #align - 1
867 assert(MI->mayStore() && "Expecting spill instruction");
869 // These switches all fall through.
870 switch(NumAlignedDPRCS2Regs) {
873 assert(MI->mayStore() && "Expecting spill instruction");
876 assert(MI->mayStore() && "Expecting spill instruction");
880 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
886 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
887 /// starting from d8. These instructions are assumed to execute while the
888 /// stack is still aligned, unlike the code inserted by emitPopInst.
889 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
890 MachineBasicBlock::iterator MI,
891 unsigned NumAlignedDPRCS2Regs,
892 const std::vector<CalleeSavedInfo> &CSI,
893 const TargetRegisterInfo *TRI) {
894 MachineFunction &MF = *MBB.getParent();
895 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
896 DebugLoc DL = MI->getDebugLoc();
897 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
899 // Find the frame index assigned to d8.
901 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
902 if (CSI[i].getReg() == ARM::D8) {
903 D8SpillFI = CSI[i].getFrameIdx();
907 // Materialize the address of the d8 spill slot into the scratch register r4.
908 // This can be fairly complicated if the stack frame is large, so just use
909 // the normal frame index elimination mechanism to do it. This code runs as
910 // the initial part of the epilog where the stack and base pointers haven't
912 bool isThumb = AFI->isThumbFunction();
913 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
915 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
916 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
917 .addFrameIndex(D8SpillFI).addImm(0)));
919 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
920 unsigned NextReg = ARM::D8;
922 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
923 if (NumAlignedDPRCS2Regs >= 6) {
924 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
926 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
927 .addReg(ARM::R4, RegState::Define)
928 .addReg(ARM::R4, RegState::Kill).addImm(16)
929 .addReg(SupReg, RegState::ImplicitDefine));
931 NumAlignedDPRCS2Regs -= 4;
934 // We won't modify r4 beyond this point. It currently points to the next
935 // register to be spilled.
936 unsigned R4BaseReg = NextReg;
938 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
939 if (NumAlignedDPRCS2Regs >= 4) {
940 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
942 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
943 .addReg(ARM::R4).addImm(16)
944 .addReg(SupReg, RegState::ImplicitDefine));
946 NumAlignedDPRCS2Regs -= 4;
949 // 16-byte aligned vld1.64 with 2 d-regs.
950 if (NumAlignedDPRCS2Regs >= 2) {
951 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
953 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
954 .addReg(ARM::R4).addImm(16));
956 NumAlignedDPRCS2Regs -= 2;
959 // Finally, use a vanilla vldr.64 for the remaining odd register.
960 if (NumAlignedDPRCS2Regs)
961 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
962 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
964 // Last store kills r4.
965 llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
968 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
969 MachineBasicBlock::iterator MI,
970 const std::vector<CalleeSavedInfo> &CSI,
971 const TargetRegisterInfo *TRI) const {
975 MachineFunction &MF = *MBB.getParent();
976 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
978 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
979 unsigned PushOneOpc = AFI->isThumbFunction() ?
980 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
981 unsigned FltOpc = ARM::VSTMDDB_UPD;
982 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
983 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
984 MachineInstr::FrameSetup);
985 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
986 MachineInstr::FrameSetup);
987 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
988 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
990 // The code above does not insert spill code for the aligned DPRCS2 registers.
991 // The stack realignment code will be inserted between the push instructions
993 if (NumAlignedDPRCS2Regs)
994 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
999 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1000 MachineBasicBlock::iterator MI,
1001 const std::vector<CalleeSavedInfo> &CSI,
1002 const TargetRegisterInfo *TRI) const {
1006 MachineFunction &MF = *MBB.getParent();
1007 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1008 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1009 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1011 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1012 // registers. Do that here instead.
1013 if (NumAlignedDPRCS2Regs)
1014 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1016 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1017 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1018 unsigned FltOpc = ARM::VLDMDIA_UPD;
1019 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1020 NumAlignedDPRCS2Regs);
1021 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1022 &isARMArea2Register, 0);
1023 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1024 &isARMArea1Register, 0);
1029 // FIXME: Make generic?
1030 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1031 const ARMBaseInstrInfo &TII) {
1032 unsigned FnSize = 0;
1033 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1034 MBBI != E; ++MBBI) {
1035 const MachineBasicBlock &MBB = *MBBI;
1036 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1038 FnSize += TII.GetInstSizeInBytes(I);
1043 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1044 /// frames and return the stack size limit beyond which some of these
1045 /// instructions will require a scratch register during their expansion later.
1046 // FIXME: Move to TII?
1047 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1048 const TargetFrameLowering *TFI) {
1049 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1050 unsigned Limit = (1 << 12) - 1;
1051 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1052 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1054 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1055 if (!I->getOperand(i).isFI()) continue;
1057 // When using ADDri to get the address of a stack object, 255 is the
1058 // largest offset guaranteed to fit in the immediate offset.
1059 if (I->getOpcode() == ARM::ADDri) {
1060 Limit = std::min(Limit, (1U << 8) - 1);
1064 // Otherwise check the addressing mode.
1065 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1066 case ARMII::AddrMode3:
1067 case ARMII::AddrModeT2_i8:
1068 Limit = std::min(Limit, (1U << 8) - 1);
1070 case ARMII::AddrMode5:
1071 case ARMII::AddrModeT2_i8s4:
1072 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1074 case ARMII::AddrModeT2_i12:
1075 // i12 supports only positive offset so these will be converted to
1076 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1077 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1078 Limit = std::min(Limit, (1U << 8) - 1);
1080 case ARMII::AddrMode4:
1081 case ARMII::AddrMode6:
1082 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1083 // immediate offset for stack references.
1088 break; // At most one FI per instruction
1096 // In functions that realign the stack, it can be an advantage to spill the
1097 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1098 // instructions take alignment hints that can improve performance.
1100 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1101 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1102 if (!SpillAlignedNEONRegs)
1105 // Naked functions don't spill callee-saved registers.
1106 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1110 // We are planning to use NEON instructions vst1 / vld1.
1111 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1114 // Don't bother if the default stack alignment is sufficiently high.
1115 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1118 // Aligned spills require stack realignment.
1119 const ARMBaseRegisterInfo *RegInfo =
1120 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1121 if (!RegInfo->canRealignStack(MF))
1124 // We always spill contiguous d-registers starting from d8. Count how many
1125 // needs spilling. The register allocator will almost always use the
1126 // callee-saved registers in order, but it can happen that there are holes in
1127 // the range. Registers above the hole will be spilled to the standard DPRCS
1129 MachineRegisterInfo &MRI = MF.getRegInfo();
1130 unsigned NumSpills = 0;
1131 for (; NumSpills < 8; ++NumSpills)
1132 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1135 // Don't do this for just one d-register. It's not worth it.
1139 // Spill the first NumSpills D-registers after realigning the stack.
1140 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1142 // A scratch register is required for the vst1 / vld1 instructions.
1143 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1147 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1148 RegScavenger *RS) const {
1149 // This tells PEI to spill the FP as if it is any other callee-save register
1150 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1151 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1152 // to combine multiple loads / stores.
1153 bool CanEliminateFrame = true;
1154 bool CS1Spilled = false;
1155 bool LRSpilled = false;
1156 unsigned NumGPRSpills = 0;
1157 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1158 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1159 const ARMBaseRegisterInfo *RegInfo =
1160 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1161 const ARMBaseInstrInfo &TII =
1162 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1163 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1164 MachineFrameInfo *MFI = MF.getFrameInfo();
1165 MachineRegisterInfo &MRI = MF.getRegInfo();
1166 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1168 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1169 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1170 // since it's not always possible to restore sp from fp in a single
1172 // FIXME: It will be better just to find spare register here.
1173 if (AFI->isThumb2Function() &&
1174 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1175 MRI.setPhysRegUsed(ARM::R4);
1177 if (AFI->isThumb1OnlyFunction()) {
1178 // Spill LR if Thumb1 function uses variable length argument lists.
1179 if (AFI->getArgRegsSaveSize() > 0)
1180 MRI.setPhysRegUsed(ARM::LR);
1182 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1183 // for sure what the stack size will be, but for this, an estimate is good
1184 // enough. If there anything changes it, it'll be a spill, which implies
1185 // we've used all the registers and so R4 is already used, so not marking
1186 // it here will be OK.
1187 // FIXME: It will be better just to find spare register here.
1188 unsigned StackSize = MFI->estimateStackSize(MF);
1189 if (MFI->hasVarSizedObjects() || StackSize > 508)
1190 MRI.setPhysRegUsed(ARM::R4);
1193 // See if we can spill vector registers to aligned stack.
1194 checkNumAlignedDPRCS2Regs(MF);
1196 // Spill the BasePtr if it's used.
1197 if (RegInfo->hasBasePointer(MF))
1198 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1200 // Don't spill FP if the frame can be eliminated. This is determined
1201 // by scanning the callee-save registers to see if any is used.
1202 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
1203 for (unsigned i = 0; CSRegs[i]; ++i) {
1204 unsigned Reg = CSRegs[i];
1205 bool Spilled = false;
1206 if (MRI.isPhysRegUsed(Reg)) {
1208 CanEliminateFrame = false;
1211 if (!ARM::GPRRegClass.contains(Reg))
1217 if (!STI.isTargetIOS()) {
1224 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1229 case ARM::R4: case ARM::R5:
1230 case ARM::R6: case ARM::R7:
1237 if (!STI.isTargetIOS()) {
1238 UnspilledCS1GPRs.push_back(Reg);
1243 case ARM::R4: case ARM::R5:
1244 case ARM::R6: case ARM::R7:
1246 UnspilledCS1GPRs.push_back(Reg);
1249 UnspilledCS2GPRs.push_back(Reg);
1255 bool ForceLRSpill = false;
1256 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1257 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1258 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1259 // use of BL to implement far jump. If it turns out that it's not needed
1260 // then the branch fix up path will undo it.
1261 if (FnSize >= (1 << 11)) {
1262 CanEliminateFrame = false;
1263 ForceLRSpill = true;
1267 // If any of the stack slot references may be out of range of an immediate
1268 // offset, make sure a register (or a spill slot) is available for the
1269 // register scavenger. Note that if we're indexing off the frame pointer, the
1270 // effective stack size is 4 bytes larger since the FP points to the stack
1271 // slot of the previous FP. Also, if we have variable sized objects in the
1272 // function, stack slot references will often be negative, and some of
1273 // our instructions are positive-offset only, so conservatively consider
1274 // that case to want a spill slot (or register) as well. Similarly, if
1275 // the function adjusts the stack pointer during execution and the
1276 // adjustments aren't already part of our stack size estimate, our offset
1277 // calculations may be off, so be conservative.
1278 // FIXME: We could add logic to be more precise about negative offsets
1279 // and which instructions will need a scratch register for them. Is it
1280 // worth the effort and added fragility?
1283 (MFI->estimateStackSize(MF) +
1284 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1285 estimateRSStackSizeLimit(MF, this)))
1286 || MFI->hasVarSizedObjects()
1287 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1289 bool ExtraCSSpill = false;
1290 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1291 AFI->setHasStackFrame(true);
1293 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1294 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1295 if (!LRSpilled && CS1Spilled) {
1296 MRI.setPhysRegUsed(ARM::LR);
1298 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1299 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1300 ForceLRSpill = false;
1301 ExtraCSSpill = true;
1305 MRI.setPhysRegUsed(FramePtr);
1309 // If stack and double are 8-byte aligned and we are spilling an odd number
1310 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1311 // the integer and double callee save areas.
1312 unsigned TargetAlign = getStackAlignment();
1313 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1314 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1315 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1316 unsigned Reg = UnspilledCS1GPRs[i];
1317 // Don't spill high register if the function is thumb1
1318 if (!AFI->isThumb1OnlyFunction() ||
1319 isARMLowRegister(Reg) || Reg == ARM::LR) {
1320 MRI.setPhysRegUsed(Reg);
1321 if (!MRI.isReserved(Reg))
1322 ExtraCSSpill = true;
1326 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1327 unsigned Reg = UnspilledCS2GPRs.front();
1328 MRI.setPhysRegUsed(Reg);
1329 if (!MRI.isReserved(Reg))
1330 ExtraCSSpill = true;
1334 // Estimate if we might need to scavenge a register at some point in order
1335 // to materialize a stack offset. If so, either spill one additional
1336 // callee-saved register or reserve a special spill slot to facilitate
1337 // register scavenging. Thumb1 needs a spill slot for stack pointer
1338 // adjustments also, even when the frame itself is small.
1339 if (BigStack && !ExtraCSSpill) {
1340 // If any non-reserved CS register isn't spilled, just spill one or two
1341 // extra. That should take care of it!
1342 unsigned NumExtras = TargetAlign / 4;
1343 SmallVector<unsigned, 2> Extras;
1344 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1345 unsigned Reg = UnspilledCS1GPRs.back();
1346 UnspilledCS1GPRs.pop_back();
1347 if (!MRI.isReserved(Reg) &&
1348 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1350 Extras.push_back(Reg);
1354 // For non-Thumb1 functions, also check for hi-reg CS registers
1355 if (!AFI->isThumb1OnlyFunction()) {
1356 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1357 unsigned Reg = UnspilledCS2GPRs.back();
1358 UnspilledCS2GPRs.pop_back();
1359 if (!MRI.isReserved(Reg)) {
1360 Extras.push_back(Reg);
1365 if (Extras.size() && NumExtras == 0) {
1366 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1367 MRI.setPhysRegUsed(Extras[i]);
1369 } else if (!AFI->isThumb1OnlyFunction()) {
1370 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1371 // closest to SP or frame pointer.
1372 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1373 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1381 MRI.setPhysRegUsed(ARM::LR);
1382 AFI->setLRIsSpilledForFarJump(true);
1387 void ARMFrameLowering::
1388 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1389 MachineBasicBlock::iterator I) const {
1390 const ARMBaseInstrInfo &TII =
1391 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1392 if (!hasReservedCallFrame(MF)) {
1393 // If we have alloca, convert as follows:
1394 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1395 // ADJCALLSTACKUP -> add, sp, sp, amount
1396 MachineInstr *Old = I;
1397 DebugLoc dl = Old->getDebugLoc();
1398 unsigned Amount = Old->getOperand(0).getImm();
1400 // We need to keep the stack aligned properly. To do this, we round the
1401 // amount of space needed for the outgoing arguments up to the next
1402 // alignment boundary.
1403 unsigned Align = getStackAlignment();
1404 Amount = (Amount+Align-1)/Align*Align;
1406 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1407 assert(!AFI->isThumb1OnlyFunction() &&
1408 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1409 bool isARM = !AFI->isThumbFunction();
1411 // Replace the pseudo instruction with a new instruction...
1412 unsigned Opc = Old->getOpcode();
1413 int PIdx = Old->findFirstPredOperandIdx();
1414 ARMCC::CondCodes Pred = (PIdx == -1)
1415 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1416 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1417 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1418 unsigned PredReg = Old->getOperand(2).getReg();
1419 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1422 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1423 unsigned PredReg = Old->getOperand(3).getReg();
1424 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1425 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,