Add debug-only=jit printout, so we see when lazily resolved symbols are
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
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 contains the pass that transforms the X86 machine instructions into
11 // actual executable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "jit"
16 #include "X86TargetMachine.h"
17 #include "X86.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Config/alloca.h"
27 using namespace llvm;
28
29 namespace {
30   Statistic<>
31   NumEmitted("x86-emitter", "Number of machine instructions emitted");
32
33   class JITResolver {
34     MachineCodeEmitter &MCE;
35
36     // LazyCodeGenMap - Keep track of call sites for functions that are to be
37     // lazily resolved.
38     std::map<unsigned, Function*> LazyCodeGenMap;
39
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*, unsigned> LazyResolverMap;
43   public:
44     JITResolver(MachineCodeEmitter &mce) : MCE(mce) {}
45     unsigned getLazyResolver(Function *F);
46     unsigned addFunctionReference(unsigned Address, Function *F);
47     
48   private:
49     unsigned emitStubForFunction(Function *F);
50     static void CompilationCallback();
51     unsigned resolveFunctionReference(unsigned RetAddr);
52   };
53
54   static JITResolver &getResolver(MachineCodeEmitter &MCE) {
55     static JITResolver *TheJITResolver = 0;
56     if (TheJITResolver == 0)
57       TheJITResolver = new JITResolver(MCE);
58     return *TheJITResolver;
59   }
60 }
61
62
63 void *X86JITInfo::getJITStubForFunction(Function *F, MachineCodeEmitter &MCE) {
64   return (void*)(intptr_t)getResolver(MCE).getLazyResolver(F);
65 }
66
67 void X86JITInfo::replaceMachineCodeForFunction (void *Old, void *New) {
68   unsigned char *OldByte = (unsigned char *) Old;
69   *OldByte++ = 0xE9;                // Emit JMP opcode.
70   int32_t *OldWord = (int32_t *) OldByte;
71   int32_t NewAddr = (intptr_t) New;
72   int32_t OldAddr = (intptr_t) OldWord;
73   *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
74 }
75
76 /// addFunctionReference - This method is called when we need to emit the
77 /// address of a function that has not yet been emitted, so we don't know the
78 /// address.  Instead, we emit a call to the CompilationCallback method, and
79 /// keep track of where we are.
80 ///
81 unsigned JITResolver::addFunctionReference(unsigned Address, Function *F) {
82   DEBUG(std::cerr << "Emitting lazily resolved reference to function '"
83         << F->getName() << "' at address " << std::hex << Address << "\n");
84   LazyCodeGenMap[Address] = F;  
85   return (intptr_t)&JITResolver::CompilationCallback;
86 }
87
88 unsigned JITResolver::resolveFunctionReference(unsigned RetAddr) {
89   std::map<unsigned, Function*>::iterator I = LazyCodeGenMap.find(RetAddr);
90   assert(I != LazyCodeGenMap.end() && "Not in map!");
91   Function *F = I->second;
92   LazyCodeGenMap.erase(I);
93   return MCE.forceCompilationOf(F);
94 }
95
96 unsigned JITResolver::getLazyResolver(Function *F) {
97   std::map<Function*, unsigned>::iterator I = LazyResolverMap.lower_bound(F);
98   if (I != LazyResolverMap.end() && I->first == F) return I->second;
99   
100 //std::cerr << "Getting lazy resolver for : " << ((Value*)F)->getName() << "\n";
101
102   unsigned Stub = emitStubForFunction(F);
103   LazyResolverMap.insert(I, std::make_pair(F, Stub));
104   return Stub;
105 }
106
107 #ifdef _MSC_VER
108 #pragma optimize("y", off)
109 #endif
110
111 void JITResolver::CompilationCallback() {
112 #ifdef _MSC_VER
113   unsigned *StackPtr, RetAddr;
114   __asm mov StackPtr, ebp;
115   __asm mov eax, DWORD PTR [ebp + 4];
116   __asm mov RetAddr, eax;
117 #else
118   unsigned *StackPtr = (unsigned*)__builtin_frame_address(0);
119   unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(0);
120 #endif
121   assert(StackPtr[1] == RetAddr &&
122          "Could not find return address on the stack!");
123
124   // It's a stub if there is an interrupt marker after the call...
125   bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
126
127 #ifndef _MSC_VER
128   // FIXME FIXME FIXME FIXME: __builtin_frame_address doesn't work if frame
129   // pointer elimination has been performed.  Having a variable sized alloca
130   // disables frame pointer elimination currently, even if it's dead.  This is a
131   // gross hack.
132   alloca(10+isStub);
133   // FIXME FIXME FIXME FIXME
134 #endif
135
136   // The call instruction should have pushed the return value onto the stack...
137   RetAddr -= 4;  // Backtrack to the reference itself...
138
139 #if 0
140   DEBUG(std::cerr << "In callback! Addr=0x" << std::hex << RetAddr
141                   << " ESP=0x" << (unsigned)StackPtr << std::dec
142                   << ": Resolving call to function: "
143                   << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
144 #endif
145
146   // Sanity check to make sure this really is a call instruction...
147   assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
148   
149   JITResolver &JR = getResolver(*(MachineCodeEmitter*)0);
150   unsigned NewVal = JR.resolveFunctionReference(RetAddr);
151
152   // Rewrite the call target... so that we don't fault every time we execute
153   // the call.
154   *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;    
155
156   if (isStub) {
157     // If this is a stub, rewrite the call into an unconditional branch
158     // instruction so that two return addresses are not pushed onto the stack
159     // when the requested function finally gets called.  This also makes the
160     // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
161     ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
162   }
163
164   // Change the return address to reexecute the call instruction...
165   StackPtr[1] -= 5;
166 }
167
168 #ifdef _MSC_VER
169 #pragma optimize( "", on )
170 #endif
171
172 /// emitStubForFunction - This method is used by the JIT when it needs to emit
173 /// the address of a function for a function whose code has not yet been
174 /// generated.  In order to do this, it generates a stub which jumps to the lazy
175 /// function compiler, which will eventually get fixed to call the function
176 /// directly.
177 ///
178 unsigned JITResolver::emitStubForFunction(Function *F) {
179   MCE.startFunctionStub(*F, 6);
180   MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...
181
182   unsigned Address = addFunctionReference(MCE.getCurrentPCValue(), F);
183   MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
184
185   MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
186   return (intptr_t)MCE.finishFunctionStub(*F);
187 }
188
189
190 namespace {
191   class Emitter : public MachineFunctionPass {
192     const X86InstrInfo  *II;
193     MachineCodeEmitter  &MCE;
194     std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
195     std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
196   public:
197     explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
198     Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
199         : II(&ii), MCE(mce) {}
200
201     bool runOnMachineFunction(MachineFunction &MF);
202
203     virtual const char *getPassName() const {
204       return "X86 Machine Code Emitter";
205     }
206
207     void emitInstruction(const MachineInstr &MI);
208
209   private:
210     void emitBasicBlock(const MachineBasicBlock &MBB);
211
212     void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
213     void emitMaybePCRelativeValue(unsigned Address, bool isPCRelative);
214     void emitGlobalAddressForCall(GlobalValue *GV);
215     void emitGlobalAddressForPtr(GlobalValue *GV, int Disp = 0);
216
217     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
218     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
219     void emitConstant(unsigned Val, unsigned Size);
220
221     void emitMemModRMByte(const MachineInstr &MI,
222                           unsigned Op, unsigned RegOpcodeField);
223
224   };
225 }
226
227 // This function is required by X86AsmPrinter.cpp to work around GAS bugs
228 void llvm::X86::emitInstruction(MachineCodeEmitter& mce,
229                                 const X86InstrInfo& ii,
230                                 const MachineInstr& mi)
231 {
232     Emitter(mce, ii).emitInstruction(mi);
233 }
234
235 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
236 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
237 /// actually outputting the machine code and resolving things like the address
238 /// of functions.  This method should returns true if machine code emission is
239 /// not supported.
240 ///
241 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
242                                                   MachineCodeEmitter &MCE) {
243   PM.add(new Emitter(MCE));
244   // Delete machine code for this function
245   PM.add(createMachineCodeDeleter());
246   return false;
247 }
248
249 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
250   II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
251
252   MCE.startFunction(MF);
253   MCE.emitConstantPool(MF.getConstantPool());
254   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
255     emitBasicBlock(*I);
256   MCE.finishFunction(MF);
257
258   // Resolve all forward branches now...
259   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
260     unsigned Location = BasicBlockAddrs[BBRefs[i].first];
261     unsigned Ref = BBRefs[i].second;
262     MCE.emitWordAt (Location-Ref-4, (unsigned*)(intptr_t)Ref);
263   }
264   BBRefs.clear();
265   BasicBlockAddrs.clear();
266   return false;
267 }
268
269 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
270   if (uint64_t Addr = MCE.getCurrentPCValue())
271     BasicBlockAddrs[&MBB] = Addr;
272
273   for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end(); I != E; ++I)
274     emitInstruction(*I);
275 }
276
277 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
278 /// the specified basic block, or if the basic block hasn't been emitted yet
279 /// (because this is a forward branch), it keeps track of the information
280 /// necessary to resolve this address later (and emits a dummy value).
281 ///
282 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
283   // FIXME: Emit backward branches directly
284   BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
285   MCE.emitWord(0);
286 }
287
288 /// emitMaybePCRelativeValue - Emit a 32-bit address which may be PC relative.
289 ///
290 void Emitter::emitMaybePCRelativeValue(unsigned Address, bool isPCRelative) {
291   if (isPCRelative)
292     MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
293   else
294     MCE.emitWord(Address);
295 }
296
297 /// emitGlobalAddressForCall - Emit the specified address to the code stream
298 /// assuming this is part of a function call, which is PC relative.
299 ///
300 void Emitter::emitGlobalAddressForCall(GlobalValue *GV) {
301   // Get the address from the backend...
302   unsigned Address = MCE.getGlobalValueAddress(GV);
303   
304   if (Address == 0) {
305     // FIXME: this is JIT specific!
306     Address = getResolver(MCE).addFunctionReference(MCE.getCurrentPCValue(),
307                                                     cast<Function>(GV));
308   }
309   emitMaybePCRelativeValue(Address, true);
310 }
311
312 /// emitGlobalAddress - Emit the specified address to the code stream assuming
313 /// this is part of a "take the address of a global" instruction, which is not
314 /// PC relative.
315 ///
316 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, int Disp /* = 0 */) {
317   // Get the address from the backend...
318   unsigned Address = MCE.getGlobalValueAddress(GV);
319
320   // If the machine code emitter doesn't know what the address IS yet, we have
321   // to take special measures.
322   //
323   if (Address == 0) {
324     // FIXME: this is JIT specific!
325     Address = getResolver(MCE).getLazyResolver((Function*)GV);
326   }
327
328   emitMaybePCRelativeValue(Address + Disp, false);
329 }
330
331
332
333 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
334 ///
335 namespace N86 {
336   enum {
337     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
338   };
339 }
340
341
342 // getX86RegNum - This function maps LLVM register identifiers to their X86
343 // specific numbering, which is used in various places encoding instructions.
344 //
345 static unsigned getX86RegNum(unsigned RegNo) {
346   switch(RegNo) {
347   case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
348   case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
349   case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
350   case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
351   case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
352   case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
353   case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
354   case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
355
356   case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
357   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
358     return RegNo-X86::ST0;
359   default:
360     assert(MRegisterInfo::isVirtualRegister(RegNo) &&
361            "Unknown physical register!");
362     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
363     return 0;
364   }
365 }
366
367 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
368                                       unsigned RM) {
369   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
370   return RM | (RegOpcode << 3) | (Mod << 6);
371 }
372
373 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
374   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
375 }
376
377 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
378   // SIB byte is in the same format as the ModRMByte...
379   MCE.emitByte(ModRMByte(SS, Index, Base));
380 }
381
382 void Emitter::emitConstant(unsigned Val, unsigned Size) {
383   // Output the constant in little endian byte order...
384   for (unsigned i = 0; i != Size; ++i) {
385     MCE.emitByte(Val & 255);
386     Val >>= 8;
387   }
388 }
389
390 static bool isDisp8(int Value) {
391   return Value == (signed char)Value;
392 }
393
394 void Emitter::emitMemModRMByte(const MachineInstr &MI,
395                                unsigned Op, unsigned RegOpcodeField) {
396   const MachineOperand &Op3 = MI.getOperand(Op+3);
397   GlobalValue *GV = 0;
398   int DispVal = 0;
399
400   if (Op3.isGlobalAddress()) {
401     GV = Op3.getGlobal();
402     DispVal = Op3.getOffset();
403   } else {
404     DispVal = Op3.getImmedValue();
405   }
406
407   const MachineOperand &Base     = MI.getOperand(Op);
408   const MachineOperand &Scale    = MI.getOperand(Op+1);
409   const MachineOperand &IndexReg = MI.getOperand(Op+2);
410
411   unsigned BaseReg = 0;
412
413   if (Base.isConstantPoolIndex()) {
414     // Emit a direct address reference [disp32] where the displacement of the
415     // constant pool entry is controlled by the MCE.
416     assert(!GV && "Constant Pool reference cannot be relative to global!");
417     DispVal += MCE.getConstantPoolEntryAddress(Base.getConstantPoolIndex());
418   } else {
419     BaseReg = Base.getReg();
420   }
421
422   // Is a SIB byte needed?
423   if (IndexReg.getReg() == 0 && BaseReg != X86::ESP) {
424     if (BaseReg == 0) {  // Just a displacement?
425       // Emit special case [disp32] encoding
426       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
427       if (GV)
428         emitGlobalAddressForPtr(GV, DispVal);
429       else
430         emitConstant(DispVal, 4);
431     } else {
432       unsigned BaseRegNo = getX86RegNum(BaseReg);
433       if (GV) {
434         // Emit the most general non-SIB encoding: [REG+disp32]
435         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
436         emitGlobalAddressForPtr(GV, DispVal);
437       } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
438         // Emit simple indirect register encoding... [EAX] f.e.
439         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
440       } else if (isDisp8(DispVal)) {
441         // Emit the disp8 encoding... [REG+disp8]
442         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
443         emitConstant(DispVal, 1);
444       } else {
445         // Emit the most general non-SIB encoding: [REG+disp32]
446         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
447         emitConstant(DispVal, 4);
448       }
449     }
450
451   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
452     assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
453
454     bool ForceDisp32 = false;
455     bool ForceDisp8  = false;
456     if (BaseReg == 0) {
457       // If there is no base register, we emit the special case SIB byte with
458       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
459       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
460       ForceDisp32 = true;
461     } else if (GV) {
462       // Emit the normal disp32 encoding...
463       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
464       ForceDisp32 = true;
465     } else if (DispVal == 0 && BaseReg != X86::EBP) {
466       // Emit no displacement ModR/M byte
467       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
468     } else if (isDisp8(DispVal)) {
469       // Emit the disp8 encoding...
470       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
471       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
472     } else {
473       // Emit the normal disp32 encoding...
474       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
475     }
476
477     // Calculate what the SS field value should be...
478     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
479     unsigned SS = SSTable[Scale.getImmedValue()];
480
481     if (BaseReg == 0) {
482       // Handle the SIB byte for the case where there is no base.  The
483       // displacement has already been output.
484       assert(IndexReg.getReg() && "Index register must be specified!");
485       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
486     } else {
487       unsigned BaseRegNo = getX86RegNum(BaseReg);
488       unsigned IndexRegNo;
489       if (IndexReg.getReg())
490         IndexRegNo = getX86RegNum(IndexReg.getReg());
491       else
492         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
493       emitSIBByte(SS, IndexRegNo, BaseRegNo);
494     }
495
496     // Do we need to output a displacement?
497     if (DispVal != 0 || ForceDisp32 || ForceDisp8) {
498       if (!ForceDisp32 && isDisp8(DispVal))
499         emitConstant(DispVal, 1);
500       else if (GV)
501         emitGlobalAddressForPtr(GV, DispVal);
502       else
503         emitConstant(DispVal, 4);
504     }
505   }
506 }
507
508 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
509   switch (Desc.TSFlags & X86II::ImmMask) {
510   case X86II::Imm8:   return 1;
511   case X86II::Imm16:  return 2;
512   case X86II::Imm32:  return 4;
513   default: assert(0 && "Immediate size not set!");
514     return 0;
515   }
516 }
517
518 void Emitter::emitInstruction(const MachineInstr &MI) {
519   NumEmitted++;  // Keep track of the # of mi's emitted
520
521   unsigned Opcode = MI.getOpcode();
522   const TargetInstrDescriptor &Desc = II->get(Opcode);
523
524   // Emit the repeat opcode prefix as needed.
525   if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
526
527   // Emit instruction prefixes if necessary
528   if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
529
530   switch (Desc.TSFlags & X86II::Op0Mask) {
531   case X86II::TB:
532     MCE.emitByte(0x0F);   // Two-byte opcode prefix
533     break;
534   case X86II::REP: break; // already handled.
535   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
536   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
537     MCE.emitByte(0xD8+
538                  (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
539                                    >> X86II::Op0Shift));
540     break; // Two-byte opcode prefix
541   default: assert(0 && "Invalid prefix!");
542   case 0: break;  // No prefix!
543   }
544
545   unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
546   switch (Desc.TSFlags & X86II::FormMask) {
547   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
548   case X86II::Pseudo:
549     if (Opcode != X86::IMPLICIT_USE &&
550         Opcode != X86::IMPLICIT_DEF &&
551         Opcode != X86::FP_REG_KILL)
552       std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
553     break;
554
555   case X86II::RawFrm:
556     MCE.emitByte(BaseOpcode);
557     if (MI.getNumOperands() == 1) {
558       const MachineOperand &MO = MI.getOperand(0);
559       if (MO.isMachineBasicBlock()) {
560         emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
561       } else if (MO.isGlobalAddress()) {
562         assert(MO.isPCRelative() && "Call target is not PC Relative?");
563         emitGlobalAddressForCall(MO.getGlobal());
564       } else if (MO.isExternalSymbol()) {
565         unsigned Address = MCE.getGlobalValueAddress(MO.getSymbolName());
566         assert(Address && "Unknown external symbol!");
567         emitMaybePCRelativeValue(Address, MO.isPCRelative());
568       } else if (MO.isImmediate()) {
569         emitConstant(MO.getImmedValue(), sizeOfImm(Desc));        
570       } else {
571         assert(0 && "Unknown RawFrm operand!");
572       }
573     }
574     break;
575
576   case X86II::AddRegFrm:
577     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
578     if (MI.getNumOperands() == 2) {
579       const MachineOperand &MO1 = MI.getOperand(1);
580       if (Value *V = MO1.getVRegValueOrNull()) {
581         assert(sizeOfImm(Desc) == 4 &&
582                "Don't know how to emit non-pointer values!");
583         emitGlobalAddressForPtr(cast<GlobalValue>(V));
584       } else if (MO1.isGlobalAddress()) {
585         assert(sizeOfImm(Desc) == 4 &&
586                "Don't know how to emit non-pointer values!");
587         assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
588         emitGlobalAddressForPtr(MO1.getGlobal(), MO1.getOffset());
589       } else if (MO1.isExternalSymbol()) {
590         assert(sizeOfImm(Desc) == 4 &&
591                "Don't know how to emit non-pointer values!");
592         unsigned Address = MCE.getGlobalValueAddress(MO1.getSymbolName());
593         assert(Address && "Unknown external symbol!");
594         emitMaybePCRelativeValue(Address, MO1.isPCRelative());
595       } else {
596         emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
597       }
598     }
599     break;
600
601   case X86II::MRMDestReg: {
602     MCE.emitByte(BaseOpcode);
603     emitRegModRMByte(MI.getOperand(0).getReg(),
604                      getX86RegNum(MI.getOperand(1).getReg()));
605     if (MI.getNumOperands() == 3)
606       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
607     break;
608   }
609   case X86II::MRMDestMem:
610     MCE.emitByte(BaseOpcode);
611     emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
612     if (MI.getNumOperands() == 6)
613       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
614     break;
615
616   case X86II::MRMSrcReg:
617     MCE.emitByte(BaseOpcode);
618
619     emitRegModRMByte(MI.getOperand(1).getReg(),
620                      getX86RegNum(MI.getOperand(0).getReg()));
621     if (MI.getNumOperands() == 3)
622       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
623     break;
624
625   case X86II::MRMSrcMem:
626     MCE.emitByte(BaseOpcode);
627     emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
628     if (MI.getNumOperands() == 2+4)
629       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
630     break;
631
632   case X86II::MRM0r: case X86II::MRM1r:
633   case X86II::MRM2r: case X86II::MRM3r:
634   case X86II::MRM4r: case X86II::MRM5r:
635   case X86II::MRM6r: case X86II::MRM7r:
636     MCE.emitByte(BaseOpcode);
637     emitRegModRMByte(MI.getOperand(0).getReg(),
638                      (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
639
640     if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
641       emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(), sizeOfImm(Desc));
642     }
643     break;
644
645   case X86II::MRM0m: case X86II::MRM1m:
646   case X86II::MRM2m: case X86II::MRM3m:
647   case X86II::MRM4m: case X86II::MRM5m:
648   case X86II::MRM6m: case X86II::MRM7m: 
649     MCE.emitByte(BaseOpcode);
650     emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
651
652     if (MI.getNumOperands() == 5) {
653       if (MI.getOperand(4).isImmediate())
654         emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
655       else if (MI.getOperand(4).isGlobalAddress())
656         emitGlobalAddressForPtr(MI.getOperand(4).getGlobal(),
657                                 MI.getOperand(4).getOffset());
658       else
659         assert(0 && "Unknown operand!");
660     }
661     break;
662   }
663 }