c855a463219e5e723cdde334c7381be5a33d8be0
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9TargetMachine.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      Sparc.cpp
5 // 
6 // Purpose:
7 //      
8 // History:
9 //      7/15/01  -  Vikram Adve  -  Created
10 //**************************************************************************/
11
12
13 #include "SparcInternals.h"
14 #include "llvm/Target/Sparc.h"
15 #include "llvm/CodeGen/InstrScheduling.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineCodeForMethod.h"
19 #include "llvm/CodeGen/RegisterAllocation.h"
20 #include "llvm/Method.h"
21 #include "llvm/PassManager.h"
22 #include <iostream>
23 using std::cerr;
24
25 // Build the MachineInstruction Description Array...
26 const MachineInstrDescriptor SparcMachineInstrDesc[] = {
27 #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
28           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS)             \
29   { OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE,             \
30           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS },
31 #include "SparcInstr.def"
32 };
33
34 //----------------------------------------------------------------------------
35 // allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
36 // that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
37 //----------------------------------------------------------------------------
38 //
39
40 TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); }
41
42
43 //---------------------------------------------------------------------------
44 // class InsertPrologEpilogCode
45 //
46 // Insert SAVE/RESTORE instructions for the method
47 //
48 // Insert prolog code at the unique method entry point.
49 // Insert epilog code at each method exit point.
50 // InsertPrologEpilog invokes these only if the method is not compiled
51 // with the leaf method optimization.
52 //
53 //---------------------------------------------------------------------------
54 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
55
56 class InsertPrologEpilogCode : public MethodPass {
57   TargetMachine &Target;
58 public:
59   inline InsertPrologEpilogCode(TargetMachine &T) : Target(T) {}
60   bool runOnMethod(Method *M) {
61     MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(M);
62     if (!mcodeInfo.isCompiledAsLeafMethod()) {
63       InsertPrologCode(M);
64       InsertEpilogCode(M);
65     }
66     return false;
67   }
68
69   void InsertPrologCode(Method *M);
70   void InsertEpilogCode(Method *M);
71 };
72
73 void InsertPrologEpilogCode::InsertPrologCode(Method* method)
74 {
75   BasicBlock* entryBB = method->getEntryNode();
76   unsigned N = GetInstructionsForProlog(entryBB, Target, minstrVec);
77   assert(N <= MAX_INSTR_PER_VMINSTR);
78   MachineCodeForBasicBlock& bbMvec = entryBB->getMachineInstrVec();
79   bbMvec.insert(bbMvec.begin(), minstrVec, minstrVec+N);
80 }
81
82
83 void InsertPrologEpilogCode::InsertEpilogCode(Method* method)
84 {
85   for (Method::iterator I=method->begin(), E=method->end(); I != E; ++I)
86     if ((*I)->getTerminator()->getOpcode() == Instruction::Ret)
87       {
88         BasicBlock* exitBB = *I;
89         unsigned N = GetInstructionsForEpilog(exitBB, Target, minstrVec);
90         
91         MachineCodeForBasicBlock& bbMvec = exitBB->getMachineInstrVec();
92         MachineCodeForInstruction &termMvec =
93           MachineCodeForInstruction::get(exitBB->getTerminator());
94         
95         // Remove the NOPs in the delay slots of the return instruction
96         const MachineInstrInfo &mii = Target.getInstrInfo();
97         unsigned numNOPs = 0;
98         while (termMvec.back()->getOpCode() == NOP)
99           {
100             assert( termMvec.back() == bbMvec.back());
101             termMvec.pop_back();
102             bbMvec.pop_back();
103             ++numNOPs;
104           }
105         assert(termMvec.back() == bbMvec.back());
106         
107         // Check that we found the right number of NOPs and have the right
108         // number of instructions to replace them.
109         unsigned ndelays = mii.getNumDelaySlots(termMvec.back()->getOpCode());
110         assert(numNOPs == ndelays && "Missing NOPs in delay slots?");
111         assert(N == ndelays && "Cannot use epilog code for delay slots?");
112         
113         // Append the epilog code to the end of the basic block.
114         bbMvec.push_back(minstrVec[0]);
115       }
116 }
117
118
119 //---------------------------------------------------------------------------
120 // class UltraSparcFrameInfo 
121 // 
122 // Purpose:
123 //   Interface to stack frame layout info for the UltraSPARC.
124 //   Starting offsets for each area of the stack frame are aligned at
125 //   a multiple of getStackFrameSizeAlignment().
126 //---------------------------------------------------------------------------
127
128 int
129 UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& ,
130                                                 bool& pos) const
131 {
132   pos = false;                          // static stack area grows downwards
133   return StaticAreaOffsetFromFP;
134 }
135
136 int
137 UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo,
138                                            bool& pos) const
139 {
140   pos = false;                          // static stack area grows downwards
141   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
142   if (int mod = autoVarsSize % getStackFrameSizeAlignment())  
143     autoVarsSize += (getStackFrameSizeAlignment() - mod);
144   return StaticAreaOffsetFromFP - autoVarsSize; 
145 }
146
147 int
148 UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo,
149                                       bool& pos) const
150 {
151   pos = false;                          // static stack area grows downwards
152   unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
153   unsigned int spillAreaSize = mcInfo.getRegSpillsSize();
154   int offset = autoVarsSize + spillAreaSize;
155   if (int mod = offset % getStackFrameSizeAlignment())  
156     offset += (getStackFrameSizeAlignment() - mod);
157   return StaticAreaOffsetFromFP - offset;
158 }
159
160 int
161 UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo,
162                                           bool& pos) const
163 {
164   // dynamic stack area grows downwards starting at top of opt-args area
165   unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize();
166   int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
167   assert(offset % getStackFrameSizeAlignment() == 0);
168   return offset;
169 }
170
171
172 //---------------------------------------------------------------------------
173 // class UltraSparcMachine 
174 // 
175 // Purpose:
176 //   Primary interface to machine description for the UltraSPARC.
177 //   Primarily just initializes machine-dependent parameters in
178 //   class TargetMachine, and creates machine-dependent subclasses
179 //   for classes such as MachineInstrInfo. 
180 // 
181 //---------------------------------------------------------------------------
182
183 UltraSparc::UltraSparc()
184   : TargetMachine("UltraSparc-Native"),
185     instrInfo(*this),
186     schedInfo(*this),
187     regInfo(*this),
188     frameInfo(*this),
189     cacheInfo(*this)
190 {
191   optSizeForSubWordData = 4;
192   minMemOpWordSize = 8; 
193   maxAtomicMemOpWordSize = 8;
194 }
195
196
197
198 //===---------------------------------------------------------------------===//
199 // GenerateCodeForTarget Pass
200 // 
201 // Native code generation for a specified target.
202 //===---------------------------------------------------------------------===//
203
204 class ConstructMachineCodeForMethod : public MethodPass {
205   TargetMachine &Target;
206 public:
207   inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
208   bool runOnMethod(Method *M) {
209     MachineCodeForMethod::construct(M, Target);
210     return false;
211   }
212 };
213
214 class InstructionSelection : public MethodPass {
215   TargetMachine &Target;
216 public:
217   inline InstructionSelection(TargetMachine &T) : Target(T) {}
218   bool runOnMethod(Method *M) {
219     if (SelectInstructionsForMethod(M, Target))
220       cerr << "Instr selection failed for method " << M->getName() << "\n";
221     return false;
222   }
223 };
224
225 class InstructionScheduling : public MethodPass {
226   TargetMachine &Target;
227 public:
228   inline InstructionScheduling(TargetMachine &T) : Target(T) {}
229   bool runOnMethod(Method *M) {
230     if (ScheduleInstructionsWithSSA(M, Target))
231       cerr << "Instr scheduling failed for method " << M->getName() << "\n\n";
232     return false;
233   }
234 };
235
236 struct FreeMachineCodeForMethod : public MethodPass {
237   static void freeMachineCode(Instruction *I) {
238     MachineCodeForInstruction::destroy(I);
239   }
240
241   bool runOnMethod(Method *M) {
242     for_each(M->inst_begin(), M->inst_end(), freeMachineCode);
243     // Don't destruct MachineCodeForMethod - The global printer needs it
244     //MachineCodeForMethod::destruct(M);
245     return false;
246   }
247 };
248
249
250
251 // addPassesToEmitAssembly - This method controls the entire code generation
252 // process for the ultra sparc.
253 //
254 void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
255   // Construct and initialize the MachineCodeForMethod object for this method.
256   PM.add(new ConstructMachineCodeForMethod(*this));
257
258   PM.add(new InstructionSelection(*this));
259
260   //PM.add(new InstructionScheduling(*this));
261
262   PM.add(new RegisterAllocation(*this));
263   
264   //PM.add(new OptimizeLeafProcedures());
265   //PM.add(new DeleteFallThroughBranches());
266   //PM.add(new RemoveChainedBranches());    // should be folded with previous
267   //PM.add(new RemoveRedundantOps());       // operations with %g0, NOP, etc.
268   
269   PM.add(new InsertPrologEpilogCode(*this));
270   
271   // Output assembly language to the .s file.  Assembly emission is split into
272   // two parts: Method output and Global value output.  This is because method
273   // output is pipelined with all of the rest of code generation stuff,
274   // allowing machine code representations for methods to be free'd after the
275   // method has been emitted.
276   //
277   PM.add(getMethodAsmPrinterPass(PM, Out));
278   PM.add(new FreeMachineCodeForMethod());  // Free stuff no longer needed
279
280   // Emit Module level assembly after all of the methods have been processed.
281   PM.add(getModuleAsmPrinterPass(PM, Out));
282 }