Add support for C++ exception handling.
[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 }
89
90 bool MipsFrameLowering::targetHandlesStackFrameRounding() const {
91   return true;
92 }
93
94 static unsigned AlignOffset(unsigned Offset, unsigned Align) {
95   return (Offset + Align - 1) / Align * Align; 
96
97
98 // expand pair of register and immediate if the immediate doesn't fit in the
99 // 16-bit offset field.
100 // e.g.
101 //  if OrigImm = 0x10000, OrigReg = $sp:
102 //    generate the following sequence of instrs:
103 //      lui  $at, hi(0x10000)
104 //      addu $at, $sp, $at
105 //
106 //    (NewReg, NewImm) = ($at, lo(Ox10000))
107 //    return true
108 static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm,
109                                   unsigned& NewReg, int& NewImm,
110                                   MachineBasicBlock& MBB,
111                                   MachineBasicBlock::iterator I) {
112   // OrigImm fits in the 16-bit field
113   if (OrigImm < 0x8000 && OrigImm >= -0x8000) {
114     NewReg = OrigReg;
115     NewImm = OrigImm;
116     return false;
117   }
118
119   MachineFunction* MF = MBB.getParent();
120   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
121   DebugLoc DL = I->getDebugLoc();
122   int ImmLo = (short)(OrigImm & 0xffff);
123   int ImmHi = (((unsigned)OrigImm & 0xffff0000) >> 16) +
124               ((OrigImm & 0x8000) != 0);
125
126   // FIXME: change this when mips goes MC".
127   BuildMI(MBB, I, DL, TII->get(Mips::NOAT));
128   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi);
129   BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg)
130                                                      .addReg(Mips::AT);
131   NewReg = Mips::AT;
132   NewImm = ImmLo;
133
134   return true;
135 }
136
137 void MipsFrameLowering::emitPrologue(MachineFunction &MF) const {
138   MachineBasicBlock &MBB   = MF.front();
139   MachineFrameInfo *MFI    = MF.getFrameInfo();
140   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
141   const MipsRegisterInfo *RegInfo =
142     static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo());
143   const MipsInstrInfo &TII =
144     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
145   MachineBasicBlock::iterator MBBI = MBB.begin();
146   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
147   bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_);
148   unsigned NewReg = 0;
149   int NewImm = 0;
150   bool ATUsed;
151
152   // First, compute final stack size.
153   unsigned RegSize = STI.isGP32bit() ? 4 : 8;
154   unsigned StackAlign = getStackAlignment();
155   unsigned LocalVarAreaOffset = MipsFI->needGPSaveRestore() ? 
156     (MFI->getObjectOffset(MipsFI->getGPFI()) + RegSize) :
157     MipsFI->getMaxCallFrameSize();
158   unsigned StackSize = AlignOffset(LocalVarAreaOffset, StackAlign) +
159     AlignOffset(MFI->getStackSize(), StackAlign);
160
161    // Update stack size
162   MFI->setStackSize(StackSize); 
163   
164   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER));
165
166   // TODO: check need from GP here.
167   if (isPIC && STI.isABI_O32())
168     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD))
169       .addReg(RegInfo->getPICCallReg());
170   BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
171
172   // No need to allocate space on the stack.
173   if (StackSize == 0 && !MFI->adjustsStack()) return;
174
175   // Adjust stack : addi sp, sp, (-imm)
176   ATUsed = expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, MBB,
177                                  MBBI);
178   BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
179     .addReg(NewReg).addImm(NewImm);
180
181   // FIXME: change this when mips goes MC".
182   if (ATUsed)
183     BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
184
185   // Find the instruction past the last instruction that saves a callee-saved
186   // register to the stack.
187   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
188   
189   for (unsigned i = 0; i < CSI.size(); ++i)
190     ++MBBI;
191  
192   // if framepointer enabled, set it to point to the stack pointer.
193   if (hasFP(MF))
194     // Insert instruction "move $fp, $sp" at this location.    
195     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP)
196       .addReg(Mips::SP).addReg(Mips::ZERO);
197
198   // Restore GP from the saved stack location
199   if (MipsFI->needGPSaveRestore())
200     BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE))
201       .addImm(MFI->getObjectOffset(MipsFI->getGPFI()));
202
203   // EH Frame infomation.
204   MachineModuleInfo &MMI = MF.getMMI();
205   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
206   MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
207   BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL)).addSym(FrameLabel);
208
209   if (hasFP(MF)) {
210     MachineLocation SPDst(Mips::FP);
211     MachineLocation SPSrc(Mips::SP);
212     Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc)); 
213   }
214     
215   if (StackSize) {
216     MachineLocation SPDst(MachineLocation::VirtualFP);
217     MachineLocation SPSrc(MachineLocation::VirtualFP, -StackSize);
218     Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc)); 
219   }
220
221   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
222        E = CSI.end(); I != E; ++I) {
223     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
224     MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
225     MachineLocation CSSrc(I->getReg());
226     Moves.push_back(MachineMove(FrameLabel, CSDst, CSSrc));
227   }        
228 }
229
230 void MipsFrameLowering::emitEpilogue(MachineFunction &MF,
231                                  MachineBasicBlock &MBB) const {
232   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
233   MachineFrameInfo *MFI            = MF.getFrameInfo();
234   const MipsInstrInfo &TII =
235     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
236   DebugLoc dl = MBBI->getDebugLoc();
237
238   // Get the number of bytes from FrameInfo
239   unsigned StackSize = MFI->getStackSize();
240
241   unsigned NewReg = 0;
242   int NewImm = 0;
243   bool ATUsed = false;
244
245   // if framepointer enabled, restore the stack pointer.
246   if (hasFP(MF)) {
247     // Find the first instruction that restores a callee-saved register.
248     MachineBasicBlock::iterator I = MBBI;
249     
250     for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i)
251       --I;
252
253     // Insert instruction "move $sp, $fp" at this location.
254     BuildMI(MBB, I, dl, TII.get(Mips::ADDu), Mips::SP)
255       .addReg(Mips::FP).addReg(Mips::ZERO);
256   }
257
258   // adjust stack  : insert addi sp, sp, (imm)
259   if (StackSize) {
260     ATUsed = expandRegLargeImmPair(Mips::SP, StackSize, NewReg, NewImm, MBB,
261                                    MBBI);
262     BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
263       .addReg(NewReg).addImm(NewImm);
264
265     // FIXME: change this when mips goes MC".
266     if (ATUsed)
267       BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
268   }
269 }
270
271 void
272 MipsFrameLowering::getInitialFrameState(std::vector<MachineMove> &Moves) const {
273   MachineLocation Dst(MachineLocation::VirtualFP);
274   MachineLocation Src(Mips::SP, 0);
275   Moves.push_back(MachineMove(0, Dst, Src));
276 }
277
278 void MipsFrameLowering::
279 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
280                                      RegScavenger *RS) const {
281   MachineRegisterInfo& MRI = MF.getRegInfo();
282   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
283
284   // FIXME: remove this code if register allocator can correctly mark
285   //        $fp and $ra used or unused.
286
287   // Mark $fp and $ra as used or unused.
288   if (hasFP(MF))
289     MRI.setPhysRegUsed(Mips::FP);
290
291   // The register allocator might determine $ra is used after seeing 
292   // instruction "jr $ra", but we do not want PrologEpilogInserter to insert
293   // instructions to save/restore $ra unless there is a function call.
294   // To correct this, $ra is explicitly marked unused if there is no
295   // function call.
296   if (MipsFI->hasCall())
297     MRI.setPhysRegUsed(Mips::RA);
298   else
299     MRI.setPhysRegUnused(Mips::RA);
300 }