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