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