Include RegSaveAreaSize in the computation of stack size.
[oota-llvm.git] / lib / Target / Mips / MipsFrameLowering.cpp
1 //=======- MipsFrameLowering.cpp - Mips 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 Mips implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MipsFrameLowering.h"
15 #include "MipsInstrInfo.h"
16 #include "MipsMachineFunction.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Support/CommandLine.h"
26
27 using namespace llvm;
28
29
30 //===----------------------------------------------------------------------===//
31 //
32 // Stack Frame Processing methods
33 // +----------------------------+
34 //
35 // The stack is allocated decrementing the stack pointer on
36 // the first instruction of a function prologue. Once decremented,
37 // all stack references are done thought a positive offset
38 // from the stack/frame pointer, so the stack is considering
39 // to grow up! Otherwise terrible hacks would have to be made
40 // to get this stack ABI compliant :)
41 //
42 //  The stack frame required by the ABI (after call):
43 //  Offset
44 //
45 //  0                 ----------
46 //  4                 Args to pass
47 //  .                 saved $GP  (used in PIC)
48 //  .                 Alloca allocations
49 //  .                 Local Area
50 //  .                 CPU "Callee Saved" Registers
51 //  .                 saved FP
52 //  .                 saved RA
53 //  .                 FPU "Callee Saved" Registers
54 //  StackSize         -----------
55 //
56 // Offset - offset from sp after stack allocation on function prologue
57 //
58 // The sp is the stack pointer subtracted/added from the stack size
59 // at the Prologue/Epilogue
60 //
61 // References to the previous stack (to obtain arguments) are done
62 // with offsets that exceeds the stack size: (stacksize+(4*(num_arg-1))
63 //
64 // Examples:
65 // - reference to the actual stack frame
66 //   for any local area var there is smt like : FI >= 0, StackOffset: 4
67 //     sw REGX, 4(SP)
68 //
69 // - reference to previous stack frame
70 //   suppose there's a load to the 5th arguments : FI < 0, StackOffset: 16.
71 //   The emitted instruction will be something like:
72 //     lw REGX, 16+StackSize(SP)
73 //
74 // Since the total stack size is unknown on LowerFormalArguments, all
75 // stack references (ObjectOffset) created to reference the function
76 // arguments, are negative numbers. This way, on eliminateFrameIndex it's
77 // possible to detect those references and the offsets are adjusted to
78 // their real location.
79 //
80 //===----------------------------------------------------------------------===//
81
82 // hasFP - Return true if the specified function should have a dedicated frame
83 // pointer register.  This is true if the function has variable sized allocas or
84 // if frame pointer elimination is disabled.
85 bool MipsFrameLowering::hasFP(const MachineFunction &MF) const {
86   const MachineFrameInfo *MFI = MF.getFrameInfo();
87   return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects()
88       || MFI->isFrameAddressTaken();
89 }
90
91 bool MipsFrameLowering::targetHandlesStackFrameRounding() const {
92   return true;
93 }
94
95 static unsigned AlignOffset(unsigned Offset, unsigned Align) {
96   return (Offset + Align - 1) / Align * Align; 
97
98
99 // expand pair of register and immediate if the immediate doesn't fit in the
100 // 16-bit offset field.
101 // e.g.
102 //  if OrigImm = 0x10000, OrigReg = $sp:
103 //    generate the following sequence of instrs:
104 //      lui  $at, hi(0x10000)
105 //      addu $at, $sp, $at
106 //
107 //    (NewReg, NewImm) = ($at, lo(Ox10000))
108 //    return true
109 static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm,
110                                   unsigned& NewReg, int& NewImm,
111                                   MachineBasicBlock& MBB,
112                                   MachineBasicBlock::iterator I) {
113   // OrigImm fits in the 16-bit field
114   if (OrigImm < 0x8000 && OrigImm >= -0x8000) {
115     NewReg = OrigReg;
116     NewImm = OrigImm;
117     return false;
118   }
119
120   MachineFunction* MF = MBB.getParent();
121   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
122   DebugLoc DL = I->getDebugLoc();
123   int ImmLo = (short)(OrigImm & 0xffff);
124   int ImmHi = (((unsigned)OrigImm & 0xffff0000) >> 16) +
125               ((OrigImm & 0x8000) != 0);
126
127   // FIXME: change this when mips goes MC".
128   BuildMI(MBB, I, DL, TII->get(Mips::NOAT));
129   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi);
130   BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg)
131                                                      .addReg(Mips::AT);
132   NewReg = Mips::AT;
133   NewImm = ImmLo;
134
135   return true;
136 }
137
138 void MipsFrameLowering::emitPrologue(MachineFunction &MF) const {
139   MachineBasicBlock &MBB   = MF.front();
140   MachineFrameInfo *MFI    = MF.getFrameInfo();
141   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
142   const MipsRegisterInfo *RegInfo =
143     static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo());
144   const MipsInstrInfo &TII =
145     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
146   MachineBasicBlock::iterator MBBI = MBB.begin();
147   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
148   bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_);
149   unsigned NewReg = 0;
150   int NewImm = 0;
151   bool ATUsed;
152
153   // First, compute final stack size.
154   unsigned RegSize = STI.isGP32bit() ? 4 : 8;
155   unsigned StackAlign = getStackAlignment();
156   unsigned LocalVarAreaOffset = MipsFI->needGPSaveRestore() ? 
157     (MFI->getObjectOffset(MipsFI->getGPFI()) + RegSize) :
158     MipsFI->getMaxCallFrameSize();
159   unsigned StackSize = AlignOffset(LocalVarAreaOffset, StackAlign) +
160     AlignOffset(MipsFI->getRegSaveAreaSize(), StackAlign) +
161     AlignOffset(MFI->getStackSize(), StackAlign);
162
163    // Update stack size
164   MFI->setStackSize(StackSize); 
165   
166   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER));
167
168   // TODO: check need from GP here.
169   if (isPIC && STI.isABI_O32())
170     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD))
171       .addReg(RegInfo->getPICCallReg());
172   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
173
174   // No need to allocate space on the stack.
175   if (StackSize == 0 && !MFI->adjustsStack()) return;
176
177   MachineModuleInfo &MMI = MF.getMMI();
178   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
179   MachineLocation DstML, SrcML;
180
181   // Adjust stack : addi sp, sp, (-imm)
182   ATUsed = expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, MBB,
183                                  MBBI);
184   BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
185     .addReg(NewReg).addImm(NewImm);
186
187   // FIXME: change this when mips goes MC".
188   if (ATUsed)
189     BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
190
191   // emit ".cfi_def_cfa_offset StackSize"
192   MCSymbol *AdjustSPLabel = MMI.getContext().CreateTempSymbol();
193   BuildMI(MBB, MBBI, dl,
194           TII.get(TargetOpcode::PROLOG_LABEL)).addSym(AdjustSPLabel);
195   DstML = MachineLocation(MachineLocation::VirtualFP);
196   SrcML = MachineLocation(MachineLocation::VirtualFP, -StackSize);
197   Moves.push_back(MachineMove(AdjustSPLabel, DstML, SrcML));
198
199   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
200
201   if (CSI.size()) {
202     // Find the instruction past the last instruction that saves a callee-saved
203     // register to the stack.
204     for (unsigned i = 0; i < CSI.size(); ++i)
205       ++MBBI;
206  
207     // Iterate over list of callee-saved registers and emit .cfi_offset
208     // directives.
209     MCSymbol *CSLabel = MMI.getContext().CreateTempSymbol();
210     BuildMI(MBB, MBBI, dl,
211             TII.get(TargetOpcode::PROLOG_LABEL)).addSym(CSLabel);
212  
213     for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
214            E = CSI.end(); I != E; ++I) {
215       int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
216       unsigned Reg = I->getReg();
217
218       // If Reg is a double precision register, emit two cfa_offsets,
219       // one for each of the paired single precision registers.
220       if (Mips::AFGR64RegisterClass->contains(Reg)) {
221         const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
222         MachineLocation DstML0(MachineLocation::VirtualFP, Offset);
223         MachineLocation DstML1(MachineLocation::VirtualFP, Offset + 4);
224         MachineLocation SrcML0(*SubRegs);
225         MachineLocation SrcML1(*(SubRegs + 1));
226
227         if (!STI.isLittle())
228           std::swap(SrcML0, SrcML1);
229
230         Moves.push_back(MachineMove(CSLabel, DstML0, SrcML0));
231         Moves.push_back(MachineMove(CSLabel, DstML1, SrcML1));
232       }
233       else {
234         // Reg is either in CPURegs or FGR32.
235         DstML = MachineLocation(MachineLocation::VirtualFP, Offset);
236         SrcML = MachineLocation(Reg);
237         Moves.push_back(MachineMove(CSLabel, DstML, SrcML));
238       }
239     }
240   }    
241
242   // if framepointer enabled, set it to point to the stack pointer.
243   if (hasFP(MF)) {
244     // Insert instruction "move $fp, $sp" at this location.    
245     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP)
246       .addReg(Mips::SP).addReg(Mips::ZERO);
247
248     // emit ".cfi_def_cfa_register $fp" 
249     MCSymbol *SetFPLabel = MMI.getContext().CreateTempSymbol();
250     BuildMI(MBB, MBBI, dl,
251             TII.get(TargetOpcode::PROLOG_LABEL)).addSym(SetFPLabel);
252     DstML = MachineLocation(Mips::FP);
253     SrcML = MachineLocation(MachineLocation::VirtualFP);
254     Moves.push_back(MachineMove(SetFPLabel, DstML, SrcML));
255   }
256
257   // Restore GP from the saved stack location
258   if (MipsFI->needGPSaveRestore()) {
259     unsigned Offset = MFI->getObjectOffset(MipsFI->getGPFI());
260     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE)).addImm(Offset);
261
262     if (Offset >= 0x8000) {
263       BuildMI(MBB, llvm::prior(MBBI), dl, TII.get(Mips::MACRO));
264       BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
265     }
266   }
267 }
268
269 void MipsFrameLowering::emitEpilogue(MachineFunction &MF,
270                                  MachineBasicBlock &MBB) const {
271   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
272   MachineFrameInfo *MFI            = MF.getFrameInfo();
273   const MipsInstrInfo &TII =
274     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
275   DebugLoc dl = MBBI->getDebugLoc();
276
277   // Get the number of bytes from FrameInfo
278   unsigned StackSize = MFI->getStackSize();
279
280   unsigned NewReg = 0;
281   int NewImm = 0;
282   bool ATUsed = false;
283
284   // if framepointer enabled, restore the stack pointer.
285   if (hasFP(MF)) {
286     // Find the first instruction that restores a callee-saved register.
287     MachineBasicBlock::iterator I = MBBI;
288     
289     for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i)
290       --I;
291
292     // Insert instruction "move $sp, $fp" at this location.
293     BuildMI(MBB, I, dl, TII.get(Mips::ADDu), Mips::SP)
294       .addReg(Mips::FP).addReg(Mips::ZERO);
295   }
296
297   // adjust stack  : insert addi sp, sp, (imm)
298   if (StackSize) {
299     ATUsed = expandRegLargeImmPair(Mips::SP, StackSize, NewReg, NewImm, MBB,
300                                    MBBI);
301     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
302       .addReg(NewReg).addImm(NewImm);
303
304     // FIXME: change this when mips goes MC".
305     if (ATUsed)
306       BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
307   }
308 }
309
310 void MipsFrameLowering::
311 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
312                                      RegScavenger *RS) const {
313   MachineRegisterInfo& MRI = MF.getRegInfo();
314
315   // FIXME: remove this code if register allocator can correctly mark
316   //        $fp and $ra used or unused.
317
318   // Mark $fp and $ra as used or unused.
319   if (hasFP(MF))
320     MRI.setPhysRegUsed(Mips::FP);
321
322   // The register allocator might determine $ra is used after seeing 
323   // instruction "jr $ra", but we do not want PrologEpilogInserter to insert
324   // instructions to save/restore $ra unless there is a function call.
325   // To correct this, $ra is explicitly marked unused if there is no
326   // function call.
327   if (MF.getFrameInfo()->hasCalls())
328     MRI.setPhysRegUsed(Mips::RA);
329   else
330     MRI.setPhysRegUnused(Mips::RA);
331 }