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