ARMFrameLowering.cpp revision f06f6f50e9844b88cfbb9fb896fff9c3a752966b
1//=======- ARMFrameLowering.cpp - ARM Frame Information --------*- C++ -*-====//
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 ARM implementation of TargetFrameLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMFrameLowering.h"
15#include "ARMBaseInstrInfo.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMMachineFunctionInfo.h"
18#include "MCTargetDesc/ARMAddressingModes.h"
19#include "llvm/Function.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineRegisterInfo.h"
24#include "llvm/CodeGen/RegisterScavenging.h"
25#include "llvm/Target/TargetOptions.h"
26#include "llvm/Support/CommandLine.h"
27
28using namespace llvm;
29
30cl::opt<bool>
31SpillAlignedNEONRegs("align-neon-spills", cl::Hidden,
32                     cl::desc("Align ARM NEON spills in prolog and epilog"));
33
34static MachineBasicBlock::iterator
35skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
36                        unsigned NumAlignedDPRCS2Regs);
37
38/// hasFP - Return true if the specified function should have a dedicated frame
39/// pointer register.  This is true if the function has variable sized allocas
40/// or if frame pointer elimination is disabled.
41bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
42  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
43
44  // Mac OS X requires FP not to be clobbered for backtracing purpose.
45  if (STI.isTargetDarwin())
46    return true;
47
48  const MachineFrameInfo *MFI = MF.getFrameInfo();
49  // Always eliminate non-leaf frame pointers.
50  return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
51           MFI->hasCalls()) ||
52          RegInfo->needsStackRealignment(MF) ||
53          MFI->hasVarSizedObjects() ||
54          MFI->isFrameAddressTaken());
55}
56
57/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
58/// not required, we reserve argument space for call sites in the function
59/// immediately on entry to the current function.  This eliminates the need for
60/// add/sub sp brackets around call sites.  Returns true if the call frame is
61/// included as part of the stack frame.
62bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
63  const MachineFrameInfo *FFI = MF.getFrameInfo();
64  unsigned CFSize = FFI->getMaxCallFrameSize();
65  // It's not always a good idea to include the call frame as part of the
66  // stack frame. ARM (especially Thumb) has small immediate offset to
67  // address the stack frame. So a large call frame can cause poor codegen
68  // and may even makes it impossible to scavenge a register.
69  if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
70    return false;
71
72  return !MF.getFrameInfo()->hasVarSizedObjects();
73}
74
75/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
76/// call frame pseudos can be simplified.  Unlike most targets, having a FP
77/// is not sufficient here since we still may reference some objects via SP
78/// even when FP is available in Thumb2 mode.
79bool
80ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
81  return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
82}
83
84static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
85  for (unsigned i = 0; CSRegs[i]; ++i)
86    if (Reg == CSRegs[i])
87      return true;
88  return false;
89}
90
91static bool isCSRestore(MachineInstr *MI,
92                        const ARMBaseInstrInfo &TII,
93                        const unsigned *CSRegs) {
94  // Integer spill area is handled with "pop".
95  if (MI->getOpcode() == ARM::LDMIA_RET ||
96      MI->getOpcode() == ARM::t2LDMIA_RET ||
97      MI->getOpcode() == ARM::LDMIA_UPD ||
98      MI->getOpcode() == ARM::t2LDMIA_UPD ||
99      MI->getOpcode() == ARM::VLDMDIA_UPD) {
100    // The first two operands are predicates. The last two are
101    // imp-def and imp-use of SP. Check everything in between.
102    for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
103      if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
104        return false;
105    return true;
106  }
107  if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
108       MI->getOpcode() == ARM::LDR_POST_REG ||
109       MI->getOpcode() == ARM::t2LDR_POST) &&
110      isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
111      MI->getOperand(1).getReg() == ARM::SP)
112    return true;
113
114  return false;
115}
116
117static void
118emitSPUpdate(bool isARM,
119             MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
120             DebugLoc dl, const ARMBaseInstrInfo &TII,
121             int NumBytes, unsigned MIFlags = MachineInstr::NoFlags) {
122  if (isARM)
123    emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
124                            ARMCC::AL, 0, TII, MIFlags);
125  else
126    emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
127                           ARMCC::AL, 0, TII, MIFlags);
128}
129
130void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
131  MachineBasicBlock &MBB = MF.front();
132  MachineBasicBlock::iterator MBBI = MBB.begin();
133  MachineFrameInfo  *MFI = MF.getFrameInfo();
134  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
135  const ARMBaseRegisterInfo *RegInfo =
136    static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
137  const ARMBaseInstrInfo &TII =
138    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
139  assert(!AFI->isThumb1OnlyFunction() &&
140         "This emitPrologue does not support Thumb1!");
141  bool isARM = !AFI->isThumbFunction();
142  unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
143  unsigned NumBytes = MFI->getStackSize();
144  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
145  DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
146  unsigned FramePtr = RegInfo->getFrameRegister(MF);
147
148  // Determine the sizes of each callee-save spill areas and record which frame
149  // belongs to which callee-save spill areas.
150  unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
151  int FramePtrSpillFI = 0;
152  int D8SpillFI = 0;
153
154  // Allocate the vararg register save area. This is not counted in NumBytes.
155  if (VARegSaveSize)
156    emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize,
157                 MachineInstr::FrameSetup);
158
159  if (!AFI->hasStackFrame()) {
160    if (NumBytes != 0)
161      emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
162                   MachineInstr::FrameSetup);
163    return;
164  }
165
166  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
167    unsigned Reg = CSI[i].getReg();
168    int FI = CSI[i].getFrameIdx();
169    switch (Reg) {
170    case ARM::R4:
171    case ARM::R5:
172    case ARM::R6:
173    case ARM::R7:
174    case ARM::LR:
175      if (Reg == FramePtr)
176        FramePtrSpillFI = FI;
177      AFI->addGPRCalleeSavedArea1Frame(FI);
178      GPRCS1Size += 4;
179      break;
180    case ARM::R8:
181    case ARM::R9:
182    case ARM::R10:
183    case ARM::R11:
184      if (Reg == FramePtr)
185        FramePtrSpillFI = FI;
186      if (STI.isTargetDarwin()) {
187        AFI->addGPRCalleeSavedArea2Frame(FI);
188        GPRCS2Size += 4;
189      } else {
190        AFI->addGPRCalleeSavedArea1Frame(FI);
191        GPRCS1Size += 4;
192      }
193      break;
194    default:
195      // This is a DPR. Exclude the aligned DPRCS2 spills.
196      if (Reg == ARM::D8)
197        D8SpillFI = FI;
198      if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs()) {
199        AFI->addDPRCalleeSavedAreaFrame(FI);
200        DPRCSSize += 8;
201      }
202    }
203  }
204
205  // Move past area 1.
206  if (GPRCS1Size > 0) MBBI++;
207
208  // Set FP to point to the stack slot that contains the previous FP.
209  // For Darwin, FP is R7, which has now been stored in spill area 1.
210  // Otherwise, if this is not Darwin, all the callee-saved registers go
211  // into spill area 1, including the FP in R11.  In either case, it is
212  // now safe to emit this assignment.
213  bool HasFP = hasFP(MF);
214  if (HasFP) {
215    unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
216    MachineInstrBuilder MIB =
217      BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
218      .addFrameIndex(FramePtrSpillFI).addImm(0)
219      .setMIFlag(MachineInstr::FrameSetup);
220    AddDefaultCC(AddDefaultPred(MIB));
221  }
222
223  // Move past area 2.
224  if (GPRCS2Size > 0) MBBI++;
225
226  // Determine starting offsets of spill areas.
227  unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
228  unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
229  unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
230  if (HasFP)
231    AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
232                                NumBytes);
233  AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
234  AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
235  AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
236
237  // Move past area 3.
238  if (DPRCSSize > 0) {
239    MBBI++;
240    // Since vpush register list cannot have gaps, there may be multiple vpush
241    // instructions in the prologue.
242    while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
243      MBBI++;
244  }
245
246  // Move past the aligned DPRCS2 area.
247  if (AFI->getNumAlignedDPRCS2Regs() > 0) {
248    MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
249    // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
250    // leaves the stack pointer pointing to the DPRCS2 area.
251    //
252    // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
253    NumBytes += MFI->getObjectOffset(D8SpillFI);
254  } else
255    NumBytes = DPRCSOffset;
256
257  if (NumBytes) {
258    // Adjust SP after all the callee-save spills.
259    emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
260                 MachineInstr::FrameSetup);
261    if (HasFP && isARM)
262      // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
263      // Note it's not safe to do this in Thumb2 mode because it would have
264      // taken two instructions:
265      // mov sp, r7
266      // sub sp, #24
267      // If an interrupt is taken between the two instructions, then sp is in
268      // an inconsistent state (pointing to the middle of callee-saved area).
269      // The interrupt handler can end up clobbering the registers.
270      AFI->setShouldRestoreSPFromFP(true);
271  }
272
273  if (STI.isTargetELF() && hasFP(MF))
274    MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
275                             AFI->getFramePtrSpillOffset());
276
277  AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
278  AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
279  AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
280
281  // If we need dynamic stack realignment, do it here. Be paranoid and make
282  // sure if we also have VLAs, we have a base pointer for frame access.
283  // If aligned NEON registers were sp[illed, the stack has already been
284  // realigned.
285  if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
286    unsigned MaxAlign = MFI->getMaxAlignment();
287    assert (!AFI->isThumb1OnlyFunction());
288    if (!AFI->isThumbFunction()) {
289      // Emit bic sp, sp, MaxAlign
290      AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
291                                          TII.get(ARM::BICri), ARM::SP)
292                                  .addReg(ARM::SP, RegState::Kill)
293                                  .addImm(MaxAlign-1)));
294    } else {
295      // We cannot use sp as source/dest register here, thus we're emitting the
296      // following sequence:
297      // mov r4, sp
298      // bic r4, r4, MaxAlign
299      // mov sp, r4
300      // FIXME: It will be better just to find spare register here.
301      AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
302        .addReg(ARM::SP, RegState::Kill));
303      AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
304                                          TII.get(ARM::t2BICri), ARM::R4)
305                                  .addReg(ARM::R4, RegState::Kill)
306                                  .addImm(MaxAlign-1)));
307      AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
308        .addReg(ARM::R4, RegState::Kill));
309    }
310
311    AFI->setShouldRestoreSPFromFP(true);
312  }
313
314  // If we need a base pointer, set it up here. It's whatever the value
315  // of the stack pointer is at this point. Any variable size objects
316  // will be allocated after this, so we can still use the base pointer
317  // to reference locals.
318  // FIXME: Clarify FrameSetup flags here.
319  if (RegInfo->hasBasePointer(MF)) {
320    if (isARM)
321      BuildMI(MBB, MBBI, dl,
322              TII.get(ARM::MOVr), RegInfo->getBaseRegister())
323        .addReg(ARM::SP)
324        .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
325    else
326      AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
327                             RegInfo->getBaseRegister())
328        .addReg(ARM::SP));
329  }
330
331  // If the frame has variable sized objects then the epilogue must restore
332  // the sp from fp. We can assume there's an FP here since hasFP already
333  // checks for hasVarSizedObjects.
334  if (MFI->hasVarSizedObjects())
335    AFI->setShouldRestoreSPFromFP(true);
336}
337
338void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
339                                    MachineBasicBlock &MBB) const {
340  MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
341  assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
342  unsigned RetOpcode = MBBI->getOpcode();
343  DebugLoc dl = MBBI->getDebugLoc();
344  MachineFrameInfo *MFI = MF.getFrameInfo();
345  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
346  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
347  const ARMBaseInstrInfo &TII =
348    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
349  assert(!AFI->isThumb1OnlyFunction() &&
350         "This emitEpilogue does not support Thumb1!");
351  bool isARM = !AFI->isThumbFunction();
352
353  unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
354  int NumBytes = (int)MFI->getStackSize();
355  unsigned FramePtr = RegInfo->getFrameRegister(MF);
356
357  if (!AFI->hasStackFrame()) {
358    if (NumBytes != 0)
359      emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
360  } else {
361    // Unwind MBBI to point to first LDR / VLDRD.
362    const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
363    if (MBBI != MBB.begin()) {
364      do
365        --MBBI;
366      while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
367      if (!isCSRestore(MBBI, TII, CSRegs))
368        ++MBBI;
369    }
370
371    // Move SP to start of FP callee save spill area.
372    NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
373                 AFI->getGPRCalleeSavedArea2Size() +
374                 AFI->getDPRCalleeSavedAreaSize());
375
376    // Reset SP based on frame pointer only if the stack frame extends beyond
377    // frame pointer stack slot or target is ELF and the function has FP.
378    if (AFI->shouldRestoreSPFromFP()) {
379      NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
380      if (NumBytes) {
381        if (isARM)
382          emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
383                                  ARMCC::AL, 0, TII);
384        else {
385          // It's not possible to restore SP from FP in a single instruction.
386          // For Darwin, this looks like:
387          // mov sp, r7
388          // sub sp, #24
389          // This is bad, if an interrupt is taken after the mov, sp is in an
390          // inconsistent state.
391          // Use the first callee-saved register as a scratch register.
392          assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
393                 "No scratch register to restore SP from FP!");
394          emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
395                                 ARMCC::AL, 0, TII);
396          AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
397                                 ARM::SP)
398            .addReg(ARM::R4));
399        }
400      } else {
401        // Thumb2 or ARM.
402        if (isARM)
403          BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
404            .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
405        else
406          AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
407                                 ARM::SP)
408            .addReg(FramePtr));
409      }
410    } else if (NumBytes)
411      emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
412
413    // Increment past our save areas.
414    if (AFI->getDPRCalleeSavedAreaSize()) {
415      MBBI++;
416      // Since vpop register list cannot have gaps, there may be multiple vpop
417      // instructions in the epilogue.
418      while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
419        MBBI++;
420    }
421    if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
422    if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
423  }
424
425  if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
426      RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
427    // Tail call return: adjust the stack pointer and jump to callee.
428    MBBI = MBB.getLastNonDebugInstr();
429    MachineOperand &JumpTarget = MBBI->getOperand(0);
430
431    // Jump to label or value in register.
432    if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
433      unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
434        ? (STI.isThumb() ? ARM::tTAILJMPd : ARM::TAILJMPd)
435        : (STI.isThumb() ? ARM::tTAILJMPdND : ARM::TAILJMPdND);
436      MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
437      if (JumpTarget.isGlobal())
438        MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
439                             JumpTarget.getTargetFlags());
440      else {
441        assert(JumpTarget.isSymbol());
442        MIB.addExternalSymbol(JumpTarget.getSymbolName(),
443                              JumpTarget.getTargetFlags());
444      }
445
446      // Add the default predicate in Thumb mode.
447      if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
448    } else if (RetOpcode == ARM::TCRETURNri) {
449      BuildMI(MBB, MBBI, dl,
450              TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
451        addReg(JumpTarget.getReg(), RegState::Kill);
452    } else if (RetOpcode == ARM::TCRETURNriND) {
453      BuildMI(MBB, MBBI, dl,
454              TII.get(STI.isThumb() ? ARM::tTAILJMPrND : ARM::TAILJMPrND)).
455        addReg(JumpTarget.getReg(), RegState::Kill);
456    }
457
458    MachineInstr *NewMI = prior(MBBI);
459    for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
460      NewMI->addOperand(MBBI->getOperand(i));
461
462    // Delete the pseudo instruction TCRETURN.
463    MBB.erase(MBBI);
464    MBBI = NewMI;
465  }
466
467  if (VARegSaveSize)
468    emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
469}
470
471/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
472/// debug info.  It's the same as what we use for resolving the code-gen
473/// references for now.  FIXME: This can go wrong when references are
474/// SP-relative and simple call frames aren't used.
475int
476ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
477                                         unsigned &FrameReg) const {
478  return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
479}
480
481int
482ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
483                                             int FI, unsigned &FrameReg,
484                                             int SPAdj) const {
485  const MachineFrameInfo *MFI = MF.getFrameInfo();
486  const ARMBaseRegisterInfo *RegInfo =
487    static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
488  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
489  int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
490  int FPOffset = Offset - AFI->getFramePtrSpillOffset();
491  bool isFixed = MFI->isFixedObjectIndex(FI);
492
493  FrameReg = ARM::SP;
494  Offset += SPAdj;
495  if (AFI->isGPRCalleeSavedArea1Frame(FI))
496    return Offset - AFI->getGPRCalleeSavedArea1Offset();
497  else if (AFI->isGPRCalleeSavedArea2Frame(FI))
498    return Offset - AFI->getGPRCalleeSavedArea2Offset();
499  else if (AFI->isDPRCalleeSavedAreaFrame(FI))
500    return Offset - AFI->getDPRCalleeSavedAreaOffset();
501
502  // When dynamically realigning the stack, use the frame pointer for
503  // parameters, and the stack/base pointer for locals.
504  if (RegInfo->needsStackRealignment(MF)) {
505    assert (hasFP(MF) && "dynamic stack realignment without a FP!");
506    if (isFixed) {
507      FrameReg = RegInfo->getFrameRegister(MF);
508      Offset = FPOffset;
509    } else if (MFI->hasVarSizedObjects()) {
510      assert(RegInfo->hasBasePointer(MF) &&
511             "VLAs and dynamic stack alignment, but missing base pointer!");
512      FrameReg = RegInfo->getBaseRegister();
513    }
514    return Offset;
515  }
516
517  // If there is a frame pointer, use it when we can.
518  if (hasFP(MF) && AFI->hasStackFrame()) {
519    // Use frame pointer to reference fixed objects. Use it for locals if
520    // there are VLAs (and thus the SP isn't reliable as a base).
521    if (isFixed || (MFI->hasVarSizedObjects() &&
522                    !RegInfo->hasBasePointer(MF))) {
523      FrameReg = RegInfo->getFrameRegister(MF);
524      return FPOffset;
525    } else if (MFI->hasVarSizedObjects()) {
526      assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
527      if (AFI->isThumb2Function()) {
528        // Try to use the frame pointer if we can, else use the base pointer
529        // since it's available. This is handy for the emergency spill slot, in
530        // particular.
531        if (FPOffset >= -255 && FPOffset < 0) {
532          FrameReg = RegInfo->getFrameRegister(MF);
533          return FPOffset;
534        }
535      }
536    } else if (AFI->isThumb2Function()) {
537      // Use  add <rd>, sp, #<imm8>
538      //      ldr <rd>, [sp, #<imm8>]
539      // if at all possible to save space.
540      if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
541        return Offset;
542      // In Thumb2 mode, the negative offset is very limited. Try to avoid
543      // out of range references. ldr <rt>,[<rn>, #-<imm8>]
544      if (FPOffset >= -255 && FPOffset < 0) {
545        FrameReg = RegInfo->getFrameRegister(MF);
546        return FPOffset;
547      }
548    } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
549      // Otherwise, use SP or FP, whichever is closer to the stack slot.
550      FrameReg = RegInfo->getFrameRegister(MF);
551      return FPOffset;
552    }
553  }
554  // Use the base pointer if we have one.
555  if (RegInfo->hasBasePointer(MF))
556    FrameReg = RegInfo->getBaseRegister();
557  return Offset;
558}
559
560int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
561                                          int FI) const {
562  unsigned FrameReg;
563  return getFrameIndexReference(MF, FI, FrameReg);
564}
565
566void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
567                                    MachineBasicBlock::iterator MI,
568                                    const std::vector<CalleeSavedInfo> &CSI,
569                                    unsigned StmOpc, unsigned StrOpc,
570                                    bool NoGap,
571                                    bool(*Func)(unsigned, bool),
572                                    unsigned NumAlignedDPRCS2Regs,
573                                    unsigned MIFlags) const {
574  MachineFunction &MF = *MBB.getParent();
575  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
576
577  DebugLoc DL;
578  if (MI != MBB.end()) DL = MI->getDebugLoc();
579
580  SmallVector<std::pair<unsigned,bool>, 4> Regs;
581  unsigned i = CSI.size();
582  while (i != 0) {
583    unsigned LastReg = 0;
584    for (; i != 0; --i) {
585      unsigned Reg = CSI[i-1].getReg();
586      if (!(Func)(Reg, STI.isTargetDarwin())) continue;
587
588      // D-registers in the aligned area DPRCS2 are NOT spilled here.
589      if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
590        continue;
591
592      // Add the callee-saved register as live-in unless it's LR and
593      // @llvm.returnaddress is called. If LR is returned for
594      // @llvm.returnaddress then it's already added to the function and
595      // entry block live-in sets.
596      bool isKill = true;
597      if (Reg == ARM::LR) {
598        if (MF.getFrameInfo()->isReturnAddressTaken() &&
599            MF.getRegInfo().isLiveIn(Reg))
600          isKill = false;
601      }
602
603      if (isKill)
604        MBB.addLiveIn(Reg);
605
606      // If NoGap is true, push consecutive registers and then leave the rest
607      // for other instructions. e.g.
608      // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
609      if (NoGap && LastReg && LastReg != Reg-1)
610        break;
611      LastReg = Reg;
612      Regs.push_back(std::make_pair(Reg, isKill));
613    }
614
615    if (Regs.empty())
616      continue;
617    if (Regs.size() > 1 || StrOpc== 0) {
618      MachineInstrBuilder MIB =
619        AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
620                       .addReg(ARM::SP).setMIFlags(MIFlags));
621      for (unsigned i = 0, e = Regs.size(); i < e; ++i)
622        MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
623    } else if (Regs.size() == 1) {
624      MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
625                                        ARM::SP)
626        .addReg(Regs[0].first, getKillRegState(Regs[0].second))
627        .addReg(ARM::SP).setMIFlags(MIFlags)
628        .addImm(-4);
629      AddDefaultPred(MIB);
630    }
631    Regs.clear();
632  }
633}
634
635void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
636                                   MachineBasicBlock::iterator MI,
637                                   const std::vector<CalleeSavedInfo> &CSI,
638                                   unsigned LdmOpc, unsigned LdrOpc,
639                                   bool isVarArg, bool NoGap,
640                                   bool(*Func)(unsigned, bool),
641                                   unsigned NumAlignedDPRCS2Regs) const {
642  MachineFunction &MF = *MBB.getParent();
643  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
644  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
645  DebugLoc DL = MI->getDebugLoc();
646  unsigned RetOpcode = MI->getOpcode();
647  bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
648                     RetOpcode == ARM::TCRETURNdiND ||
649                     RetOpcode == ARM::TCRETURNri ||
650                     RetOpcode == ARM::TCRETURNriND);
651
652  SmallVector<unsigned, 4> Regs;
653  unsigned i = CSI.size();
654  while (i != 0) {
655    unsigned LastReg = 0;
656    bool DeleteRet = false;
657    for (; i != 0; --i) {
658      unsigned Reg = CSI[i-1].getReg();
659      if (!(Func)(Reg, STI.isTargetDarwin())) continue;
660
661      // The aligned reloads from area DPRCS2 are not inserted here.
662      if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
663        continue;
664
665      if (Reg == ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps()) {
666        Reg = ARM::PC;
667        LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
668        // Fold the return instruction into the LDM.
669        DeleteRet = true;
670      }
671
672      // If NoGap is true, pop consecutive registers and then leave the rest
673      // for other instructions. e.g.
674      // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
675      if (NoGap && LastReg && LastReg != Reg-1)
676        break;
677
678      LastReg = Reg;
679      Regs.push_back(Reg);
680    }
681
682    if (Regs.empty())
683      continue;
684    if (Regs.size() > 1 || LdrOpc == 0) {
685      MachineInstrBuilder MIB =
686        AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
687                       .addReg(ARM::SP));
688      for (unsigned i = 0, e = Regs.size(); i < e; ++i)
689        MIB.addReg(Regs[i], getDefRegState(true));
690      if (DeleteRet) {
691        MIB->copyImplicitOps(&*MI);
692        MI->eraseFromParent();
693      }
694      MI = MIB;
695    } else if (Regs.size() == 1) {
696      // If we adjusted the reg to PC from LR above, switch it back here. We
697      // only do that for LDM.
698      if (Regs[0] == ARM::PC)
699        Regs[0] = ARM::LR;
700      MachineInstrBuilder MIB =
701        BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
702          .addReg(ARM::SP, RegState::Define)
703          .addReg(ARM::SP);
704      // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
705      // that refactoring is complete (eventually).
706      if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
707        MIB.addReg(0);
708        MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
709      } else
710        MIB.addImm(4);
711      AddDefaultPred(MIB);
712    }
713    Regs.clear();
714  }
715}
716
717/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
718/// starting from d8.  It is assumed that the stack will be realigned before
719/// these instructions are executed.
720static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
721                                    MachineBasicBlock::iterator MI,
722                                    unsigned NumAlignedDPRCS2Regs,
723                                    const std::vector<CalleeSavedInfo> &CSI,
724                                    const TargetRegisterInfo *TRI) {
725  MachineFunction &MF = *MBB.getParent();
726  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
727  DebugLoc DL = MI->getDebugLoc();
728  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
729  MachineFrameInfo &MFI = *MF.getFrameInfo();
730
731  // Mark the D-register spill slots as properly aligned.  Since MFI computes
732  // stack slot layout backwards, this can actually mean that the d-reg stack
733  // slot offsets can be wrong. The offset for d8 will always be correct.
734  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
735    unsigned DNum = CSI[i].getReg() - ARM::D8;
736    if (DNum >= 8)
737      continue;
738    int FI = CSI[i].getFrameIdx();
739    // The even-numbered registers will be 16-byte aligned, the odd-numbered
740    // registers will be 8-byte aligned.
741    MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
742
743    // The stack slot for D8 needs to be maximally aligned because this is
744    // actually the point where we align the stack pointer.  MachineFrameInfo
745    // computes all offsets relative to the incoming stack pointer which is a
746    // bit weird when realigning the stack.  Any extra padding for this
747    // over-alignment is not realized because the code inserted below adjusts
748    // the stack pointer by numregs * 8 before aligning the stack pointer.
749    if (DNum == 0)
750      MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
751  }
752
753  // Move the stack pointer to the d8 spill slot, and align it at the same
754  // time. Leave the stack slot address in the scratch register r4.
755  //
756  //   sub r4, sp, #numregs * 8
757  //   bic r4, r4, #align - 1
758  //   mov sp, r4
759  //
760  bool isThumb = AFI->isThumbFunction();
761  assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
762  AFI->setShouldRestoreSPFromFP(true);
763
764  // sub r4, sp, #numregs * 8
765  // The immediate is <= 64, so it doesn't need any special encoding.
766  unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
767  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
768                              .addReg(ARM::SP)
769                              .addImm(8 * NumAlignedDPRCS2Regs)));
770
771  // bic r4, r4, #align-1
772  Opc = isThumb ? ARM::t2BICri : ARM::BICri;
773  unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
774  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
775                              .addReg(ARM::R4, RegState::Kill)
776                              .addImm(MaxAlign - 1)));
777
778  // mov sp, r4
779  // The stack pointer must be adjusted before spilling anything, otherwise
780  // the stack slots could be clobbered by an interrupt handler.
781  // Leave r4 live, it is used below.
782  Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
783  MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
784                            .addReg(ARM::R4);
785  MIB = AddDefaultPred(MIB);
786  if (!isThumb)
787    AddDefaultCC(MIB);
788
789  // Now spill NumAlignedDPRCS2Regs registers starting from d8.
790  // r4 holds the stack slot address.
791  unsigned NextReg = ARM::D8;
792
793  // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
794  // The writeback is only needed when emitting two vst1.64 instructions.
795  if (NumAlignedDPRCS2Regs >= 6) {
796    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
797                                               ARM::QQPRRegisterClass);
798    MBB.addLiveIn(SupReg);
799    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
800                           ARM::R4)
801                   .addReg(ARM::R4, RegState::Kill).addImm(16)
802                   .addReg(NextReg)
803                   .addReg(SupReg, RegState::ImplicitKill));
804    NextReg += 4;
805    NumAlignedDPRCS2Regs -= 4;
806  }
807
808  // We won't modify r4 beyond this point.  It currently points to the next
809  // register to be spilled.
810  unsigned R4BaseReg = NextReg;
811
812  // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
813  if (NumAlignedDPRCS2Regs >= 4) {
814    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
815                                               ARM::QQPRRegisterClass);
816    MBB.addLiveIn(SupReg);
817    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
818                   .addReg(ARM::R4).addImm(16).addReg(NextReg)
819                   .addReg(SupReg, RegState::ImplicitKill));
820    NextReg += 4;
821    NumAlignedDPRCS2Regs -= 4;
822  }
823
824  // 16-byte aligned vst1.64 with 2 d-regs.
825  if (NumAlignedDPRCS2Regs >= 2) {
826    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
827                                               ARM::QPRRegisterClass);
828    MBB.addLiveIn(SupReg);
829    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
830                   .addReg(ARM::R4).addImm(16).addReg(NextReg)
831                   .addReg(SupReg, RegState::ImplicitKill));
832    NextReg += 2;
833    NumAlignedDPRCS2Regs -= 2;
834  }
835
836  // Finally, use a vanilla vstr.64 for the odd last register.
837  if (NumAlignedDPRCS2Regs) {
838    MBB.addLiveIn(NextReg);
839    // vstr.64 uses addrmode5 which has an offset scale of 4.
840    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
841                   .addReg(NextReg)
842                   .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
843  }
844
845  // The last spill instruction inserted should kill the scratch register r4.
846  llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
847}
848
849/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
850/// iterator to the following instruction.
851static MachineBasicBlock::iterator
852skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
853                        unsigned NumAlignedDPRCS2Regs) {
854  //   sub r4, sp, #numregs * 8
855  //   bic r4, r4, #align - 1
856  //   mov sp, r4
857  ++MI; ++MI; ++MI;
858  assert(MI->mayStore() && "Expecting spill instruction");
859
860  // These switches all fall through.
861  switch(NumAlignedDPRCS2Regs) {
862  case 7:
863    ++MI;
864    assert(MI->mayStore() && "Expecting spill instruction");
865  default:
866    ++MI;
867    assert(MI->mayStore() && "Expecting spill instruction");
868  case 1:
869  case 2:
870  case 4:
871    assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
872    ++MI;
873  }
874  return MI;
875}
876
877/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
878/// starting from d8.  These instructions are assumed to execute while the
879/// stack is still aligned, unlike the code inserted by emitPopInst.
880static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
881                                      MachineBasicBlock::iterator MI,
882                                      unsigned NumAlignedDPRCS2Regs,
883                                      const std::vector<CalleeSavedInfo> &CSI,
884                                      const TargetRegisterInfo *TRI) {
885  MachineFunction &MF = *MBB.getParent();
886  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
887  DebugLoc DL = MI->getDebugLoc();
888  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
889
890  // Find the frame index assigned to d8.
891  int D8SpillFI = 0;
892  for (unsigned i = 0, e = CSI.size(); i != e; ++i)
893    if (CSI[i].getReg() == ARM::D8) {
894      D8SpillFI = CSI[i].getFrameIdx();
895      break;
896    }
897
898  // Materialize the address of the d8 spill slot into the scratch register r4.
899  // This can be fairly complicated if the stack frame is large, so just use
900  // the normal frame index elimination mechanism to do it.  This code runs as
901  // the initial part of the epilog where the stack and base pointers haven't
902  // been changed yet.
903  bool isThumb = AFI->isThumbFunction();
904  assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
905
906  unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
907  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
908                              .addFrameIndex(D8SpillFI).addImm(0)));
909
910  // Now restore NumAlignedDPRCS2Regs registers starting from d8.
911  unsigned NextReg = ARM::D8;
912
913  // 16-byte aligned vld1.64 with 4 d-regs and writeback.
914  if (NumAlignedDPRCS2Regs >= 6) {
915    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
916                                               ARM::QQPRRegisterClass);
917    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
918                   .addReg(ARM::R4, RegState::Define)
919                   .addReg(ARM::R4, RegState::Kill).addImm(16)
920                   .addReg(SupReg, RegState::ImplicitDefine));
921    NextReg += 4;
922    NumAlignedDPRCS2Regs -= 4;
923  }
924
925  // We won't modify r4 beyond this point.  It currently points to the next
926  // register to be spilled.
927  unsigned R4BaseReg = NextReg;
928
929  // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
930  if (NumAlignedDPRCS2Regs >= 4) {
931    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
932                                               ARM::QQPRRegisterClass);
933    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
934                   .addReg(ARM::R4).addImm(16)
935                   .addReg(SupReg, RegState::ImplicitDefine));
936    NextReg += 4;
937    NumAlignedDPRCS2Regs -= 4;
938  }
939
940  // 16-byte aligned vld1.64 with 2 d-regs.
941  if (NumAlignedDPRCS2Regs >= 2) {
942    unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
943                                               ARM::QPRRegisterClass);
944    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), NextReg)
945                   .addReg(ARM::R4).addImm(16)
946                   .addReg(SupReg, RegState::ImplicitDefine));
947    NextReg += 2;
948    NumAlignedDPRCS2Regs -= 2;
949  }
950
951  // Finally, use a vanilla vldr.64 for the remaining odd register.
952  if (NumAlignedDPRCS2Regs)
953    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
954                   .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
955
956  // Last store kills r4.
957  llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
958}
959
960bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
961                                        MachineBasicBlock::iterator MI,
962                                        const std::vector<CalleeSavedInfo> &CSI,
963                                        const TargetRegisterInfo *TRI) const {
964  if (CSI.empty())
965    return false;
966
967  MachineFunction &MF = *MBB.getParent();
968  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
969
970  unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
971  unsigned PushOneOpc = AFI->isThumbFunction() ?
972    ARM::t2STR_PRE : ARM::STR_PRE_IMM;
973  unsigned FltOpc = ARM::VSTMDDB_UPD;
974  unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
975  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
976               MachineInstr::FrameSetup);
977  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
978               MachineInstr::FrameSetup);
979  emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
980               NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
981
982  // The code above does not insert spill code for the aligned DPRCS2 registers.
983  // The stack realignment code will be inserted between the push instructions
984  // and these spills.
985  if (NumAlignedDPRCS2Regs)
986    emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
987
988  return true;
989}
990
991bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
992                                        MachineBasicBlock::iterator MI,
993                                        const std::vector<CalleeSavedInfo> &CSI,
994                                        const TargetRegisterInfo *TRI) const {
995  if (CSI.empty())
996    return false;
997
998  MachineFunction &MF = *MBB.getParent();
999  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1000  bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
1001  unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1002
1003  // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1004  // registers. Do that here instead.
1005  if (NumAlignedDPRCS2Regs)
1006    emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1007
1008  unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1009  unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1010  unsigned FltOpc = ARM::VLDMDIA_UPD;
1011  emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1012              NumAlignedDPRCS2Regs);
1013  emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1014              &isARMArea2Register, 0);
1015  emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1016              &isARMArea1Register, 0);
1017
1018  return true;
1019}
1020
1021// FIXME: Make generic?
1022static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1023                                       const ARMBaseInstrInfo &TII) {
1024  unsigned FnSize = 0;
1025  for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
1026       MBBI != E; ++MBBI) {
1027    const MachineBasicBlock &MBB = *MBBI;
1028    for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
1029         I != E; ++I)
1030      FnSize += TII.GetInstSizeInBytes(I);
1031  }
1032  return FnSize;
1033}
1034
1035/// estimateStackSize - Estimate and return the size of the frame.
1036/// FIXME: Make generic?
1037static unsigned estimateStackSize(MachineFunction &MF) {
1038  const MachineFrameInfo *MFI = MF.getFrameInfo();
1039  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1040  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
1041  unsigned MaxAlign = MFI->getMaxAlignment();
1042  int Offset = 0;
1043
1044  // This code is very, very similar to PEI::calculateFrameObjectOffsets().
1045  // It really should be refactored to share code. Until then, changes
1046  // should keep in mind that there's tight coupling between the two.
1047
1048  for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
1049    int FixedOff = -MFI->getObjectOffset(i);
1050    if (FixedOff > Offset) Offset = FixedOff;
1051  }
1052  for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
1053    if (MFI->isDeadObjectIndex(i))
1054      continue;
1055    Offset += MFI->getObjectSize(i);
1056    unsigned Align = MFI->getObjectAlignment(i);
1057    // Adjust to alignment boundary
1058    Offset = (Offset+Align-1)/Align*Align;
1059
1060    MaxAlign = std::max(Align, MaxAlign);
1061  }
1062
1063  if (MFI->adjustsStack() && TFI->hasReservedCallFrame(MF))
1064    Offset += MFI->getMaxCallFrameSize();
1065
1066  // Round up the size to a multiple of the alignment.  If the function has
1067  // any calls or alloca's, align to the target's StackAlignment value to
1068  // ensure that the callee's frame or the alloca data is suitably aligned;
1069  // otherwise, for leaf functions, align to the TransientStackAlignment
1070  // value.
1071  unsigned StackAlign;
1072  if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
1073      (RegInfo->needsStackRealignment(MF) && MFI->getObjectIndexEnd() != 0))
1074    StackAlign = TFI->getStackAlignment();
1075  else
1076    StackAlign = TFI->getTransientStackAlignment();
1077
1078  // If the frame pointer is eliminated, all frame offsets will be relative to
1079  // SP not FP. Align to MaxAlign so this works.
1080  StackAlign = std::max(StackAlign, MaxAlign);
1081  unsigned AlignMask = StackAlign - 1;
1082  Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
1083
1084  return (unsigned)Offset;
1085}
1086
1087/// estimateRSStackSizeLimit - Look at each instruction that references stack
1088/// frames and return the stack size limit beyond which some of these
1089/// instructions will require a scratch register during their expansion later.
1090// FIXME: Move to TII?
1091static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1092                                         const TargetFrameLowering *TFI) {
1093  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1094  unsigned Limit = (1 << 12) - 1;
1095  for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
1096    for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1097         I != E; ++I) {
1098      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1099        if (!I->getOperand(i).isFI()) continue;
1100
1101        // When using ADDri to get the address of a stack object, 255 is the
1102        // largest offset guaranteed to fit in the immediate offset.
1103        if (I->getOpcode() == ARM::ADDri) {
1104          Limit = std::min(Limit, (1U << 8) - 1);
1105          break;
1106        }
1107
1108        // Otherwise check the addressing mode.
1109        switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
1110        case ARMII::AddrMode3:
1111        case ARMII::AddrModeT2_i8:
1112          Limit = std::min(Limit, (1U << 8) - 1);
1113          break;
1114        case ARMII::AddrMode5:
1115        case ARMII::AddrModeT2_i8s4:
1116          Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1117          break;
1118        case ARMII::AddrModeT2_i12:
1119          // i12 supports only positive offset so these will be converted to
1120          // i8 opcodes. See llvm::rewriteT2FrameIndex.
1121          if (TFI->hasFP(MF) && AFI->hasStackFrame())
1122            Limit = std::min(Limit, (1U << 8) - 1);
1123          break;
1124        case ARMII::AddrMode4:
1125        case ARMII::AddrMode6:
1126          // Addressing modes 4 & 6 (load/store) instructions can't encode an
1127          // immediate offset for stack references.
1128          return 0;
1129        default:
1130          break;
1131        }
1132        break; // At most one FI per instruction
1133      }
1134    }
1135  }
1136
1137  return Limit;
1138}
1139
1140// In functions that realign the stack, it can be an advantage to spill the
1141// callee-saved vector registers after realigning the stack. The vst1 and vld1
1142// instructions take alignment hints that can improve performance.
1143//
1144static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1145  MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1146  if (!SpillAlignedNEONRegs)
1147    return;
1148
1149  // Naked functions don't spill callee-saved registers.
1150  if (MF.getFunction()->hasFnAttr(Attribute::Naked))
1151    return;
1152
1153  // We are planning to use NEON instructions vst1 / vld1.
1154  if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1155    return;
1156
1157  // Don't bother if the default stack alignment is sufficiently high.
1158  if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1159    return;
1160
1161  // Aligned spills require stack realignment.
1162  const ARMBaseRegisterInfo *RegInfo =
1163    static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1164  if (!RegInfo->canRealignStack(MF))
1165    return;
1166
1167  // We always spill contiguous d-registers starting from d8. Count how many
1168  // needs spilling.  The register allocator will almost always use the
1169  // callee-saved registers in order, but it can happen that there are holes in
1170  // the range.  Registers above the hole will be spilled to the standard DPRCS
1171  // area.
1172  MachineRegisterInfo &MRI = MF.getRegInfo();
1173  unsigned NumSpills = 0;
1174  for (; NumSpills < 8; ++NumSpills)
1175    if (!MRI.isPhysRegOrOverlapUsed(ARM::D8 + NumSpills))
1176      break;
1177
1178  // Don't do this for just one d-register. It's not worth it.
1179  if (NumSpills < 2)
1180    return;
1181
1182  // Spill the first NumSpills D-registers after realigning the stack.
1183  MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1184
1185  // A scratch register is required for the vst1 / vld1 instructions.
1186  MF.getRegInfo().setPhysRegUsed(ARM::R4);
1187}
1188
1189void
1190ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1191                                                       RegScavenger *RS) const {
1192  // This tells PEI to spill the FP as if it is any other callee-save register
1193  // to take advantage the eliminateFrameIndex machinery. This also ensures it
1194  // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1195  // to combine multiple loads / stores.
1196  bool CanEliminateFrame = true;
1197  bool CS1Spilled = false;
1198  bool LRSpilled = false;
1199  unsigned NumGPRSpills = 0;
1200  SmallVector<unsigned, 4> UnspilledCS1GPRs;
1201  SmallVector<unsigned, 4> UnspilledCS2GPRs;
1202  const ARMBaseRegisterInfo *RegInfo =
1203    static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1204  const ARMBaseInstrInfo &TII =
1205    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1206  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1207  MachineFrameInfo *MFI = MF.getFrameInfo();
1208  unsigned FramePtr = RegInfo->getFrameRegister(MF);
1209
1210  // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1211  // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1212  // since it's not always possible to restore sp from fp in a single
1213  // instruction.
1214  // FIXME: It will be better just to find spare register here.
1215  if (AFI->isThumb2Function() &&
1216      (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1217    MF.getRegInfo().setPhysRegUsed(ARM::R4);
1218
1219  if (AFI->isThumb1OnlyFunction()) {
1220    // Spill LR if Thumb1 function uses variable length argument lists.
1221    if (AFI->getVarArgsRegSaveSize() > 0)
1222      MF.getRegInfo().setPhysRegUsed(ARM::LR);
1223
1224    // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1225    // for sure what the stack size will be, but for this, an estimate is good
1226    // enough. If there anything changes it, it'll be a spill, which implies
1227    // we've used all the registers and so R4 is already used, so not marking
1228    // it here will be OK.
1229    // FIXME: It will be better just to find spare register here.
1230    unsigned StackSize = estimateStackSize(MF);
1231    if (MFI->hasVarSizedObjects() || StackSize > 508)
1232      MF.getRegInfo().setPhysRegUsed(ARM::R4);
1233  }
1234
1235  // See if we can spill vector registers to aligned stack.
1236  checkNumAlignedDPRCS2Regs(MF);
1237
1238  // Spill the BasePtr if it's used.
1239  if (RegInfo->hasBasePointer(MF))
1240    MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1241
1242  // Don't spill FP if the frame can be eliminated. This is determined
1243  // by scanning the callee-save registers to see if any is used.
1244  const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
1245  for (unsigned i = 0; CSRegs[i]; ++i) {
1246    unsigned Reg = CSRegs[i];
1247    bool Spilled = false;
1248    if (MF.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
1249      Spilled = true;
1250      CanEliminateFrame = false;
1251    }
1252
1253    if (!ARM::GPRRegisterClass->contains(Reg))
1254      continue;
1255
1256    if (Spilled) {
1257      NumGPRSpills++;
1258
1259      if (!STI.isTargetDarwin()) {
1260        if (Reg == ARM::LR)
1261          LRSpilled = true;
1262        CS1Spilled = true;
1263        continue;
1264      }
1265
1266      // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1267      switch (Reg) {
1268      case ARM::LR:
1269        LRSpilled = true;
1270        // Fallthrough
1271      case ARM::R4: case ARM::R5:
1272      case ARM::R6: case ARM::R7:
1273        CS1Spilled = true;
1274        break;
1275      default:
1276        break;
1277      }
1278    } else {
1279      if (!STI.isTargetDarwin()) {
1280        UnspilledCS1GPRs.push_back(Reg);
1281        continue;
1282      }
1283
1284      switch (Reg) {
1285      case ARM::R4: case ARM::R5:
1286      case ARM::R6: case ARM::R7:
1287      case ARM::LR:
1288        UnspilledCS1GPRs.push_back(Reg);
1289        break;
1290      default:
1291        UnspilledCS2GPRs.push_back(Reg);
1292        break;
1293      }
1294    }
1295  }
1296
1297  bool ForceLRSpill = false;
1298  if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1299    unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1300    // Force LR to be spilled if the Thumb function size is > 2048. This enables
1301    // use of BL to implement far jump. If it turns out that it's not needed
1302    // then the branch fix up path will undo it.
1303    if (FnSize >= (1 << 11)) {
1304      CanEliminateFrame = false;
1305      ForceLRSpill = true;
1306    }
1307  }
1308
1309  // If any of the stack slot references may be out of range of an immediate
1310  // offset, make sure a register (or a spill slot) is available for the
1311  // register scavenger. Note that if we're indexing off the frame pointer, the
1312  // effective stack size is 4 bytes larger since the FP points to the stack
1313  // slot of the previous FP. Also, if we have variable sized objects in the
1314  // function, stack slot references will often be negative, and some of
1315  // our instructions are positive-offset only, so conservatively consider
1316  // that case to want a spill slot (or register) as well. Similarly, if
1317  // the function adjusts the stack pointer during execution and the
1318  // adjustments aren't already part of our stack size estimate, our offset
1319  // calculations may be off, so be conservative.
1320  // FIXME: We could add logic to be more precise about negative offsets
1321  //        and which instructions will need a scratch register for them. Is it
1322  //        worth the effort and added fragility?
1323  bool BigStack =
1324    (RS &&
1325     (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1326      estimateRSStackSizeLimit(MF, this)))
1327    || MFI->hasVarSizedObjects()
1328    || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1329
1330  bool ExtraCSSpill = false;
1331  if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1332    AFI->setHasStackFrame(true);
1333
1334    // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1335    // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1336    if (!LRSpilled && CS1Spilled) {
1337      MF.getRegInfo().setPhysRegUsed(ARM::LR);
1338      NumGPRSpills++;
1339      UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1340                                    UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1341      ForceLRSpill = false;
1342      ExtraCSSpill = true;
1343    }
1344
1345    if (hasFP(MF)) {
1346      MF.getRegInfo().setPhysRegUsed(FramePtr);
1347      NumGPRSpills++;
1348    }
1349
1350    // If stack and double are 8-byte aligned and we are spilling an odd number
1351    // of GPRs, spill one extra callee save GPR so we won't have to pad between
1352    // the integer and double callee save areas.
1353    unsigned TargetAlign = getStackAlignment();
1354    if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1355      if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1356        for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1357          unsigned Reg = UnspilledCS1GPRs[i];
1358          // Don't spill high register if the function is thumb1
1359          if (!AFI->isThumb1OnlyFunction() ||
1360              isARMLowRegister(Reg) || Reg == ARM::LR) {
1361            MF.getRegInfo().setPhysRegUsed(Reg);
1362            if (!RegInfo->isReservedReg(MF, Reg))
1363              ExtraCSSpill = true;
1364            break;
1365          }
1366        }
1367      } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1368        unsigned Reg = UnspilledCS2GPRs.front();
1369        MF.getRegInfo().setPhysRegUsed(Reg);
1370        if (!RegInfo->isReservedReg(MF, Reg))
1371          ExtraCSSpill = true;
1372      }
1373    }
1374
1375    // Estimate if we might need to scavenge a register at some point in order
1376    // to materialize a stack offset. If so, either spill one additional
1377    // callee-saved register or reserve a special spill slot to facilitate
1378    // register scavenging. Thumb1 needs a spill slot for stack pointer
1379    // adjustments also, even when the frame itself is small.
1380    if (BigStack && !ExtraCSSpill) {
1381      // If any non-reserved CS register isn't spilled, just spill one or two
1382      // extra. That should take care of it!
1383      unsigned NumExtras = TargetAlign / 4;
1384      SmallVector<unsigned, 2> Extras;
1385      while (NumExtras && !UnspilledCS1GPRs.empty()) {
1386        unsigned Reg = UnspilledCS1GPRs.back();
1387        UnspilledCS1GPRs.pop_back();
1388        if (!RegInfo->isReservedReg(MF, Reg) &&
1389            (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1390             Reg == ARM::LR)) {
1391          Extras.push_back(Reg);
1392          NumExtras--;
1393        }
1394      }
1395      // For non-Thumb1 functions, also check for hi-reg CS registers
1396      if (!AFI->isThumb1OnlyFunction()) {
1397        while (NumExtras && !UnspilledCS2GPRs.empty()) {
1398          unsigned Reg = UnspilledCS2GPRs.back();
1399          UnspilledCS2GPRs.pop_back();
1400          if (!RegInfo->isReservedReg(MF, Reg)) {
1401            Extras.push_back(Reg);
1402            NumExtras--;
1403          }
1404        }
1405      }
1406      if (Extras.size() && NumExtras == 0) {
1407        for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1408          MF.getRegInfo().setPhysRegUsed(Extras[i]);
1409        }
1410      } else if (!AFI->isThumb1OnlyFunction()) {
1411        // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
1412        // closest to SP or frame pointer.
1413        const TargetRegisterClass *RC = ARM::GPRRegisterClass;
1414        RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1415                                                           RC->getAlignment(),
1416                                                           false));
1417      }
1418    }
1419  }
1420
1421  if (ForceLRSpill) {
1422    MF.getRegInfo().setPhysRegUsed(ARM::LR);
1423    AFI->setLRIsSpilledForFarJump(true);
1424  }
1425}
1426