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