* Must save FP registers when calling CompilationCallback(), because FP
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9CodeEmitter.cpp
1 //===-- SparcV9CodeEmitter.cpp --------------------------------------------===//
2 //
3 // FIXME: document
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Constants.h"
8 #include "llvm/Function.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/CodeGen/MachineCodeEmitter.h"
12 #include "llvm/CodeGen/MachineConstantPool.h"
13 #include "llvm/CodeGen/MachineFunctionInfo.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/TargetData.h"
18 #include "Support/Debug.h"
19 #include "Support/hash_set"
20 #include "SparcInternals.h"
21 #include "SparcV9CodeEmitter.h"
22
23 bool UltraSparc::addPassesToEmitMachineCode(FunctionPassManager &PM,
24                                             MachineCodeEmitter &MCE) {
25   MachineCodeEmitter *M = &MCE;
26   DEBUG(M = MachineCodeEmitter::createFilePrinterEmitter(MCE));
27   PM.add(new SparcV9CodeEmitter(*this, *M));
28   PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
29   return false;
30 }
31
32 namespace {
33   class JITResolver {
34     SparcV9CodeEmitter &SparcV9;
35     MachineCodeEmitter &MCE;
36
37     /// LazyCodeGenMap - Keep track of call sites for functions that are to be
38     /// lazily resolved.
39     ///
40     std::map<uint64_t, Function*> LazyCodeGenMap;
41
42     /// LazyResolverMap - Keep track of the lazy resolver created for a
43     /// particular function so that we can reuse them if necessary.
44     ///
45     std::map<Function*, uint64_t> LazyResolverMap;
46
47   public:
48     enum CallType { ShortCall, FarCall };
49
50   private:
51     /// We need to keep track of whether we used a simple call or a far call
52     /// (many instructions) in sequence. This means we need to keep track of
53     /// what type of stub we generate.
54     static std::map<uint64_t, CallType> LazyCallFlavor;
55
56   public:
57     JITResolver(SparcV9CodeEmitter &V9,
58                 MachineCodeEmitter &mce) : SparcV9(V9), MCE(mce) {}
59     uint64_t getLazyResolver(Function *F);
60     uint64_t addFunctionReference(uint64_t Address, Function *F);
61     void deleteFunctionReference(uint64_t Address);
62     void addCallFlavor(uint64_t Address, CallType Flavor) {
63       LazyCallFlavor[Address] = Flavor;
64     }
65
66     // Utility functions for accessing data from static callback
67     uint64_t getCurrentPCValue() {
68       return MCE.getCurrentPCValue();
69     }
70     unsigned getBinaryCodeForInstr(MachineInstr &MI) {
71       return SparcV9.getBinaryCodeForInstr(MI);
72     }
73
74     inline uint64_t insertFarJumpAtAddr(int64_t Value, uint64_t Addr);
75
76   private:
77     uint64_t emitStubForFunction(Function *F);
78     static void SaveRestoreRegisters();
79     static uint64_t CompilationCallback();
80     uint64_t resolveFunctionReference(uint64_t RetAddr);
81
82   };
83
84   JITResolver *TheJITResolver;
85   std::map<uint64_t, JITResolver::CallType> JITResolver::LazyCallFlavor;
86 }
87
88 /// addFunctionReference - This method is called when we need to emit the
89 /// address of a function that has not yet been emitted, so we don't know the
90 /// address.  Instead, we emit a call to the CompilationCallback method, and
91 /// keep track of where we are.
92 ///
93 uint64_t JITResolver::addFunctionReference(uint64_t Address, Function *F) {
94   LazyCodeGenMap[Address] = F;
95   return (intptr_t)&JITResolver::SaveRestoreRegisters;
96 }
97
98 /// deleteFunctionReference - If we are emitting a far call, we already added a
99 /// reference to the function, but it is now incorrect, since the address to the
100 /// JIT resolver is too far away to be a simple call instruction. This is used
101 /// to remove the address from the map.
102 ///
103 void JITResolver::deleteFunctionReference(uint64_t Address) {
104   std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(Address);
105   assert(I != LazyCodeGenMap.end() && "Not in map!");
106   LazyCodeGenMap.erase(I);  
107 }
108
109 uint64_t JITResolver::resolveFunctionReference(uint64_t RetAddr) {
110   std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
111   assert(I != LazyCodeGenMap.end() && "Not in map!");
112   Function *F = I->second;
113   LazyCodeGenMap.erase(I);
114   return MCE.forceCompilationOf(F);
115 }
116
117 uint64_t JITResolver::getLazyResolver(Function *F) {
118   std::map<Function*, uint64_t>::iterator I = LazyResolverMap.lower_bound(F);
119   if (I != LazyResolverMap.end() && I->first == F) return I->second;
120   
121 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
122
123   uint64_t Stub = emitStubForFunction(F);
124   LazyResolverMap.insert(I, std::make_pair(F, Stub));
125   return Stub;
126 }
127
128 uint64_t JITResolver::insertFarJumpAtAddr(int64_t Target, uint64_t Addr) {
129
130   static const unsigned 
131     o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0,
132     g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
133
134   MachineInstr* BinaryCode[] = {
135     //
136     // Get address to branch into %g1, using %g5 as a temporary
137     //
138     // sethi %uhi(Target), %g5     ;; get upper 22 bits of Target into %g5
139     BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
140     // or %g5, %ulo(Target), %g5   ;; get 10 lower bits of upper word into %g5
141     BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
142     // sllx %g5, 32, %g5           ;; shift those 10 bits to the upper word
143     BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
144     // sethi %hi(Target), %g1      ;; extract bits 10-31 into the dest reg
145     BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
146     // or %g5, %g1, %g1            ;; get upper word (in %g5) into %g1
147     BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
148     // or %g1, %lo(Target), %g1    ;; get lowest 10 bits of Target into %g1
149     BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
150     // jmpl %g1, %g0, %g0          ;; indirect branch on %g1
151     BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(g0),
152     // nop                         ;; delay slot
153     BuildMI(V9::NOP, 0)
154   };
155
156   for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
157     *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*BinaryCode[i]);
158     delete BinaryCode[i];
159     Addr += 4;
160   }
161
162   return Addr;
163 }
164
165 void JITResolver::SaveRestoreRegisters() {
166   uint32_t SingleFP[32];
167   uint64_t DoubleFP[16];
168   // FIXME: uint128_t QuadFloatRegs[..];
169   uint64_t CCR, FSR, FPRS, g1, g5;
170
171 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
172   __asm__ __volatile__ (// Save g1 and g5
173                         "stx %%g1, %0;\n\t" "stx %%g5, %1;\n\t"
174                         : "=m"(g1), "=m"(g5));
175
176   __asm__ __volatile__ (// Save condition-code registers
177                         "stx %%fsr, %0;\n\t" 
178                         "rd %%fprs, %1;\n\t" 
179                         "rd %%ccr,  %2;\n\t"
180                         : "=m"(FSR), "=r"(FPRS), "=r"(CCR));
181
182   // GCC says: `asm' only allows up to thirty parameters!
183   __asm__ __volatile__ (// Save Single FP registers, part 1
184                         "st  %%f0,  %0;\n\t"  "st  %%f1,  %1;\n\t"
185                         "st  %%f2,  %2;\n\t"  "st  %%f3,  %3;\n\t"
186                         "st  %%f4,  %4;\n\t"  "st  %%f5,  %5;\n\t"
187                         "st  %%f6,  %6;\n\t"  "st  %%f7,  %7;\n\t"
188                         "st  %%f8,  %8;\n\t"  "st  %%f9,  %9;\n\t"
189                         "st  %%f10, %10;\n\t" "st  %%f11, %11;\n\t"
190                         "st  %%f12, %12;\n\t" "st  %%f13, %13;\n\t"
191                         "st  %%f14, %14;\n\t" "st  %%f15, %15;\n\t"
192                         : "=m"(SingleFP[ 0]), "=m"(SingleFP[ 1]),
193                           "=m"(SingleFP[ 2]), "=m"(SingleFP[ 3]),
194                           "=m"(SingleFP[ 4]), "=m"(SingleFP[ 5]),
195                           "=m"(SingleFP[ 6]), "=m"(SingleFP[ 7]),
196                           "=m"(SingleFP[ 8]), "=m"(SingleFP[ 9]),
197                           "=m"(SingleFP[10]), "=m"(SingleFP[11]),
198                           "=m"(SingleFP[12]), "=m"(SingleFP[13]),
199                           "=m"(SingleFP[14]), "=m"(SingleFP[15]));
200                         
201   __asm__ __volatile__ (// Save Single FP registers, part 2
202                         "st  %%f16, %0;\n\t"  "st  %%f17, %1;\n\t"
203                         "st  %%f18, %2;\n\t"  "st  %%f19, %3;\n\t"
204                         "st  %%f20, %4;\n\t"  "st  %%f21, %5;\n\t"
205                         "st  %%f22, %6;\n\t"  "st  %%f23, %7;\n\t"
206                         "st  %%f24, %8;\n\t"  "st  %%f25, %9;\n\t"
207                         "st  %%f26, %10;\n\t" "st  %%f27, %11;\n\t"
208                         "st  %%f28, %12;\n\t" "st  %%f29, %13;\n\t"
209                         "st  %%f30, %14;\n\t" "st  %%f31, %15;\n\t"
210                         : "=m"(SingleFP[16]), "=m"(SingleFP[17]),
211                           "=m"(SingleFP[18]), "=m"(SingleFP[19]),
212                           "=m"(SingleFP[20]), "=m"(SingleFP[21]),
213                           "=m"(SingleFP[22]), "=m"(SingleFP[23]),
214                           "=m"(SingleFP[24]), "=m"(SingleFP[25]),
215                           "=m"(SingleFP[26]), "=m"(SingleFP[27]),
216                           "=m"(SingleFP[28]), "=m"(SingleFP[29]),
217                           "=m"(SingleFP[30]), "=m"(SingleFP[31]));
218
219   __asm__ __volatile__ (// Save Double FP registers
220                         "std %%f32, %0;\n\t"  "std %%f34, %1;\n\t"
221                         "std %%f32, %0;\n\t"  "std %%f34, %1;\n\t"
222                         "std %%f40, %4;\n\t"  "std %%f42, %5;\n\t"
223                         "std %%f44, %6;\n\t"  "std %%f46, %7;\n\t"
224                         "std %%f48, %8;\n\t"  "std %%f50, %9;\n\t"
225                         "std %%f52, %10;\n\t" "std %%f54, %11;\n\t"
226                         "std %%f56, %12;\n\t" "std %%f58, %13;\n\t"
227                         "std %%f60, %14;\n\t" "std %%f62, %15;\n\t"
228                         : "=m"(DoubleFP[32/2-16]), "=m"(DoubleFP[34/2-16]),
229                           "=m"(DoubleFP[36/2-16]), "=m"(DoubleFP[38/2-16]),
230                           "=m"(DoubleFP[40/2-16]), "=m"(DoubleFP[42/2-16]),
231                           "=m"(DoubleFP[44/2-16]), "=m"(DoubleFP[46/2-16]),
232                           "=m"(DoubleFP[48/2-16]), "=m"(DoubleFP[50/2-16]),
233                           "=m"(DoubleFP[52/2-16]), "=m"(DoubleFP[54/2-16]),
234                           "=m"(DoubleFP[56/2-16]), "=m"(DoubleFP[58/2-16]),
235                           "=m"(DoubleFP[60/2-16]), "=m"(DoubleFP[62/2-16]));
236 #endif
237
238   // Resolve the function call
239   register uint64_t restoreAddr = CompilationCallback();
240
241 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
242   // Set the return address to re-execute the `restore' instruction
243   __asm__ __volatile__ ("or %%o0, %%g0, %%i7;\n\t"
244
245                         // Restore g1 and g5
246                         "ldx %0, %%g1;\n\t" "ldx %1, %%g5;\n\t"
247                         :: "m"(g1), "m"(g5));
248
249   __asm__ __volatile__ (// Restore condition-code registers
250                         "ldx %0,    %%fsr;\n\t" 
251                         "wr  %1, 0, %%fprs;\n\t"
252                         "wr  %2, 0, %%ccr;\n\t" 
253                         :: "m"(FSR), "r"(FPRS), "r"(CCR));
254
255   // GCC says: `asm' only allows up to thirty parameters!
256   __asm__ __volatile__ (// Restore Single FP registers, part 1
257                         "ld  %0, %%f0;\n\t"   "ld  %1, %%f1;\n\t" 
258                         "ld  %2, %%f2;\n\t"   "ld  %3, %%f3;\n\t" 
259                         "ld  %4, %%f4;\n\t"   "ld  %5, %%f5;\n\t" 
260                         "ld  %6, %%f6;\n\t"   "ld  %7, %%f7;\n\t" 
261                         "ld  %8, %%f8;\n\t"   "ld  %9, %%f9;\n\t" 
262                         "ld  %10, %%f10;\n\t" "ld  %11, %%f11;\n\t"
263                         "ld  %12, %%f12;\n\t" "ld  %13, %%f13;\n\t"
264                         "ld  %14, %%f14;\n\t" "ld  %15, %%f15;\n\t"
265                         :: "m"(SingleFP[0]), "m"(SingleFP[1]),
266                            "m"(SingleFP[2]), "m"(SingleFP[3]),
267                            "m"(SingleFP[4]), "m"(SingleFP[5]),
268                            "m"(SingleFP[6]), "m"(SingleFP[7]),
269                            "m"(SingleFP[8]), "m"(SingleFP[9]),
270                            "m"(SingleFP[10]), "m"(SingleFP[11]),
271                            "m"(SingleFP[12]), "m"(SingleFP[13]),
272                            "m"(SingleFP[14]), "m"(SingleFP[15]));
273
274   __asm__ __volatile__ (// Restore Single FP registers, part 2
275                         "ld  %0, %%f16;\n\t"  "ld  %1, %%f17;\n\t"
276                         "ld  %2, %%f18;\n\t"  "ld  %3, %%f19;\n\t"
277                         "ld  %4, %%f20;\n\t"  "ld  %5, %%f21;\n\t"
278                         "ld  %6, %%f22;\n\t"  "ld  %7, %%f23;\n\t"
279                         "ld  %8, %%f24;\n\t"  "ld  %9, %%f25;\n\t"
280                         "ld  %10, %%f26;\n\t" "ld  %11, %%f27;\n\t"
281                         "ld  %12, %%f28;\n\t" "ld  %13, %%f29;\n\t"
282                         "ld  %14, %%f30;\n\t" "ld  %15, %%f31;\n\t"
283                         :: "m"(SingleFP[16]), "m"(SingleFP[17]),
284                            "m"(SingleFP[18]), "m"(SingleFP[19]),
285                            "m"(SingleFP[20]), "m"(SingleFP[21]),
286                            "m"(SingleFP[22]), "m"(SingleFP[23]),
287                            "m"(SingleFP[24]), "m"(SingleFP[25]),
288                            "m"(SingleFP[26]), "m"(SingleFP[27]),
289                            "m"(SingleFP[28]), "m"(SingleFP[29]),
290                            "m"(SingleFP[30]), "m"(SingleFP[31]));
291
292   __asm__ __volatile__ (// Restore Double FP registers
293                         "ldd %0, %%f32;\n\t"  "ldd %1, %%f34;\n\t"
294                         "ldd %2, %%f36;\n\t"  "ldd %3, %%f38;\n\t"
295                         "ldd %4, %%f40;\n\t"  "ldd %5, %%f42;\n\t"
296                         "ldd %6, %%f44;\n\t"  "ldd %7, %%f46;\n\t"
297                         "ldd %8, %%f48;\n\t"  "ldd %9, %%f50;\n\t"
298                         "ldd %10, %%f52;\n\t" "ldd %11, %%f54;\n\t"
299                         "ldd %12, %%f56;\n\t" "ldd %13, %%f58;\n\t"
300                         "ldd %14, %%f60;\n\t" "ldd %15, %%f62;\n\t"
301                         :: "m"(DoubleFP[32/2-16]), "m"(DoubleFP[34/2-16]),
302                            "m"(DoubleFP[36/2-16]), "m"(DoubleFP[38/2-16]),
303                            "m"(DoubleFP[40/2-16]), "m"(DoubleFP[42/2-16]),
304                            "m"(DoubleFP[44/2-16]), "m"(DoubleFP[46/2-16]),
305                            "m"(DoubleFP[48/2-16]), "m"(DoubleFP[50/2-16]),
306                            "m"(DoubleFP[52/2-16]), "m"(DoubleFP[54/2-16]),
307                            "m"(DoubleFP[56/2-16]), "m"(DoubleFP[58/2-16]),
308                            "m"(DoubleFP[60/2-16]), "m"(DoubleFP[62/2-16]));
309 #endif
310 }
311
312 uint64_t JITResolver::CompilationCallback() {
313   uint64_t CameFrom = (uint64_t)(intptr_t)__builtin_return_address(1);
314   int64_t Target = (int64_t)TheJITResolver->resolveFunctionReference(CameFrom);
315   DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << CameFrom << "\n");
316   register int64_t returnAddr = 0;
317 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
318   __asm__ __volatile__ ("add %%i7, %%g0, %0" : "=r" (returnAddr) : );
319   DEBUG(std::cerr << "Read i7 (return addr) = "
320                   << std::hex << returnAddr << ", value: "
321                   << std::hex << *(unsigned*)returnAddr << "\n");
322 #endif
323
324   // Rewrite the call target so that we don't fault every time we execute it.
325   //
326
327   static const unsigned o6 = SparcIntRegClass::o6;
328
329   // Subtract enough to overwrite up to the 'save' instruction
330   // This depends on whether we made a short call (1 instruction) or the
331   // farCall (7 instructions)
332   uint64_t Offset = (LazyCallFlavor[CameFrom] == ShortCall) ? 4 : 28;
333   uint64_t CodeBegin = CameFrom - Offset;
334   
335   // Make sure that what we're about to overwrite is indeed "save"
336   MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
337   unsigned SaveInst = TheJITResolver->getBinaryCodeForInstr(*SV);
338   delete SV;
339   unsigned CodeInMem = *(unsigned*)(intptr_t)CodeBegin;
340   assert(CodeInMem == SaveInst && "About to overwrite smthg not a save instr!");
341   DEBUG(std::cerr << "Emitting a far jump to 0x" << std::hex << Target << "\n");
342   TheJITResolver->insertFarJumpAtAddr(Target, CodeBegin);
343
344   // FIXME: if the target function is close enough to fit into the 19bit disp of
345   // BA, we should use this version, as its much cheaper to generate.
346 #if 0  
347   uint64_t InstAddr = CodeBegin;
348   // ba <target>
349   MachineInstr *MI = BuildMI(V9::BA, 1).addSImm(Target);
350   *((unsigned*)(intptr_t)InstAddr)=TheJITResolver->getBinaryCodeForInstr(*MI);
351   InstAddr += 4;
352   delete MI;
353
354   // nop
355   MI = BuildMI(V9::NOP, 0);
356   *((unsigned*)(intptr_t))=TheJITResolver->getBinaryCodeForInstr(*Nop);
357   delete MI;
358 #endif
359
360   // Change the return address to reexecute the restore, then the jump However,
361   // we can't just modify %i7 here, because we return to the function that will
362   // restore the floating-point registers for us. Thus, we just return the value
363   // we want it to be, and the parent will take care of setting %i7 correctly.
364   DEBUG(std::cerr << "Callback returning the addr of restore inst: "
365                   << std::hex << (CameFrom-Offset-12) << "\n");
366   return CameFrom - Offset - 12; // 8 because of call+delay, 4 more to restore
367 }
368
369 /// emitStubForFunction - This method is used by the JIT when it needs to emit
370 /// the address of a function for a function whose code has not yet been
371 /// generated.  In order to do this, it generates a stub which jumps to the lazy
372 /// function compiler, which will eventually get fixed to call the function
373 /// directly.
374 ///
375 uint64_t JITResolver::emitStubForFunction(Function *F) {
376   MCE.startFunctionStub(*F, 20);
377
378   DEBUG(std::cerr << "Emitting stub at addr: 0x" 
379                   << std::hex << MCE.getCurrentPCValue() << "\n");
380
381   unsigned o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0;
382
383   // restore %g0, 0, %g0
384   MachineInstr *R = BuildMI(V9::RESTOREi, 3).addMReg(g0).addSImm(0)
385                                             .addMReg(g0, MOTy::Def);
386   SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*R));
387   delete R;
388
389   // save %sp, -192, %sp
390   MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
391   SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*SV));
392   delete SV;
393
394   int64_t CurrPC = MCE.getCurrentPCValue();
395   int64_t Addr = (int64_t)addFunctionReference(CurrPC, F);
396   int64_t CallTarget = (Addr-CurrPC) >> 2;
397   //if (CallTarget >= (1 << 29) || CallTarget <= -(1 << 29)) {
398   // Since this is a far call, the actual address of the call is shifted
399   // by the number of instructions it takes to calculate the exact address
400     deleteFunctionReference(CurrPC);
401     SparcV9.emitFarCall(Addr, F);
402 #if 0
403   else {
404     // call CallTarget              ;; invoke the callback
405     MachineInstr *Call = BuildMI(V9::CALL, 1).addSImm(CallTarget);
406     SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Call));
407     delete Call;
408   
409     // nop                          ;; call delay slot
410     MachineInstr *Nop = BuildMI(V9::NOP, 0);
411     SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Nop));
412     delete Nop;
413
414     addCallFlavor(CurrPC, ShortCall);
415   }
416 #endif
417
418   SparcV9.emitWord(0xDEADBEEF); // marker so that we know it's really a stub
419   return (intptr_t)MCE.finishFunctionStub(*F)+4; /* 1 instr past the restore */
420 }
421
422
423 SparcV9CodeEmitter::SparcV9CodeEmitter(TargetMachine &tm,
424                                        MachineCodeEmitter &M): TM(tm), MCE(M)
425 {
426   TheJITResolver = new JITResolver(*this, M);
427 }
428
429 SparcV9CodeEmitter::~SparcV9CodeEmitter() {
430   delete TheJITResolver;
431 }
432
433 void SparcV9CodeEmitter::emitWord(unsigned Val) {
434   // Output the constant in big endian byte order...
435   unsigned byteVal;
436   for (int i = 3; i >= 0; --i) {
437     byteVal = Val >> 8*i;
438     MCE.emitByte(byteVal & 255);
439   }
440 }
441
442 unsigned 
443 SparcV9CodeEmitter::getRealRegNum(unsigned fakeReg,
444                                   MachineInstr &MI) {
445   const TargetRegInfo &RI = TM.getRegInfo();
446   unsigned regClass, regType = RI.getRegType(fakeReg);
447   // At least map fakeReg into its class
448   fakeReg = RI.getClassRegNum(fakeReg, regClass);
449
450   switch (regClass) {
451   case UltraSparcRegInfo::IntRegClassID: {
452     // Sparc manual, p31
453     static const unsigned IntRegMap[] = {
454       // "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
455       8, 9, 10, 11, 12, 13, 15,
456       // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
457       16, 17, 18, 19, 20, 21, 22, 23,
458       // "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
459       24, 25, 26, 27, 28, 29, 30, 31,
460       // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", 
461       0, 1, 2, 3, 4, 5, 6, 7,
462       // "o6"
463       14
464     }; 
465  
466     return IntRegMap[fakeReg];
467     break;
468   }
469   case UltraSparcRegInfo::FloatRegClassID: {
470     DEBUG(std::cerr << "FP reg: " << fakeReg << "\n");
471     if (regType == UltraSparcRegInfo::FPSingleRegType) {
472       // only numbered 0-31, hence can already fit into 5 bits (and 6)
473       DEBUG(std::cerr << "FP single reg, returning: " << fakeReg << "\n");
474     } else if (regType == UltraSparcRegInfo::FPDoubleRegType) {
475       // FIXME: This assumes that we only have 5-bit register fiels!
476       // From Sparc Manual, page 40.
477       // The bit layout becomes: b[4], b[3], b[2], b[1], b[5]
478       fakeReg |= (fakeReg >> 5) & 1;
479       fakeReg &= 0x1f;
480       DEBUG(std::cerr << "FP double reg, returning: " << fakeReg << "\n");      
481     }
482     return fakeReg;
483   }
484   case UltraSparcRegInfo::IntCCRegClassID: {
485     /*                                   xcc, icc, ccr */
486     static const unsigned IntCCReg[] = {  6,   4,   2 };
487     
488     assert(fakeReg < sizeof(IntCCReg)/sizeof(IntCCReg[0])
489              && "CC register out of bounds for IntCCReg map");      
490     DEBUG(std::cerr << "IntCC reg: " << IntCCReg[fakeReg] << "\n");
491     return IntCCReg[fakeReg];
492   }
493   case UltraSparcRegInfo::FloatCCRegClassID: {
494     /* These are laid out %fcc0 - %fcc3 => 0 - 3, so are correct */
495     DEBUG(std::cerr << "FP CC reg: " << fakeReg << "\n");
496     return fakeReg;
497   }
498   default:
499     assert(0 && "Invalid unified register number in getRegType");
500     return fakeReg;
501   }
502 }
503
504
505 // WARNING: if the call used the delay slot to do meaningful work, that's not
506 // being accounted for, and the behavior will be incorrect!!
507 inline void SparcV9CodeEmitter::emitFarCall(uint64_t Target, Function *F) {
508   static const unsigned o6 = SparcIntRegClass::o6,
509       o7 = SparcIntRegClass::o7, g0 = SparcIntRegClass::g0,
510       g1 = SparcIntRegClass::g1, g5 = SparcIntRegClass::g5;
511
512   MachineInstr* BinaryCode[] = {
513     //
514     // Get address to branch into %g1, using %g5 as a temporary
515     //
516     // sethi %uhi(Target), %g5   ;; get upper 22 bits of Target into %g5
517     BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(g5),
518     // or %g5, %ulo(Target), %g5 ;; get 10 lower bits of upper word into %1
519     BuildMI(V9::ORi, 3).addReg(g5).addSImm((Target >> 32) & 0x03ff).addReg(g5),
520     // sllx %g5, 32, %g5         ;; shift those 10 bits to the upper word
521     BuildMI(V9::SLLXi6, 3).addReg(g5).addSImm(32).addReg(g5),
522     // sethi %hi(Target), %g1    ;; extract bits 10-31 into the dest reg
523     BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(g1),
524     // or %g5, %g1, %g1          ;; get upper word (in %g5) into %g1
525     BuildMI(V9::ORr, 3).addReg(g5).addReg(g1).addReg(g1),
526     // or %g1, %lo(Target), %g1  ;; get lowest 10 bits of Target into %g1
527     BuildMI(V9::ORi, 3).addReg(g1).addSImm(Target & 0x03ff).addReg(g1),
528     // jmpl %g1, %g0, %o7        ;; indirect call on %g1
529     BuildMI(V9::JMPLRETr, 3).addReg(g1).addReg(g0).addReg(o7),
530     // nop                       ;; delay slot
531     BuildMI(V9::NOP, 0)
532   };
533
534   for (unsigned i=0, e=sizeof(BinaryCode)/sizeof(BinaryCode[0]); i!=e; ++i) {
535     // This is where we save the return address in the LazyResolverMap!!
536     if (i == 6 && F != 0) { // Do this right before the JMPL
537       uint64_t CurrPC = MCE.getCurrentPCValue();
538       TheJITResolver->addFunctionReference(CurrPC, F);
539       // Remember that this is a far call, to subtract appropriate offset later
540       TheJITResolver->addCallFlavor(CurrPC, JITResolver::FarCall);
541     }
542
543     emitWord(getBinaryCodeForInstr(*BinaryCode[i]));
544     delete BinaryCode[i];
545   }
546 }
547
548
549 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
550                                               MachineOperand &MO) {
551   int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
552                   // or things that get fixed up later by the JIT.
553
554   if (MO.isVirtualRegister()) {
555     std::cerr << "ERROR: virtual register found in machine code.\n";
556     abort();
557   } else if (MO.isPCRelativeDisp()) {
558     DEBUG(std::cerr << "PCRelativeDisp: ");
559     Value *V = MO.getVRegValue();
560     if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
561       DEBUG(std::cerr << "Saving reference to BB (VReg)\n");
562       unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
563       BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
564     } else if (const Constant *C = dyn_cast<Constant>(V)) {
565       if (ConstantMap.find(C) != ConstantMap.end()) {
566         rv = (int64_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
567         DEBUG(std::cerr << "const: 0x" << std::hex << rv << "\n");
568       } else {
569         std::cerr << "ERROR: constant not in map:" << MO << "\n";
570         abort();
571       }
572     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
573       // same as MO.isGlobalAddress()
574       DEBUG(std::cerr << "GlobalValue: ");
575       // external function calls, etc.?
576       if (Function *F = dyn_cast<Function>(GV)) {
577         DEBUG(std::cerr << "Function: ");
578         if (F->isExternal()) {
579           // Sparc backend broken: this MO should be `ExternalSymbol'
580           rv = (int64_t)MCE.getGlobalValueAddress(F->getName());
581         } else {
582           rv = (int64_t)MCE.getGlobalValueAddress(F);
583         }
584         if (rv == 0) {
585           DEBUG(std::cerr << "not yet generated\n");
586           // Function has not yet been code generated!
587           TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(), F);
588           // Delayed resolution...
589           rv = TheJITResolver->getLazyResolver(F);
590         } else {
591           DEBUG(std::cerr << "already generated: 0x" << std::hex << rv << "\n");
592         }
593       } else {
594         rv = (int64_t)MCE.getGlobalValueAddress(GV);
595         if (rv == 0) {
596           if (Constant *C = ConstantPointerRef::get(GV)) {
597             if (ConstantMap.find(C) != ConstantMap.end()) {
598               rv = MCE.getConstantPoolEntryAddress(ConstantMap[C]);
599             } else {
600               std::cerr << "Constant: 0x" << std::hex << (intptr_t)C
601                         << ", " << *V << " not found in ConstantMap!\n";
602               abort();
603             }
604           }
605         }
606         DEBUG(std::cerr << "Global addr: 0x" << std::hex << rv << "\n");
607       }
608       // The real target of the call is Addr = PC + (rv * 4)
609       // So undo that: give the instruction (Addr - PC) / 4
610       if (MI.getOpcode() == V9::CALL) {
611         int64_t CurrPC = MCE.getCurrentPCValue();
612         DEBUG(std::cerr << "rv addr: 0x" << std::hex << rv << "\n"
613                         << "curr PC: 0x" << std::hex << CurrPC << "\n");
614         int64_t CallInstTarget = (rv - CurrPC) >> 2;
615         if (CallInstTarget >= (1<<29) || CallInstTarget <= -(1<<29)) {
616           DEBUG(std::cerr << "Making far call!\n");
617           // addresss is out of bounds for the 30-bit call,
618           // make an indirect jump-and-link
619           emitFarCall(rv);
620           // this invalidates the instruction so that the call with an incorrect
621           // address will not be emitted
622           rv = 0; 
623         } else {
624           // The call fits into 30 bits, so just return the corrected address
625           rv = CallInstTarget;
626         }
627         DEBUG(std::cerr << "returning addr: 0x" << rv << "\n");
628       }
629     } else {
630       std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
631       abort();
632     }
633   } else if (MO.isPhysicalRegister() ||
634              MO.getType() == MachineOperand::MO_CCRegister)
635   {
636     // This is necessary because the Sparc backend doesn't actually lay out
637     // registers in the real fashion -- it skips those that it chooses not to
638     // allocate, i.e. those that are the FP, SP, etc.
639     unsigned fakeReg = MO.getAllocatedRegNum();
640     unsigned realRegByClass = getRealRegNum(fakeReg, MI);
641     DEBUG(std::cerr << MO << ": Reg[" << std::dec << fakeReg << "] => "
642                     << realRegByClass << " (LLC: " 
643                     << TM.getRegInfo().getUnifiedRegName(fakeReg) << ")\n");
644     rv = realRegByClass;
645   } else if (MO.isImmediate()) {
646     rv = MO.getImmedValue();
647     DEBUG(std::cerr << "immed: " << rv << "\n");
648   } else if (MO.isGlobalAddress()) {
649     DEBUG(std::cerr << "GlobalAddress: not PC-relative\n");
650     rv = (int64_t)
651       (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
652                                  MI, MO.isPCRelative());
653   } else if (MO.isMachineBasicBlock()) {
654     // Duplicate code of the above case for VirtualRegister, BasicBlock... 
655     // It should really hit this case, but Sparc backend uses VRegs instead
656     DEBUG(std::cerr << "Saving reference to MBB\n");
657     const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
658     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
659     BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
660   } else if (MO.isExternalSymbol()) {
661     // Sparc backend doesn't generate this (yet...)
662     std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
663     abort();
664   } else if (MO.isFrameIndex()) {
665     // Sparc backend doesn't generate this (yet...)
666     int FrameIndex = MO.getFrameIndex();
667     std::cerr << "ERROR: Frame index unhandled.\n";
668     abort();
669   } else if (MO.isConstantPoolIndex()) {
670     // Sparc backend doesn't generate this (yet...)
671     std::cerr << "ERROR: Constant Pool index unhandled.\n";
672     abort();
673   } else {
674     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
675     abort();
676   }
677
678   // Finally, deal with the various bitfield-extracting functions that
679   // are used in SPARC assembly. (Some of these make no sense in combination
680   // with some of the above; we'll trust that the instruction selector
681   // will not produce nonsense, and not check for valid combinations here.)
682   if (MO.opLoBits32()) {          // %lo(val) == %lo() in Sparc ABI doc
683     return rv & 0x03ff;
684   } else if (MO.opHiBits32()) {   // %lm(val) == %hi() in Sparc ABI doc
685     return (rv >> 10) & 0x03fffff;
686   } else if (MO.opLoBits64()) {   // %hm(val) == %ulo() in Sparc ABI doc
687     return (rv >> 32) & 0x03ff;
688   } else if (MO.opHiBits64()) {   // %hh(val) == %uhi() in Sparc ABI doc
689     return rv >> 42;
690   } else {                        // (unadorned) val
691     return rv;
692   }
693 }
694
695 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
696   Val >>= bit;
697   return (Val & 1);
698 }
699
700 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
701   MCE.startFunction(MF);
702   DEBUG(std::cerr << "Starting function " << MF.getFunction()->getName()
703             << ", address: " << "0x" << std::hex 
704             << (long)MCE.getCurrentPCValue() << "\n");
705
706   // The Sparc backend does not use MachineConstantPool;
707   // instead, it has its own constant pool implementation.
708   // We create a new MachineConstantPool here to be compatible with the emitter.
709   MachineConstantPool MCP;
710   const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
711   for (hash_set<const Constant*>::const_iterator I = pool.begin(),
712          E = pool.end();  I != E; ++I)
713   {
714     Constant *C = (Constant*)*I;
715     unsigned idx = MCP.getConstantPoolIndex(C);
716     DEBUG(std::cerr << "Constant[" << idx << "] = 0x" << (intptr_t)C << "\n");
717     ConstantMap[C] = idx;
718   }  
719   MCE.emitConstantPool(&MCP);
720
721   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
722     emitBasicBlock(*I);
723   MCE.finishFunction(MF);
724
725   DEBUG(std::cerr << "Finishing fn " << MF.getFunction()->getName() << "\n");
726   ConstantMap.clear();
727
728   // Resolve branches to BasicBlocks for the entire function
729   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
730     long Location = BBLocations[BBRefs[i].first];
731     unsigned *Ref = BBRefs[i].second.first;
732     MachineInstr *MI = BBRefs[i].second.second;
733     DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
734                     << " in instr: " << std::dec << *MI);
735     for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
736       MachineOperand &op = MI->getOperand(ii);
737       if (op.isPCRelativeDisp()) {
738         // the instruction's branch target is made such that it branches to
739         // PC + (branchTarget * 4), so undo that arithmetic here:
740         // Location is the target of the branch
741         // Ref is the location of the instruction, and hence the PC
742         int64_t branchTarget = (Location - (long)Ref) >> 2;
743         // Save the flags.
744         bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;   
745         if (op.opLoBits32()) { loBits32=true; }
746         if (op.opHiBits32()) { hiBits32=true; }
747         if (op.opLoBits64()) { loBits64=true; }
748         if (op.opHiBits64()) { hiBits64=true; }
749         MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
750                                    branchTarget);
751         if (loBits32) { MI->setOperandLo32(ii); }
752         else if (hiBits32) { MI->setOperandHi32(ii); }
753         else if (loBits64) { MI->setOperandLo64(ii); }
754         else if (hiBits64) { MI->setOperandHi64(ii); }
755         DEBUG(std::cerr << "Rewrote BB ref: ");
756         unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
757         *Ref = fixedInstr;
758         break;
759       }
760     }
761   }
762   BBRefs.clear();
763   BBLocations.clear();
764
765   return false;
766 }
767
768 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
769   currBB = MBB.getBasicBlock();
770   BBLocations[currBB] = MCE.getCurrentPCValue();
771   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
772     unsigned binCode = getBinaryCodeForInstr(**I);
773     if (binCode == (1 << 30)) {
774       // this is an invalid call: the addr is out of bounds. that means a code
775       // sequence has already been emitted, and this is a no-op
776       DEBUG(std::cerr << "Call supressed: already emitted far call.\n");
777     } else {
778       emitWord(binCode);
779     }
780   }
781 }
782
783 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
784                                            bool isPCRelative)
785 {
786   if (isPCRelative) { // must be a call, this is a major hack!
787     // Try looking up the function to see if it is already compiled!
788     if (void *Addr = (void*)(intptr_t)MCE.getGlobalValueAddress(V)) {
789       intptr_t CurByte = MCE.getCurrentPCValue();
790       // The real target of the call is Addr = PC + (target * 4)
791       // CurByte is the PC, Addr we just received
792       return (void*) (((long)Addr - (long)CurByte) >> 2);
793     } else {
794       if (Function *F = dyn_cast<Function>(V)) {
795         // Function has not yet been code generated!
796         TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
797                                              cast<Function>(V));
798         // Delayed resolution...
799         return 
800           (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
801
802       } else if (Constant *C = ConstantPointerRef::get(V)) {
803         if (ConstantMap.find(C) != ConstantMap.end()) {
804           return (void*)
805             (intptr_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
806         } else {
807           std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
808                     << ", " << *V << " not found in ConstantMap!\n";
809           abort();
810         }
811       } else {
812         std::cerr << "Unhandled global: " << *V << "\n";
813         abort();
814       }
815     }
816   } else {
817     return (void*)(intptr_t)MCE.getGlobalValueAddress(V);
818   }
819 }
820
821 #include "SparcV9CodeEmitter.inc"