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