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 "ARMBaseInstrInfo.h"
16 #include "ARMMachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/RegisterScavenging.h"
22 #include "llvm/Target/TargetOptions.h"
26 /// hasFP - Return true if the specified function should have a dedicated frame
27 /// pointer register. This is true if the function has variable sized allocas
28 /// or if frame pointer elimination is disabled.
30 bool ARMFrameInfo::hasFP(const MachineFunction &MF) const {
31 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
33 // Mac OS X requires FP not to be clobbered for backtracing purpose.
34 if (STI.isTargetDarwin())
37 const MachineFrameInfo *MFI = MF.getFrameInfo();
38 // Always eliminate non-leaf frame pointers.
39 return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
40 RegInfo->needsStackRealignment(MF) ||
41 MFI->hasVarSizedObjects() ||
42 MFI->isFrameAddressTaken());
45 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
46 // not required, we reserve argument space for call sites in the function
47 // immediately on entry to the current function. This eliminates the need for
48 // add/sub sp brackets around call sites. Returns true if the call frame is
49 // included as part of the stack frame.
50 bool ARMFrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
51 const MachineFrameInfo *FFI = MF.getFrameInfo();
52 unsigned CFSize = FFI->getMaxCallFrameSize();
53 // It's not always a good idea to include the call frame as part of the
54 // stack frame. ARM (especially Thumb) has small immediate offset to
55 // address the stack frame. So a large call frame can cause poor codegen
56 // and may even makes it impossible to scavenge a register.
57 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
60 return !MF.getFrameInfo()->hasVarSizedObjects();
63 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
64 // call frame pseudos can be simplified. Unlike most targets, having a FP
65 // is not sufficient here since we still may reference some objects via SP
66 // even when FP is available in Thumb2 mode.
67 bool ARMFrameInfo::canSimplifyCallFramePseudos(const MachineFunction &MF)const {
68 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
71 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
72 for (unsigned i = 0; CSRegs[i]; ++i)
78 static bool isCSRestore(MachineInstr *MI,
79 const ARMBaseInstrInfo &TII,
80 const unsigned *CSRegs) {
81 // Integer spill area is handled with "pop".
82 if (MI->getOpcode() == ARM::LDMIA_RET ||
83 MI->getOpcode() == ARM::t2LDMIA_RET ||
84 MI->getOpcode() == ARM::LDMIA_UPD ||
85 MI->getOpcode() == ARM::t2LDMIA_UPD ||
86 MI->getOpcode() == ARM::VLDMDIA_UPD) {
87 // The first two operands are predicates. The last two are
88 // imp-def and imp-use of SP. Check everything in between.
89 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
90 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
99 emitSPUpdate(bool isARM,
100 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
101 DebugLoc dl, const ARMBaseInstrInfo &TII,
103 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
105 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
108 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
112 void ARMFrameInfo::emitPrologue(MachineFunction &MF) const {
113 MachineBasicBlock &MBB = MF.front();
114 MachineBasicBlock::iterator MBBI = MBB.begin();
115 MachineFrameInfo *MFI = MF.getFrameInfo();
116 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
117 const ARMBaseRegisterInfo *RegInfo =
118 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
119 const ARMBaseInstrInfo &TII =
120 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
121 assert(!AFI->isThumb1OnlyFunction() &&
122 "This emitPrologue does not support Thumb1!");
123 bool isARM = !AFI->isThumbFunction();
124 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
125 unsigned NumBytes = MFI->getStackSize();
126 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
127 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
128 unsigned FramePtr = RegInfo->getFrameRegister(MF);
130 // Determine the sizes of each callee-save spill areas and record which frame
131 // belongs to which callee-save spill areas.
132 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
133 int FramePtrSpillFI = 0;
135 // Allocate the vararg register save area. This is not counted in NumBytes.
137 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
139 if (!AFI->hasStackFrame()) {
141 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
145 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
146 unsigned Reg = CSI[i].getReg();
147 int FI = CSI[i].getFrameIdx();
155 FramePtrSpillFI = FI;
156 AFI->addGPRCalleeSavedArea1Frame(FI);
164 FramePtrSpillFI = FI;
165 if (STI.isTargetDarwin()) {
166 AFI->addGPRCalleeSavedArea2Frame(FI);
169 AFI->addGPRCalleeSavedArea1Frame(FI);
174 AFI->addDPRCalleeSavedAreaFrame(FI);
180 if (GPRCS1Size > 0) MBBI++;
182 // Set FP to point to the stack slot that contains the previous FP.
183 // For Darwin, FP is R7, which has now been stored in spill area 1.
184 // Otherwise, if this is not Darwin, all the callee-saved registers go
185 // into spill area 1, including the FP in R11. In either case, it is
186 // now safe to emit this assignment.
187 bool HasFP = hasFP(MF);
189 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
190 MachineInstrBuilder MIB =
191 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
192 .addFrameIndex(FramePtrSpillFI).addImm(0);
193 AddDefaultCC(AddDefaultPred(MIB));
197 if (GPRCS2Size > 0) MBBI++;
199 // Determine starting offsets of spill areas.
200 unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
201 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
202 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
204 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
206 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
207 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
208 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
211 if (DPRCSSize > 0) MBBI++;
213 NumBytes = DPRCSOffset;
215 // Adjust SP after all the callee-save spills.
216 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
218 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
219 // Note it's not safe to do this in Thumb2 mode because it would have
220 // taken two instructions:
223 // If an interrupt is taken between the two instructions, then sp is in
224 // an inconsistent state (pointing to the middle of callee-saved area).
225 // The interrupt handler can end up clobbering the registers.
226 AFI->setShouldRestoreSPFromFP(true);
229 if (STI.isTargetELF() && hasFP(MF))
230 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
231 AFI->getFramePtrSpillOffset());
233 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
234 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
235 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
237 // If we need dynamic stack realignment, do it here. Be paranoid and make
238 // sure if we also have VLAs, we have a base pointer for frame access.
239 if (RegInfo->needsStackRealignment(MF)) {
240 unsigned MaxAlign = MFI->getMaxAlignment();
241 assert (!AFI->isThumb1OnlyFunction());
242 if (!AFI->isThumbFunction()) {
243 // Emit bic sp, sp, MaxAlign
244 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
245 TII.get(ARM::BICri), ARM::SP)
246 .addReg(ARM::SP, RegState::Kill)
247 .addImm(MaxAlign-1)));
249 // We cannot use sp as source/dest register here, thus we're emitting the
250 // following sequence:
252 // bic r4, r4, MaxAlign
254 // FIXME: It will be better just to find spare register here.
255 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
256 .addReg(ARM::SP, RegState::Kill);
257 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
258 TII.get(ARM::t2BICri), ARM::R4)
259 .addReg(ARM::R4, RegState::Kill)
260 .addImm(MaxAlign-1)));
261 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
262 .addReg(ARM::R4, RegState::Kill);
265 AFI->setShouldRestoreSPFromFP(true);
268 // If we need a base pointer, set it up here. It's whatever the value
269 // of the stack pointer is at this point. Any variable size objects
270 // will be allocated after this, so we can still use the base pointer
271 // to reference locals.
272 if (RegInfo->hasBasePointer(MF)) {
274 BuildMI(MBB, MBBI, dl,
275 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
277 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
279 BuildMI(MBB, MBBI, dl,
280 TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
284 // If the frame has variable sized objects then the epilogue must restore
286 if (MFI->hasVarSizedObjects())
287 AFI->setShouldRestoreSPFromFP(true);
290 void ARMFrameInfo::emitEpilogue(MachineFunction &MF,
291 MachineBasicBlock &MBB) const {
292 MachineBasicBlock::iterator MBBI = prior(MBB.end());
293 assert(MBBI->getDesc().isReturn() &&
294 "Can only insert epilog into returning blocks");
295 unsigned RetOpcode = MBBI->getOpcode();
296 DebugLoc dl = MBBI->getDebugLoc();
297 MachineFrameInfo *MFI = MF.getFrameInfo();
298 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
299 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
300 const ARMBaseInstrInfo &TII =
301 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
302 assert(!AFI->isThumb1OnlyFunction() &&
303 "This emitEpilogue does not support Thumb1!");
304 bool isARM = !AFI->isThumbFunction();
306 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
307 int NumBytes = (int)MFI->getStackSize();
308 unsigned FramePtr = RegInfo->getFrameRegister(MF);
310 if (!AFI->hasStackFrame()) {
312 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
314 // Unwind MBBI to point to first LDR / VLDRD.
315 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
316 if (MBBI != MBB.begin()) {
319 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
320 if (!isCSRestore(MBBI, TII, CSRegs))
324 // Move SP to start of FP callee save spill area.
325 NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
326 AFI->getGPRCalleeSavedArea2Size() +
327 AFI->getDPRCalleeSavedAreaSize());
329 // Reset SP based on frame pointer only if the stack frame extends beyond
330 // frame pointer stack slot or target is ELF and the function has FP.
331 if (AFI->shouldRestoreSPFromFP()) {
332 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
335 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
338 // It's not possible to restore SP from FP in a single instruction.
339 // For Darwin, this looks like:
342 // This is bad, if an interrupt is taken after the mov, sp is in an
343 // inconsistent state.
344 // Use the first callee-saved register as a scratch register.
345 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
346 "No scratch register to restore SP from FP!");
347 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
349 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
355 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
356 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
358 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
362 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
364 // Increment past our save areas.
365 if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
366 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
367 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
370 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
371 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
372 // Tail call return: adjust the stack pointer and jump to callee.
373 MBBI = prior(MBB.end());
374 MachineOperand &JumpTarget = MBBI->getOperand(0);
376 // Jump to label or value in register.
377 if (RetOpcode == ARM::TCRETURNdi) {
378 BuildMI(MBB, MBBI, dl,
379 TII.get(STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)).
380 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
381 JumpTarget.getTargetFlags());
382 } else if (RetOpcode == ARM::TCRETURNdiND) {
383 BuildMI(MBB, MBBI, dl,
384 TII.get(STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND)).
385 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
386 JumpTarget.getTargetFlags());
387 } else if (RetOpcode == ARM::TCRETURNri) {
388 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
389 addReg(JumpTarget.getReg(), RegState::Kill);
390 } else if (RetOpcode == ARM::TCRETURNriND) {
391 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
392 addReg(JumpTarget.getReg(), RegState::Kill);
395 MachineInstr *NewMI = prior(MBBI);
396 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
397 NewMI->addOperand(MBBI->getOperand(i));
399 // Delete the pseudo instruction TCRETURN.
404 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
407 // Provide a base+offset reference to an FI slot for debug info. It's the
408 // same as what we use for resolving the code-gen references for now.
409 // FIXME: This can go wrong when references are SP-relative and simple call
410 // frames aren't used.
412 ARMFrameInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
413 unsigned &FrameReg) const {
414 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
418 ARMFrameInfo::ResolveFrameIndexReference(const MachineFunction &MF,
422 const MachineFrameInfo *MFI = MF.getFrameInfo();
423 const ARMBaseRegisterInfo *RegInfo =
424 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
425 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
426 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
427 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
428 bool isFixed = MFI->isFixedObjectIndex(FI);
432 if (AFI->isGPRCalleeSavedArea1Frame(FI))
433 return Offset - AFI->getGPRCalleeSavedArea1Offset();
434 else if (AFI->isGPRCalleeSavedArea2Frame(FI))
435 return Offset - AFI->getGPRCalleeSavedArea2Offset();
436 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
437 return Offset - AFI->getDPRCalleeSavedAreaOffset();
439 // When dynamically realigning the stack, use the frame pointer for
440 // parameters, and the stack/base pointer for locals.
441 if (RegInfo->needsStackRealignment(MF)) {
442 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
444 FrameReg = RegInfo->getFrameRegister(MF);
446 } else if (MFI->hasVarSizedObjects()) {
447 assert(RegInfo->hasBasePointer(MF) &&
448 "VLAs and dynamic stack alignment, but missing base pointer!");
449 FrameReg = RegInfo->getBaseRegister();
454 // If there is a frame pointer, use it when we can.
455 if (hasFP(MF) && AFI->hasStackFrame()) {
456 // Use frame pointer to reference fixed objects. Use it for locals if
457 // there are VLAs (and thus the SP isn't reliable as a base).
458 if (isFixed || (MFI->hasVarSizedObjects() && !RegInfo->hasBasePointer(MF))) {
459 FrameReg = RegInfo->getFrameRegister(MF);
461 } else if (MFI->hasVarSizedObjects()) {
462 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
463 // Try to use the frame pointer if we can, else use the base pointer
464 // since it's available. This is handy for the emergency spill slot, in
466 if (AFI->isThumb2Function()) {
467 if (FPOffset >= -255 && FPOffset < 0) {
468 FrameReg = RegInfo->getFrameRegister(MF);
472 FrameReg = RegInfo->getBaseRegister();
473 } else if (AFI->isThumb2Function()) {
474 // In Thumb2 mode, the negative offset is very limited. Try to avoid
475 // out of range references.
476 if (FPOffset >= -255 && FPOffset < 0) {
477 FrameReg = RegInfo->getFrameRegister(MF);
480 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
481 // Otherwise, use SP or FP, whichever is closer to the stack slot.
482 FrameReg = RegInfo->getFrameRegister(MF);
486 // Use the base pointer if we have one.
487 if (RegInfo->hasBasePointer(MF))
488 FrameReg = RegInfo->getBaseRegister();
492 int ARMFrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
494 return getFrameIndexReference(MF, FI, FrameReg);
497 void ARMFrameInfo::emitPushInst(MachineBasicBlock &MBB,
498 MachineBasicBlock::iterator MI,
499 const std::vector<CalleeSavedInfo> &CSI,
501 bool(*Func)(unsigned, bool)) const {
502 MachineFunction &MF = *MBB.getParent();
503 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
506 if (MI != MBB.end()) DL = MI->getDebugLoc();
508 MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(Opc));
509 MIB.addReg(ARM::SP, getDefRegState(true));
512 bool NumRegs = false;
513 for (unsigned i = CSI.size(); i != 0; --i) {
514 unsigned Reg = CSI[i-1].getReg();
515 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
517 // Add the callee-saved register as live-in unless it's LR and
518 // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
519 // then it's already added to the function and entry block live-in sets.
521 if (Reg == ARM::LR) {
522 if (MF.getFrameInfo()->isReturnAddressTaken() &&
523 MF.getRegInfo().isLiveIn(Reg))
531 MIB.addReg(Reg, getKillRegState(isKill));
534 // It's illegal to emit push instruction without operands.
536 MBB.insert(MI, &*MIB);
538 MF.DeleteMachineInstr(MIB);
541 bool ARMFrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
542 MachineBasicBlock::iterator MI,
543 const std::vector<CalleeSavedInfo> &CSI,
544 const TargetRegisterInfo *TRI) const {
548 MachineFunction &MF = *MBB.getParent();
549 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
550 DebugLoc DL = MI->getDebugLoc();
552 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
553 unsigned FltOpc = ARM::VSTMDDB_UPD;
554 emitPushInst(MBB, MI, CSI, PushOpc, &isARMArea1Register);
555 emitPushInst(MBB, MI, CSI, PushOpc, &isARMArea2Register);
556 emitPushInst(MBB, MI, CSI, FltOpc, &isARMArea3Register);
561 void ARMFrameInfo::emitPopInst(MachineBasicBlock &MBB,
562 MachineBasicBlock::iterator MI,
563 const std::vector<CalleeSavedInfo> &CSI,
564 unsigned Opc, bool isVarArg,
565 bool(*Func)(unsigned, bool)) const {
566 MachineFunction &MF = *MBB.getParent();
567 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
568 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
569 DebugLoc DL = MI->getDebugLoc();
571 MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(Opc));
572 MIB.addReg(ARM::SP, getDefRegState(true));
575 bool NumRegs = false;
576 for (unsigned i = CSI.size(); i != 0; --i) {
577 unsigned Reg = CSI[i-1].getReg();
578 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
580 if (Reg == ARM::LR && !isVarArg) {
582 unsigned Opc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
583 (*MIB).setDesc(TII.get(Opc));
587 MIB.addReg(Reg, RegState::Define);
591 // It's illegal to emit pop instruction without operands.
593 MBB.insert(MI, &*MIB);
595 MF.DeleteMachineInstr(MIB);
598 bool ARMFrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
599 MachineBasicBlock::iterator MI,
600 const std::vector<CalleeSavedInfo> &CSI,
601 const TargetRegisterInfo *TRI) const {
605 MachineFunction &MF = *MBB.getParent();
606 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
607 bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
608 DebugLoc DL = MI->getDebugLoc();
610 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
611 unsigned FltOpc = ARM::VLDMDIA_UPD;
612 emitPopInst(MBB, MI, CSI, FltOpc, isVarArg, &isARMArea3Register);
613 emitPopInst(MBB, MI, CSI, PopOpc, isVarArg, &isARMArea2Register);
614 emitPopInst(MBB, MI, CSI, PopOpc, isVarArg, &isARMArea1Register);
619 // FIXME: Make generic?
620 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
621 const ARMBaseInstrInfo &TII) {
623 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
625 const MachineBasicBlock &MBB = *MBBI;
626 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
628 FnSize += TII.GetInstSizeInBytes(I);
633 /// estimateStackSize - Estimate and return the size of the frame.
634 /// FIXME: Make generic?
635 static unsigned estimateStackSize(MachineFunction &MF) {
636 const MachineFrameInfo *FFI = MF.getFrameInfo();
638 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
639 int FixedOff = -FFI->getObjectOffset(i);
640 if (FixedOff > Offset) Offset = FixedOff;
642 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
643 if (FFI->isDeadObjectIndex(i))
645 Offset += FFI->getObjectSize(i);
646 unsigned Align = FFI->getObjectAlignment(i);
647 // Adjust to alignment boundary
648 Offset = (Offset+Align-1)/Align*Align;
650 return (unsigned)Offset;
653 /// estimateRSStackSizeLimit - Look at each instruction that references stack
654 /// frames and return the stack size limit beyond which some of these
655 /// instructions will require a scratch register during their expansion later.
656 // FIXME: Move to TII?
657 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
658 const TargetFrameInfo *TFI) {
659 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
660 unsigned Limit = (1 << 12) - 1;
661 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
662 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
664 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
665 if (!I->getOperand(i).isFI()) continue;
667 // When using ADDri to get the address of a stack object, 255 is the
668 // largest offset guaranteed to fit in the immediate offset.
669 if (I->getOpcode() == ARM::ADDri) {
670 Limit = std::min(Limit, (1U << 8) - 1);
674 // Otherwise check the addressing mode.
675 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
676 case ARMII::AddrMode3:
677 case ARMII::AddrModeT2_i8:
678 Limit = std::min(Limit, (1U << 8) - 1);
680 case ARMII::AddrMode5:
681 case ARMII::AddrModeT2_i8s4:
682 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
684 case ARMII::AddrModeT2_i12:
685 // i12 supports only positive offset so these will be converted to
686 // i8 opcodes. See llvm::rewriteT2FrameIndex.
687 if (TFI->hasFP(MF) && AFI->hasStackFrame())
688 Limit = std::min(Limit, (1U << 8) - 1);
690 case ARMII::AddrMode4:
691 case ARMII::AddrMode6:
692 // Addressing modes 4 & 6 (load/store) instructions can't encode an
693 // immediate offset for stack references.
698 break; // At most one FI per instruction
707 ARMFrameInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
708 RegScavenger *RS) const {
709 // This tells PEI to spill the FP as if it is any other callee-save register
710 // to take advantage the eliminateFrameIndex machinery. This also ensures it
711 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
712 // to combine multiple loads / stores.
713 bool CanEliminateFrame = true;
714 bool CS1Spilled = false;
715 bool LRSpilled = false;
716 unsigned NumGPRSpills = 0;
717 SmallVector<unsigned, 4> UnspilledCS1GPRs;
718 SmallVector<unsigned, 4> UnspilledCS2GPRs;
719 const ARMBaseRegisterInfo *RegInfo =
720 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
721 const ARMBaseInstrInfo &TII =
722 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
723 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
724 MachineFrameInfo *MFI = MF.getFrameInfo();
725 unsigned FramePtr = RegInfo->getFrameRegister(MF);
727 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
728 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
729 // since it's always posible to restore sp from fp in a single instruction.
730 // FIXME: It will be better just to find spare register here.
731 if (AFI->isThumb2Function() &&
732 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
733 MF.getRegInfo().setPhysRegUsed(ARM::R4);
735 // Spill LR if Thumb1 function uses variable length argument lists.
736 if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
737 MF.getRegInfo().setPhysRegUsed(ARM::LR);
739 // Spill the BasePtr if it's used.
740 if (RegInfo->hasBasePointer(MF))
741 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
743 // Don't spill FP if the frame can be eliminated. This is determined
744 // by scanning the callee-save registers to see if any is used.
745 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
746 for (unsigned i = 0; CSRegs[i]; ++i) {
747 unsigned Reg = CSRegs[i];
748 bool Spilled = false;
749 if (MF.getRegInfo().isPhysRegUsed(Reg)) {
750 AFI->setCSRegisterIsSpilled(Reg);
752 CanEliminateFrame = false;
754 // Check alias registers too.
755 for (const unsigned *Aliases =
756 RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
757 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
759 CanEliminateFrame = false;
764 if (!ARM::GPRRegisterClass->contains(Reg))
770 if (!STI.isTargetDarwin()) {
777 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
782 case ARM::R4: case ARM::R5:
783 case ARM::R6: case ARM::R7:
790 if (!STI.isTargetDarwin()) {
791 UnspilledCS1GPRs.push_back(Reg);
796 case ARM::R4: case ARM::R5:
797 case ARM::R6: case ARM::R7:
799 UnspilledCS1GPRs.push_back(Reg);
802 UnspilledCS2GPRs.push_back(Reg);
808 bool ForceLRSpill = false;
809 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
810 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
811 // Force LR to be spilled if the Thumb function size is > 2048. This enables
812 // use of BL to implement far jump. If it turns out that it's not needed
813 // then the branch fix up path will undo it.
814 if (FnSize >= (1 << 11)) {
815 CanEliminateFrame = false;
820 // If any of the stack slot references may be out of range of an immediate
821 // offset, make sure a register (or a spill slot) is available for the
822 // register scavenger. Note that if we're indexing off the frame pointer, the
823 // effective stack size is 4 bytes larger since the FP points to the stack
824 // slot of the previous FP. Also, if we have variable sized objects in the
825 // function, stack slot references will often be negative, and some of
826 // our instructions are positive-offset only, so conservatively consider
827 // that case to want a spill slot (or register) as well. Similarly, if
828 // the function adjusts the stack pointer during execution and the
829 // adjustments aren't already part of our stack size estimate, our offset
830 // calculations may be off, so be conservative.
831 // FIXME: We could add logic to be more precise about negative offsets
832 // and which instructions will need a scratch register for them. Is it
833 // worth the effort and added fragility?
836 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
837 estimateRSStackSizeLimit(MF, this)))
838 || MFI->hasVarSizedObjects()
839 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
841 bool ExtraCSSpill = false;
842 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
843 AFI->setHasStackFrame(true);
845 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
846 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
847 if (!LRSpilled && CS1Spilled) {
848 MF.getRegInfo().setPhysRegUsed(ARM::LR);
849 AFI->setCSRegisterIsSpilled(ARM::LR);
851 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
852 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
853 ForceLRSpill = false;
858 MF.getRegInfo().setPhysRegUsed(FramePtr);
862 // If stack and double are 8-byte aligned and we are spilling an odd number
863 // of GPRs, spill one extra callee save GPR so we won't have to pad between
864 // the integer and double callee save areas.
865 unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
866 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
867 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
868 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
869 unsigned Reg = UnspilledCS1GPRs[i];
870 // Don't spill high register if the function is thumb1
871 if (!AFI->isThumb1OnlyFunction() ||
872 isARMLowRegister(Reg) || Reg == ARM::LR) {
873 MF.getRegInfo().setPhysRegUsed(Reg);
874 AFI->setCSRegisterIsSpilled(Reg);
875 if (!RegInfo->isReservedReg(MF, Reg))
880 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
881 unsigned Reg = UnspilledCS2GPRs.front();
882 MF.getRegInfo().setPhysRegUsed(Reg);
883 AFI->setCSRegisterIsSpilled(Reg);
884 if (!RegInfo->isReservedReg(MF, Reg))
889 // Estimate if we might need to scavenge a register at some point in order
890 // to materialize a stack offset. If so, either spill one additional
891 // callee-saved register or reserve a special spill slot to facilitate
892 // register scavenging. Thumb1 needs a spill slot for stack pointer
893 // adjustments also, even when the frame itself is small.
894 if (BigStack && !ExtraCSSpill) {
895 // If any non-reserved CS register isn't spilled, just spill one or two
896 // extra. That should take care of it!
897 unsigned NumExtras = TargetAlign / 4;
898 SmallVector<unsigned, 2> Extras;
899 while (NumExtras && !UnspilledCS1GPRs.empty()) {
900 unsigned Reg = UnspilledCS1GPRs.back();
901 UnspilledCS1GPRs.pop_back();
902 if (!RegInfo->isReservedReg(MF, Reg) &&
903 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
905 Extras.push_back(Reg);
909 // For non-Thumb1 functions, also check for hi-reg CS registers
910 if (!AFI->isThumb1OnlyFunction()) {
911 while (NumExtras && !UnspilledCS2GPRs.empty()) {
912 unsigned Reg = UnspilledCS2GPRs.back();
913 UnspilledCS2GPRs.pop_back();
914 if (!RegInfo->isReservedReg(MF, Reg)) {
915 Extras.push_back(Reg);
920 if (Extras.size() && NumExtras == 0) {
921 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
922 MF.getRegInfo().setPhysRegUsed(Extras[i]);
923 AFI->setCSRegisterIsSpilled(Extras[i]);
925 } else if (!AFI->isThumb1OnlyFunction()) {
926 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
927 // closest to SP or frame pointer.
928 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
929 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
937 MF.getRegInfo().setPhysRegUsed(ARM::LR);
938 AFI->setCSRegisterIsSpilled(ARM::LR);
939 AFI->setLRIsSpilledForFarJump(true);