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/MachineFunctionInfo.h"
12 #include "llvm/CodeGen/MachineFunctionPass.h"
13 #include "llvm/CodeGen/MachineInstr.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Target/TargetData.h"
16 #include "Support/hash_set"
17 #include "SparcInternals.h"
18 #include "SparcV9CodeEmitter.h"
20 bool UltraSparc::addPassesToEmitMachineCode(PassManager &PM,
21 MachineCodeEmitter &MCE) {
22 //PM.add(new SparcV9CodeEmitter(MCE));
23 //MachineCodeEmitter *M = MachineCodeEmitter::createDebugMachineCodeEmitter();
24 MachineCodeEmitter *M = MachineCodeEmitter::createFilePrinterEmitter(MCE);
25 PM.add(new SparcV9CodeEmitter(this, *M));
26 PM.add(createMachineCodeDestructionPass()); // Free stuff no longer needed
32 MachineCodeEmitter &MCE;
34 // LazyCodeGenMap - Keep track of call sites for functions that are to be
36 std::map<unsigned, Function*> LazyCodeGenMap;
38 // LazyResolverMap - Keep track of the lazy resolver created for a
39 // particular function so that we can reuse them if necessary.
40 std::map<Function*, unsigned> LazyResolverMap;
42 JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
43 unsigned getLazyResolver(Function *F);
44 unsigned addFunctionReference(unsigned Address, Function *F);
47 unsigned emitStubForFunction(Function *F);
48 static void CompilationCallback();
49 unsigned resolveFunctionReference(unsigned RetAddr);
52 JITResolver *TheJITResolver;
55 /// addFunctionReference - This method is called when we need to emit the
56 /// address of a function that has not yet been emitted, so we don't know the
57 /// address. Instead, we emit a call to the CompilationCallback method, and
58 /// keep track of where we are.
60 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
61 LazyCodeGenMap[Address] = F;
62 return (intptr_t)&JITResolver::CompilationCallback;
65 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
66 std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
67 assert(I != LazyCodeGenMap.end() && "Not in map!");
68 Function *F = I->second;
69 LazyCodeGenMap.erase(I);
70 return MCE.forceCompilationOf(F);
73 unsigned JITResolver::getLazyResolver(Function *F) {
74 std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
75 if (I != LazyResolverMap.end() && I->first == F) return I->second;
77 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
79 unsigned Stub = emitStubForFunction(F);
80 LazyResolverMap.insert(I, std::make_pair(F, Stub));
84 void JITResolver::CompilationCallback() {
85 uint64_t *StackPtr = (uint64_t*)__builtin_frame_address(0);
86 uint64_t RetAddr = (uint64_t)(intptr_t)__builtin_return_address(0);
89 std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
90 << " SP=0x" << (unsigned)StackPtr << std::dec
91 << ": Resolving call to function: "
92 << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n";
95 std::cerr << "Sparc's JIT Resolver not implemented!\n";
99 unsigned NewVal = TheJITResolver->resolveFunctionReference((void*)RetAddr);
101 // Rewrite the call target... so that we don't fault every time we execute
103 *(unsigned*)RetAddr = NewVal;
105 // Change the return address to reexecute the call instruction...
110 /// emitStubForFunction - This method is used by the JIT when it needs to emit
111 /// the address of a function for a function whose code has not yet been
112 /// generated. In order to do this, it generates a stub which jumps to the lazy
113 /// function compiler, which will eventually get fixed to call the function
116 unsigned JITResolver::emitStubForFunction(Function *F) {
118 MCE.startFunctionStub(*F, 6);
119 MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
121 unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
122 MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
124 MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
125 return (intptr_t)MCE.finishFunctionStub(*F);
127 std::cerr << "Sparc's JITResolver::emitStubForFunction() not implemented!\n";
132 void SparcV9CodeEmitter::emitConstant(unsigned Val, unsigned Size) {
133 // Output the constant in big endian byte order...
135 for (int i = Size-1; i >= 0; --i) {
136 byteVal = Val >> 8*i;
137 MCE->emitByte(byteVal & 255);
141 unsigned getRealRegNum(unsigned fakeReg, unsigned regClass) {
143 case UltraSparcRegInfo::IntRegType: {
145 static const unsigned IntRegMap[] = {
146 // "o0", "o1", "o2", "o3", "o4", "o5", "o7",
147 8, 9, 10, 11, 12, 13, 15,
148 // "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
149 16, 17, 18, 19, 20, 21, 22, 23,
150 // "i0", "i1", "i2", "i3", "i4", "i5",
151 24, 25, 26, 27, 28, 29,
154 // "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
155 0, 1, 2, 3, 4, 5, 6, 7,
160 return IntRegMap[fakeReg];
163 case UltraSparcRegInfo::FPSingleRegType: {
166 case UltraSparcRegInfo::FPDoubleRegType: {
169 case UltraSparcRegInfo::FloatCCRegType: {
173 case UltraSparcRegInfo::IntCCRegType: {
177 assert(0 && "Invalid unified register number in getRegType");
182 int64_t SparcV9CodeEmitter::getMachineOpValue(MachineInstr &MI,
183 MachineOperand &MO) {
184 int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
185 // or things that get fixed up later by the JIT.
187 if (MO.isVirtualRegister()) {
188 std::cerr << "ERROR: virtual register found in machine code.\n";
190 } else if (MO.isPCRelativeDisp()) {
191 Value *V = MO.getVRegValue();
192 if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
193 std::cerr << "Saving reference to BB (VReg)\n";
194 unsigned* CurrPC = (unsigned*)(intptr_t)MCE->getCurrentPCValue();
195 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
196 } else if (Constant *C = dyn_cast<Constant>(V)) {
197 if (ConstantMap.find(C) != ConstantMap.end())
198 rv = (int64_t)(intptr_t)ConstantMap[C] - MCE->getCurrentPCValue();
200 std::cerr << "ERROR: constant not in map:" << MO << "\n";
204 std::cerr << "ERROR: PC relative disp unhandled:" << MO << "\n";
207 } else if (MO.isPhysicalRegister()) {
208 // This is necessary because the Sparc doesn't actually lay out registers
209 // in the real fashion -- it skips those that it chooses not to allocate,
210 // i.e. those that are the SP, etc.
211 unsigned fakeReg = MO.getReg(), realReg, regClass, regType;
212 regType = TM->getRegInfo().getRegType(fakeReg);
213 // At least map fakeReg into its class
214 fakeReg = TM->getRegInfo().getClassRegNum(fakeReg, regClass);
215 // Find the real register number for use in an instruction
216 realReg = getRealRegNum(fakeReg, regClass);
217 std::cerr << "Reg[" << std::dec << fakeReg << "] = " << realReg << "\n";
219 } else if (MO.isImmediate()) {
220 rv = MO.getImmedValue();
221 } else if (MO.isGlobalAddress()) {
223 (intptr_t)getGlobalAddress(cast<GlobalValue>(MO.getVRegValue()),
224 MI, MO.isPCRelative());
225 } else if (MO.isMachineBasicBlock()) {
226 // Duplicate code of the above case for VirtualRegister, BasicBlock...
227 // It should really hit this case, but Sparc backend uses VRegs instead
228 std::cerr << "Saving reference to MBB\n";
229 BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
230 unsigned* CurrPC = (unsigned*)(intptr_t)MCE->getCurrentPCValue();
231 BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
232 } else if (MO.isExternalSymbol()) {
233 // Sparc backend doesn't generate this (yet...)
234 std::cerr << "ERROR: External symbol unhandled: " << MO << "\n";
236 } else if (MO.isFrameIndex()) {
237 // Sparc backend doesn't generate this (yet...)
238 int FrameIndex = MO.getFrameIndex();
239 std::cerr << "ERROR: Frame index unhandled.\n";
241 } else if (MO.isConstantPoolIndex()) {
242 // Sparc backend doesn't generate this (yet...)
243 std::cerr << "ERROR: Constant Pool index unhandled.\n";
246 std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
250 // Finally, deal with the various bitfield-extracting functions that
251 // are used in SPARC assembly. (Some of these make no sense in combination
252 // with some of the above; we'll trust that the instruction selector
253 // will not produce nonsense, and not check for valid combinations here.)
254 if (MO.opLoBits32()) { // %lo(val)
256 } else if (MO.opHiBits32()) { // %lm(val)
257 return (rv >> 10) & 0x03fffff;
258 } else if (MO.opLoBits64()) { // %hm(val)
259 return (rv >> 32) & 0x03ff;
260 } else if (MO.opHiBits64()) { // %hh(val)
262 } else { // (unadorned) val
267 unsigned SparcV9CodeEmitter::getValueBit(int64_t Val, unsigned bit) {
272 void* SparcV9CodeEmitter::convertAddress(intptr_t Addr, bool isPCRelative) {
274 return (void*)(Addr - (intptr_t)MCE->getCurrentPCValue());
282 bool SparcV9CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
283 std::cerr << "Starting function " << MF.getFunction()->getName()
284 << ", address: " << "0x" << std::hex
285 << (long)MCE->getCurrentPCValue() << "\n";
287 MCE->startFunction(MF);
289 // FIXME: the Sparc backend does not use the ConstantPool!!
290 //MCE->emitConstantPool(MF.getConstantPool());
292 // Instead, the Sparc backend has its own constant pool implementation:
293 const hash_set<const Constant*> &pool = MF.getInfo()->getConstantPoolValues();
294 for (hash_set<const Constant*>::const_iterator I = pool.begin(),
295 E = pool.end(); I != E; ++I)
297 const Constant *C = *I;
298 // For now we just allocate some memory on the heap, this can be
299 // dramatically improved.
300 const Type *Ty = ((Value*)C)->getType();
301 void *Addr = malloc(TM->getTargetData().getTypeSize(Ty));
303 //TheVM.InitializeMemory(C, Addr);
304 std::cerr << "Adding ConstantMap[" << C << "]=" << std::dec << Addr << "\n";
305 ConstantMap[C] = Addr;
308 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
310 MCE->finishFunction(MF);
312 std::cerr << "Finishing function " << MF.getFunction()->getName() << "\n";
314 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
315 long Location = BBLocations[BBRefs[i].first];
316 unsigned *Ref = BBRefs[i].second.first;
317 MachineInstr *MI = BBRefs[i].second.second;
318 std::cerr << "Fixup @" << std::hex << Ref << " to " << Location
319 << " in instr: " << std::dec << *MI << "\n";
322 // Resolve branches to BasicBlocks for the entire function
323 for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
324 long Location = BBLocations[BBRefs[i].first];
325 unsigned *Ref = BBRefs[i].second.first;
326 MachineInstr *MI = BBRefs[i].second.second;
327 std::cerr << "attempting to resolve BB: " << i << "\n";
328 for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
329 MachineOperand &op = MI->getOperand(ii);
330 if (op.isPCRelativeDisp()) {
331 // the instruction's branch target is made such that it branches to
332 // PC + (br target * 4), so undo that arithmetic here:
333 // Location is the target of the branch
334 // Ref is the location of the instruction, and hence the PC
335 unsigned branchTarget = (Location - (long)Ref) >> 2;
337 bool loBits32=false, hiBits32=false, loBits64=false, hiBits64=false;
338 if (op.opLoBits32()) { loBits32=true; }
339 if (op.opHiBits32()) { hiBits32=true; }
340 if (op.opLoBits64()) { loBits64=true; }
341 if (op.opHiBits64()) { hiBits64=true; }
342 MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
344 if (loBits32) { MI->setOperandLo32(ii); }
345 else if (hiBits32) { MI->setOperandHi32(ii); }
346 else if (loBits64) { MI->setOperandLo64(ii); }
347 else if (hiBits64) { MI->setOperandHi64(ii); }
348 std::cerr << "Rewrote BB ref: ";
349 unsigned fixedInstr = SparcV9CodeEmitter::getBinaryCodeForInstr(*MI);
361 void SparcV9CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
362 currBB = MBB.getBasicBlock();
363 BBLocations[currBB] = MCE->getCurrentPCValue();
364 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
365 emitInstruction(**I);
368 void SparcV9CodeEmitter::emitInstruction(MachineInstr &MI) {
369 emitConstant(getBinaryCodeForInstr(MI), 4);
372 void* SparcV9CodeEmitter::getGlobalAddress(GlobalValue *V, MachineInstr &MI,
375 if (isPCRelative) { // must be a call, this is a major hack!
376 // Try looking up the function to see if it is already compiled!
377 if (void *Addr = (void*)(intptr_t)MCE->getGlobalValueAddress(V)) {
378 intptr_t CurByte = MCE->getCurrentPCValue();
379 // The real target of the call is Addr = PC + (target * 4)
380 // CurByte is the PC, Addr we just received
381 return (void*) (((long)Addr - (long)CurByte) >> 2);
383 if (Function *F = dyn_cast<Function>(V)) {
384 // Function has not yet been code generated!
385 TheJITResolver->addFunctionReference(MCE->getCurrentPCValue(),
387 // Delayed resolution...
389 (void*)(intptr_t)TheJITResolver->getLazyResolver(cast<Function>(V));
391 } else if (Constant *C = ConstantPointerRef::get(V)) {
392 if (ConstantMap.find(C) != ConstantMap.end()) {
393 return ConstantMap[C];
395 std::cerr << "Constant: 0x" << std::hex << &*C << std::dec
396 << ", " << *V << " not found in ConstantMap!\n";
401 } else if (const GlobalVariable *G = dyn_cast<GlobalVariable>(V)) {
402 if (G->isConstant()) {
403 const Constant* C = G->getInitializer();
404 if (ConstantMap.find(C) != ConstantMap.end()) {
405 return ConstantMap[C];
407 std::cerr << "Constant: " << *G << " not found in ConstantMap!\n";
411 std::cerr << "Variable: " << *G << " address not found!\n";
416 std::cerr << "Unhandled global: " << *V << "\n";
421 return convertAddress((intptr_t)MCE->getGlobalValueAddress(V),
427 #include "SparcV9CodeEmitter.inc"