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