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