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