Remove debug code emitter from the JIT
[oota-llvm.git] / lib / Target / PowerPC / PPCCodeEmitter.cpp
1 //===-- PPC32CodeEmitter.cpp - JIT Code Emitter for PowerPC32 -----*- C++ -*-=//
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 // This file defines the PowerPC 32-bit CodeEmitter and associated machinery to
11 // JIT-compile bytecode to native PowerPC.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC32JITInfo.h"
16 #include "PPC32TargetMachine.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/MachineCodeEmitter.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/Support/Debug.h"
22
23 namespace llvm {
24
25 namespace {
26   class JITResolver {
27     MachineCodeEmitter &MCE;
28
29     // LazyCodeGenMap - Keep track of call sites for functions that are to be
30     // lazily resolved.
31     std::map<unsigned, Function*> LazyCodeGenMap;
32
33     // LazyResolverMap - Keep track of the lazy resolver created for a
34     // particular function so that we can reuse them if necessary.
35     std::map<Function*, unsigned> LazyResolverMap;
36
37   public:
38     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
39     unsigned getLazyResolver(Function *F);
40     unsigned addFunctionReference(unsigned Address, Function *F);
41     
42   private:
43     unsigned emitStubForFunction(Function *F);
44     static void CompilationCallback();
45     unsigned resolveFunctionReference(unsigned RetAddr);
46   };
47
48   static JITResolver &getResolver(MachineCodeEmitter &MCE) {
49     static JITResolver *TheJITResolver = 0;
50     if (TheJITResolver == 0)
51       TheJITResolver = new JITResolver(MCE);
52     return *TheJITResolver;
53   }
54 }
55
56 unsigned JITResolver::getLazyResolver(Function *F) {
57   std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
58   if (I != LazyResolverMap.end() && I->first == F) return I->second;
59
60   unsigned Stub = emitStubForFunction(F);
61   LazyResolverMap.insert(I, std::make_pair(F, Stub));
62   return Stub;
63 }
64
65 /// addFunctionReference - This method is called when we need to emit the
66 /// address of a function that has not yet been emitted, so we don't know the
67 /// address.  Instead, we emit a call to the CompilationCallback method, and
68 /// keep track of where we are.
69 ///
70 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
71   LazyCodeGenMap[Address] = F;
72   return (intptr_t)&JITResolver::CompilationCallback;
73 }
74
75 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
76   std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
77   assert(I != LazyCodeGenMap.end() && "Not in map!");
78   Function *F = I->second;
79   LazyCodeGenMap.erase(I);
80   return MCE.forceCompilationOf(F);
81 }
82
83 /// emitStubForFunction - This method is used by the JIT when it needs to emit
84 /// the address of a function for a function whose code has not yet been
85 /// generated.  In order to do this, it generates a stub which jumps to the lazy
86 /// function compiler, which will eventually get fixed to call the function
87 /// directly.
88 ///
89 unsigned JITResolver::emitStubForFunction(Function *F) {
90   std::cerr << "PPC32CodeEmitter::emitStubForFunction() unimplemented!\n";
91   abort();
92   return 0;
93 }
94
95 void JITResolver::CompilationCallback() {
96   std::cerr << "PPC32CodeEmitter: CompilationCallback() unimplemented!";
97   abort();
98 }
99
100 namespace {
101   class PPC32CodeEmitter : public MachineFunctionPass {
102     TargetMachine &TM;
103     MachineCodeEmitter &MCE;
104
105     // Tracks which instruction references which BasicBlock
106     std::vector<std::pair<const BasicBlock*,
107                           std::pair<unsigned*,MachineInstr*> > > BBRefs;
108     // Tracks where each BasicBlock starts
109     std::map<const BasicBlock*, long> BBLocations;
110
111     /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr
112     ///
113     int64_t getMachineOpValue(MachineInstr &MI, MachineOperand &MO);
114
115     unsigned getAddressOfExternalFunction(Function *F);
116
117   public:
118     PPC32CodeEmitter(TargetMachine &T, MachineCodeEmitter &M) 
119       : TM(T), MCE(M) {}
120
121     const char *getPassName() const { return "PowerPC Machine Code Emitter"; }
122
123     /// runOnMachineFunction - emits the given MachineFunction to memory
124     ///
125     bool runOnMachineFunction(MachineFunction &MF);
126
127     /// emitBasicBlock - emits the given MachineBasicBlock to memory
128     ///
129     void emitBasicBlock(MachineBasicBlock &MBB);
130
131     /// emitWord - write a 32-bit word to memory at the current PC
132     ///
133     void emitWord(unsigned w) { MCE.emitWord(w); }
134     
135     /// getValueBit - return the particular bit of Val
136     ///
137     unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; }
138
139     /// getBinaryCodeForInstr - This function, generated by the
140     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
141     /// machine instructions.
142     ///
143     unsigned getBinaryCodeForInstr(MachineInstr &MI);
144   };
145 }
146
147 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
148 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
149 /// actually outputting the machine code and resolving things like the address
150 /// of functions.  This method should returns true if machine code emission is
151 /// not supported.
152 ///
153 bool PPC32TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
154                                                     MachineCodeEmitter &MCE) {
155   // Keep as `true' until this is a functional JIT to allow llvm-gcc to build
156   return true;
157
158   // Machine code emitter pass for PowerPC
159   PM.add(new PPC32CodeEmitter(*this, MCE)); 
160   // Delete machine code for this function after emitting it
161   PM.add(createMachineCodeDeleter());
162   return false;
163 }
164
165 bool PPC32CodeEmitter::runOnMachineFunction(MachineFunction &MF) {
166   MCE.startFunction(MF);
167   MCE.emitConstantPool(MF.getConstantPool());
168   for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
169     emitBasicBlock(*BB);
170   MCE.finishFunction(MF);
171
172   // Resolve branches to BasicBlocks for the entire function
173   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
174     long Location = BBLocations[BBRefs[i].first];
175     unsigned *Ref = BBRefs[i].second.first;
176     MachineInstr *MI = BBRefs[i].second.second;
177     DEBUG(std::cerr << "Fixup @ " << std::hex << Ref << " to 0x" << Location
178                     << " in instr: " << std::dec << *MI);
179     for (unsigned ii = 0, ee = MI->getNumOperands(); ii != ee; ++ii) {
180       MachineOperand &op = MI->getOperand(ii);
181       if (op.isPCRelativeDisp()) {
182         // the instruction's branch target is made such that it branches to
183         // PC + (branchTarget * 4), so undo that arithmetic here:
184         // Location is the target of the branch
185         // Ref is the location of the instruction, and hence the PC
186         int64_t branchTarget = (Location - (long)Ref) >> 2;
187         MI->SetMachineOperandConst(ii, MachineOperand::MO_SignExtendedImmed,
188                                    branchTarget);
189         unsigned fixedInstr = PPC32CodeEmitter::getBinaryCodeForInstr(*MI);
190         MCE.emitWordAt(fixedInstr, Ref);
191         break;
192       }
193     }
194   }
195   BBRefs.clear();
196   BBLocations.clear();
197
198   return false;
199 }
200
201 void PPC32CodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) {
202   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
203     emitWord(getBinaryCodeForInstr(*I));
204 }
205
206 unsigned PPC32CodeEmitter::getAddressOfExternalFunction(Function *F) {
207   static std::map<Function*, unsigned> ExternalFn2Addr;
208   std::map<Function*, unsigned>::iterator Addr = ExternalFn2Addr.find(F);
209
210   if (Addr == ExternalFn2Addr.end())
211     ExternalFn2Addr[F] = MCE.forceCompilationOf(F);
212   return ExternalFn2Addr[F];
213 }
214
215 int64_t PPC32CodeEmitter::getMachineOpValue(MachineInstr &MI, 
216                                             MachineOperand &MO) {
217   int64_t rv = 0; // Return value; defaults to 0 for unhandled cases
218                   // or things that get fixed up later by the JIT.
219   if (MO.isRegister()) {
220     rv = MO.getReg();
221   } else if (MO.isImmediate()) {
222     rv = MO.getImmedValue();
223   } else if (MO.isGlobalAddress()) {
224     GlobalValue *GV = MO.getGlobal();
225     intptr_t Addr = (intptr_t)MCE.getGlobalValueAddress(GV);
226     if (Addr == 0) {
227       if (Function *F = dyn_cast<Function>(GV)) {
228         if (F->isExternal())
229           rv = getAddressOfExternalFunction(F);
230         else {
231           // Function has not yet been code generated!
232           getResolver(MCE).addFunctionReference(MCE.getCurrentPCValue(), F);
233           // Delayed resolution...
234           return (intptr_t)getResolver(MCE).getLazyResolver(F);
235         }
236       } else if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
237         if (GVar->isExternal())
238           rv = MCE.getGlobalValueAddress(MO.getSymbolName());
239         else {
240           std::cerr << "PPC32CodeEmitter: External global addr not found: " 
241                     << *GVar;
242           abort();
243         }
244       }
245     }
246     if (MO.isPCRelative()) { // Global variable reference
247       rv = (Addr - MCE.getCurrentPCValue()) >> 2;
248     }
249   } else if (MO.isMachineBasicBlock()) {
250     const BasicBlock *BB = MO.getMachineBasicBlock()->getBasicBlock();
251     unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue();
252     BBRefs.push_back(std::make_pair(BB, std::make_pair(CurrPC, &MI)));
253   } else if (MO.isConstantPoolIndex()) {
254     unsigned index = MO.getConstantPoolIndex();
255     rv = MCE.getConstantPoolEntryAddress(index);
256   } else if (MO.isFrameIndex()) {
257     std::cerr << "PPC32CodeEmitter: error: Frame index unhandled!\n";
258     abort();
259   } else {
260     std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
261     abort();
262   }
263
264   return rv;
265 }
266
267
268 void *PPC32JITInfo::getJITStubForFunction(Function *F, MachineCodeEmitter &MCE){
269   return (void*)((unsigned long)getResolver(MCE).getLazyResolver(F));
270 }
271
272 void PPC32JITInfo::replaceMachineCodeForFunction (void *Old, void *New) {
273   std::cerr << "PPC32JITInfo::replaceMachineCodeForFunction not implemented\n";
274   abort();
275 }
276
277 #include "PPC32GenCodeEmitter.inc"
278
279 } // end llvm namespace
280