1 //=======- ARMFrameInfo.cpp - ARM Frame Information ------------*- C++ -*-====//
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 TargetFrameInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameInfo.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/RegisterScavenging.h"
23 #include "llvm/Target/TargetOptions.h"
27 /// hasFP - Return true if the specified function should have a dedicated frame
28 /// pointer register. This is true if the function has variable sized allocas
29 /// or if frame pointer elimination is disabled.
31 bool ARMFrameInfo::hasFP(const MachineFunction &MF) const {
32 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
34 // Mac OS X requires FP not to be clobbered for backtracing purpose.
35 if (STI.isTargetDarwin())
38 const MachineFrameInfo *MFI = MF.getFrameInfo();
39 // Always eliminate non-leaf frame pointers.
40 return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
41 RegInfo->needsStackRealignment(MF) ||
42 MFI->hasVarSizedObjects() ||
43 MFI->isFrameAddressTaken());
46 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
47 // not required, we reserve argument space for call sites in the function
48 // immediately on entry to the current function. This eliminates the need for
49 // add/sub sp brackets around call sites. Returns true if the call frame is
50 // included as part of the stack frame.
51 bool ARMFrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
52 const MachineFrameInfo *FFI = MF.getFrameInfo();
53 unsigned CFSize = FFI->getMaxCallFrameSize();
54 // It's not always a good idea to include the call frame as part of the
55 // stack frame. ARM (especially Thumb) has small immediate offset to
56 // address the stack frame. So a large call frame can cause poor codegen
57 // and may even makes it impossible to scavenge a register.
58 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
61 return !MF.getFrameInfo()->hasVarSizedObjects();
64 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
65 // call frame pseudos can be simplified. Unlike most targets, having a FP
66 // is not sufficient here since we still may reference some objects via SP
67 // even when FP is available in Thumb2 mode.
68 bool ARMFrameInfo::canSimplifyCallFramePseudos(const MachineFunction &MF)const {
69 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
72 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
73 for (unsigned i = 0; CSRegs[i]; ++i)
79 static bool isCSRestore(MachineInstr *MI,
80 const ARMBaseInstrInfo &TII,
81 const unsigned *CSRegs) {
82 // Integer spill area is handled with "pop".
83 if (MI->getOpcode() == ARM::LDMIA_RET ||
84 MI->getOpcode() == ARM::t2LDMIA_RET ||
85 MI->getOpcode() == ARM::LDMIA_UPD ||
86 MI->getOpcode() == ARM::t2LDMIA_UPD ||
87 MI->getOpcode() == ARM::VLDMDIA_UPD) {
88 // The first two operands are predicates. The last two are
89 // imp-def and imp-use of SP. Check everything in between.
90 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
91 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
100 emitSPUpdate(bool isARM,
101 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
102 DebugLoc dl, const ARMBaseInstrInfo &TII,
104 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
106 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
109 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
113 void ARMFrameInfo::emitPrologue(MachineFunction &MF) const {
114 MachineBasicBlock &MBB = MF.front();
115 MachineBasicBlock::iterator MBBI = MBB.begin();
116 MachineFrameInfo *MFI = MF.getFrameInfo();
117 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
118 const ARMBaseRegisterInfo *RegInfo =
119 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
120 const ARMBaseInstrInfo &TII =
121 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
122 assert(!AFI->isThumb1OnlyFunction() &&
123 "This emitPrologue does not support Thumb1!");
124 bool isARM = !AFI->isThumbFunction();
125 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
126 unsigned NumBytes = MFI->getStackSize();
127 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
128 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
129 unsigned FramePtr = RegInfo->getFrameRegister(MF);
131 // Determine the sizes of each callee-save spill areas and record which frame
132 // belongs to which callee-save spill areas.
133 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
134 int FramePtrSpillFI = 0;
136 // Allocate the vararg register save area. This is not counted in NumBytes.
138 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
140 if (!AFI->hasStackFrame()) {
142 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
146 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
147 unsigned Reg = CSI[i].getReg();
148 int FI = CSI[i].getFrameIdx();
156 FramePtrSpillFI = FI;
157 AFI->addGPRCalleeSavedArea1Frame(FI);
165 FramePtrSpillFI = FI;
166 if (STI.isTargetDarwin()) {
167 AFI->addGPRCalleeSavedArea2Frame(FI);
170 AFI->addGPRCalleeSavedArea1Frame(FI);
175 AFI->addDPRCalleeSavedAreaFrame(FI);
181 if (GPRCS1Size > 0) MBBI++;
183 // Set FP to point to the stack slot that contains the previous FP.
184 // For Darwin, FP is R7, which has now been stored in spill area 1.
185 // Otherwise, if this is not Darwin, all the callee-saved registers go
186 // into spill area 1, including the FP in R11. In either case, it is
187 // now safe to emit this assignment.
188 bool HasFP = hasFP(MF);
190 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
191 MachineInstrBuilder MIB =
192 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
193 .addFrameIndex(FramePtrSpillFI).addImm(0);
194 AddDefaultCC(AddDefaultPred(MIB));
198 if (GPRCS2Size > 0) MBBI++;
200 // Determine starting offsets of spill areas.
201 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
202 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
203 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
205 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
207 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
208 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
209 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
212 if (DPRCSSize > 0) MBBI++;
214 NumBytes = DPRCSOffset;
216 // Adjust SP after all the callee-save spills.
217 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
219 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
220 // Note it's not safe to do this in Thumb2 mode because it would have
221 // taken two instructions:
224 // If an interrupt is taken between the two instructions, then sp is in
225 // an inconsistent state (pointing to the middle of callee-saved area).
226 // The interrupt handler can end up clobbering the registers.
227 AFI->setShouldRestoreSPFromFP(true);
230 if (STI.isTargetELF() && hasFP(MF))
231 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
232 AFI->getFramePtrSpillOffset());
234 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
235 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
236 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
238 // If we need dynamic stack realignment, do it here. Be paranoid and make
239 // sure if we also have VLAs, we have a base pointer for frame access.
240 if (RegInfo->needsStackRealignment(MF)) {
241 unsigned MaxAlign = MFI->getMaxAlignment();
242 assert (!AFI->isThumb1OnlyFunction());
243 if (!AFI->isThumbFunction()) {
244 // Emit bic sp, sp, MaxAlign
245 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
246 TII.get(ARM::BICri), ARM::SP)
247 .addReg(ARM::SP, RegState::Kill)
248 .addImm(MaxAlign-1)));
250 // We cannot use sp as source/dest register here, thus we're emitting the
251 // following sequence:
253 // bic r4, r4, MaxAlign
255 // FIXME: It will be better just to find spare register here.
256 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
257 .addReg(ARM::SP, RegState::Kill);
258 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
259 TII.get(ARM::t2BICri), ARM::R4)
260 .addReg(ARM::R4, RegState::Kill)
261 .addImm(MaxAlign-1)));
262 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
263 .addReg(ARM::R4, RegState::Kill);
266 AFI->setShouldRestoreSPFromFP(true);
269 // If we need a base pointer, set it up here. It's whatever the value
270 // of the stack pointer is at this point. Any variable size objects
271 // will be allocated after this, so we can still use the base pointer
272 // to reference locals.
273 if (RegInfo->hasBasePointer(MF)) {
275 BuildMI(MBB, MBBI, dl,
276 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
278 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
280 BuildMI(MBB, MBBI, dl,
281 TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
285 // If the frame has variable sized objects then the epilogue must restore
287 if (MFI->hasVarSizedObjects())
288 AFI->setShouldRestoreSPFromFP(true);
291 void ARMFrameInfo::emitEpilogue(MachineFunction &MF,
292 MachineBasicBlock &MBB) const {
293 MachineBasicBlock::iterator MBBI = prior(MBB.end());
294 assert(MBBI->getDesc().isReturn() &&
295 "Can only insert epilog into returning blocks");
296 unsigned RetOpcode = MBBI->getOpcode();
297 DebugLoc dl = MBBI->getDebugLoc();
298 MachineFrameInfo *MFI = MF.getFrameInfo();
299 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
300 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
301 const ARMBaseInstrInfo &TII =
302 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
303 assert(!AFI->isThumb1OnlyFunction() &&
304 "This emitEpilogue does not support Thumb1!");
305 bool isARM = !AFI->isThumbFunction();
307 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
308 int NumBytes = (int)MFI->getStackSize();
309 unsigned FramePtr = RegInfo->getFrameRegister(MF);
311 if (!AFI->hasStackFrame()) {
313 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
315 // Unwind MBBI to point to first LDR / VLDRD.
316 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
317 if (MBBI != MBB.begin()) {
320 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
321 if (!isCSRestore(MBBI, TII, CSRegs))
325 // Move SP to start of FP callee save spill area.
326 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
327 AFI->getGPRCalleeSavedArea2Size() +
328 AFI->getDPRCalleeSavedAreaSize());
330 // Reset SP based on frame pointer only if the stack frame extends beyond
331 // frame pointer stack slot or target is ELF and the function has FP.
332 if (AFI->shouldRestoreSPFromFP()) {
333 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
336 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
339 // It's not possible to restore SP from FP in a single instruction.
340 // For Darwin, this looks like:
343 // This is bad, if an interrupt is taken after the mov, sp is in an
344 // inconsistent state.
345 // Use the first callee-saved register as a scratch register.
346 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
347 "No scratch register to restore SP from FP!");
348 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
350 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
356 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
357 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
359 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
363 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
365 // Increment past our save areas.
366 if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
367 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
368 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
371 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
372 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
373 // Tail call return: adjust the stack pointer and jump to callee.
374 MBBI = prior(MBB.end());
375 MachineOperand &JumpTarget = MBBI->getOperand(0);
377 // Jump to label or value in register.
378 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
379 unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
380 ? (STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)
381 : (STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND);
382 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
383 if (JumpTarget.isGlobal())
384 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
385 JumpTarget.getTargetFlags());
387 assert(JumpTarget.isSymbol());
388 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
389 JumpTarget.getTargetFlags());
391 } else if (RetOpcode == ARM::TCRETURNri) {
392 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
393 addReg(JumpTarget.getReg(), RegState::Kill);
394 } else if (RetOpcode == ARM::TCRETURNriND) {
395 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
396 addReg(JumpTarget.getReg(), RegState::Kill);
399 MachineInstr *NewMI = prior(MBBI);
400 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
401 NewMI->addOperand(MBBI->getOperand(i));
403 // Delete the pseudo instruction TCRETURN.
408 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
411 // Provide a base+offset reference to an FI slot for debug info. It's the
412 // same as what we use for resolving the code-gen references for now.
413 // FIXME: This can go wrong when references are SP-relative and simple call
414 // frames aren't used.
416 ARMFrameInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
417 unsigned &FrameReg) const {
418 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
422 ARMFrameInfo::ResolveFrameIndexReference(const MachineFunction &MF,
426 const MachineFrameInfo *MFI = MF.getFrameInfo();
427 const ARMBaseRegisterInfo *RegInfo =
428 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
429 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
430 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
431 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
432 bool isFixed = MFI->isFixedObjectIndex(FI);
436 if (AFI->isGPRCalleeSavedArea1Frame(FI))
437 return Offset - AFI->getGPRCalleeSavedArea1Offset();
438 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
439 return Offset - AFI->getGPRCalleeSavedArea2Offset();
440 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
441 return Offset - AFI->getDPRCalleeSavedAreaOffset();
443 // When dynamically realigning the stack, use the frame pointer for
444 // parameters, and the stack/base pointer for locals.
445 if (RegInfo->needsStackRealignment(MF)) {
446 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
448 FrameReg = RegInfo->getFrameRegister(MF);
450 } else if (MFI->hasVarSizedObjects()) {
451 assert(RegInfo->hasBasePointer(MF) &&
452 "VLAs and dynamic stack alignment, but missing base pointer!");
453 FrameReg = RegInfo->getBaseRegister();
458 // If there is a frame pointer, use it when we can.
459 if (hasFP(MF) && AFI->hasStackFrame()) {
460 // Use frame pointer to reference fixed objects. Use it for locals if
461 // there are VLAs (and thus the SP isn't reliable as a base).
462 if (isFixed || (MFI->hasVarSizedObjects() &&
463 !RegInfo->hasBasePointer(MF))) {
464 FrameReg = RegInfo->getFrameRegister(MF);
466 } else if (MFI->hasVarSizedObjects()) {
467 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
468 // Try to use the frame pointer if we can, else use the base pointer
469 // since it's available. This is handy for the emergency spill slot, in
471 if (AFI->isThumb2Function()) {
472 if (FPOffset >= -255 && FPOffset < 0) {
473 FrameReg = RegInfo->getFrameRegister(MF);
477 FrameReg = RegInfo->getBaseRegister();
478 } else if (AFI->isThumb2Function()) {
479 // In Thumb2 mode, the negative offset is very limited. Try to avoid
480 // out of range references.
481 if (FPOffset >= -255 && FPOffset < 0) {
482 FrameReg = RegInfo->getFrameRegister(MF);
485 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
486 // Otherwise, use SP or FP, whichever is closer to the stack slot.
487 FrameReg = RegInfo->getFrameRegister(MF);
491 // Use the base pointer if we have one.
492 if (RegInfo->hasBasePointer(MF))
493 FrameReg = RegInfo->getBaseRegister();
497 int ARMFrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
499 return getFrameIndexReference(MF, FI, FrameReg);
502 void ARMFrameInfo::emitPushInst(MachineBasicBlock &MBB,
503 MachineBasicBlock::iterator MI,
504 const std::vector<CalleeSavedInfo> &CSI,
505 unsigned StmOpc, unsigned StrOpc, bool NoGap,
506 bool(*Func)(unsigned, bool)) const {
507 MachineFunction &MF = *MBB.getParent();
508 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
511 if (MI != MBB.end()) DL = MI->getDebugLoc();
513 SmallVector<std::pair<unsigned,bool>, 4> Regs;
514 unsigned i = CSI.size();
516 unsigned LastReg = 0;
517 for (; i != 0; --i) {
518 unsigned Reg = CSI[i-1].getReg();
519 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
521 // Add the callee-saved register as live-in unless it's LR and
522 // @llvm.returnaddress is called. If LR is returned for
523 // @llvm.returnaddress then it's already added to the function and
524 // entry block live-in sets.
526 if (Reg == ARM::LR) {
527 if (MF.getFrameInfo()->isReturnAddressTaken() &&
528 MF.getRegInfo().isLiveIn(Reg))
535 // If NoGap is true, push consecutive registers and then leave the rest
536 // for other instructions. e.g.
537 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
538 if (NoGap && LastReg && LastReg != Reg-1)
541 Regs.push_back(std::make_pair(Reg, isKill));
546 if (Regs.size() > 1 || StrOpc== 0) {
547 MachineInstrBuilder MIB =
548 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
550 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
551 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
552 } else if (Regs.size() == 1) {
553 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
555 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
557 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
558 // that refactoring is complete (eventually).
559 if (StrOpc == ARM::STR_PRE) {
561 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::sub, 4, ARM_AM::no_shift));
570 void ARMFrameInfo::emitPopInst(MachineBasicBlock &MBB,
571 MachineBasicBlock::iterator MI,
572 const std::vector<CalleeSavedInfo> &CSI,
573 unsigned LdmOpc, unsigned LdrOpc,
574 bool isVarArg, bool NoGap,
575 bool(*Func)(unsigned, bool)) const {
576 MachineFunction &MF = *MBB.getParent();
577 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
578 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
579 DebugLoc DL = MI->getDebugLoc();
581 SmallVector<unsigned, 4> Regs;
582 unsigned i = CSI.size();
584 unsigned LastReg = 0;
585 bool DeleteRet = false;
586 for (; i != 0; --i) {
587 unsigned Reg = CSI[i-1].getReg();
588 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
590 if (Reg == ARM::LR && !isVarArg) {
592 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
593 // Fold the return instruction into the LDM.
597 // If NoGap is true, pop consecutive registers and then leave the rest
598 // for other instructions. e.g.
599 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
600 if (NoGap && LastReg && LastReg != Reg-1)
609 if (Regs.size() > 1 || LdrOpc == 0) {
610 MachineInstrBuilder MIB =
611 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
613 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
614 MIB.addReg(Regs[i], getDefRegState(true));
616 MI->eraseFromParent();
618 } else if (Regs.size() == 1) {
619 // If we adjusted the reg to PC from LR above, switch it back here. We
620 // only do that for LDM.
621 if (Regs[0] == ARM::PC)
623 MachineInstrBuilder MIB =
624 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
625 .addReg(ARM::SP, RegState::Define)
627 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
628 // that refactoring is complete (eventually).
629 if (LdrOpc == ARM::LDR_POST) {
631 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
640 bool ARMFrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
641 MachineBasicBlock::iterator MI,
642 const std::vector<CalleeSavedInfo> &CSI,
643 const TargetRegisterInfo *TRI) const {
647 MachineFunction &MF = *MBB.getParent();
648 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
649 DebugLoc DL = MI->getDebugLoc();
651 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
652 unsigned PushOneOpc = AFI->isThumbFunction() ? ARM::t2STR_PRE : ARM::STR_PRE;
653 unsigned FltOpc = ARM::VSTMDDB_UPD;
654 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register);
655 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register);
656 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register);
661 bool ARMFrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
662 MachineBasicBlock::iterator MI,
663 const std::vector<CalleeSavedInfo> &CSI,
664 const TargetRegisterInfo *TRI) const {
668 MachineFunction &MF = *MBB.getParent();
669 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
670 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
671 DebugLoc DL = MI->getDebugLoc();
673 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
674 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST;
675 unsigned FltOpc = ARM::VLDMDIA_UPD;
676 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register);
677 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
678 &isARMArea2Register);
679 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
680 &isARMArea1Register);
685 // FIXME: Make generic?
686 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
687 const ARMBaseInstrInfo &TII) {
689 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
691 const MachineBasicBlock &MBB = *MBBI;
692 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
694 FnSize += TII.GetInstSizeInBytes(I);
699 /// estimateStackSize - Estimate and return the size of the frame.
700 /// FIXME: Make generic?
701 static unsigned estimateStackSize(MachineFunction &MF) {
702 const MachineFrameInfo *FFI = MF.getFrameInfo();
704 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
705 int FixedOff = -FFI->getObjectOffset(i);
706 if (FixedOff > Offset) Offset = FixedOff;
708 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
709 if (FFI->isDeadObjectIndex(i))
711 Offset += FFI->getObjectSize(i);
712 unsigned Align = FFI->getObjectAlignment(i);
713 // Adjust to alignment boundary
714 Offset = (Offset+Align-1)/Align*Align;
716 return (unsigned)Offset;
719 /// estimateRSStackSizeLimit - Look at each instruction that references stack
720 /// frames and return the stack size limit beyond which some of these
721 /// instructions will require a scratch register during their expansion later.
722 // FIXME: Move to TII?
723 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
724 const TargetFrameInfo *TFI) {
725 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
726 unsigned Limit = (1 << 12) - 1;
727 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
728 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
730 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
731 if (!I->getOperand(i).isFI()) continue;
733 // When using ADDri to get the address of a stack object, 255 is the
734 // largest offset guaranteed to fit in the immediate offset.
735 if (I->getOpcode() == ARM::ADDri) {
736 Limit = std::min(Limit, (1U << 8) - 1);
740 // Otherwise check the addressing mode.
741 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
742 case ARMII::AddrMode3:
743 case ARMII::AddrModeT2_i8:
744 Limit = std::min(Limit, (1U << 8) - 1);
746 case ARMII::AddrMode5:
747 case ARMII::AddrModeT2_i8s4:
748 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
750 case ARMII::AddrModeT2_i12:
751 // i12 supports only positive offset so these will be converted to
752 // i8 opcodes. See llvm::rewriteT2FrameIndex.
753 if (TFI->hasFP(MF) && AFI->hasStackFrame())
754 Limit = std::min(Limit, (1U << 8) - 1);
756 case ARMII::AddrMode4:
757 case ARMII::AddrMode6:
758 // Addressing modes 4 & 6 (load/store) instructions can't encode an
759 // immediate offset for stack references.
764 break; // At most one FI per instruction
773 ARMFrameInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
774 RegScavenger *RS) const {
775 // This tells PEI to spill the FP as if it is any other callee-save register
776 // to take advantage the eliminateFrameIndex machinery. This also ensures it
777 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
778 // to combine multiple loads / stores.
779 bool CanEliminateFrame = true;
780 bool CS1Spilled = false;
781 bool LRSpilled = false;
782 unsigned NumGPRSpills = 0;
783 SmallVector<unsigned, 4> UnspilledCS1GPRs;
784 SmallVector<unsigned, 4> UnspilledCS2GPRs;
785 const ARMBaseRegisterInfo *RegInfo =
786 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
787 const ARMBaseInstrInfo &TII =
788 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
789 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
790 MachineFrameInfo *MFI = MF.getFrameInfo();
791 unsigned FramePtr = RegInfo->getFrameRegister(MF);
793 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
794 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
795 // since it's always posible to restore sp from fp in a single instruction.
796 // FIXME: It will be better just to find spare register here.
797 if (AFI->isThumb2Function() &&
798 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
799 MF.getRegInfo().setPhysRegUsed(ARM::R4);
801 // Spill LR if Thumb1 function uses variable length argument lists.
802 if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
803 MF.getRegInfo().setPhysRegUsed(ARM::LR);
805 // Spill the BasePtr if it's used.
806 if (RegInfo->hasBasePointer(MF))
807 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
809 // Don't spill FP if the frame can be eliminated. This is determined
810 // by scanning the callee-save registers to see if any is used.
811 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
812 for (unsigned i = 0; CSRegs[i]; ++i) {
813 unsigned Reg = CSRegs[i];
814 bool Spilled = false;
815 if (MF.getRegInfo().isPhysRegUsed(Reg)) {
816 AFI->setCSRegisterIsSpilled(Reg);
818 CanEliminateFrame = false;
820 // Check alias registers too.
821 for (const unsigned *Aliases =
822 RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
823 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
825 CanEliminateFrame = false;
830 if (!ARM::GPRRegisterClass->contains(Reg))
836 if (!STI.isTargetDarwin()) {
843 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
848 case ARM::R4: case ARM::R5:
849 case ARM::R6: case ARM::R7:
856 if (!STI.isTargetDarwin()) {
857 UnspilledCS1GPRs.push_back(Reg);
862 case ARM::R4: case ARM::R5:
863 case ARM::R6: case ARM::R7:
865 UnspilledCS1GPRs.push_back(Reg);
868 UnspilledCS2GPRs.push_back(Reg);
874 bool ForceLRSpill = false;
875 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
876 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
877 // Force LR to be spilled if the Thumb function size is > 2048. This enables
878 // use of BL to implement far jump. If it turns out that it's not needed
879 // then the branch fix up path will undo it.
880 if (FnSize >= (1 << 11)) {
881 CanEliminateFrame = false;
886 // If any of the stack slot references may be out of range of an immediate
887 // offset, make sure a register (or a spill slot) is available for the
888 // register scavenger. Note that if we're indexing off the frame pointer, the
889 // effective stack size is 4 bytes larger since the FP points to the stack
890 // slot of the previous FP. Also, if we have variable sized objects in the
891 // function, stack slot references will often be negative, and some of
892 // our instructions are positive-offset only, so conservatively consider
893 // that case to want a spill slot (or register) as well. Similarly, if
894 // the function adjusts the stack pointer during execution and the
895 // adjustments aren't already part of our stack size estimate, our offset
896 // calculations may be off, so be conservative.
897 // FIXME: We could add logic to be more precise about negative offsets
898 // and which instructions will need a scratch register for them. Is it
899 // worth the effort and added fragility?
902 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
903 estimateRSStackSizeLimit(MF, this)))
904 || MFI->hasVarSizedObjects()
905 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
907 bool ExtraCSSpill = false;
908 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
909 AFI->setHasStackFrame(true);
911 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
912 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
913 if (!LRSpilled && CS1Spilled) {
914 MF.getRegInfo().setPhysRegUsed(ARM::LR);
915 AFI->setCSRegisterIsSpilled(ARM::LR);
917 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
918 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
919 ForceLRSpill = false;
924 MF.getRegInfo().setPhysRegUsed(FramePtr);
928 // If stack and double are 8-byte aligned and we are spilling an odd number
929 // of GPRs, spill one extra callee save GPR so we won't have to pad between
930 // the integer and double callee save areas.
931 unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
932 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
933 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
934 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
935 unsigned Reg = UnspilledCS1GPRs[i];
936 // Don't spill high register if the function is thumb1
937 if (!AFI->isThumb1OnlyFunction() ||
938 isARMLowRegister(Reg) || Reg == ARM::LR) {
939 MF.getRegInfo().setPhysRegUsed(Reg);
940 AFI->setCSRegisterIsSpilled(Reg);
941 if (!RegInfo->isReservedReg(MF, Reg))
946 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
947 unsigned Reg = UnspilledCS2GPRs.front();
948 MF.getRegInfo().setPhysRegUsed(Reg);
949 AFI->setCSRegisterIsSpilled(Reg);
950 if (!RegInfo->isReservedReg(MF, Reg))
955 // Estimate if we might need to scavenge a register at some point in order
956 // to materialize a stack offset. If so, either spill one additional
957 // callee-saved register or reserve a special spill slot to facilitate
958 // register scavenging. Thumb1 needs a spill slot for stack pointer
959 // adjustments also, even when the frame itself is small.
960 if (BigStack && !ExtraCSSpill) {
961 // If any non-reserved CS register isn't spilled, just spill one or two
962 // extra. That should take care of it!
963 unsigned NumExtras = TargetAlign / 4;
964 SmallVector<unsigned, 2> Extras;
965 while (NumExtras && !UnspilledCS1GPRs.empty()) {
966 unsigned Reg = UnspilledCS1GPRs.back();
967 UnspilledCS1GPRs.pop_back();
968 if (!RegInfo->isReservedReg(MF, Reg) &&
969 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
971 Extras.push_back(Reg);
975 // For non-Thumb1 functions, also check for hi-reg CS registers
976 if (!AFI->isThumb1OnlyFunction()) {
977 while (NumExtras && !UnspilledCS2GPRs.empty()) {
978 unsigned Reg = UnspilledCS2GPRs.back();
979 UnspilledCS2GPRs.pop_back();
980 if (!RegInfo->isReservedReg(MF, Reg)) {
981 Extras.push_back(Reg);
986 if (Extras.size() && NumExtras == 0) {
987 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
988 MF.getRegInfo().setPhysRegUsed(Extras[i]);
989 AFI->setCSRegisterIsSpilled(Extras[i]);
991 } else if (!AFI->isThumb1OnlyFunction()) {
992 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
993 // closest to SP or frame pointer.
994 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
995 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1003 MF.getRegInfo().setPhysRegUsed(ARM::LR);
1004 AFI->setCSRegisterIsSpilled(ARM::LR);
1005 AFI->setLRIsSpilledForFarJump(true);