Fixed stack frame addressing bug
[oota-llvm.git] / lib / Target / Mips / MipsRegisterInfo.cpp
1 //===- MipsRegisterInfo.cpp - MIPS Register Information -== -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Bruno Cardoso Lopes and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the MIPS implementation of the MRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "mips-reg-info"
15
16 #include "Mips.h"
17 #include "MipsRegisterInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Type.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/ValueTypes.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 //#include "MipsSubtarget.h"
36
37 using namespace llvm;
38
39 // TODO: add subtarget support
40 MipsRegisterInfo::MipsRegisterInfo(const TargetInstrInfo &tii)
41   : MipsGenRegisterInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
42   TII(tii) {}
43
44 void MipsRegisterInfo::
45 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
46           unsigned SrcReg, int FI, 
47           const TargetRegisterClass *RC) const 
48 {
49   if (RC == Mips::CPURegsRegisterClass)
50     BuildMI(MBB, I, TII.get(Mips::SW)).addReg(SrcReg, false, false, true)
51           .addImm(0).addFrameIndex(FI);
52   else
53     assert(0 && "Can't store this register to stack slot");
54 }
55
56 void MipsRegisterInfo::
57 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
58                      unsigned DestReg, int FI,
59                      const TargetRegisterClass *RC) const 
60 {
61   if (RC == Mips::CPURegsRegisterClass)
62     BuildMI(MBB, I, TII.get(Mips::LW), DestReg).addImm(0).addFrameIndex(FI);
63   else
64     assert(0 && "Can't load this register from stack slot");
65 }
66
67 void MipsRegisterInfo::
68 copyRegToReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
69              unsigned DestReg, unsigned SrcReg,
70              const TargetRegisterClass *RC) const 
71 {
72   if (RC == Mips::CPURegsRegisterClass)
73     BuildMI(MBB, I, TII.get(Mips::ADDu), DestReg).addReg(Mips::ZERO)
74       .addReg(SrcReg);
75   else
76     assert (0 && "Can't copy this register");
77 }
78
79 void MipsRegisterInfo::reMaterialize(MachineBasicBlock &MBB, 
80                                       MachineBasicBlock::iterator I,
81                                       unsigned DestReg, 
82                                       const MachineInstr *Orig) const 
83 {
84     MachineInstr *MI = Orig->clone();
85     MI->getOperand(0).setReg(DestReg);
86     MBB.insert(I, MI);
87 }
88
89 MachineInstr *MipsRegisterInfo::
90 foldMemoryOperand(MachineInstr* MI, unsigned OpNum, int FI) const 
91 {
92   MachineInstr *NewMI = NULL;
93
94   switch (MI->getOpcode()) 
95   {
96     case Mips::ADDu:
97       if ((MI->getOperand(0).isRegister()) &&
98         (MI->getOperand(1).isRegister()) && 
99         (MI->getOperand(1).getReg() == Mips::ZERO) &&
100         (MI->getOperand(2).isRegister())) 
101       {
102         if (OpNum == 0)    // COPY -> STORE
103           NewMI = BuildMI(TII.get(Mips::SW)).addFrameIndex(FI)
104                   .addImm(0).addReg(MI->getOperand(2).getReg());
105         else               // COPY -> LOAD
106           NewMI = BuildMI(TII.get(Mips::LW), MI->getOperand(0)
107                   .getReg()).addImm(0).addFrameIndex(FI);
108       }
109       break;
110   }
111
112   if (NewMI)
113     NewMI->copyKillDeadInfo(MI);
114   return NewMI;
115 }
116
117 /// Mips Callee Saved Registers
118 const unsigned* MipsRegisterInfo::
119 getCalleeSavedRegs(const MachineFunction *MF) const 
120 {
121   // Mips calle-save register range is $16-$26(s0-s7)
122   static const unsigned CalleeSavedRegs[] = {  
123     Mips::S0, Mips::S1, Mips::S2, Mips::S3, 
124     Mips::S4, Mips::S5, Mips::S6, Mips::S7, 0
125   };
126   return CalleeSavedRegs;
127 }
128
129 /// Mips Callee Saved Register Classes
130 const TargetRegisterClass* const* 
131 MipsRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const 
132 {
133   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
134     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
135     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
136     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass,
137     &Mips::CPURegsRegClass, &Mips::CPURegsRegClass, 0 
138   };
139   return CalleeSavedRegClasses;
140 }
141
142 BitVector MipsRegisterInfo::
143 getReservedRegs(const MachineFunction &MF) const
144 {
145   BitVector Reserved(getNumRegs());
146   Reserved.set(Mips::ZERO);
147   Reserved.set(Mips::AT);
148   Reserved.set(Mips::K0);
149   Reserved.set(Mips::K1);
150   Reserved.set(Mips::GP);
151   Reserved.set(Mips::SP);
152   Reserved.set(Mips::FP);
153   Reserved.set(Mips::RA);
154   return Reserved;
155 }
156
157 //===----------------------------------------------------------------------===//
158 //
159 // Stack Frame Processing methods
160 // +----------------------------+
161 //
162 // Too meet ABI, we construct the frame on the reverse
163 // of natural order.
164 //
165 // The LLVM Frame will look like this:
166 //
167 // As the stack grows down, we start at 0, and the reference
168 // is decrement.
169 //
170 //  0          ----------
171 // -4          Args to pass
172 //  .          saved "Callee Saved" Registers
173 //  .          Local Area
174 //  .          saved FP
175 //  .          saved RA
176 // -StackSize  -----------
177 //
178 // On the EliminateFrameIndex we just negate the address above
179 // and we get the stack frame required by the ABI, which is:
180 //
181 // sp + stacksize  -------------
182 //                 saved $RA  (only on non-leaf functions)
183 //                 saved $FP  (only with frame pointer)
184 //                 saved "Callee Saved" Registers
185 //                 Local Area
186 //                 saved $GP  (used in PIC - not supported yet)
187 //                 Args to pass area
188 // sp              -------------
189 //
190 // The sp is the stack pointer subtracted/added from the stack size
191 // at the Prologue/Epilogue
192 //
193 // References to the previous stack (to obtain arguments) are done
194 // with fixed location stack frames using positive stack offsets.
195 //
196 // Examples:
197 // - reference to the actual stack frame
198 //   for any local area var there is smt like : FI >= 0, StackOffset: -4
199 //     sw REGX, 4(REGY)
200 //
201 // - reference to previous stack frame
202 //   suppose there's a store to the 5th arguments : FI < 0, StackOffset: 16.
203 //   The emitted instruction will be something like:
204 //     sw REGX, 16+StackSize (REGY)
205 //
206 //===----------------------------------------------------------------------===//
207
208 // hasFP - Return true if the specified function should have a dedicated frame
209 // pointer register.  This is true if the function has variable sized allocas or
210 // if frame pointer elimination is disabled.
211 bool MipsRegisterInfo::
212 hasFP(const MachineFunction &MF) const {
213   return (NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects());
214 }
215
216 // This function eliminate ADJCALLSTACKDOWN, 
217 // ADJCALLSTACKUP pseudo instructions
218 void MipsRegisterInfo::
219 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
220                               MachineBasicBlock::iterator I) const {
221   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
222   MBB.erase(I);
223 }
224
225 // FrameIndex represent objects inside a abstract stack.
226 // We must replace FrameIndex with an stack/frame pointer
227 // direct reference.
228 void MipsRegisterInfo::
229 eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, 
230                     RegScavenger *RS) const 
231 {
232   MachineInstr &MI    = *II;
233   MachineFunction &MF = *MI.getParent()->getParent();
234
235   unsigned i = 0;
236   while (!MI.getOperand(i).isFrameIndex()) {
237     ++i;
238     assert(i < MI.getNumOperands() && 
239            "Instr doesn't have FrameIndex operand!");
240   }
241
242   int FrameIndex = MI.getOperand(i).getFrameIndex();
243   int stackSize  = MF.getFrameInfo()->getStackSize();
244   int spOffset   = MF.getFrameInfo()->getObjectOffset(FrameIndex);
245
246   #ifndef NDEBUG
247   DOUT << "\nFunction : " << MF.getFunction()->getName() << "\n";
248   DOUT << "<--------->\n";
249   MI.print(DOUT);
250   DOUT << "FrameIndex : " << FrameIndex << "\n";
251   DOUT << "spOffset   : " << spOffset << "\n";
252   DOUT << "stackSize  : " << stackSize << "\n";
253   #endif
254
255   int Offset = ( (spOffset >= 0) ? (stackSize + spOffset) : (-spOffset));
256
257   #ifndef NDEBUG
258   DOUT << "Offset     : " << Offset << "\n";
259   DOUT << "<--------->\n";
260   #endif
261
262   MI.getOperand(i-1).ChangeToImmediate(Offset);
263   MI.getOperand(i).ChangeToRegister(getFrameRegister(MF),false);
264 }
265
266 void MipsRegisterInfo::
267 emitPrologue(MachineFunction &MF) const 
268 {
269   MachineBasicBlock &MBB   = MF.front();
270   MachineFrameInfo *MFI    = MF.getFrameInfo();
271   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
272   MachineBasicBlock::iterator MBBI = MBB.begin();
273
274   // Get the number of bytes to allocate from the FrameInfo.
275   int NumBytes = (int) MFI->getStackSize();
276
277   #ifndef NDEBUG
278   DOUT << "\n<--- EMIT PROLOGUE --->\n";
279   DOUT << "Stack size :" << NumBytes << "\n";
280   #endif
281
282   // Don't need to allocate space on the stack.
283   if (NumBytes == 0) return;
284
285   int FPOffset, RAOffset;
286   
287   // Always allocate space for saved RA and FP,
288   // even if FramePointer is not used. When not
289   // using FP, the last stack slot becomes empty
290   // and RA is saved before it.
291   if ((hasFP(MF)) && (MFI->hasCalls())) {
292     FPOffset = NumBytes+4;
293     RAOffset = (NumBytes+8);
294   } else if ((!hasFP(MF)) && (MFI->hasCalls())) {
295     FPOffset = 0;
296     RAOffset = NumBytes+4;
297   } else if ((hasFP(MF)) && (!MFI->hasCalls())) {
298     FPOffset = NumBytes+4;
299     RAOffset = 0;
300   }
301
302   MFI->setObjectOffset(MFI->CreateStackObject(4,4), -FPOffset);
303   MFI->setObjectOffset(MFI->CreateStackObject(4,4), -RAOffset);
304   MipsFI->setFPStackOffset(FPOffset);
305   MipsFI->setRAStackOffset(RAOffset);
306
307   #ifndef NDEBUG
308   DOUT << "FPOffset :" << FPOffset << "\n";
309   DOUT << "RAOffset :" << RAOffset << "\n";
310   #endif
311
312   // Align stack. 
313   NumBytes += 12;
314   unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
315   NumBytes = ((NumBytes+Align-1)/Align*Align);
316
317   #ifndef NDEBUG
318   DOUT << "New stack size :" << NumBytes << "\n\n";
319   #endif
320
321   // Update frame info
322   MFI->setStackSize(NumBytes);
323
324   // Adjust stack : addi sp, sp, (-imm)
325   BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP)
326       .addReg(Mips::SP).addImm(-NumBytes);
327
328   // Save the return address only if the function isnt a leaf one.
329   // sw  $ra, stack_loc($sp)
330   if (MFI->hasCalls()) { 
331     BuildMI(MBB, MBBI, TII.get(Mips::SW))
332         .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP);
333   }
334
335   // if framepointer enabled, save it and set it
336   // to point to the stack pointer
337   if (hasFP(MF)) {
338     // sw  $fp,stack_loc($sp)
339     BuildMI(MBB, MBBI, TII.get(Mips::SW))
340       .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP);
341
342     // move $fp, $sp
343     BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::FP)
344       .addReg(Mips::SP).addReg(Mips::ZERO);
345   }
346 }
347
348 void MipsRegisterInfo::
349 emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const 
350 {
351   MachineBasicBlock::iterator MBBI = prior(MBB.end());
352   MachineFrameInfo *MFI            = MF.getFrameInfo();
353   MipsFunctionInfo *MipsFI         = MF.getInfo<MipsFunctionInfo>();
354
355   // Get the number of bytes from FrameInfo
356   int NumBytes = (int) MFI->getStackSize();
357
358   // Get the FI's where RA and FP are saved.
359   int FPOffset = MipsFI->getFPStackOffset();
360   int RAOffset = MipsFI->getRAStackOffset();
361
362   #ifndef NDEBUG
363   DOUT << "\n<--- EMIT EPILOGUE --->" << "\n";
364   DOUT << "Stack size :" << NumBytes << "\n";
365   DOUT << "FPOffset :" << FPOffset << "\n";
366   DOUT << "RAOffset :" << RAOffset << "\n\n";
367   #endif
368
369   // if framepointer enabled, restore it and restore the
370   // stack pointer
371   if (hasFP(MF)) {
372     // move $sp, $fp
373     BuildMI(MBB, MBBI, TII.get(Mips::ADDu), Mips::SP)
374       .addReg(Mips::FP).addReg(Mips::ZERO);
375
376     // lw  $fp,stack_loc($sp)
377     BuildMI(MBB, MBBI, TII.get(Mips::LW))
378       .addReg(Mips::FP).addImm(FPOffset).addReg(Mips::SP);
379   }
380
381   // Restore the return address only if the function isnt a leaf one.
382   // lw  $ra, stack_loc($sp)
383   if (MFI->hasCalls()) { 
384     BuildMI(MBB, MBBI, TII.get(Mips::LW))
385         .addReg(Mips::RA).addImm(RAOffset).addReg(Mips::SP);
386   }
387
388   // adjust stack  : insert addi sp, sp, (imm)
389   if (NumBytes) {
390     BuildMI(MBB, MBBI, TII.get(Mips::ADDiu), Mips::SP)
391       .addReg(Mips::SP).addImm(NumBytes);
392   }
393 }
394
395 void MipsRegisterInfo::
396 processFunctionBeforeFrameFinalized(MachineFunction &MF) const {
397 }
398
399 unsigned MipsRegisterInfo::
400 getRARegister() const {
401   return Mips::RA;
402 }
403
404 unsigned MipsRegisterInfo::
405 getFrameRegister(MachineFunction &MF) const {
406   return hasFP(MF) ? Mips::FP : Mips::SP;
407 }
408
409 unsigned MipsRegisterInfo::
410 getEHExceptionRegister() const {
411   assert(0 && "What is the exception register");
412   return 0;
413 }
414
415 unsigned MipsRegisterInfo::
416 getEHHandlerRegister() const {
417   assert(0 && "What is the exception handler register");
418   return 0;
419 }
420
421 #include "MipsGenRegisterInfo.inc"
422