Fix thumbv5e frame lowering assertion failure.
[oota-llvm.git] / lib / Target / ARM / Thumb1FrameLowering.cpp
1 //===-- Thumb1FrameLowering.cpp - Thumb1 Frame Information ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the Thumb1 implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Thumb1FrameLowering.h"
15 #include "ARMMachineFunctionInfo.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20
21 using namespace llvm;
22
23 bool Thumb1FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const{
24   const MachineFrameInfo *FFI = MF.getFrameInfo();
25   unsigned CFSize = FFI->getMaxCallFrameSize();
26   // It's not always a good idea to include the call frame as part of the
27   // stack frame. ARM (especially Thumb) has small immediate offset to
28   // address the stack frame. So a large call frame can cause poor codegen
29   // and may even makes it impossible to scavenge a register.
30   if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
31     return false;
32
33   return !MF.getFrameInfo()->hasVarSizedObjects();
34 }
35
36 static void
37 emitSPUpdate(MachineBasicBlock &MBB,
38              MachineBasicBlock::iterator &MBBI,
39              const TargetInstrInfo &TII, DebugLoc dl,
40              const Thumb1RegisterInfo &MRI,
41              int NumBytes, unsigned MIFlags = MachineInstr::NoFlags)  {
42   emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes, TII,
43                             MRI, MIFlags);
44 }
45
46 void Thumb1FrameLowering::emitPrologue(MachineFunction &MF) const {
47   MachineBasicBlock &MBB = MF.front();
48   MachineBasicBlock::iterator MBBI = MBB.begin();
49   MachineFrameInfo  *MFI = MF.getFrameInfo();
50   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
51   const Thumb1RegisterInfo *RegInfo =
52     static_cast<const Thumb1RegisterInfo*>(MF.getTarget().getRegisterInfo());
53   const Thumb1InstrInfo &TII =
54     *static_cast<const Thumb1InstrInfo*>(MF.getTarget().getInstrInfo());
55
56   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
57   unsigned NumBytes = MFI->getStackSize();
58   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
59   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
60   unsigned FramePtr = RegInfo->getFrameRegister(MF);
61   unsigned BasePtr = RegInfo->getBaseRegister();
62
63   // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
64   NumBytes = (NumBytes + 3) & ~3;
65   MFI->setStackSize(NumBytes);
66
67   // Determine the sizes of each callee-save spill areas and record which frame
68   // belongs to which callee-save spill areas.
69   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
70   int FramePtrSpillFI = 0;
71
72   if (VARegSaveSize)
73     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -VARegSaveSize,
74                  MachineInstr::FrameSetup);
75
76   if (!AFI->hasStackFrame()) {
77     if (NumBytes != 0)
78       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
79                    MachineInstr::FrameSetup);
80     return;
81   }
82
83   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
84     unsigned Reg = CSI[i].getReg();
85     int FI = CSI[i].getFrameIdx();
86     switch (Reg) {
87     case ARM::R4:
88     case ARM::R5:
89     case ARM::R6:
90     case ARM::R7:
91     case ARM::LR:
92       if (Reg == FramePtr)
93         FramePtrSpillFI = FI;
94       AFI->addGPRCalleeSavedArea1Frame(FI);
95       GPRCS1Size += 4;
96       break;
97     case ARM::R8:
98     case ARM::R9:
99     case ARM::R10:
100     case ARM::R11:
101       if (Reg == FramePtr)
102         FramePtrSpillFI = FI;
103       if (STI.isTargetIOS()) {
104         AFI->addGPRCalleeSavedArea2Frame(FI);
105         GPRCS2Size += 4;
106       } else {
107         AFI->addGPRCalleeSavedArea1Frame(FI);
108         GPRCS1Size += 4;
109       }
110       break;
111     default:
112       AFI->addDPRCalleeSavedAreaFrame(FI);
113       DPRCSSize += 8;
114     }
115   }
116
117   if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH) {
118     ++MBBI;
119     if (MBBI != MBB.end())
120       dl = MBBI->getDebugLoc();
121   }
122
123   // Determine starting offsets of spill areas.
124   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
125   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
126   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
127   bool HasFP = hasFP(MF);
128   if (HasFP)
129     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
130                                 NumBytes);
131   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
132   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
133   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
134   NumBytes = DPRCSOffset;
135
136   // Adjust FP so it point to the stack slot that contains the previous FP.
137   if (HasFP) {
138     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
139       .addFrameIndex(FramePtrSpillFI).addImm(0)
140       .setMIFlags(MachineInstr::FrameSetup));
141     if (NumBytes > 508)
142       // If offset is > 508 then sp cannot be adjusted in a single instruction,
143       // try restoring from fp instead.
144       AFI->setShouldRestoreSPFromFP(true);
145   }
146
147   if (NumBytes)
148     // Insert it after all the callee-save spills.
149     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
150                  MachineInstr::FrameSetup);
151
152   if (STI.isTargetELF() && HasFP)
153     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
154                              AFI->getFramePtrSpillOffset());
155
156   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
157   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
158   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
159
160   // Thumb1 does not currently support dynamic stack realignment.  Report a
161   // fatal error rather then silently generate bad code.
162   if (RegInfo->needsStackRealignment(MF))
163       report_fatal_error("Dynamic stack realignment not supported for thumb1.");
164
165   // If we need a base pointer, set it up here. It's whatever the value
166   // of the stack pointer is at this point. Any variable size objects
167   // will be allocated after this, so we can still use the base pointer
168   // to reference locals.
169   if (RegInfo->hasBasePointer(MF))
170     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
171                    .addReg(ARM::SP));
172
173   // If the frame has variable sized objects then the epilogue must restore
174   // the sp from fp. We can assume there's an FP here since hasFP already
175   // checks for hasVarSizedObjects.
176   if (MFI->hasVarSizedObjects())
177     AFI->setShouldRestoreSPFromFP(true);
178 }
179
180 static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
181   for (unsigned i = 0; CSRegs[i]; ++i)
182     if (Reg == CSRegs[i])
183       return true;
184   return false;
185 }
186
187 static bool isCSRestore(MachineInstr *MI, const uint16_t *CSRegs) {
188   if (MI->getOpcode() == ARM::tLDRspi &&
189       MI->getOperand(1).isFI() &&
190       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
191     return true;
192   else if (MI->getOpcode() == ARM::tPOP) {
193     // The first two operands are predicates. The last two are
194     // imp-def and imp-use of SP. Check everything in between.
195     for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
196       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
197         return false;
198     return true;
199   }
200   return false;
201 }
202
203 void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
204                                    MachineBasicBlock &MBB) const {
205   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
206   assert((MBBI->getOpcode() == ARM::tBX_RET ||
207           MBBI->getOpcode() == ARM::tPOP_RET) &&
208          "Can only insert epilog into returning blocks");
209   DebugLoc dl = MBBI->getDebugLoc();
210   MachineFrameInfo *MFI = MF.getFrameInfo();
211   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
212   const Thumb1RegisterInfo *RegInfo =
213     static_cast<const Thumb1RegisterInfo*>(MF.getTarget().getRegisterInfo());
214   const Thumb1InstrInfo &TII =
215     *static_cast<const Thumb1InstrInfo*>(MF.getTarget().getInstrInfo());
216
217   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
218   int NumBytes = (int)MFI->getStackSize();
219   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
220   unsigned FramePtr = RegInfo->getFrameRegister(MF);
221
222   if (!AFI->hasStackFrame()) {
223     if (NumBytes != 0)
224       emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
225   } else {
226     // Unwind MBBI to point to first LDR / VLDRD.
227     if (MBBI != MBB.begin()) {
228       do
229         --MBBI;
230       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
231       if (!isCSRestore(MBBI, CSRegs))
232         ++MBBI;
233     }
234
235     // Move SP to start of FP callee save spill area.
236     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
237                  AFI->getGPRCalleeSavedArea2Size() +
238                  AFI->getDPRCalleeSavedAreaSize());
239
240     if (AFI->shouldRestoreSPFromFP()) {
241       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
242       // Reset SP based on frame pointer only if the stack frame extends beyond
243       // frame pointer stack slot, the target is ELF and the function has FP, or
244       // the target uses var sized objects.
245       if (NumBytes) {
246         assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
247                "No scratch register to restore SP from FP!");
248         emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
249                                   TII, *RegInfo);
250         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
251                                ARM::SP)
252           .addReg(ARM::R4));
253       } else
254         AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
255                                ARM::SP)
256           .addReg(FramePtr));
257     } else {
258       if (MBBI->getOpcode() == ARM::tBX_RET &&
259           &MBB.front() != MBBI &&
260           prior(MBBI)->getOpcode() == ARM::tPOP) {
261         MachineBasicBlock::iterator PMBBI = prior(MBBI);
262         emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
263       } else
264         emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
265     }
266   }
267
268   if (VARegSaveSize) {
269     // Unlike T2 and ARM mode, the T1 pop instruction cannot restore
270     // to LR, and we can't pop the value directly to the PC since
271     // we need to update the SP after popping the value. Therefore, we
272     // pop the old LR into R3 as a temporary.
273
274     // Move back past the callee-saved register restoration
275     while (MBBI != MBB.end() && isCSRestore(MBBI, CSRegs))
276       ++MBBI;
277     // Epilogue for vararg functions: pop LR to R3 and branch off it.
278     AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
279       .addReg(ARM::R3, RegState::Define);
280
281     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, VARegSaveSize);
282
283     MachineInstrBuilder MIB =
284       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET_vararg))
285       .addReg(ARM::R3, RegState::Kill);
286     AddDefaultPred(MIB);
287     MIB.copyImplicitOps(&*MBBI);
288     // erase the old tBX_RET instruction
289     MBB.erase(MBBI);
290   }
291 }
292
293 bool Thumb1FrameLowering::
294 spillCalleeSavedRegisters(MachineBasicBlock &MBB,
295                           MachineBasicBlock::iterator MI,
296                           const std::vector<CalleeSavedInfo> &CSI,
297                           const TargetRegisterInfo *TRI) const {
298   if (CSI.empty())
299     return false;
300
301   DebugLoc DL;
302   MachineFunction &MF = *MBB.getParent();
303   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
304
305   if (MI != MBB.end()) DL = MI->getDebugLoc();
306
307   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
308   AddDefaultPred(MIB);
309   for (unsigned i = CSI.size(); i != 0; --i) {
310     unsigned Reg = CSI[i-1].getReg();
311     bool isKill = true;
312
313     // Add the callee-saved register as live-in unless it's LR and
314     // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
315     // then it's already added to the function and entry block live-in sets.
316     if (Reg == ARM::LR) {
317       MachineFunction &MF = *MBB.getParent();
318       if (MF.getFrameInfo()->isReturnAddressTaken() &&
319           MF.getRegInfo().isLiveIn(Reg))
320         isKill = false;
321     }
322
323     if (isKill)
324       MBB.addLiveIn(Reg);
325
326     MIB.addReg(Reg, getKillRegState(isKill));
327   }
328   MIB.setMIFlags(MachineInstr::FrameSetup);
329   return true;
330 }
331
332 bool Thumb1FrameLowering::
333 restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
334                             MachineBasicBlock::iterator MI,
335                             const std::vector<CalleeSavedInfo> &CSI,
336                             const TargetRegisterInfo *TRI) const {
337   if (CSI.empty())
338     return false;
339
340   MachineFunction &MF = *MBB.getParent();
341   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
342   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
343
344   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
345   DebugLoc DL = MI->getDebugLoc();
346   MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
347   AddDefaultPred(MIB);
348
349   bool NumRegs = false;
350   for (unsigned i = CSI.size(); i != 0; --i) {
351     unsigned Reg = CSI[i-1].getReg();
352     if (Reg == ARM::LR) {
353       // Special epilogue for vararg functions. See emitEpilogue
354       if (isVarArg)
355         continue;
356       Reg = ARM::PC;
357       (*MIB).setDesc(TII.get(ARM::tPOP_RET));
358       MIB.copyImplicitOps(&*MI);
359       MI = MBB.erase(MI);
360     }
361     MIB.addReg(Reg, getDefRegState(true));
362     NumRegs = true;
363   }
364
365   // It's illegal to emit pop instruction without operands.
366   if (NumRegs)
367     MBB.insert(MI, &*MIB);
368   else
369     MF.DeleteMachineInstr(MIB);
370
371   return true;
372 }