1dc6e7692506822f8531b8ea630c1836ebf18888
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-emitter"
16 #include "X86InstrInfo.h"
17 #include "X86JITInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "X86Relocations.h"
21 #include "X86.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/CodeGen/MachineCodeEmitter.h"
24 #include "llvm/CodeGen/JITCodeEmitter.h"
25 #include "llvm/CodeGen/ObjectCodeEmitter.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/Function.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37
38 STATISTIC(NumEmitted, "Number of machine instructions emitted");
39
40 namespace {
41 template<class CodeEmitter>
42   class VISIBILITY_HIDDEN Emitter : public MachineFunctionPass {
43     const X86InstrInfo  *II;
44     const TargetData    *TD;
45     X86TargetMachine    &TM;
46     CodeEmitter         &MCE;
47     intptr_t PICBaseOffset;
48     bool Is64BitMode;
49     bool IsPIC;
50   public:
51     static char ID;
52     explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
53       : MachineFunctionPass(&ID), II(0), TD(0), TM(tm), 
54       MCE(mce), PICBaseOffset(0), Is64BitMode(false),
55       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
56     Emitter(X86TargetMachine &tm, CodeEmitter &mce,
57             const X86InstrInfo &ii, const TargetData &td, bool is64)
58       : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm), 
59       MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
60       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
61
62     bool runOnMachineFunction(MachineFunction &MF);
63
64     virtual const char *getPassName() const {
65       return "X86 Machine Code Emitter";
66     }
67
68     void emitInstruction(const MachineInstr &MI,
69                          const TargetInstrDesc *Desc);
70     
71     void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.addRequired<MachineModuleInfo>();
73       MachineFunctionPass::getAnalysisUsage(AU);
74     }
75
76   private:
77     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
78     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
79                            intptr_t Disp = 0, intptr_t PCAdj = 0,
80                            bool NeedStub = false, bool Indirect = false);
81     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
82     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
83                               intptr_t PCAdj = 0);
84     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
85                               intptr_t PCAdj = 0);
86
87     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
88                                intptr_t PCAdj = 0);
89
90     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
91     void emitRegModRMByte(unsigned RegOpcodeField);
92     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
93     void emitConstant(uint64_t Val, unsigned Size);
94
95     void emitMemModRMByte(const MachineInstr &MI,
96                           unsigned Op, unsigned RegOpcodeField,
97                           intptr_t PCAdj = 0);
98
99     unsigned getX86RegNum(unsigned RegNo) const;
100
101     bool gvNeedsNonLazyPtr(const GlobalValue *GV);
102   };
103
104 template<class CodeEmitter>
105   char Emitter<CodeEmitter>::ID = 0;
106 }
107
108 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
109 /// to the specified templated MachineCodeEmitter object.
110
111 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
112                                              MachineCodeEmitter &MCE) {
113   return new Emitter<MachineCodeEmitter>(TM, MCE);
114 }
115 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
116                                                 JITCodeEmitter &JCE) {
117   return new Emitter<JITCodeEmitter>(TM, JCE);
118 }
119 FunctionPass *llvm::createX86ObjectCodeEmitterPass(X86TargetMachine &TM,
120                                                    ObjectCodeEmitter &OCE) {
121   return new Emitter<ObjectCodeEmitter>(TM, OCE);
122 }
123
124 template<class CodeEmitter>
125 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
126  
127   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
128   
129   II = TM.getInstrInfo();
130   TD = TM.getTargetData();
131   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
132   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
133   
134   do {
135     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
136     MCE.startFunction(MF);
137     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
138          MBB != E; ++MBB) {
139       MCE.StartMachineBasicBlock(MBB);
140       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
141            I != E; ++I) {
142         const TargetInstrDesc &Desc = I->getDesc();
143         emitInstruction(*I, &Desc);
144         // MOVPC32r is basically a call plus a pop instruction.
145         if (Desc.getOpcode() == X86::MOVPC32r)
146           emitInstruction(*I, &II->get(X86::POP32r));
147         NumEmitted++;  // Keep track of the # of mi's emitted
148       }
149     }
150   } while (MCE.finishFunction(MF));
151
152   return false;
153 }
154
155 /// emitPCRelativeBlockAddress - This method keeps track of the information
156 /// necessary to resolve the address of this block later and emits a dummy
157 /// value.
158 ///
159 template<class CodeEmitter>
160 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
161   // Remember where this reference was and where it is to so we can
162   // deal with it later.
163   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
164                                              X86::reloc_pcrel_word, MBB));
165   MCE.emitWordLE(0);
166 }
167
168 /// emitGlobalAddress - Emit the specified address to the code stream assuming
169 /// this is part of a "take the address of a global" instruction.
170 ///
171 template<class CodeEmitter>
172 void Emitter<CodeEmitter>::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
173                                 intptr_t Disp /* = 0 */,
174                                 intptr_t PCAdj /* = 0 */,
175                                 bool NeedStub /* = false */,
176                                 bool Indirect /* = false */) {
177   intptr_t RelocCST = 0;
178   if (Reloc == X86::reloc_picrel_word)
179     RelocCST = PICBaseOffset;
180   else if (Reloc == X86::reloc_pcrel_word)
181     RelocCST = PCAdj;
182   MachineRelocation MR = Indirect
183     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
184                                            GV, RelocCST, NeedStub)
185     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
186                                GV, RelocCST, NeedStub);
187   MCE.addRelocation(MR);
188   // The relocated value will be added to the displacement
189   if (Reloc == X86::reloc_absolute_dword)
190     MCE.emitDWordLE(Disp);
191   else
192     MCE.emitWordLE((int32_t)Disp);
193 }
194
195 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
196 /// be emitted to the current location in the function, and allow it to be PC
197 /// relative.
198 template<class CodeEmitter>
199 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
200                                                      unsigned Reloc) {
201   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
202   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
203                                                  Reloc, ES, RelocCST));
204   if (Reloc == X86::reloc_absolute_dword)
205     MCE.emitDWordLE(0);
206   else
207     MCE.emitWordLE(0);
208 }
209
210 /// emitConstPoolAddress - Arrange for the address of an constant pool
211 /// to be emitted to the current location in the function, and allow it to be PC
212 /// relative.
213 template<class CodeEmitter>
214 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
215                                    intptr_t Disp /* = 0 */,
216                                    intptr_t PCAdj /* = 0 */) {
217   intptr_t RelocCST = 0;
218   if (Reloc == X86::reloc_picrel_word)
219     RelocCST = PICBaseOffset;
220   else if (Reloc == X86::reloc_pcrel_word)
221     RelocCST = PCAdj;
222   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
223                                                     Reloc, CPI, RelocCST));
224   // The relocated value will be added to the displacement
225   if (Reloc == X86::reloc_absolute_dword)
226     MCE.emitDWordLE(Disp);
227   else
228     MCE.emitWordLE((int32_t)Disp);
229 }
230
231 /// emitJumpTableAddress - Arrange for the address of a jump table to
232 /// be emitted to the current location in the function, and allow it to be PC
233 /// relative.
234 template<class CodeEmitter>
235 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
236                                    intptr_t PCAdj /* = 0 */) {
237   intptr_t RelocCST = 0;
238   if (Reloc == X86::reloc_picrel_word)
239     RelocCST = PICBaseOffset;
240   else if (Reloc == X86::reloc_pcrel_word)
241     RelocCST = PCAdj;
242   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
243                                                     Reloc, JTI, RelocCST));
244   // The relocated value will be added to the displacement
245   if (Reloc == X86::reloc_absolute_dword)
246     MCE.emitDWordLE(0);
247   else
248     MCE.emitWordLE(0);
249 }
250
251 template<class CodeEmitter>
252 unsigned Emitter<CodeEmitter>::getX86RegNum(unsigned RegNo) const {
253   return II->getRegisterInfo().getX86RegNum(RegNo);
254 }
255
256 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
257                                       unsigned RM) {
258   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
259   return RM | (RegOpcode << 3) | (Mod << 6);
260 }
261
262 template<class CodeEmitter>
263 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
264                                             unsigned RegOpcodeFld){
265   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
266 }
267
268 template<class CodeEmitter>
269 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
270   MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
271 }
272
273 template<class CodeEmitter>
274 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS, 
275                                        unsigned Index,
276                                        unsigned Base) {
277   // SIB byte is in the same format as the ModRMByte...
278   MCE.emitByte(ModRMByte(SS, Index, Base));
279 }
280
281 template<class CodeEmitter>
282 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
283   // Output the constant in little endian byte order...
284   for (unsigned i = 0; i != Size; ++i) {
285     MCE.emitByte(Val & 255);
286     Val >>= 8;
287   }
288 }
289
290 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
291 /// sign-extended field. 
292 static bool isDisp8(int Value) {
293   return Value == (signed char)Value;
294 }
295
296 template<class CodeEmitter>
297 bool Emitter<CodeEmitter>::gvNeedsNonLazyPtr(const GlobalValue *GV) {
298   // For Darwin, simulate the linktime GOT by using the same non-lazy-pointer
299   // mechanism as 32-bit mode.
300   return (!Is64BitMode || TM.getSubtarget<X86Subtarget>().isTargetDarwin()) &&
301     TM.getSubtarget<X86Subtarget>().GVRequiresExtraLoad(GV, TM, false);
302 }
303
304 template<class CodeEmitter>
305 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
306                                                  int DispVal, intptr_t PCAdj) {
307   // If this is a simple integer displacement that doesn't require a relocation,
308   // emit it now.
309   if (!RelocOp) {
310     emitConstant(DispVal, 4);
311     return;
312   }
313   
314   // Otherwise, this is something that requires a relocation.  Emit it as such
315   // now.
316   if (RelocOp->isGlobal()) {
317     // In 64-bit static small code model, we could potentially emit absolute.
318     // But it's probably not beneficial.
319     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
320     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
321     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
322       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
323     bool NeedStub = isa<Function>(RelocOp->getGlobal());
324     bool Indirect = gvNeedsNonLazyPtr(RelocOp->getGlobal());
325     emitGlobalAddress(RelocOp->getGlobal(), rt, RelocOp->getOffset(),
326                       PCAdj, NeedStub, Indirect);
327   } else if (RelocOp->isCPI()) {
328     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_picrel_word;
329     emitConstPoolAddress(RelocOp->getIndex(), rt,
330                          RelocOp->getOffset(), PCAdj);
331   } else if (RelocOp->isJTI()) {
332     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word : X86::reloc_picrel_word;
333     emitJumpTableAddress(RelocOp->getIndex(), rt, PCAdj);
334   } else {
335     assert(0 && "Unknown value to relocate!");
336   }
337 }
338
339 template<class CodeEmitter>
340 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
341                                unsigned Op, unsigned RegOpcodeField,
342                                intptr_t PCAdj) {
343   const MachineOperand &Op3 = MI.getOperand(Op+3);
344   int DispVal = 0;
345   const MachineOperand *DispForReloc = 0;
346   
347   // Figure out what sort of displacement we have to handle here.
348   if (Op3.isGlobal()) {
349     DispForReloc = &Op3;
350   } else if (Op3.isCPI()) {
351     if (Is64BitMode || IsPIC) {
352       DispForReloc = &Op3;
353     } else {
354       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
355       DispVal += Op3.getOffset();
356     }
357   } else if (Op3.isJTI()) {
358     if (Is64BitMode || IsPIC) {
359       DispForReloc = &Op3;
360     } else {
361       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
362     }
363   } else {
364     DispVal = Op3.getImm();
365   }
366
367   const MachineOperand &Base     = MI.getOperand(Op);
368   const MachineOperand &Scale    = MI.getOperand(Op+1);
369   const MachineOperand &IndexReg = MI.getOperand(Op+2);
370
371   unsigned BaseReg = Base.getReg();
372
373   // Is a SIB byte needed?
374   if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
375       IndexReg.getReg() == 0 &&
376       (BaseReg == 0 || BaseReg == X86::RIP ||
377        getX86RegNum(BaseReg) != N86::ESP)) {
378     if (BaseReg == 0 ||
379         BaseReg == X86::RIP) {  // Just a displacement?
380       // Emit special case [disp32] encoding
381       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
382       
383       emitDisplacementField(DispForReloc, DispVal, PCAdj);
384     } else {
385       unsigned BaseRegNo = getX86RegNum(BaseReg);
386       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
387         // Emit simple indirect register encoding... [EAX] f.e.
388         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
389       } else if (!DispForReloc && isDisp8(DispVal)) {
390         // Emit the disp8 encoding... [REG+disp8]
391         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
392         emitConstant(DispVal, 1);
393       } else {
394         // Emit the most general non-SIB encoding: [REG+disp32]
395         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
396         emitDisplacementField(DispForReloc, DispVal, PCAdj);
397       }
398     }
399
400   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
401     assert(IndexReg.getReg() != X86::ESP &&
402            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
403
404     bool ForceDisp32 = false;
405     bool ForceDisp8  = false;
406     if (BaseReg == 0) {
407       // If there is no base register, we emit the special case SIB byte with
408       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
409       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
410       ForceDisp32 = true;
411     } else if (DispForReloc) {
412       // Emit the normal disp32 encoding.
413       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
414       ForceDisp32 = true;
415     } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
416       // Emit no displacement ModR/M byte
417       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
418     } else if (isDisp8(DispVal)) {
419       // Emit the disp8 encoding...
420       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
421       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
422     } else {
423       // Emit the normal disp32 encoding...
424       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
425     }
426
427     // Calculate what the SS field value should be...
428     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
429     unsigned SS = SSTable[Scale.getImm()];
430
431     if (BaseReg == 0) {
432       // Handle the SIB byte for the case where there is no base.  The
433       // displacement has already been output.
434       unsigned IndexRegNo;
435       if (IndexReg.getReg())
436         IndexRegNo = getX86RegNum(IndexReg.getReg());
437       else
438         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
439       emitSIBByte(SS, IndexRegNo, 5);
440     } else {
441       unsigned BaseRegNo = getX86RegNum(BaseReg);
442       unsigned IndexRegNo;
443       if (IndexReg.getReg())
444         IndexRegNo = getX86RegNum(IndexReg.getReg());
445       else
446         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
447       emitSIBByte(SS, IndexRegNo, BaseRegNo);
448     }
449
450     // Do we need to output a displacement?
451     if (ForceDisp8) {
452       emitConstant(DispVal, 1);
453     } else if (DispVal != 0 || ForceDisp32) {
454       emitDisplacementField(DispForReloc, DispVal, PCAdj);
455     }
456   }
457 }
458
459 template<class CodeEmitter>
460 void Emitter<CodeEmitter>::emitInstruction(
461                               const MachineInstr &MI,
462                               const TargetInstrDesc *Desc) {
463   DOUT << MI;
464
465   unsigned Opcode = Desc->Opcode;
466
467   // Emit the lock opcode prefix as needed.
468   if (Desc->TSFlags & X86II::LOCK) MCE.emitByte(0xF0);
469
470   // Emit segment override opcode prefix as needed.
471   switch (Desc->TSFlags & X86II::SegOvrMask) {
472   case X86II::FS:
473     MCE.emitByte(0x64);
474     break;
475   case X86II::GS:
476     MCE.emitByte(0x65);
477     break;
478   default: assert(0 && "Invalid segment!");
479   case 0: break;  // No segment override!
480   }
481
482   // Emit the repeat opcode prefix as needed.
483   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
484
485   // Emit the operand size opcode prefix as needed.
486   if (Desc->TSFlags & X86II::OpSize) MCE.emitByte(0x66);
487
488   // Emit the address size opcode prefix as needed.
489   if (Desc->TSFlags & X86II::AdSize) MCE.emitByte(0x67);
490
491   bool Need0FPrefix = false;
492   switch (Desc->TSFlags & X86II::Op0Mask) {
493   case X86II::TB:  // Two-byte opcode prefix
494   case X86II::T8:  // 0F 38
495   case X86II::TA:  // 0F 3A
496     Need0FPrefix = true;
497     break;
498   case X86II::REP: break; // already handled.
499   case X86II::XS:   // F3 0F
500     MCE.emitByte(0xF3);
501     Need0FPrefix = true;
502     break;
503   case X86II::XD:   // F2 0F
504     MCE.emitByte(0xF2);
505     Need0FPrefix = true;
506     break;
507   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
508   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
509     MCE.emitByte(0xD8+
510                  (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
511                                    >> X86II::Op0Shift));
512     break; // Two-byte opcode prefix
513   default: assert(0 && "Invalid prefix!");
514   case 0: break;  // No prefix!
515   }
516
517   if (Is64BitMode) {
518     // REX prefix
519     unsigned REX = X86InstrInfo::determineREX(MI);
520     if (REX)
521       MCE.emitByte(0x40 | REX);
522   }
523
524   // 0x0F escape code must be emitted just before the opcode.
525   if (Need0FPrefix)
526     MCE.emitByte(0x0F);
527
528   switch (Desc->TSFlags & X86II::Op0Mask) {
529   case X86II::T8:  // 0F 38
530     MCE.emitByte(0x38);
531     break;
532   case X86II::TA:    // 0F 3A
533     MCE.emitByte(0x3A);
534     break;
535   }
536
537   // If this is a two-address instruction, skip one of the register operands.
538   unsigned NumOps = Desc->getNumOperands();
539   unsigned CurOp = 0;
540   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
541     ++CurOp;
542   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
543     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
544     --NumOps;
545
546   unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
547   switch (Desc->TSFlags & X86II::FormMask) {
548   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
549   case X86II::Pseudo:
550     // Remember the current PC offset, this is the PIC relocation
551     // base address.
552     switch (Opcode) {
553     default: 
554       assert(0 && "psuedo instructions should be removed before code emission");
555       break;
556     case TargetInstrInfo::INLINEASM: {
557       // We allow inline assembler nodes with empty bodies - they can
558       // implicitly define registers, which is ok for JIT.
559       if (MI.getOperand(0).getSymbolName()[0]) {
560         llvm_report_error("JIT does not support inline asm!");
561       }
562       break;
563     }
564     case TargetInstrInfo::DBG_LABEL:
565     case TargetInstrInfo::EH_LABEL:
566       MCE.emitLabel(MI.getOperand(0).getImm());
567       break;
568     case TargetInstrInfo::IMPLICIT_DEF:
569     case TargetInstrInfo::DECLARE:
570     case X86::DWARF_LOC:
571     case X86::FP_REG_KILL:
572       break;
573     case X86::MOVPC32r: {
574       // This emits the "call" portion of this pseudo instruction.
575       MCE.emitByte(BaseOpcode);
576       emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
577       // Remember PIC base.
578       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
579       X86JITInfo *JTI = TM.getJITInfo();
580       JTI->setPICBase(MCE.getCurrentPCValue());
581       break;
582     }
583     }
584     CurOp = NumOps;
585     break;
586   case X86II::RawFrm:
587     MCE.emitByte(BaseOpcode);
588
589     if (CurOp != NumOps) {
590       const MachineOperand &MO = MI.getOperand(CurOp++);
591
592       DOUT << "RawFrm CurOp " << CurOp << "\n";
593       DOUT << "isMBB " << MO.isMBB() << "\n";
594       DOUT << "isGlobal " << MO.isGlobal() << "\n";
595       DOUT << "isSymbol " << MO.isSymbol() << "\n";
596       DOUT << "isImm " << MO.isImm() << "\n";
597
598       if (MO.isMBB()) {
599         emitPCRelativeBlockAddress(MO.getMBB());
600       } else if (MO.isGlobal()) {
601         // Assume undefined functions may be outside the Small codespace.
602         bool NeedStub = 
603           (Is64BitMode && 
604               (TM.getCodeModel() == CodeModel::Large ||
605                TM.getSubtarget<X86Subtarget>().isTargetDarwin())) ||
606           Opcode == X86::TAILJMPd;
607         emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
608                           MO.getOffset(), 0, NeedStub);
609       } else if (MO.isSymbol()) {
610         emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
611       } else if (MO.isImm()) {
612         if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
613           // Fix up immediate operand for pc relative calls.
614           intptr_t Imm = (intptr_t)MO.getImm();
615           Imm = Imm - MCE.getCurrentPCValue() - 4;
616           emitConstant(Imm, X86InstrInfo::sizeOfImm(Desc));
617         } else
618           emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
619       } else {
620         assert(0 && "Unknown RawFrm operand!");
621       }
622     }
623     break;
624
625   case X86II::AddRegFrm:
626     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
627     
628     if (CurOp != NumOps) {
629       const MachineOperand &MO1 = MI.getOperand(CurOp++);
630       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
631       if (MO1.isImm())
632         emitConstant(MO1.getImm(), Size);
633       else {
634         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
635           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
636         // This should not occur on Darwin for relocatable objects.
637         if (Opcode == X86::MOV64ri)
638           rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
639         if (MO1.isGlobal()) {
640           bool NeedStub = isa<Function>(MO1.getGlobal());
641           bool Indirect = gvNeedsNonLazyPtr(MO1.getGlobal());
642           emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
643                             NeedStub, Indirect);
644         } else if (MO1.isSymbol())
645           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
646         else if (MO1.isCPI())
647           emitConstPoolAddress(MO1.getIndex(), rt);
648         else if (MO1.isJTI())
649           emitJumpTableAddress(MO1.getIndex(), rt);
650       }
651     }
652     break;
653
654   case X86II::MRMDestReg: {
655     MCE.emitByte(BaseOpcode);
656     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
657                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
658     CurOp += 2;
659     if (CurOp != NumOps)
660       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
661     break;
662   }
663   case X86II::MRMDestMem: {
664     MCE.emitByte(BaseOpcode);
665     emitMemModRMByte(MI, CurOp,
666                      getX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)
667                                   .getReg()));
668     CurOp +=  X86AddrNumOperands + 1;
669     if (CurOp != NumOps)
670       emitConstant(MI.getOperand(CurOp++).getImm(), X86InstrInfo::sizeOfImm(Desc));
671     break;
672   }
673
674   case X86II::MRMSrcReg:
675     MCE.emitByte(BaseOpcode);
676     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
677                      getX86RegNum(MI.getOperand(CurOp).getReg()));
678     CurOp += 2;
679     if (CurOp != NumOps)
680       emitConstant(MI.getOperand(CurOp++).getImm(),
681                    X86InstrInfo::sizeOfImm(Desc));
682     break;
683
684   case X86II::MRMSrcMem: {
685     // FIXME: Maybe lea should have its own form?
686     int AddrOperands;
687     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
688         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
689       AddrOperands = X86AddrNumOperands - 1; // No segment register
690     else
691       AddrOperands = X86AddrNumOperands;
692
693     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
694       X86InstrInfo::sizeOfImm(Desc) : 0;
695
696     MCE.emitByte(BaseOpcode);
697     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
698                      PCAdj);
699     CurOp += AddrOperands + 1;
700     if (CurOp != NumOps)
701       emitConstant(MI.getOperand(CurOp++).getImm(),
702                    X86InstrInfo::sizeOfImm(Desc));
703     break;
704   }
705
706   case X86II::MRM0r: case X86II::MRM1r:
707   case X86II::MRM2r: case X86II::MRM3r:
708   case X86II::MRM4r: case X86II::MRM5r:
709   case X86II::MRM6r: case X86II::MRM7r: {
710     MCE.emitByte(BaseOpcode);
711
712     // Special handling of lfence, mfence, monitor, and mwait.
713     if (Desc->getOpcode() == X86::LFENCE ||
714         Desc->getOpcode() == X86::MFENCE ||
715         Desc->getOpcode() == X86::MONITOR ||
716         Desc->getOpcode() == X86::MWAIT) {
717       emitRegModRMByte((Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
718
719       switch (Desc->getOpcode()) {
720       default: break;
721       case X86::MONITOR:
722         MCE.emitByte(0xC8);
723         break;
724       case X86::MWAIT:
725         MCE.emitByte(0xC9);
726         break;
727       }
728     } else {
729       emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
730                        (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
731     }
732
733     if (CurOp != NumOps) {
734       const MachineOperand &MO1 = MI.getOperand(CurOp++);
735       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
736       if (MO1.isImm())
737         emitConstant(MO1.getImm(), Size);
738       else {
739         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
740           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
741         if (Opcode == X86::MOV64ri32)
742           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
743         if (MO1.isGlobal()) {
744           bool NeedStub = isa<Function>(MO1.getGlobal());
745           bool Indirect = gvNeedsNonLazyPtr(MO1.getGlobal());
746           emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
747                             NeedStub, Indirect);
748         } else if (MO1.isSymbol())
749           emitExternalSymbolAddress(MO1.getSymbolName(), rt);
750         else if (MO1.isCPI())
751           emitConstPoolAddress(MO1.getIndex(), rt);
752         else if (MO1.isJTI())
753           emitJumpTableAddress(MO1.getIndex(), rt);
754       }
755     }
756     break;
757   }
758
759   case X86II::MRM0m: case X86II::MRM1m:
760   case X86II::MRM2m: case X86II::MRM3m:
761   case X86II::MRM4m: case X86II::MRM5m:
762   case X86II::MRM6m: case X86II::MRM7m: {
763     intptr_t PCAdj = (CurOp + X86AddrNumOperands != NumOps) ?
764       (MI.getOperand(CurOp+X86AddrNumOperands).isImm() ? 
765           X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
766
767     MCE.emitByte(BaseOpcode);
768     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
769                      PCAdj);
770     CurOp += X86AddrNumOperands;
771
772     if (CurOp != NumOps) {
773       const MachineOperand &MO = MI.getOperand(CurOp++);
774       unsigned Size = X86InstrInfo::sizeOfImm(Desc);
775       if (MO.isImm())
776         emitConstant(MO.getImm(), Size);
777       else {
778         unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
779           : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
780         if (Opcode == X86::MOV64mi32)
781           rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
782         if (MO.isGlobal()) {
783           bool NeedStub = isa<Function>(MO.getGlobal());
784           bool Indirect = gvNeedsNonLazyPtr(MO.getGlobal());
785           emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
786                             NeedStub, Indirect);
787         } else if (MO.isSymbol())
788           emitExternalSymbolAddress(MO.getSymbolName(), rt);
789         else if (MO.isCPI())
790           emitConstPoolAddress(MO.getIndex(), rt);
791         else if (MO.isJTI())
792           emitJumpTableAddress(MO.getIndex(), rt);
793       }
794     }
795     break;
796   }
797
798   case X86II::MRMInitReg:
799     MCE.emitByte(BaseOpcode);
800     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
801     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
802                      getX86RegNum(MI.getOperand(CurOp).getReg()));
803     ++CurOp;
804     break;
805   }
806
807   if (!Desc->isVariadic() && CurOp != NumOps) {
808 #ifndef NDEBUG
809     cerr << "Cannot encode: " << MI << "\n";
810 #endif
811     llvm_unreachable();
812   }
813 }
814