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
21using namespace llvm;
22
23bool 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
36static void
37emitSPUpdate(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
46void 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  AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
128  AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
129  AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
130  AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
131  NumBytes = DPRCSOffset;
132
133  // Adjust FP so it point to the stack slot that contains the previous FP.
134  if (hasFP(MF)) {
135    AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tADDrSPi), FramePtr)
136      .addFrameIndex(FramePtrSpillFI).addImm(0)
137      .setMIFlags(MachineInstr::FrameSetup));
138    if (NumBytes > 508)
139      // If offset is > 508 then sp cannot be adjusted in a single instruction,
140      // try restoring from fp instead.
141      AFI->setShouldRestoreSPFromFP(true);
142  }
143
144  if (NumBytes)
145    // Insert it after all the callee-save spills.
146    emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, -NumBytes,
147                 MachineInstr::FrameSetup);
148
149  if (STI.isTargetELF() && hasFP(MF))
150    MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
151                             AFI->getFramePtrSpillOffset());
152
153  AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
154  AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
155  AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
156
157  // Thumb1 does not currently support dynamic stack realignment.  Report a
158  // fatal error rather then silently generate bad code.
159  if (RegInfo->needsStackRealignment(MF))
160      report_fatal_error("Dynamic stack realignment not supported for thumb1.");
161
162  // If we need a base pointer, set it up here. It's whatever the value
163  // of the stack pointer is at this point. Any variable size objects
164  // will be allocated after this, so we can still use the base pointer
165  // to reference locals.
166  if (RegInfo->hasBasePointer(MF))
167    AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), BasePtr)
168                   .addReg(ARM::SP));
169
170  // If the frame has variable sized objects then the epilogue must restore
171  // the sp from fp. We can assume there's an FP here since hasFP already
172  // checks for hasVarSizedObjects.
173  if (MFI->hasVarSizedObjects())
174    AFI->setShouldRestoreSPFromFP(true);
175}
176
177static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
178  for (unsigned i = 0; CSRegs[i]; ++i)
179    if (Reg == CSRegs[i])
180      return true;
181  return false;
182}
183
184static bool isCSRestore(MachineInstr *MI, const uint16_t *CSRegs) {
185  if (MI->getOpcode() == ARM::tLDRspi &&
186      MI->getOperand(1).isFI() &&
187      isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
188    return true;
189  else if (MI->getOpcode() == ARM::tPOP) {
190    // The first two operands are predicates. The last two are
191    // imp-def and imp-use of SP. Check everything in between.
192    for (int i = 2, e = MI->getNumOperands() - 2; i != e; ++i)
193      if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
194        return false;
195    return true;
196  }
197  return false;
198}
199
200void Thumb1FrameLowering::emitEpilogue(MachineFunction &MF,
201                                   MachineBasicBlock &MBB) const {
202  MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
203  assert((MBBI->getOpcode() == ARM::tBX_RET ||
204          MBBI->getOpcode() == ARM::tPOP_RET) &&
205         "Can only insert epilog into returning blocks");
206  DebugLoc dl = MBBI->getDebugLoc();
207  MachineFrameInfo *MFI = MF.getFrameInfo();
208  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
209  const Thumb1RegisterInfo *RegInfo =
210    static_cast<const Thumb1RegisterInfo*>(MF.getTarget().getRegisterInfo());
211  const Thumb1InstrInfo &TII =
212    *static_cast<const Thumb1InstrInfo*>(MF.getTarget().getInstrInfo());
213
214  unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
215  int NumBytes = (int)MFI->getStackSize();
216  const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
217  unsigned FramePtr = RegInfo->getFrameRegister(MF);
218
219  if (!AFI->hasStackFrame()) {
220    if (NumBytes != 0)
221      emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
222  } else {
223    // Unwind MBBI to point to first LDR / VLDRD.
224    if (MBBI != MBB.begin()) {
225      do
226        --MBBI;
227      while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
228      if (!isCSRestore(MBBI, CSRegs))
229        ++MBBI;
230    }
231
232    // Move SP to start of FP callee save spill area.
233    NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
234                 AFI->getGPRCalleeSavedArea2Size() +
235                 AFI->getDPRCalleeSavedAreaSize());
236
237    if (AFI->shouldRestoreSPFromFP()) {
238      NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
239      // Reset SP based on frame pointer only if the stack frame extends beyond
240      // frame pointer stack slot, the target is ELF and the function has FP, or
241      // the target uses var sized objects.
242      if (NumBytes) {
243        assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
244               "No scratch register to restore SP from FP!");
245        emitThumbRegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
246                                  TII, *RegInfo);
247        AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
248                               ARM::SP)
249          .addReg(ARM::R4));
250      } else
251        AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
252                               ARM::SP)
253          .addReg(FramePtr));
254    } else {
255      if (MBBI->getOpcode() == ARM::tBX_RET &&
256          &MBB.front() != MBBI &&
257          prior(MBBI)->getOpcode() == ARM::tPOP) {
258        MachineBasicBlock::iterator PMBBI = prior(MBBI);
259        emitSPUpdate(MBB, PMBBI, TII, dl, *RegInfo, NumBytes);
260      } else
261        emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, NumBytes);
262    }
263  }
264
265  if (VARegSaveSize) {
266    // Unlike T2 and ARM mode, the T1 pop instruction cannot restore
267    // to LR, and we can't pop the value directly to the PC since
268    // we need to update the SP after popping the value. Therefore, we
269    // pop the old LR into R3 as a temporary.
270
271    // Move back past the callee-saved register restoration
272    while (MBBI != MBB.end() && isCSRestore(MBBI, CSRegs))
273      ++MBBI;
274    // Epilogue for vararg functions: pop LR to R3 and branch off it.
275    AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tPOP)))
276      .addReg(ARM::R3, RegState::Define);
277
278    emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, VARegSaveSize);
279
280    MachineInstrBuilder MIB =
281      BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET_vararg))
282      .addReg(ARM::R3, RegState::Kill);
283    AddDefaultPred(MIB);
284    MIB->copyImplicitOps(&*MBBI);
285    // erase the old tBX_RET instruction
286    MBB.erase(MBBI);
287  }
288}
289
290bool Thumb1FrameLowering::
291spillCalleeSavedRegisters(MachineBasicBlock &MBB,
292                          MachineBasicBlock::iterator MI,
293                          const std::vector<CalleeSavedInfo> &CSI,
294                          const TargetRegisterInfo *TRI) const {
295  if (CSI.empty())
296    return false;
297
298  DebugLoc DL;
299  MachineFunction &MF = *MBB.getParent();
300  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
301
302  if (MI != MBB.end()) DL = MI->getDebugLoc();
303
304  MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(ARM::tPUSH));
305  AddDefaultPred(MIB);
306  for (unsigned i = CSI.size(); i != 0; --i) {
307    unsigned Reg = CSI[i-1].getReg();
308    bool isKill = true;
309
310    // Add the callee-saved register as live-in unless it's LR and
311    // @llvm.returnaddress is called. If LR is returned for @llvm.returnaddress
312    // then it's already added to the function and entry block live-in sets.
313    if (Reg == ARM::LR) {
314      MachineFunction &MF = *MBB.getParent();
315      if (MF.getFrameInfo()->isReturnAddressTaken() &&
316          MF.getRegInfo().isLiveIn(Reg))
317        isKill = false;
318    }
319
320    if (isKill)
321      MBB.addLiveIn(Reg);
322
323    MIB.addReg(Reg, getKillRegState(isKill));
324  }
325  MIB.setMIFlags(MachineInstr::FrameSetup);
326  return true;
327}
328
329bool Thumb1FrameLowering::
330restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
331                            MachineBasicBlock::iterator MI,
332                            const std::vector<CalleeSavedInfo> &CSI,
333                            const TargetRegisterInfo *TRI) const {
334  if (CSI.empty())
335    return false;
336
337  MachineFunction &MF = *MBB.getParent();
338  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
339  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
340
341  bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
342  DebugLoc DL = MI->getDebugLoc();
343  MachineInstrBuilder MIB = BuildMI(MF, DL, TII.get(ARM::tPOP));
344  AddDefaultPred(MIB);
345
346  bool NumRegs = false;
347  for (unsigned i = CSI.size(); i != 0; --i) {
348    unsigned Reg = CSI[i-1].getReg();
349    if (Reg == ARM::LR) {
350      // Special epilogue for vararg functions. See emitEpilogue
351      if (isVarArg)
352        continue;
353      Reg = ARM::PC;
354      (*MIB).setDesc(TII.get(ARM::tPOP_RET));
355      MIB->copyImplicitOps(&*MI);
356      MI = MBB.erase(MI);
357    }
358    MIB.addReg(Reg, getDefRegState(true));
359    NumRegs = true;
360  }
361
362  // It's illegal to emit pop instruction without operands.
363  if (NumRegs)
364    MBB.insert(MI, &*MIB);
365  else
366    MF.DeleteMachineInstr(MIB);
367
368  return true;
369}
370