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