1 //===-- SparcV9CodeEmitter.cpp - --------===//
4 //===----------------------------------------------------------------------===//
6 #include "llvm/Constants.h"
7 #include "llvm/Function.h"
8 #include "llvm/GlobalVariable.h"
9 #include "llvm/PassManager.h"
10 #include "llvm/CodeGen/MachineCodeEmitter.h"
11 #include "llvm/CodeGen/MachineConstantPool.h"
12 #include "llvm/CodeGen/MachineFunctionInfo.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/TargetData.h"
17 #include "Support/Statistic.h"
18 #include "Support/hash_set"
19 #include "SparcInternals.h"
20 #include "SparcV9CodeEmitter.h"
22 bool UltraSparc::addPassesToEmitMachineCode(PassManager &PM,
23 MachineCodeEmitter &MCE) {
24 MachineCodeEmitter *M = &MCE;
25 DEBUG(M = MachineCodeEmitter::createFilePrinterEmitter(MCE));
26 PM.add(new SparcV9CodeEmitter(*this, *M));
27 PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
33 SparcV9CodeEmitter &SparcV9;
34 MachineCodeEmitter &MCE;
36 // LazyCodeGenMap - Keep track of call sites for functions that are to be
38 std::map<uint64_t, Function*> LazyCodeGenMap;
40 // LazyResolverMap - Keep track of the lazy resolver created for a
41 // particular function so that we can reuse them if necessary.
42 std::map<Function*, uint64_t> LazyResolverMap;
44 JITResolver(SparcV9CodeEmitter &V9,
45 MachineCodeEmitter &mce) : SparcV9(V9), MCE(mce) {}
46 uint64_t getLazyResolver(Function *F);
47 uint64_t addFunctionReference(uint64_t Address, Function *F);
49 // Utility functions for accessing data from static callback
50 uint64_t getCurrentPCValue() {
51 return MCE.getCurrentPCValue();
53 unsigned getBinaryCodeForInstr(MachineInstr &MI) {
54 return SparcV9.getBinaryCodeForInstr(MI);
57 inline uint64_t insertFarJumpAtAddr(int64_t Value, uint64_t Addr);
60 uint64_t emitStubForFunction(Function *F);
61 static void CompilationCallback();
62 uint64_t resolveFunctionReference(uint64_t RetAddr);
66 JITResolver *TheJITResolver;
69 /// addFunctionReference - This method is called when we need to emit the
70 /// address of a function that has not yet been emitted, so we don't know the
71 /// address. Instead, we emit a call to the CompilationCallback method, and
72 /// keep track of where we are.
74 uint64_t JITResolver::addFunctionReference(uint64_t Address, Function *F) {
75 LazyCodeGenMap[Address] = F;
76 return (intptr_t)&JITResolver::CompilationCallback;
79 uint64_t JITResolver::resolveFunctionReference(uint64_t RetAddr) {
80 std::map<uint64_t, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
81 assert(I != LazyCodeGenMap.end() && "Not in map!");
82 Function *F = I->second;
83 LazyCodeGenMap.erase(I);
84 return MCE.forceCompilationOf(F);
87 uint64_t JITResolver::getLazyResolver(Function *F) {
88 std::map<Function*, uint64_t>::iterator I = LazyResolverMap.lower_bound(F);
89 if (I != LazyResolverMap.end() && I->first == F) return I->second;
91 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
93 uint64_t Stub = emitStubForFunction(F);
94 LazyResolverMap.insert(I, std::make_pair(F, Stub));
98 uint64_t JITResolver::insertFarJumpAtAddr(int64_t Target, uint64_t Addr) {
100 static const unsigned i1 = SparcIntRegClass::i1, i2 = SparcIntRegClass::i2,
101 i7 = SparcIntRegClass::i7,
102 o6 = SparcIntRegClass::o6, g0 = SparcIntRegClass::g0;
105 // Save %i1, %i2 to the stack so we can form a 64-bit constant in %i2
108 // stx %i1, [%sp + 2119] ;; save %i1 to the stack, used as temp
109 MachineInstr *STX = BuildMI(V9::STXi, 3).addReg(i1).addReg(o6).addSImm(2119);
110 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*STX);
114 // stx %i2, [%sp + 2127] ;; save %i2 to the stack
115 STX = BuildMI(V9::STXi, 3).addReg(i2).addReg(o6).addSImm(2127);
116 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*STX);
121 // Get address to branch into %i2, using %i1 as a temporary
124 // sethi %uhi(Target), %i1 ;; get upper 22 bits of Target into %i1
125 MachineInstr *SH = BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(i1);
126 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*SH);
130 // or %i1, %ulo(Target), %i1 ;; get 10 lower bits of upper word into %1
131 MachineInstr *OR = BuildMI(V9::ORi, 3)
132 .addReg(i1).addSImm((Target >> 32) & 0x03ff).addReg(i1);
133 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*OR);
137 // sllx %i1, 32, %i1 ;; shift those 10 bits to the upper word
138 MachineInstr *SL = BuildMI(V9::SLLXi6, 3).addReg(i1).addSImm(32).addReg(i1);
139 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*SL);
143 // sethi %hi(Target), %i2 ;; extract bits 10-31 into the dest reg
144 SH = BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(i2);
145 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*SH);
149 // or %i1, %i2, %i2 ;; get upper word (in %i1) into %i2
150 OR = BuildMI(V9::ORr, 3).addReg(i1).addReg(i2).addReg(i2);
151 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*OR);
155 // or %i2, %lo(Target), %i2 ;; get lowest 10 bits of Target into %i2
156 OR = BuildMI(V9::ORi, 3).addReg(i2).addSImm(Target & 0x03ff).addReg(i2);
157 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*OR);
161 // ldx [%sp + 2119], %i1 ;; restore %i1 -> 2119 = BIAS(2047) + 72
162 MachineInstr *LDX = BuildMI(V9::LDXi, 3).addReg(o6).addSImm(2119).addReg(i1);
163 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*LDX);
167 // jmpl %i2, %g0, %g0 ;; indirect branch on %i2
168 MachineInstr *J = BuildMI(V9::JMPLRETr, 3).addReg(i2).addReg(g0).addReg(g0);
169 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*J);
173 // ldx [%sp + 2127], %i2 ;; restore %i2 -> 2127 = BIAS(2047) + 80
174 LDX = BuildMI(V9::LDXi, 3).addReg(o6).addSImm(2127).addReg(i2);
175 *((unsigned*)(intptr_t)Addr) = getBinaryCodeForInstr(*LDX);
182 void JITResolver::CompilationCallback() {
183 uint64_t CameFrom = (uint64_t)(intptr_t)__builtin_return_address(0);
184 int64_t Target = (int64_t)TheJITResolver->resolveFunctionReference(CameFrom);
185 DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << CameFrom << "\n");
187 // Rewrite the call target... so that we don't fault every time we execute
190 int64_t RealCallTarget = (int64_t)
191 ((NewVal - TheJITResolver->getCurrentPCValue()) >> 4);
192 if (RealCallTarget >= (1<<22) || RealCallTarget <= -(1<<22)) {
193 std::cerr << "Address out of bounds for 22bit BA: " << RealCallTarget<<"\n";
198 //uint64_t CurrPC = TheJITResolver->getCurrentPCValue();
199 // we will insert 9 instructions before we do the actual jump
200 //int64_t NewTarget = (NewVal - 9*4 - InstAddr) >> 2;
202 static const unsigned i1 = SparcIntRegClass::i1, i2 = SparcIntRegClass::i2,
203 i7 = SparcIntRegClass::i7, o6 = SparcIntRegClass::o6,
204 o7 = SparcIntRegClass::o7, g0 = SparcIntRegClass::g0;
206 // Subtract 4 to overwrite the 'save' that's there now
207 uint64_t InstAddr = CameFrom-4;
209 InstAddr = TheJITResolver->insertFarJumpAtAddr(Target, InstAddr);
211 // CODE SHOULD NEVER GO PAST THIS LOAD!! The real function should return to
212 // the original caller, not here!!
214 // FIXME: add call 0 to make sure?!?
216 // =============== THE REAL STUB ENDS HERE =========================
218 // What follows below is one-time restore code, because this callback may be
219 // changing registers in unpredictible ways. However, since it is executed
220 // only once per function (after the function is resolved, the callback is no
221 // longer in the path), this has to be done only once.
223 // Thus, it is after the regular stub code. The call back returns to THIS
224 // point, but every other call to the target function will execute the code
225 // above. Hence, this code is one-time use.
227 uint64_t OneTimeRestore = InstAddr;
229 // restore %g0, 0, %g0
230 //MachineInstr *R = BuildMI(V9::RESTOREi, 3).addMReg(g0).addSImm(0)
231 // .addMReg(g0, MOTy::Def);
232 //*((unsigned*)(intptr_t)InstAddr)=TheJITResolver->getBinaryCodeForInstr(*R);
235 // FIXME: BuildMI() above crashes. Encode the instruction directly.
236 // restore %g0, 0, %g0
237 *((unsigned*)(intptr_t)InstAddr) = 0x81e82000U;
240 InstAddr = TheJITResolver->insertFarJumpAtAddr(Target, InstAddr);
242 // FIXME: if the target function is close enough to fit into the 19bit disp of
243 // BA, we should use this version, as its much cheaper to generate.
245 MachineInstr *MI = BuildMI(V9::BA, 1).addSImm(RealCallTarget);
246 *((unsigned*)(intptr_t)InstAddr) = TheJITResolver->getBinaryCodeForInstr(*MI);
251 MachineInstr *Nop = BuildMI(V9::NOP, 0);
252 *((unsigned*)(intptr_t)InstAddr)=TheJITResolver->getBinaryCodeForInstr(*Nop);
256 MachineInstr *BA = BuildMI(V9::BA, 1).addSImm(RealCallTarget-2);
257 *((unsigned*)(intptr_t)InstAddr) = TheJITResolver->getBinaryCodeForInstr(*BA);
261 // Change the return address to reexecute the call instruction...
262 // The return address is really %o7, but will disappear after this function
263 // returns, and the register windows are rotated away.
264 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
265 __asm__ __volatile__ ("or %%g0, %0, %%i7" : : "r" (OneTimeRestore-8));
269 /// emitStubForFunction - This method is used by the JIT when it needs to emit
270 /// the address of a function for a function whose code has not yet been
271 /// generated. In order to do this, it generates a stub which jumps to the lazy
272 /// function compiler, which will eventually get fixed to call the function
275 uint64_t JITResolver::emitStubForFunction(Function *F) {
276 MCE.startFunctionStub(*F, 6);
278 DEBUG(std::cerr << "Emitting stub at addr: 0x"
279 << std::hex << MCE.getCurrentPCValue() << "\n");
281 unsigned o6 = SparcIntRegClass::o6;
282 // save %sp, -192, %sp
283 MachineInstr *SV = BuildMI(V9::SAVEi, 3).addReg(o6).addSImm(-192).addReg(o6);
284 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*SV));
287 int64_t CurrPC = MCE.getCurrentPCValue();
288 int64_t Addr = (int64_t)addFunctionReference(CurrPC, F);
289 int64_t CallTarget = (Addr-CurrPC) >> 2;
290 if (CallTarget >= (1 << 30) || CallTarget <= -(1 << 30)) {
291 SparcV9.emitFarCall(Addr);
293 // call CallTarget ;; invoke the callback
294 MachineInstr *Call = BuildMI(V9::CALL, 1).addSImm(CallTarget);
295 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Call));
298 // nop ;; call delay slot
299 MachineInstr *Nop = BuildMI(V9::NOP, 0);
300 SparcV9.emitWord(SparcV9.getBinaryCodeForInstr(*Nop));
304 SparcV9.emitWord(0xDEADBEEF); // marker so that we know it's really a stub
305 return (intptr_t)MCE.finishFunctionStub(*F);
309 SparcV9CodeEmitter::SparcV9CodeEmitter(TargetMachine &tm,
310 MachineCodeEmitter &M): TM(tm), MCE(M)
312 TheJITResolver = new JITResolver(*this, M);
315 SparcV9CodeEmitter::~SparcV9CodeEmitter() {
316 delete TheJITResolver;
319 void SparcV9CodeEmitter::emitWord(unsigned Val) {
320 // Output the constant in big endian byte order...
322 for (int i = 3; i >= 0; --i) {
323 byteVal = Val >> 8*i;
324 MCE.emitByte(byteVal & 255);
329 SparcV9CodeEmitter::getRealRegNum(unsigned fakeReg,
331 const TargetRegInfo &RI = TM.getRegInfo();
332 unsigned regClass, regType = RI.getRegType(fakeReg);
333 // At least map fakeReg into its class
334 fakeReg = RI.getClassRegNum(fakeReg, regClass);
337 case UltraSparcRegInfo::IntRegClassID: {
339 static const unsigned IntRegMap[] = {
340 // "o0", "o1", "o2", "o3", "o4", "o5", "o7",
341 8, 9, 10, 11, 12, 13, 15,
342 // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
343 16, 17, 18, 19, 20, 21, 22, 23,
344 // "i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7",
345 24, 25, 26, 27, 28, 29, 30, 31,
346 // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
347 0, 1, 2, 3, 4, 5, 6, 7,
352 return IntRegMap[fakeReg];
355 case UltraSparcRegInfo::FloatRegClassID: {
356 DEBUG(std::cerr << "FP reg: " << fakeReg << "\n");
357 if (regType == UltraSparcRegInfo::FPSingleRegType) {
358 // only numbered 0-31, hence can already fit into 5 bits (and 6)
359 DEBUG(std::cerr << "FP single reg, returning: " << fakeReg << "\n");
360 } else if (regType == UltraSparcRegInfo::FPDoubleRegType) {
361 // FIXME: This assumes that we only have 5-bit register fiels!
362 // From Sparc Manual, page 40.
363 // The bit layout becomes: b[4], b[3], b[2], b[1], b[5]
364 fakeReg |= (fakeReg >> 5) & 1;
366 DEBUG(std::cerr << "FP double reg, returning: " << fakeReg << "\n");
370 case UltraSparcRegInfo::IntCCRegClassID: {
372 static const unsigned IntCCReg[] = { 6, 4, 2 };
374 assert(fakeReg < sizeof(IntCCReg)/sizeof(IntCCReg[0])
375 && "CC register out of bounds for IntCCReg map");
376 DEBUG(std::cerr << "IntCC reg: " << IntCCReg[fakeReg] << "\n");
377 return IntCCReg[fakeReg];
379 case UltraSparcRegInfo::FloatCCRegClassID: {
380 /* These are laid out %fcc0 - %fcc3 => 0 - 3, so are correct */
381 DEBUG(std::cerr << "FP CC reg: " << fakeReg << "\n");
385 assert(0 && "Invalid unified register number in getRegType");
391 // WARNING: if the call used the delay slot to do meaningful work, that's not
392 // being accounted for, and the behavior will be incorrect!!
393 inline void SparcV9CodeEmitter::emitFarCall(uint64_t Target) {
394 static const unsigned i1 = SparcIntRegClass::i1, i2 = SparcIntRegClass::i2,
395 i7 = SparcIntRegClass::i7, o6 = SparcIntRegClass::o6,
396 o7 = SparcIntRegClass::o7, g0 = SparcIntRegClass::g0;
399 // Save %i1, %i2 to the stack so we can form a 64-bit constant in %i2
402 // stx %i1, [%sp + 2119] ;; save %i1 to the stack, used as temp
403 MachineInstr *STX = BuildMI(V9::STXi, 3).addReg(i1).addReg(o6).addSImm(2119);
404 emitWord(getBinaryCodeForInstr(*STX));
407 // stx %i2, [%sp + 2127] ;; save %i2 to the stack
408 STX = BuildMI(V9::STXi, 3).addReg(i2).addReg(o6).addSImm(2127);
409 emitWord(getBinaryCodeForInstr(*STX));
413 // Get address to branch into %i2, using %i1 as a temporary
416 // sethi %uhi(Target), %i1 ;; get upper 22 bits of Target into %i1
417 MachineInstr *SH = BuildMI(V9::SETHI, 2).addSImm(Target >> 42).addReg(i1);
418 emitWord(getBinaryCodeForInstr(*SH));
421 // or %i1, %ulo(Target), %i1 ;; get 10 lower bits of upper word into %1
422 MachineInstr *OR = BuildMI(V9::ORi, 3)
423 .addReg(i1).addSImm((Target >> 32) & 0x03ff).addReg(i1);
424 emitWord(getBinaryCodeForInstr(*OR));
427 // sllx %i1, 32, %i1 ;; shift those 10 bits to the upper word
428 MachineInstr *SL = BuildMI(V9::SLLXi6, 3).addReg(i1).addSImm(32).addReg(i1);
429 emitWord(getBinaryCodeForInstr(*SL));
432 // sethi %hi(Target), %i2 ;; extract bits 10-31 into the dest reg
433 SH = BuildMI(V9::SETHI, 2).addSImm((Target >> 10) & 0x03fffff).addReg(i2);
434 emitWord(getBinaryCodeForInstr(*SH));
437 // or %i1, %i2, %i2 ;; get upper word (in %i1) into %i2
438 OR = BuildMI(V9::ORr, 3).addReg(i1).addReg(i2).addReg(i2);
439 emitWord(getBinaryCodeForInstr(*OR));
442 // or %i2, %lo(Target), %i2 ;; get lowest 10 bits of Target into %i2
443 OR = BuildMI(V9::ORi, 3).addReg(i2).addSImm(Target & 0x03ff).addReg(i2);
444 emitWord(getBinaryCodeForInstr(*OR));
447 // ldx [%sp + 2119], %i1 ;; restore %i1 -> 2119 = BIAS(2047) + 72
448 MachineInstr *LDX = BuildMI(V9::LDXi, 3).addReg(o6).addSImm(2119).addReg(i1);
449 emitWord(getBinaryCodeForInstr(*LDX));
452 // jmpl %i2, %g0, %o7 ;; indirect call on %i2
453 MachineInstr *J = BuildMI(V9::JMPLRETr, 3).addReg(i2).addReg(g0).addReg(o7);
454 emitWord(getBinaryCodeForInstr(*J));
457 // ldx [%sp + 2127], %i2 ;; restore %i2 -> 2127 = BIAS(2047) + 80
458 LDX = BuildMI(V9::LDXi, 3).addReg(o6).addSImm(2127).addReg(i2);
459 emitWord(getBinaryCodeForInstr(*LDX));
464 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
465 MachineOperand &MO) {
466 int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
467 // or things that get fixed up later by the JIT.
469 if (MO.isVirtualRegister()) {
470 std::cerr << "ERROR: virtual register found in machine code.\n";
472 } else if (MO.isPCRelativeDisp()) {
473 DEBUG(std::cerr << "PCRelativeDisp: ");
474 Value *V = MO.getVRegValue();
475 if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
476 DEBUG(std::cerr << "Saving reference to BB (VReg)\n");
477 unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
478 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
479 } else if (const Constant *C = dyn_cast<Constant>(V)) {
480 if (ConstantMap.find(C) != ConstantMap.end()) {
481 rv = (int64_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
482 DEBUG(std::cerr << "const: 0x" << std::hex << rv << "\n");
484 std::cerr << "ERROR: constant not in map:" << MO << "\n";
487 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
488 // same as MO.isGlobalAddress()
489 DEBUG(std::cerr << "GlobalValue: ");
490 // external function calls, etc.?
491 if (Function *F = dyn_cast<Function>(GV)) {
492 DEBUG(std::cerr << "Function: ");
493 if (F->isExternal()) {
494 // Sparc backend broken: this MO should be `ExternalSymbol'
495 rv = (int64_t)MCE.getGlobalValueAddress(F->getName());
497 rv = (int64_t)MCE.getGlobalValueAddress(F);
500 DEBUG(std::cerr << "not yet generated\n");
501 // Function has not yet been code generated!
502 TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(), F);
503 // Delayed resolution...
504 rv = TheJITResolver->getLazyResolver(F);
506 DEBUG(std::cerr << "already generated: 0x" << std::hex << rv << "\n");
509 rv = (int64_t)MCE.getGlobalValueAddress(GV);
511 if (Constant *C = ConstantPointerRef::get(GV)) {
512 if (ConstantMap.find(C) != ConstantMap.end()) {
513 rv = MCE.getConstantPoolEntryAddress(ConstantMap[C]);
515 std::cerr << "Constant: 0x" << std::hex << (intptr_t)C
516 << ", " << *V << " not found in ConstantMap!\n";
521 DEBUG(std::cerr << "Global addr: " << rv << "\n");
523 // The real target of the call is Addr = PC + (rv * 4)
524 // So undo that: give the instruction (Addr - PC) / 4
525 if (MI.getOpcode() == V9::CALL) {
526 int64_t CurrPC = MCE.getCurrentPCValue();
527 DEBUG(std::cerr << "rv addr: 0x" << std::hex << rv << "\n"
528 << "curr PC: 0x" << CurrPC << "\n");
529 int64_t CallInstTarget = (rv - CurrPC) >> 2;
530 if (CallInstTarget >= (1<<29) || CallInstTarget <= -(1<<29)) {
531 DEBUG(std::cerr << "Making far call!\n");
532 // addresss is out of bounds for the 30-bit call,
533 // make an indirect jump-and-link
535 // this invalidates the instruction so that the call with an incorrect
536 // address will not be emitted
539 // The call fits into 30 bits, so just return the corrected address
542 DEBUG(std::cerr << "returning addr: 0x" << rv << "\n");
545 std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
548 } else if (MO.isPhysicalRegister() ||
549 MO.getType() == MachineOperand::MO_CCRegister)
551 // This is necessary because the Sparc backend doesn't actually lay out
552 // registers in the real fashion -- it skips those that it chooses not to
553 // allocate, i.e. those that are the FP, SP, etc.
554 unsigned fakeReg = MO.getAllocatedRegNum();
555 unsigned realRegByClass = getRealRegNum(fakeReg, MI);
556 DEBUG(std::cerr << MO << ": Reg[" << std::dec << fakeReg << "] => "
557 << realRegByClass << " (LLC: "
558 << TM.getRegInfo().getUnifiedRegName(fakeReg) << ")\n");
560 } else if (MO.isImmediate()) {
561 rv = MO.getImmedValue();
562 DEBUG(std::cerr << "immed: " << rv << "\n");
563 } else if (MO.isGlobalAddress()) {
564 DEBUG(std::cerr << "GlobalAddress: not PC-relative\n");
566 (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
567 MI, MO.isPCRelative());
568 } else if (MO.isMachineBasicBlock()) {
569 // Duplicate code of the above case for VirtualRegister, BasicBlock...
570 // It should really hit this case, but Sparc backend uses VRegs instead
571 DEBUG(std::cerr << "Saving reference to MBB\n");
572 const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
573 unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
574 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
575 } else if (MO.isExternalSymbol()) {
576 // Sparc backend doesn't generate this (yet...)
577 std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
579 } else if (MO.isFrameIndex()) {
580 // Sparc backend doesn't generate this (yet...)
581 int FrameIndex = MO.getFrameIndex();
582 std::cerr << "ERROR: Frame index unhandled.\n";
584 } else if (MO.isConstantPoolIndex()) {
585 // Sparc backend doesn't generate this (yet...)
586 std::cerr << "ERROR: Constant Pool index unhandled.\n";
589 std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
593 // Finally, deal with the various bitfield-extracting functions that
594 // are used in SPARC assembly. (Some of these make no sense in combination
595 // with some of the above; we'll trust that the instruction selector
596 // will not produce nonsense, and not check for valid combinations here.)
597 if (MO.opLoBits32()) { // %lo(val) == %lo() in Sparc ABI doc
599 } else if (MO.opHiBits32()) { // %lm(val) == %hi() in Sparc ABI doc
600 return (rv >> 10) & 0x03fffff;
601 } else if (MO.opLoBits64()) { // %hm(val) == %ulo() in Sparc ABI doc
602 return (rv >> 32) & 0x03ff;
603 } else if (MO.opHiBits64()) { // %hh(val) == %uhi() in Sparc ABI doc
605 } else { // (unadorned) val
610 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
615 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
616 MCE.startFunction(MF);
617 DEBUG(std::cerr << "Starting function " << MF.getFunction()->getName()
618 << ", address: " << "0x" << std::hex
619 << (long)MCE.getCurrentPCValue() << "\n");
621 // The Sparc backend does not use MachineConstantPool;
622 // instead, it has its own constant pool implementation.
623 // We create a new MachineConstantPool here to be compatible with the emitter.
624 MachineConstantPool MCP;
625 const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
626 for (hash_set<const Constant*>::const_iterator I = pool.begin(),
627 E = pool.end(); I != E; ++I)
629 Constant *C = (Constant*)*I;
630 unsigned idx = MCP.getConstantPoolIndex(C);
631 DEBUG(std::cerr << "Constant[" << idx << "] = 0x" << (intptr_t)C << "\n");
632 ConstantMap[C] = idx;
634 MCE.emitConstantPool(&MCP);
636 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
638 MCE.finishFunction(MF);
640 DEBUG(std::cerr << "Finishing fn " << MF.getFunction()->getName() << "\n");
643 // Resolve branches to BasicBlocks for the entire function
644 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
645 long Location = BBLocations[BBRefs[i].first];
646 unsigned *Ref = BBRefs[i].second.first;
647 MachineInstr *MI = BBRefs[i].second.second;
648 DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
649 << " in instr: " << std::dec << *MI);
650 for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
651 MachineOperand &op = MI->getOperand(ii);
652 if (op.isPCRelativeDisp()) {
653 // the instruction's branch target is made such that it branches to
654 // PC + (branchTarget * 4), so undo that arithmetic here:
655 // Location is the target of the branch
656 // Ref is the location of the instruction, and hence the PC
657 int64_t branchTarget = (Location - (long)Ref) >> 2;
659 bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;
660 if (op.opLoBits32()) { loBits32=true; }
661 if (op.opHiBits32()) { hiBits32=true; }
662 if (op.opLoBits64()) { loBits64=true; }
663 if (op.opHiBits64()) { hiBits64=true; }
664 MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
666 if (loBits32) { MI->setOperandLo32(ii); }
667 else if (hiBits32) { MI->setOperandHi32(ii); }
668 else if (loBits64) { MI->setOperandLo64(ii); }
669 else if (hiBits64) { MI->setOperandHi64(ii); }
670 DEBUG(std::cerr << "Rewrote BB ref: ");
671 unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
683 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
684 currBB = MBB.getBasicBlock();
685 BBLocations[currBB] = MCE.getCurrentPCValue();
686 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){
687 unsigned binCode = getBinaryCodeForInstr(**I);
688 if (binCode == (1 << 30)) {
689 // this is an invalid call: the addr is out of bounds. that means a code
690 // sequence has already been emitted, and this is a no-op
691 DEBUG(std::cerr << "Call supressed: already emitted far call.\n");
698 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
701 if (isPCRelative) { // must be a call, this is a major hack!
702 // Try looking up the function to see if it is already compiled!
703 if (void *Addr = (void*)(intptr_t)MCE.getGlobalValueAddress(V)) {
704 intptr_t CurByte = MCE.getCurrentPCValue();
705 // The real target of the call is Addr = PC + (target * 4)
706 // CurByte is the PC, Addr we just received
707 return (void*) (((long)Addr - (long)CurByte) >> 2);
709 if (Function *F = dyn_cast<Function>(V)) {
710 // Function has not yet been code generated!
711 TheJITResolver->addFunctionReference(MCE.getCurrentPCValue(),
713 // Delayed resolution...
715 (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
717 } else if (Constant *C = ConstantPointerRef::get(V)) {
718 if (ConstantMap.find(C) != ConstantMap.end()) {
720 (intptr_t)MCE.getConstantPoolEntryAddress(ConstantMap[C]);
722 std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
723 << ", " << *V << " not found in ConstantMap!\n";
727 std::cerr << "Unhandled global: " << *V << "\n";
732 return (void*)(intptr_t)MCE.getGlobalValueAddress(V);
737 #include "SparcV9CodeEmitter.inc"