7766b1f48813bf247e7e3e34d54dd7ccfd7524b2
[oota-llvm.git] / lib / Target / ARM / ARMFrameInfo.cpp
1 //=======- ARMFrameInfo.cpp - ARM Frame Information ------------*- C++ -*-====//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the ARM implementation of TargetFrameInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMFrameInfo.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMMachineFunctionInfo.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/Target/TargetOptions.h"
21
22 using namespace llvm;
23
24 /// hasFP - Return true if the specified function should have a dedicated frame
25 /// pointer register.  This is true if the function has variable sized allocas
26 /// or if frame pointer elimination is disabled.
27 ///
28 bool ARMFrameInfo::hasFP(const MachineFunction &MF) const {
29   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
30
31   // Mac OS X requires FP not to be clobbered for backtracing purpose.
32   if (STI.isTargetDarwin())
33     return true;
34
35   const MachineFrameInfo *MFI = MF.getFrameInfo();
36   // Always eliminate non-leaf frame pointers.
37   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
38           RegInfo->needsStackRealignment(MF) ||
39           MFI->hasVarSizedObjects() ||
40           MFI->isFrameAddressTaken());
41 }
42
43 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
44 // not required, we reserve argument space for call sites in the function
45 // immediately on entry to the current function. This eliminates the need for
46 // add/sub sp brackets around call sites. Returns true if the call frame is
47 // included as part of the stack frame.
48 bool ARMFrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
49   const MachineFrameInfo *FFI = MF.getFrameInfo();
50   unsigned CFSize = FFI->getMaxCallFrameSize();
51   // It's not always a good idea to include the call frame as part of the
52   // stack frame. ARM (especially Thumb) has small immediate offset to
53   // address the stack frame. So a large call frame can cause poor codegen
54   // and may even makes it impossible to scavenge a register.
55   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
56     return false;
57
58   return !MF.getFrameInfo()->hasVarSizedObjects();
59 }
60
61 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
62 // call frame pseudos can be simplified. Unlike most targets, having a FP
63 // is not sufficient here since we still may reference some objects via SP
64 // even when FP is available in Thumb2 mode.
65 bool ARMFrameInfo::canSimplifyCallFramePseudos(const MachineFunction &MF)const {
66   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
67 }
68
69 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
70   for (unsigned i = 0; CSRegs[i]; ++i)
71     if (Reg == CSRegs[i])
72       return true;
73   return false;
74 }
75
76 static bool isCSRestore(MachineInstr *MI,
77                         const ARMBaseInstrInfo &TII,
78                         const unsigned *CSRegs) {
79   // Integer spill area is handled with "pop".
80   if (MI->getOpcode() == ARM::LDMIA_RET ||
81       MI->getOpcode() == ARM::t2LDMIA_RET ||
82       MI->getOpcode() == ARM::LDMIA_UPD ||
83       MI->getOpcode() == ARM::t2LDMIA_UPD ||
84       MI->getOpcode() == ARM::VLDMDIA_UPD) {
85     // The first two operands are predicates. The last two are
86     // imp-def and imp-use of SP. Check everything in between.
87     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
88       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
89         return false;
90     return true;
91   }
92
93   return false;
94 }
95
96 static void
97 emitSPUpdate(bool isARM,
98              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
99              DebugLoc dl, const ARMBaseInstrInfo &TII,
100              int NumBytes,
101              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
102   if (isARM)
103     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
104                             Pred, PredReg, TII);
105   else
106     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
107                            Pred, PredReg, TII);
108 }
109
110 void ARMFrameInfo::emitPrologue(MachineFunction &MF) const {
111   MachineBasicBlock &MBB = MF.front();
112   MachineBasicBlock::iterator MBBI = MBB.begin();
113   MachineFrameInfo  *MFI = MF.getFrameInfo();
114   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
115   const ARMBaseRegisterInfo *RegInfo =
116     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
117   const ARMBaseInstrInfo &TII =
118     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
119   assert(!AFI->isThumb1OnlyFunction() &&
120          "This emitPrologue does not support Thumb1!");
121   bool isARM = !AFI->isThumbFunction();
122   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
123   unsigned NumBytes = MFI->getStackSize();
124   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
125   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
126   unsigned FramePtr = RegInfo->getFrameRegister(MF);
127
128   // Determine the sizes of each callee-save spill areas and record which frame
129   // belongs to which callee-save spill areas.
130   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
131   int FramePtrSpillFI = 0;
132
133   // Allocate the vararg register save area. This is not counted in NumBytes.
134   if (VARegSaveSize)
135     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
136
137   if (!AFI->hasStackFrame()) {
138     if (NumBytes != 0)
139       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
140     return;
141   }
142
143   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
144     unsigned Reg = CSI[i].getReg();
145     int FI = CSI[i].getFrameIdx();
146     switch (Reg) {
147     case ARM::R4:
148     case ARM::R5:
149     case ARM::R6:
150     case ARM::R7:
151     case ARM::LR:
152       if (Reg == FramePtr)
153         FramePtrSpillFI = FI;
154       AFI->addGPRCalleeSavedArea1Frame(FI);
155       GPRCS1Size += 4;
156       break;
157     case ARM::R8:
158     case ARM::R9:
159     case ARM::R10:
160     case ARM::R11:
161       if (Reg == FramePtr)
162         FramePtrSpillFI = FI;
163       if (STI.isTargetDarwin()) {
164         AFI->addGPRCalleeSavedArea2Frame(FI);
165         GPRCS2Size += 4;
166       } else {
167         AFI->addGPRCalleeSavedArea1Frame(FI);
168         GPRCS1Size += 4;
169       }
170       break;
171     default:
172       AFI->addDPRCalleeSavedAreaFrame(FI);
173       DPRCSSize += 8;
174     }
175   }
176   
177   // Move past area 1.
178   if (GPRCS1Size > 0) MBBI++;
179   
180   // Set FP to point to the stack slot that contains the previous FP.
181   // For Darwin, FP is R7, which has now been stored in spill area 1.
182   // Otherwise, if this is not Darwin, all the callee-saved registers go
183   // into spill area 1, including the FP in R11.  In either case, it is
184   // now safe to emit this assignment.
185   bool HasFP = hasFP(MF);
186   if (HasFP) {
187     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
188     MachineInstrBuilder MIB =
189       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
190       .addFrameIndex(FramePtrSpillFI).addImm(0);
191     AddDefaultCC(AddDefaultPred(MIB));
192   }
193   
194   // Move past area 2.
195   if (GPRCS2Size > 0) MBBI++;
196   
197   // Determine starting offsets of spill areas.
198   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
199   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
200   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
201   if (HasFP)
202     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
203                                 NumBytes);
204   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
205   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
206   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
207
208   // Move past area 3.
209   if (DPRCSSize > 0) MBBI++;
210   
211   NumBytes = DPRCSOffset;
212   if (NumBytes) {
213     // Adjust SP after all the callee-save spills.
214     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
215     if (HasFP)
216       AFI->setShouldRestoreSPFromFP(true);
217   }
218
219   if (STI.isTargetELF() && hasFP(MF)) {
220     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
221                              AFI->getFramePtrSpillOffset());
222     AFI->setShouldRestoreSPFromFP(true);
223   }
224
225   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
226   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
227   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
228
229   // If we need dynamic stack realignment, do it here. Be paranoid and make
230   // sure if we also have VLAs, we have a base pointer for frame access.
231   if (RegInfo->needsStackRealignment(MF)) {
232     unsigned MaxAlign = MFI->getMaxAlignment();
233     assert (!AFI->isThumb1OnlyFunction());
234     if (!AFI->isThumbFunction()) {
235       // Emit bic sp, sp, MaxAlign
236       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
237                                           TII.get(ARM::BICri), ARM::SP)
238                                   .addReg(ARM::SP, RegState::Kill)
239                                   .addImm(MaxAlign-1)));
240     } else {
241       // We cannot use sp as source/dest register here, thus we're emitting the
242       // following sequence:
243       // mov r4, sp
244       // bic r4, r4, MaxAlign
245       // mov sp, r4
246       // FIXME: It will be better just to find spare register here.
247       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
248         .addReg(ARM::SP, RegState::Kill);
249       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
250                                           TII.get(ARM::t2BICri), ARM::R4)
251                                   .addReg(ARM::R4, RegState::Kill)
252                                   .addImm(MaxAlign-1)));
253       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
254         .addReg(ARM::R4, RegState::Kill);
255     }
256
257     AFI->setShouldRestoreSPFromFP(true);
258   }
259
260   // If we need a base pointer, set it up here. It's whatever the value
261   // of the stack pointer is at this point. Any variable size objects
262   // will be allocated after this, so we can still use the base pointer
263   // to reference locals.
264   if (RegInfo->hasBasePointer(MF)) {
265     if (isARM)
266       BuildMI(MBB, MBBI, dl,
267               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
268         .addReg(ARM::SP)
269         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
270     else
271       BuildMI(MBB, MBBI, dl,
272               TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
273         .addReg(ARM::SP);
274   }
275
276   // If the frame has variable sized objects then the epilogue must restore
277   // the sp from fp.
278   if (!AFI->shouldRestoreSPFromFP() && MFI->hasVarSizedObjects())
279     AFI->setShouldRestoreSPFromFP(true);
280 }
281
282 void ARMFrameInfo::emitEpilogue(MachineFunction &MF,
283                                 MachineBasicBlock &MBB) const {
284   MachineBasicBlock::iterator MBBI = prior(MBB.end());
285   assert(MBBI->getDesc().isReturn() &&
286          "Can only insert epilog into returning blocks");
287   unsigned RetOpcode = MBBI->getOpcode();
288   DebugLoc dl = MBBI->getDebugLoc();
289   MachineFrameInfo *MFI = MF.getFrameInfo();
290   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
291   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
292   const ARMBaseInstrInfo &TII =
293     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
294   assert(!AFI->isThumb1OnlyFunction() &&
295          "This emitEpilogue does not support Thumb1!");
296   bool isARM = !AFI->isThumbFunction();
297
298   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
299   int NumBytes = (int)MFI->getStackSize();
300   unsigned FramePtr = RegInfo->getFrameRegister(MF);
301
302   if (!AFI->hasStackFrame()) {
303     if (NumBytes != 0)
304       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
305   } else {
306     // Unwind MBBI to point to first LDR / VLDRD.
307     const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
308     if (MBBI != MBB.begin()) {
309       do
310         --MBBI;
311       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
312       if (!isCSRestore(MBBI, TII, CSRegs))
313         ++MBBI;
314     }
315
316     // Move SP to start of FP callee save spill area.
317     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
318                  AFI->getGPRCalleeSavedArea2Size() +
319                  AFI->getDPRCalleeSavedAreaSize());
320
321     // Reset SP based on frame pointer only if the stack frame extends beyond
322     // frame pointer stack slot or target is ELF and the function has FP.
323     if (AFI->shouldRestoreSPFromFP()) {
324       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
325       if (NumBytes) {
326         if (isARM)
327           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
328                                   ARMCC::AL, 0, TII);
329         else
330           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
331                                  ARMCC::AL, 0, TII);
332       } else {
333         // Thumb2 or ARM.
334         if (isARM)
335           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
336             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
337         else
338           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
339             .addReg(FramePtr);
340       }
341     } else if (NumBytes)
342       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
343
344     // Increment past our save areas.
345     if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
346     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
347     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
348   }
349
350   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
351       RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
352     // Tail call return: adjust the stack pointer and jump to callee.
353     MBBI = prior(MBB.end());
354     MachineOperand &JumpTarget = MBBI->getOperand(0);
355
356     // Jump to label or value in register.
357     if (RetOpcode == ARM::TCRETURNdi) {
358       BuildMI(MBB, MBBI, dl,
359             TII.get(STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)).
360         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
361                          JumpTarget.getTargetFlags());
362     } else if (RetOpcode == ARM::TCRETURNdiND) {
363       BuildMI(MBB, MBBI, dl,
364             TII.get(STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND)).
365         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
366                          JumpTarget.getTargetFlags());
367     } else if (RetOpcode == ARM::TCRETURNri) {
368       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
369         addReg(JumpTarget.getReg(), RegState::Kill);
370     } else if (RetOpcode == ARM::TCRETURNriND) {
371       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
372         addReg(JumpTarget.getReg(), RegState::Kill);
373     }
374
375     MachineInstr *NewMI = prior(MBBI);
376     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
377       NewMI->addOperand(MBBI->getOperand(i));
378
379     // Delete the pseudo instruction TCRETURN.
380     MBB.erase(MBBI);
381   }
382
383   if (VARegSaveSize)
384     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
385 }
386
387 // Provide a base+offset reference to an FI slot for debug info. It's the
388 // same as what we use for resolving the code-gen references for now.
389 // FIXME: This can go wrong when references are SP-relative and simple call
390 //        frames aren't used.
391 int
392 ARMFrameInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
393                                      unsigned &FrameReg) const {
394   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
395 }
396
397 int
398 ARMFrameInfo::ResolveFrameIndexReference(const MachineFunction &MF,
399                                          int FI,
400                                          unsigned &FrameReg,
401                                          int SPAdj) const {
402   const MachineFrameInfo *MFI = MF.getFrameInfo();
403   const ARMBaseRegisterInfo *RegInfo =
404     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
405   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
406   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
407   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
408   bool isFixed = MFI->isFixedObjectIndex(FI);
409
410   FrameReg = ARM::SP;
411   Offset += SPAdj;
412   if (AFI->isGPRCalleeSavedArea1Frame(FI))
413     return Offset - AFI->getGPRCalleeSavedArea1Offset();
414   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
415     return Offset - AFI->getGPRCalleeSavedArea2Offset();
416   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
417     return Offset - AFI->getDPRCalleeSavedAreaOffset();
418
419   // When dynamically realigning the stack, use the frame pointer for
420   // parameters, and the stack/base pointer for locals.
421   if (RegInfo->needsStackRealignment(MF)) {
422     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
423     if (isFixed) {
424       FrameReg = RegInfo->getFrameRegister(MF);
425       Offset = FPOffset;
426     } else if (MFI->hasVarSizedObjects()) {
427       assert(RegInfo->hasBasePointer(MF) &&
428              "VLAs and dynamic stack alignment, but missing base pointer!");
429       FrameReg = RegInfo->getBaseRegister();
430     }
431     return Offset;
432   }
433
434   // If there is a frame pointer, use it when we can.
435   if (hasFP(MF) && AFI->hasStackFrame()) {
436     // Use frame pointer to reference fixed objects. Use it for locals if
437     // there are VLAs (and thus the SP isn't reliable as a base).
438     if (isFixed || (MFI->hasVarSizedObjects() && !RegInfo->hasBasePointer(MF))) {
439       FrameReg = RegInfo->getFrameRegister(MF);
440       return FPOffset;
441     } else if (MFI->hasVarSizedObjects()) {
442       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
443       // Try to use the frame pointer if we can, else use the base pointer
444       // since it's available. This is handy for the emergency spill slot, in
445       // particular.
446       if (AFI->isThumb2Function()) {
447         if (FPOffset >= -255 && FPOffset < 0) {
448           FrameReg = RegInfo->getFrameRegister(MF);
449           return FPOffset;
450         }
451       } else
452         FrameReg = RegInfo->getBaseRegister();
453     } else if (AFI->isThumb2Function()) {
454       // In Thumb2 mode, the negative offset is very limited. Try to avoid
455       // out of range references.
456       if (FPOffset >= -255 && FPOffset < 0) {
457         FrameReg = RegInfo->getFrameRegister(MF);
458         return FPOffset;
459       }
460     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
461       // Otherwise, use SP or FP, whichever is closer to the stack slot.
462       FrameReg = RegInfo->getFrameRegister(MF);
463       return FPOffset;
464     }
465   }
466   // Use the base pointer if we have one.
467   if (RegInfo->hasBasePointer(MF))
468     FrameReg = RegInfo->getBaseRegister();
469   return Offset;
470 }
471
472 int ARMFrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
473   unsigned FrameReg;
474   return getFrameIndexReference(MF, FI, FrameReg);
475 }