Remove ISD::DEBUG_LOC and ISD::DBG_LABEL, which are no longer used.
[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/LLVMContext.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/JITCodeEmitter.h"
26 #include "llvm/CodeGen/ObjectCodeEmitter.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/Function.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/MC/MCCodeEmitter.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCInst.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 STATISTIC(NumEmitted, "Number of machine instructions emitted");
43
44 namespace {
45   template<class CodeEmitter>
46   class Emitter : public MachineFunctionPass {
47     const X86InstrInfo  *II;
48     const TargetData    *TD;
49     X86TargetMachine    &TM;
50     CodeEmitter         &MCE;
51     intptr_t PICBaseOffset;
52     bool Is64BitMode;
53     bool IsPIC;
54   public:
55     static char ID;
56     explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
57       : MachineFunctionPass(&ID), II(0), TD(0), TM(tm), 
58       MCE(mce), PICBaseOffset(0), Is64BitMode(false),
59       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
60     Emitter(X86TargetMachine &tm, CodeEmitter &mce,
61             const X86InstrInfo &ii, const TargetData &td, bool is64)
62       : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm), 
63       MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
64       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
65
66     bool runOnMachineFunction(MachineFunction &MF);
67
68     virtual const char *getPassName() const {
69       return "X86 Machine Code Emitter";
70     }
71
72     void emitInstruction(const MachineInstr &MI,
73                          const TargetInstrDesc *Desc);
74     
75     void getAnalysisUsage(AnalysisUsage &AU) const {
76       AU.setPreservesAll();
77       AU.addRequired<MachineModuleInfo>();
78       MachineFunctionPass::getAnalysisUsage(AU);
79     }
80
81   private:
82     void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
83     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
84                            intptr_t Disp = 0, intptr_t PCAdj = 0,
85                            bool Indirect = false);
86     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
87     void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
88                               intptr_t PCAdj = 0);
89     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
90                               intptr_t PCAdj = 0);
91
92     void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
93                                intptr_t Adj = 0, bool IsPCRel = true);
94
95     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
96     void emitRegModRMByte(unsigned RegOpcodeField);
97     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
98     void emitConstant(uint64_t Val, unsigned Size);
99
100     void emitMemModRMByte(const MachineInstr &MI,
101                           unsigned Op, unsigned RegOpcodeField,
102                           intptr_t PCAdj = 0);
103
104     unsigned getX86RegNum(unsigned RegNo) const;
105   };
106
107 template<class CodeEmitter>
108   char Emitter<CodeEmitter>::ID = 0;
109 } // end anonymous namespace.
110
111 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
112 /// to the specified templated MachineCodeEmitter object.
113
114 FunctionPass *llvm::createX86CodeEmitterPass(X86TargetMachine &TM,
115                                              MachineCodeEmitter &MCE) {
116   return new Emitter<MachineCodeEmitter>(TM, MCE);
117 }
118 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
119                                                 JITCodeEmitter &JCE) {
120   return new Emitter<JITCodeEmitter>(TM, JCE);
121 }
122 FunctionPass *llvm::createX86ObjectCodeEmitterPass(X86TargetMachine &TM,
123                                                    ObjectCodeEmitter &OCE) {
124   return new Emitter<ObjectCodeEmitter>(TM, OCE);
125 }
126
127 template<class CodeEmitter>
128 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
129  
130   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
131   
132   II = TM.getInstrInfo();
133   TD = TM.getTargetData();
134   Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
135   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
136   
137   do {
138     DEBUG(errs() << "JITTing function '" 
139           << MF.getFunction()->getName() << "'\n");
140     MCE.startFunction(MF);
141     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
142          MBB != E; ++MBB) {
143       MCE.StartMachineBasicBlock(MBB);
144       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
145            I != E; ++I) {
146         const TargetInstrDesc &Desc = I->getDesc();
147         emitInstruction(*I, &Desc);
148         // MOVPC32r is basically a call plus a pop instruction.
149         if (Desc.getOpcode() == X86::MOVPC32r)
150           emitInstruction(*I, &II->get(X86::POP32r));
151         NumEmitted++;  // Keep track of the # of mi's emitted
152       }
153     }
154   } while (MCE.finishFunction(MF));
155
156   return false;
157 }
158
159 /// emitPCRelativeBlockAddress - This method keeps track of the information
160 /// necessary to resolve the address of this block later and emits a dummy
161 /// value.
162 ///
163 template<class CodeEmitter>
164 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
165   // Remember where this reference was and where it is to so we can
166   // deal with it later.
167   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
168                                              X86::reloc_pcrel_word, MBB));
169   MCE.emitWordLE(0);
170 }
171
172 /// emitGlobalAddress - Emit the specified address to the code stream assuming
173 /// this is part of a "take the address of a global" instruction.
174 ///
175 template<class CodeEmitter>
176 void Emitter<CodeEmitter>::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
177                                 intptr_t Disp /* = 0 */,
178                                 intptr_t PCAdj /* = 0 */,
179                                 bool Indirect /* = false */) {
180   intptr_t RelocCST = Disp;
181   if (Reloc == X86::reloc_picrel_word)
182     RelocCST = PICBaseOffset;
183   else if (Reloc == X86::reloc_pcrel_word)
184     RelocCST = PCAdj;
185   MachineRelocation MR = Indirect
186     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
187                                            GV, RelocCST, false)
188     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
189                                GV, RelocCST, false);
190   MCE.addRelocation(MR);
191   // The relocated value will be added to the displacement
192   if (Reloc == X86::reloc_absolute_dword)
193     MCE.emitDWordLE(Disp);
194   else
195     MCE.emitWordLE((int32_t)Disp);
196 }
197
198 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
199 /// be emitted to the current location in the function, and allow it to be PC
200 /// relative.
201 template<class CodeEmitter>
202 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
203                                                      unsigned Reloc) {
204   intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
205   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
206                                                  Reloc, ES, RelocCST));
207   if (Reloc == X86::reloc_absolute_dword)
208     MCE.emitDWordLE(0);
209   else
210     MCE.emitWordLE(0);
211 }
212
213 /// emitConstPoolAddress - Arrange for the address of an constant pool
214 /// to be emitted to the current location in the function, and allow it to be PC
215 /// relative.
216 template<class CodeEmitter>
217 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
218                                    intptr_t Disp /* = 0 */,
219                                    intptr_t PCAdj /* = 0 */) {
220   intptr_t RelocCST = 0;
221   if (Reloc == X86::reloc_picrel_word)
222     RelocCST = PICBaseOffset;
223   else if (Reloc == X86::reloc_pcrel_word)
224     RelocCST = PCAdj;
225   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
226                                                     Reloc, CPI, RelocCST));
227   // The relocated value will be added to the displacement
228   if (Reloc == X86::reloc_absolute_dword)
229     MCE.emitDWordLE(Disp);
230   else
231     MCE.emitWordLE((int32_t)Disp);
232 }
233
234 /// emitJumpTableAddress - Arrange for the address of a jump table to
235 /// be emitted to the current location in the function, and allow it to be PC
236 /// relative.
237 template<class CodeEmitter>
238 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
239                                    intptr_t PCAdj /* = 0 */) {
240   intptr_t RelocCST = 0;
241   if (Reloc == X86::reloc_picrel_word)
242     RelocCST = PICBaseOffset;
243   else if (Reloc == X86::reloc_pcrel_word)
244     RelocCST = PCAdj;
245   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
246                                                     Reloc, JTI, RelocCST));
247   // The relocated value will be added to the displacement
248   if (Reloc == X86::reloc_absolute_dword)
249     MCE.emitDWordLE(0);
250   else
251     MCE.emitWordLE(0);
252 }
253
254 template<class CodeEmitter>
255 unsigned Emitter<CodeEmitter>::getX86RegNum(unsigned RegNo) const {
256   return II->getRegisterInfo().getX86RegNum(RegNo);
257 }
258
259 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
260                                       unsigned RM) {
261   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
262   return RM | (RegOpcode << 3) | (Mod << 6);
263 }
264
265 template<class CodeEmitter>
266 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
267                                             unsigned RegOpcodeFld){
268   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
269 }
270
271 template<class CodeEmitter>
272 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
273   MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
274 }
275
276 template<class CodeEmitter>
277 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS, 
278                                        unsigned Index,
279                                        unsigned Base) {
280   // SIB byte is in the same format as the ModRMByte...
281   MCE.emitByte(ModRMByte(SS, Index, Base));
282 }
283
284 template<class CodeEmitter>
285 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
286   // Output the constant in little endian byte order...
287   for (unsigned i = 0; i != Size; ++i) {
288     MCE.emitByte(Val & 255);
289     Val >>= 8;
290   }
291 }
292
293 /// isDisp8 - Return true if this signed displacement fits in a 8-bit 
294 /// sign-extended field. 
295 static bool isDisp8(int Value) {
296   return Value == (signed char)Value;
297 }
298
299 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
300                               const TargetMachine &TM) {
301   // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
302   // mechanism as 32-bit mode.
303   if (TM.getSubtarget<X86Subtarget>().is64Bit() && 
304       !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
305     return false;
306   
307   // Return true if this is a reference to a stub containing the address of the
308   // global, not the global itself.
309   return isGlobalStubReference(GVOp.getTargetFlags());
310 }
311
312 template<class CodeEmitter>
313 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
314                                                  int DispVal,
315                                                  intptr_t Adj /* = 0 */,
316                                                  bool IsPCRel /* = true */) {
317   // If this is a simple integer displacement that doesn't require a relocation,
318   // emit it now.
319   if (!RelocOp) {
320     emitConstant(DispVal, 4);
321     return;
322   }
323
324   // Otherwise, this is something that requires a relocation.  Emit it as such
325   // now.
326   unsigned RelocType = Is64BitMode ?
327     (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
328     : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
329   if (RelocOp->isGlobal()) {
330     // In 64-bit static small code model, we could potentially emit absolute.
331     // But it's probably not beneficial. If the MCE supports using RIP directly
332     // do it, otherwise fallback to absolute (this is determined by IsPCRel). 
333     //  89 05 00 00 00 00     mov    %eax,0(%rip)  # PC-relative
334     //  89 04 25 00 00 00 00  mov    %eax,0x0      # Absolute
335     bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
336     emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
337                       Adj, Indirect);
338   } else if (RelocOp->isSymbol()) {
339     emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
340   } else if (RelocOp->isCPI()) {
341     emitConstPoolAddress(RelocOp->getIndex(), RelocType,
342                          RelocOp->getOffset(), Adj);
343   } else {
344     assert(RelocOp->isJTI() && "Unexpected machine operand!");
345     emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
346   }
347 }
348
349 template<class CodeEmitter>
350 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
351                                             unsigned Op,unsigned RegOpcodeField,
352                                             intptr_t PCAdj) {
353   const MachineOperand &Op3 = MI.getOperand(Op+3);
354   int DispVal = 0;
355   const MachineOperand *DispForReloc = 0;
356   
357   // Figure out what sort of displacement we have to handle here.
358   if (Op3.isGlobal()) {
359     DispForReloc = &Op3;
360   } else if (Op3.isSymbol()) {
361     DispForReloc = &Op3;
362   } else if (Op3.isCPI()) {
363     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
364       DispForReloc = &Op3;
365     } else {
366       DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
367       DispVal += Op3.getOffset();
368     }
369   } else if (Op3.isJTI()) {
370     if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
371       DispForReloc = &Op3;
372     } else {
373       DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
374     }
375   } else {
376     DispVal = Op3.getImm();
377   }
378
379   const MachineOperand &Base     = MI.getOperand(Op);
380   const MachineOperand &Scale    = MI.getOperand(Op+1);
381   const MachineOperand &IndexReg = MI.getOperand(Op+2);
382
383   unsigned BaseReg = Base.getReg();
384
385   // Indicate that the displacement will use an pcrel or absolute reference
386   // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
387   // while others, unless explicit asked to use RIP, use absolute references.
388   bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
389
390   // Is a SIB byte needed?
391   // If no BaseReg, issue a RIP relative instruction only if the MCE can 
392   // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
393   // 2-7) and absolute references.
394   if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
395       IndexReg.getReg() == 0 && 
396       ((BaseReg == 0 && MCE.earlyResolveAddresses()) || BaseReg == X86::RIP || 
397        (BaseReg != 0 && getX86RegNum(BaseReg) != N86::ESP))) {
398     if (BaseReg == 0 || BaseReg == X86::RIP) {  // Just a displacement?
399       // Emit special case [disp32] encoding
400       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
401       emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
402     } else {
403       unsigned BaseRegNo = getX86RegNum(BaseReg);
404       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
405         // Emit simple indirect register encoding... [EAX] f.e.
406         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
407       } else if (!DispForReloc && isDisp8(DispVal)) {
408         // Emit the disp8 encoding... [REG+disp8]
409         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
410         emitConstant(DispVal, 1);
411       } else {
412         // Emit the most general non-SIB encoding: [REG+disp32]
413         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
414         emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
415       }
416     }
417
418   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
419     assert(IndexReg.getReg() != X86::ESP &&
420            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
421
422     bool ForceDisp32 = false;
423     bool ForceDisp8  = false;
424     if (BaseReg == 0) {
425       // If there is no base register, we emit the special case SIB byte with
426       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
427       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
428       ForceDisp32 = true;
429     } else if (DispForReloc) {
430       // Emit the normal disp32 encoding.
431       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
432       ForceDisp32 = true;
433     } else if (DispVal == 0 && getX86RegNum(BaseReg) != N86::EBP) {
434       // Emit no displacement ModR/M byte
435       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
436     } else if (isDisp8(DispVal)) {
437       // Emit the disp8 encoding...
438       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
439       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
440     } else {
441       // Emit the normal disp32 encoding...
442       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
443     }
444
445     // Calculate what the SS field value should be...
446     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
447     unsigned SS = SSTable[Scale.getImm()];
448
449     if (BaseReg == 0) {
450       // Handle the SIB byte for the case where there is no base, see Intel 
451       // Manual 2A, table 2-7. The displacement has already been output.
452       unsigned IndexRegNo;
453       if (IndexReg.getReg())
454         IndexRegNo = getX86RegNum(IndexReg.getReg());
455       else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
456         IndexRegNo = 4;
457       emitSIBByte(SS, IndexRegNo, 5);
458     } else {
459       unsigned BaseRegNo = getX86RegNum(BaseReg);
460       unsigned IndexRegNo;
461       if (IndexReg.getReg())
462         IndexRegNo = getX86RegNum(IndexReg.getReg());
463       else
464         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
465       emitSIBByte(SS, IndexRegNo, BaseRegNo);
466     }
467
468     // Do we need to output a displacement?
469     if (ForceDisp8) {
470       emitConstant(DispVal, 1);
471     } else if (DispVal != 0 || ForceDisp32) {
472       emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
473     }
474   }
475 }
476
477 template<class CodeEmitter>
478 void Emitter<CodeEmitter>::emitInstruction(const MachineInstr &MI,
479                                            const TargetInstrDesc *Desc) {
480   DEBUG(errs() << MI);
481
482   MCE.processDebugLoc(MI.getDebugLoc(), true);
483
484   unsigned Opcode = Desc->Opcode;
485
486   // Emit the lock opcode prefix as needed.
487   if (Desc->TSFlags & X86II::LOCK)
488     MCE.emitByte(0xF0);
489
490   // Emit segment override opcode prefix as needed.
491   switch (Desc->TSFlags & X86II::SegOvrMask) {
492   case X86II::FS:
493     MCE.emitByte(0x64);
494     break;
495   case X86II::GS:
496     MCE.emitByte(0x65);
497     break;
498   default: llvm_unreachable("Invalid segment!");
499   case 0: break;  // No segment override!
500   }
501
502   // Emit the repeat opcode prefix as needed.
503   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
504     MCE.emitByte(0xF3);
505
506   // Emit the operand size opcode prefix as needed.
507   if (Desc->TSFlags & X86II::OpSize)
508     MCE.emitByte(0x66);
509
510   // Emit the address size opcode prefix as needed.
511   if (Desc->TSFlags & X86II::AdSize)
512     MCE.emitByte(0x67);
513
514   bool Need0FPrefix = false;
515   switch (Desc->TSFlags & X86II::Op0Mask) {
516   case X86II::TB:  // Two-byte opcode prefix
517   case X86II::T8:  // 0F 38
518   case X86II::TA:  // 0F 3A
519     Need0FPrefix = true;
520     break;
521   case X86II::TF: // F2 0F 38
522     MCE.emitByte(0xF2);
523     Need0FPrefix = true;
524     break;
525   case X86II::REP: break; // already handled.
526   case X86II::XS:   // F3 0F
527     MCE.emitByte(0xF3);
528     Need0FPrefix = true;
529     break;
530   case X86II::XD:   // F2 0F
531     MCE.emitByte(0xF2);
532     Need0FPrefix = true;
533     break;
534   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
535   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
536     MCE.emitByte(0xD8+
537                  (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
538                                    >> X86II::Op0Shift));
539     break; // Two-byte opcode prefix
540   default: llvm_unreachable("Invalid prefix!");
541   case 0: break;  // No prefix!
542   }
543
544   // Handle REX prefix.
545   if (Is64BitMode) {
546     if (unsigned REX = X86InstrInfo::determineREX(MI))
547       MCE.emitByte(0x40 | REX);
548   }
549
550   // 0x0F escape code must be emitted just before the opcode.
551   if (Need0FPrefix)
552     MCE.emitByte(0x0F);
553
554   switch (Desc->TSFlags & X86II::Op0Mask) {
555   case X86II::TF:    // F2 0F 38
556   case X86II::T8:    // 0F 38
557     MCE.emitByte(0x38);
558     break;
559   case X86II::TA:    // 0F 3A
560     MCE.emitByte(0x3A);
561     break;
562   }
563
564   // If this is a two-address instruction, skip one of the register operands.
565   unsigned NumOps = Desc->getNumOperands();
566   unsigned CurOp = 0;
567   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
568     ++CurOp;
569   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
570     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
571     --NumOps;
572
573   unsigned char BaseOpcode = II->getBaseOpcodeFor(Desc);
574   switch (Desc->TSFlags & X86II::FormMask) {
575   default:
576     llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
577   case X86II::Pseudo:
578     // Remember the current PC offset, this is the PIC relocation
579     // base address.
580     switch (Opcode) {
581     default: 
582       llvm_unreachable("psuedo instructions should be removed before code"
583                        " emission");
584       break;
585     case TargetInstrInfo::INLINEASM:
586       // We allow inline assembler nodes with empty bodies - they can
587       // implicitly define registers, which is ok for JIT.
588       if (MI.getOperand(0).getSymbolName()[0])
589         llvm_report_error("JIT does not support inline asm!");
590       break;
591     case TargetInstrInfo::DBG_LABEL:
592     case TargetInstrInfo::EH_LABEL:
593     case TargetInstrInfo::GC_LABEL:
594       MCE.emitLabel(MI.getOperand(0).getImm());
595       break;
596     case TargetInstrInfo::IMPLICIT_DEF:
597     case TargetInstrInfo::KILL:
598     case X86::FP_REG_KILL:
599       break;
600     case X86::MOVPC32r: {
601       // This emits the "call" portion of this pseudo instruction.
602       MCE.emitByte(BaseOpcode);
603       emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
604       // Remember PIC base.
605       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
606       X86JITInfo *JTI = TM.getJITInfo();
607       JTI->setPICBase(MCE.getCurrentPCValue());
608       break;
609     }
610     }
611     CurOp = NumOps;
612     break;
613   case X86II::RawFrm: {
614     MCE.emitByte(BaseOpcode);
615
616     if (CurOp == NumOps)
617       break;
618       
619     const MachineOperand &MO = MI.getOperand(CurOp++);
620
621     DEBUG(errs() << "RawFrm CurOp " << CurOp << "\n");
622     DEBUG(errs() << "isMBB " << MO.isMBB() << "\n");
623     DEBUG(errs() << "isGlobal " << MO.isGlobal() << "\n");
624     DEBUG(errs() << "isSymbol " << MO.isSymbol() << "\n");
625     DEBUG(errs() << "isImm " << MO.isImm() << "\n");
626
627     if (MO.isMBB()) {
628       emitPCRelativeBlockAddress(MO.getMBB());
629       break;
630     }
631     
632     if (MO.isGlobal()) {
633       emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
634                         MO.getOffset(), 0);
635       break;
636     }
637     
638     if (MO.isSymbol()) {
639       emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
640       break;
641     }
642     
643     assert(MO.isImm() && "Unknown RawFrm operand!");
644     if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
645       // Fix up immediate operand for pc relative calls.
646       intptr_t Imm = (intptr_t)MO.getImm();
647       Imm = Imm - MCE.getCurrentPCValue() - 4;
648       emitConstant(Imm, X86InstrInfo::sizeOfImm(Desc));
649     } else
650       emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
651     break;
652   }
653       
654   case X86II::AddRegFrm: {
655     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
656     
657     if (CurOp == NumOps)
658       break;
659       
660     const MachineOperand &MO1 = MI.getOperand(CurOp++);
661     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
662     if (MO1.isImm()) {
663       emitConstant(MO1.getImm(), Size);
664       break;
665     }
666     
667     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
668       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
669     if (Opcode == X86::MOV64ri64i32)
670       rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
671     // This should not occur on Darwin for relocatable objects.
672     if (Opcode == X86::MOV64ri)
673       rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
674     if (MO1.isGlobal()) {
675       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
676       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
677                         Indirect);
678     } else if (MO1.isSymbol())
679       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
680     else if (MO1.isCPI())
681       emitConstPoolAddress(MO1.getIndex(), rt);
682     else if (MO1.isJTI())
683       emitJumpTableAddress(MO1.getIndex(), rt);
684     break;
685   }
686
687   case X86II::MRMDestReg: {
688     MCE.emitByte(BaseOpcode);
689     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
690                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
691     CurOp += 2;
692     if (CurOp != NumOps)
693       emitConstant(MI.getOperand(CurOp++).getImm(),
694                    X86InstrInfo::sizeOfImm(Desc));
695     break;
696   }
697   case X86II::MRMDestMem: {
698     MCE.emitByte(BaseOpcode);
699     emitMemModRMByte(MI, CurOp,
700                      getX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)
701                                   .getReg()));
702     CurOp +=  X86AddrNumOperands + 1;
703     if (CurOp != NumOps)
704       emitConstant(MI.getOperand(CurOp++).getImm(),
705                    X86InstrInfo::sizeOfImm(Desc));
706     break;
707   }
708
709   case X86II::MRMSrcReg:
710     MCE.emitByte(BaseOpcode);
711     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
712                      getX86RegNum(MI.getOperand(CurOp).getReg()));
713     CurOp += 2;
714     if (CurOp != NumOps)
715       emitConstant(MI.getOperand(CurOp++).getImm(),
716                    X86InstrInfo::sizeOfImm(Desc));
717     break;
718
719   case X86II::MRMSrcMem: {
720     // FIXME: Maybe lea should have its own form?
721     int AddrOperands;
722     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
723         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
724       AddrOperands = X86AddrNumOperands - 1; // No segment register
725     else
726       AddrOperands = X86AddrNumOperands;
727
728     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
729       X86InstrInfo::sizeOfImm(Desc) : 0;
730
731     MCE.emitByte(BaseOpcode);
732     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
733                      PCAdj);
734     CurOp += AddrOperands + 1;
735     if (CurOp != NumOps)
736       emitConstant(MI.getOperand(CurOp++).getImm(),
737                    X86InstrInfo::sizeOfImm(Desc));
738     break;
739   }
740
741   case X86II::MRM0r: case X86II::MRM1r:
742   case X86II::MRM2r: case X86II::MRM3r:
743   case X86II::MRM4r: case X86II::MRM5r:
744   case X86II::MRM6r: case X86II::MRM7r: {
745     MCE.emitByte(BaseOpcode);
746
747     // Special handling of lfence, mfence, monitor, and mwait.
748     if (Desc->getOpcode() == X86::LFENCE ||
749         Desc->getOpcode() == X86::MFENCE ||
750         Desc->getOpcode() == X86::MONITOR ||
751         Desc->getOpcode() == X86::MWAIT) {
752       emitRegModRMByte((Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
753
754       switch (Desc->getOpcode()) {
755       default: break;
756       case X86::MONITOR:
757         MCE.emitByte(0xC8);
758         break;
759       case X86::MWAIT:
760         MCE.emitByte(0xC9);
761         break;
762       }
763     } else {
764       emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
765                        (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
766     }
767
768     if (CurOp == NumOps)
769       break;
770     
771     const MachineOperand &MO1 = MI.getOperand(CurOp++);
772     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
773     if (MO1.isImm()) {
774       emitConstant(MO1.getImm(), Size);
775       break;
776     }
777     
778     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
779       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
780     if (Opcode == X86::MOV64ri32)
781       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
782     if (MO1.isGlobal()) {
783       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
784       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
785                         Indirect);
786     } else if (MO1.isSymbol())
787       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
788     else if (MO1.isCPI())
789       emitConstPoolAddress(MO1.getIndex(), rt);
790     else if (MO1.isJTI())
791       emitJumpTableAddress(MO1.getIndex(), rt);
792     break;
793   }
794
795   case X86II::MRM0m: case X86II::MRM1m:
796   case X86II::MRM2m: case X86II::MRM3m:
797   case X86II::MRM4m: case X86II::MRM5m:
798   case X86II::MRM6m: case X86II::MRM7m: {
799     intptr_t PCAdj = (CurOp + X86AddrNumOperands != NumOps) ?
800       (MI.getOperand(CurOp+X86AddrNumOperands).isImm() ? 
801           X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
802
803     MCE.emitByte(BaseOpcode);
804     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
805                      PCAdj);
806     CurOp += X86AddrNumOperands;
807
808     if (CurOp == NumOps)
809       break;
810     
811     const MachineOperand &MO = MI.getOperand(CurOp++);
812     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
813     if (MO.isImm()) {
814       emitConstant(MO.getImm(), Size);
815       break;
816     }
817     
818     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
819       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
820     if (Opcode == X86::MOV64mi32)
821       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
822     if (MO.isGlobal()) {
823       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
824       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
825                         Indirect);
826     } else if (MO.isSymbol())
827       emitExternalSymbolAddress(MO.getSymbolName(), rt);
828     else if (MO.isCPI())
829       emitConstPoolAddress(MO.getIndex(), rt);
830     else if (MO.isJTI())
831       emitJumpTableAddress(MO.getIndex(), rt);
832     break;
833   }
834
835   case X86II::MRMInitReg:
836     MCE.emitByte(BaseOpcode);
837     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
838     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
839                      getX86RegNum(MI.getOperand(CurOp).getReg()));
840     ++CurOp;
841     break;
842   }
843
844   if (!Desc->isVariadic() && CurOp != NumOps) {
845 #ifndef NDEBUG
846     errs() << "Cannot encode all operands of: " << MI << "\n";
847 #endif
848     llvm_unreachable(0);
849   }
850
851   MCE.processDebugLoc(MI.getDebugLoc(), false);
852 }
853
854 // Adapt the Emitter / CodeEmitter interfaces to MCCodeEmitter.
855 //
856 // FIXME: This is a total hack designed to allow work on llvm-mc to proceed
857 // without being blocked on various cleanups needed to support a clean interface
858 // to instruction encoding.
859 //
860 // Look away!
861
862 #include "llvm/DerivedTypes.h"
863
864 namespace {
865 class MCSingleInstructionCodeEmitter : public MachineCodeEmitter {
866   uint8_t Data[256];
867
868 public:
869   MCSingleInstructionCodeEmitter() { reset(); }
870
871   void reset() { 
872     BufferBegin = Data;
873     BufferEnd = array_endof(Data);
874     CurBufferPtr = Data;
875   }
876
877   StringRef str() {
878     return StringRef(reinterpret_cast<char*>(BufferBegin),
879                      CurBufferPtr - BufferBegin);
880   }
881
882   virtual void startFunction(MachineFunction &F) {}
883   virtual bool finishFunction(MachineFunction &F) { return false; }
884   virtual void emitLabel(uint64_t LabelID) {}
885   virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {}
886   virtual bool earlyResolveAddresses() const { return false; }
887   virtual void addRelocation(const MachineRelocation &MR) { }
888   virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
889     return 0;
890   }
891   virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
892     return 0;
893   }
894   virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
895     return 0;
896   }
897   virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
898     return 0;
899   }
900   virtual void setModuleInfo(MachineModuleInfo* Info) {}
901 };
902
903 class X86MCCodeEmitter : public MCCodeEmitter {
904   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
905   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
906
907 private:
908   X86TargetMachine &TM;
909   llvm::Function *DummyF;
910   TargetData *DummyTD;
911   mutable llvm::MachineFunction *DummyMF;
912   llvm::MachineBasicBlock *DummyMBB;
913   
914   MCSingleInstructionCodeEmitter *InstrEmitter;
915   Emitter<MachineCodeEmitter> *Emit;
916
917 public:
918   X86MCCodeEmitter(X86TargetMachine &_TM) : TM(_TM) {
919     // Verily, thou shouldst avert thine eyes.
920     const llvm::FunctionType *FTy =
921       FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), false);
922     DummyF = Function::Create(FTy, GlobalValue::InternalLinkage);
923     DummyTD = new TargetData("");
924     DummyMF = new MachineFunction(DummyF, TM);
925     DummyMBB = DummyMF->CreateMachineBasicBlock();
926
927     InstrEmitter = new MCSingleInstructionCodeEmitter();
928     Emit = new Emitter<MachineCodeEmitter>(TM, *InstrEmitter, 
929                                            *TM.getInstrInfo(),
930                                            *DummyTD, false);
931   }
932   ~X86MCCodeEmitter() {
933     delete Emit;
934     delete InstrEmitter;
935     delete DummyMF;
936     delete DummyF;
937   }
938
939   bool AddRegToInstr(const MCInst &MI, MachineInstr *Instr,
940                      unsigned Start) const {
941     if (Start + 1 > MI.getNumOperands())
942       return false;
943
944     const MCOperand &Op = MI.getOperand(Start);
945     if (!Op.isReg()) return false;
946
947     Instr->addOperand(MachineOperand::CreateReg(Op.getReg(), false));
948     return true;
949   }
950
951   bool AddImmToInstr(const MCInst &MI, MachineInstr *Instr,
952                      unsigned Start) const {
953     if (Start + 1 > MI.getNumOperands())
954       return false;
955
956     const MCOperand &Op = MI.getOperand(Start);
957     if (Op.isImm()) {
958       Instr->addOperand(MachineOperand::CreateImm(Op.getImm()));
959       return true;
960     }
961     if (!Op.isExpr())
962       return false;
963
964     const MCExpr *Expr = Op.getExpr();
965     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) {
966       Instr->addOperand(MachineOperand::CreateImm(CE->getValue()));
967       return true;
968     }
969
970     // FIXME: Relocation / fixup.
971     Instr->addOperand(MachineOperand::CreateImm(0));
972     return true;
973   }
974
975   bool AddLMemToInstr(const MCInst &MI, MachineInstr *Instr,
976                      unsigned Start) const {
977     return (AddRegToInstr(MI, Instr, Start + 0) &&
978             AddImmToInstr(MI, Instr, Start + 1) &&
979             AddRegToInstr(MI, Instr, Start + 2) &&
980             AddImmToInstr(MI, Instr, Start + 3));
981   }
982
983   bool AddMemToInstr(const MCInst &MI, MachineInstr *Instr,
984                      unsigned Start) const {
985     return (AddRegToInstr(MI, Instr, Start + 0) &&
986             AddImmToInstr(MI, Instr, Start + 1) &&
987             AddRegToInstr(MI, Instr, Start + 2) &&
988             AddImmToInstr(MI, Instr, Start + 3) &&
989             AddRegToInstr(MI, Instr, Start + 4));
990   }
991
992   void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
993     // Don't look yet!
994
995     // Convert the MCInst to a MachineInstr so we can (ab)use the regular
996     // emitter.
997     const X86InstrInfo &II = *TM.getInstrInfo();
998     const TargetInstrDesc &Desc = II.get(MI.getOpcode());    
999     MachineInstr *Instr = DummyMF->CreateMachineInstr(Desc, DebugLoc());
1000     DummyMBB->push_back(Instr);
1001
1002     unsigned Opcode = MI.getOpcode();
1003     unsigned NumOps = MI.getNumOperands();
1004     unsigned CurOp = 0;
1005     if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1) {
1006       Instr->addOperand(MachineOperand::CreateReg(0, false));
1007       ++CurOp;
1008     } else if (NumOps > 2 && 
1009              Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
1010       // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
1011       --NumOps;
1012
1013     bool OK = true;
1014     switch (Desc.TSFlags & X86II::FormMask) {
1015     case X86II::MRMDestReg:
1016     case X86II::MRMSrcReg:
1017       // Matching doesn't fill this in completely, we have to choose operand 0
1018       // for a tied register.
1019       OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1020       OK &= AddRegToInstr(MI, Instr, CurOp++);
1021       if (CurOp < NumOps)
1022         OK &= AddImmToInstr(MI, Instr, CurOp);
1023       break;
1024
1025     case X86II::RawFrm:
1026       if (CurOp < NumOps) {
1027         // Hack to make branches work.
1028         if (!(Desc.TSFlags & X86II::ImmMask) &&
1029             MI.getOperand(0).isExpr() &&
1030             isa<MCSymbolRefExpr>(MI.getOperand(0).getExpr()))
1031           Instr->addOperand(MachineOperand::CreateMBB(DummyMBB));
1032         else
1033           OK &= AddImmToInstr(MI, Instr, CurOp);
1034       }
1035       break;
1036
1037     case X86II::AddRegFrm:
1038       OK &= AddRegToInstr(MI, Instr, CurOp++);
1039       if (CurOp < NumOps)
1040         OK &= AddImmToInstr(MI, Instr, CurOp);
1041       break;
1042
1043     case X86II::MRM0r: case X86II::MRM1r:
1044     case X86II::MRM2r: case X86II::MRM3r:
1045     case X86II::MRM4r: case X86II::MRM5r:
1046     case X86II::MRM6r: case X86II::MRM7r:
1047       // Matching doesn't fill this in completely, we have to choose operand 0
1048       // for a tied register.
1049       OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1050       if (CurOp < NumOps)
1051         OK &= AddImmToInstr(MI, Instr, CurOp);
1052       break;
1053       
1054     case X86II::MRM0m: case X86II::MRM1m:
1055     case X86II::MRM2m: case X86II::MRM3m:
1056     case X86II::MRM4m: case X86II::MRM5m:
1057     case X86II::MRM6m: case X86II::MRM7m:
1058       OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1059       if (CurOp < NumOps)
1060         OK &= AddImmToInstr(MI, Instr, CurOp);
1061       break;
1062
1063     case X86II::MRMSrcMem:
1064       OK &= AddRegToInstr(MI, Instr, CurOp++);
1065       if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
1066           Opcode == X86::LEA16r || Opcode == X86::LEA32r)
1067         OK &= AddLMemToInstr(MI, Instr, CurOp);
1068       else
1069         OK &= AddMemToInstr(MI, Instr, CurOp);
1070       break;
1071
1072     case X86II::MRMDestMem:
1073       OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1074       OK &= AddRegToInstr(MI, Instr, CurOp);
1075       break;
1076
1077     default:
1078     case X86II::MRMInitReg:
1079     case X86II::Pseudo:
1080       OK = false;
1081       break;
1082     }
1083
1084     if (!OK) {
1085       errs() << "couldn't convert inst '";
1086       MI.dump();
1087       errs() << "' to machine instr:\n";
1088       Instr->dump();
1089     }
1090
1091     InstrEmitter->reset();
1092     if (OK)
1093       Emit->emitInstruction(*Instr, &Desc);
1094     OS << InstrEmitter->str();
1095
1096     Instr->eraseFromParent();
1097   }
1098 };
1099 }
1100
1101 // Ok, now you can look.
1102 MCCodeEmitter *llvm::createX86MCCodeEmitter(const Target &,
1103                                             TargetMachine &TM) {
1104   return new X86MCCodeEmitter(static_cast<X86TargetMachine&>(TM));
1105 }