]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Target/X86/X86CodeEmitter.cpp
Update LLVM to r89205.
[FreeBSD/FreeBSD.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::DWARF_LOC:
599     case X86::FP_REG_KILL:
600       break;
601     case X86::MOVPC32r: {
602       // This emits the "call" portion of this pseudo instruction.
603       MCE.emitByte(BaseOpcode);
604       emitConstant(0, X86InstrInfo::sizeOfImm(Desc));
605       // Remember PIC base.
606       PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
607       X86JITInfo *JTI = TM.getJITInfo();
608       JTI->setPICBase(MCE.getCurrentPCValue());
609       break;
610     }
611     }
612     CurOp = NumOps;
613     break;
614   case X86II::RawFrm: {
615     MCE.emitByte(BaseOpcode);
616
617     if (CurOp == NumOps)
618       break;
619       
620     const MachineOperand &MO = MI.getOperand(CurOp++);
621
622     DEBUG(errs() << "RawFrm CurOp " << CurOp << "\n");
623     DEBUG(errs() << "isMBB " << MO.isMBB() << "\n");
624     DEBUG(errs() << "isGlobal " << MO.isGlobal() << "\n");
625     DEBUG(errs() << "isSymbol " << MO.isSymbol() << "\n");
626     DEBUG(errs() << "isImm " << MO.isImm() << "\n");
627
628     if (MO.isMBB()) {
629       emitPCRelativeBlockAddress(MO.getMBB());
630       break;
631     }
632     
633     if (MO.isGlobal()) {
634       emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
635                         MO.getOffset(), 0);
636       break;
637     }
638     
639     if (MO.isSymbol()) {
640       emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
641       break;
642     }
643     
644     assert(MO.isImm() && "Unknown RawFrm operand!");
645     if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
646       // Fix up immediate operand for pc relative calls.
647       intptr_t Imm = (intptr_t)MO.getImm();
648       Imm = Imm - MCE.getCurrentPCValue() - 4;
649       emitConstant(Imm, X86InstrInfo::sizeOfImm(Desc));
650     } else
651       emitConstant(MO.getImm(), X86InstrInfo::sizeOfImm(Desc));
652     break;
653   }
654       
655   case X86II::AddRegFrm: {
656     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
657     
658     if (CurOp == NumOps)
659       break;
660       
661     const MachineOperand &MO1 = MI.getOperand(CurOp++);
662     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
663     if (MO1.isImm()) {
664       emitConstant(MO1.getImm(), Size);
665       break;
666     }
667     
668     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
669       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
670     if (Opcode == X86::MOV64ri64i32)
671       rt = X86::reloc_absolute_word;  // FIXME: add X86II flag?
672     // This should not occur on Darwin for relocatable objects.
673     if (Opcode == X86::MOV64ri)
674       rt = X86::reloc_absolute_dword;  // FIXME: add X86II flag?
675     if (MO1.isGlobal()) {
676       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
677       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
678                         Indirect);
679     } else if (MO1.isSymbol())
680       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
681     else if (MO1.isCPI())
682       emitConstPoolAddress(MO1.getIndex(), rt);
683     else if (MO1.isJTI())
684       emitJumpTableAddress(MO1.getIndex(), rt);
685     break;
686   }
687
688   case X86II::MRMDestReg: {
689     MCE.emitByte(BaseOpcode);
690     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
691                      getX86RegNum(MI.getOperand(CurOp+1).getReg()));
692     CurOp += 2;
693     if (CurOp != NumOps)
694       emitConstant(MI.getOperand(CurOp++).getImm(),
695                    X86InstrInfo::sizeOfImm(Desc));
696     break;
697   }
698   case X86II::MRMDestMem: {
699     MCE.emitByte(BaseOpcode);
700     emitMemModRMByte(MI, CurOp,
701                      getX86RegNum(MI.getOperand(CurOp + X86AddrNumOperands)
702                                   .getReg()));
703     CurOp +=  X86AddrNumOperands + 1;
704     if (CurOp != NumOps)
705       emitConstant(MI.getOperand(CurOp++).getImm(),
706                    X86InstrInfo::sizeOfImm(Desc));
707     break;
708   }
709
710   case X86II::MRMSrcReg:
711     MCE.emitByte(BaseOpcode);
712     emitRegModRMByte(MI.getOperand(CurOp+1).getReg(),
713                      getX86RegNum(MI.getOperand(CurOp).getReg()));
714     CurOp += 2;
715     if (CurOp != NumOps)
716       emitConstant(MI.getOperand(CurOp++).getImm(),
717                    X86InstrInfo::sizeOfImm(Desc));
718     break;
719
720   case X86II::MRMSrcMem: {
721     // FIXME: Maybe lea should have its own form?
722     int AddrOperands;
723     if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
724         Opcode == X86::LEA16r || Opcode == X86::LEA32r)
725       AddrOperands = X86AddrNumOperands - 1; // No segment register
726     else
727       AddrOperands = X86AddrNumOperands;
728
729     intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
730       X86InstrInfo::sizeOfImm(Desc) : 0;
731
732     MCE.emitByte(BaseOpcode);
733     emitMemModRMByte(MI, CurOp+1, getX86RegNum(MI.getOperand(CurOp).getReg()),
734                      PCAdj);
735     CurOp += AddrOperands + 1;
736     if (CurOp != NumOps)
737       emitConstant(MI.getOperand(CurOp++).getImm(),
738                    X86InstrInfo::sizeOfImm(Desc));
739     break;
740   }
741
742   case X86II::MRM0r: case X86II::MRM1r:
743   case X86II::MRM2r: case X86II::MRM3r:
744   case X86II::MRM4r: case X86II::MRM5r:
745   case X86II::MRM6r: case X86II::MRM7r: {
746     MCE.emitByte(BaseOpcode);
747
748     // Special handling of lfence, mfence, monitor, and mwait.
749     if (Desc->getOpcode() == X86::LFENCE ||
750         Desc->getOpcode() == X86::MFENCE ||
751         Desc->getOpcode() == X86::MONITOR ||
752         Desc->getOpcode() == X86::MWAIT) {
753       emitRegModRMByte((Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
754
755       switch (Desc->getOpcode()) {
756       default: break;
757       case X86::MONITOR:
758         MCE.emitByte(0xC8);
759         break;
760       case X86::MWAIT:
761         MCE.emitByte(0xC9);
762         break;
763       }
764     } else {
765       emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
766                        (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
767     }
768
769     if (CurOp == NumOps)
770       break;
771     
772     const MachineOperand &MO1 = MI.getOperand(CurOp++);
773     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
774     if (MO1.isImm()) {
775       emitConstant(MO1.getImm(), Size);
776       break;
777     }
778     
779     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
780       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
781     if (Opcode == X86::MOV64ri32)
782       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
783     if (MO1.isGlobal()) {
784       bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
785       emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
786                         Indirect);
787     } else if (MO1.isSymbol())
788       emitExternalSymbolAddress(MO1.getSymbolName(), rt);
789     else if (MO1.isCPI())
790       emitConstPoolAddress(MO1.getIndex(), rt);
791     else if (MO1.isJTI())
792       emitJumpTableAddress(MO1.getIndex(), rt);
793     break;
794   }
795
796   case X86II::MRM0m: case X86II::MRM1m:
797   case X86II::MRM2m: case X86II::MRM3m:
798   case X86II::MRM4m: case X86II::MRM5m:
799   case X86II::MRM6m: case X86II::MRM7m: {
800     intptr_t PCAdj = (CurOp + X86AddrNumOperands != NumOps) ?
801       (MI.getOperand(CurOp+X86AddrNumOperands).isImm() ? 
802           X86InstrInfo::sizeOfImm(Desc) : 4) : 0;
803
804     MCE.emitByte(BaseOpcode);
805     emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
806                      PCAdj);
807     CurOp += X86AddrNumOperands;
808
809     if (CurOp == NumOps)
810       break;
811     
812     const MachineOperand &MO = MI.getOperand(CurOp++);
813     unsigned Size = X86InstrInfo::sizeOfImm(Desc);
814     if (MO.isImm()) {
815       emitConstant(MO.getImm(), Size);
816       break;
817     }
818     
819     unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
820       : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
821     if (Opcode == X86::MOV64mi32)
822       rt = X86::reloc_absolute_word_sext;  // FIXME: add X86II flag?
823     if (MO.isGlobal()) {
824       bool Indirect = gvNeedsNonLazyPtr(MO, TM);
825       emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
826                         Indirect);
827     } else if (MO.isSymbol())
828       emitExternalSymbolAddress(MO.getSymbolName(), rt);
829     else if (MO.isCPI())
830       emitConstPoolAddress(MO.getIndex(), rt);
831     else if (MO.isJTI())
832       emitJumpTableAddress(MO.getIndex(), rt);
833     break;
834   }
835
836   case X86II::MRMInitReg:
837     MCE.emitByte(BaseOpcode);
838     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
839     emitRegModRMByte(MI.getOperand(CurOp).getReg(),
840                      getX86RegNum(MI.getOperand(CurOp).getReg()));
841     ++CurOp;
842     break;
843   }
844
845   if (!Desc->isVariadic() && CurOp != NumOps) {
846 #ifndef NDEBUG
847     errs() << "Cannot encode all operands of: " << MI << "\n";
848 #endif
849     llvm_unreachable(0);
850   }
851
852   MCE.processDebugLoc(MI.getDebugLoc(), false);
853 }
854
855 // Adapt the Emitter / CodeEmitter interfaces to MCCodeEmitter.
856 //
857 // FIXME: This is a total hack designed to allow work on llvm-mc to proceed
858 // without being blocked on various cleanups needed to support a clean interface
859 // to instruction encoding.
860 //
861 // Look away!
862
863 #include "llvm/DerivedTypes.h"
864
865 namespace {
866 class MCSingleInstructionCodeEmitter : public MachineCodeEmitter {
867   uint8_t Data[256];
868
869 public:
870   MCSingleInstructionCodeEmitter() { reset(); }
871
872   void reset() { 
873     BufferBegin = Data;
874     BufferEnd = array_endof(Data);
875     CurBufferPtr = Data;
876   }
877
878   StringRef str() {
879     return StringRef(reinterpret_cast<char*>(BufferBegin),
880                      CurBufferPtr - BufferBegin);
881   }
882
883   virtual void startFunction(MachineFunction &F) {}
884   virtual bool finishFunction(MachineFunction &F) { return false; }
885   virtual void emitLabel(uint64_t LabelID) {}
886   virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {}
887   virtual bool earlyResolveAddresses() const { return false; }
888   virtual void addRelocation(const MachineRelocation &MR) { }
889   virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
890     return 0;
891   }
892   virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
893     return 0;
894   }
895   virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
896     return 0;
897   }
898   virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
899     return 0;
900   }
901   virtual void setModuleInfo(MachineModuleInfo* Info) {}
902 };
903
904 class X86MCCodeEmitter : public MCCodeEmitter {
905   X86MCCodeEmitter(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
906   void operator=(const X86MCCodeEmitter &); // DO NOT IMPLEMENT
907
908 private:
909   X86TargetMachine &TM;
910   llvm::Function *DummyF;
911   TargetData *DummyTD;
912   mutable llvm::MachineFunction *DummyMF;
913   llvm::MachineBasicBlock *DummyMBB;
914   
915   MCSingleInstructionCodeEmitter *InstrEmitter;
916   Emitter<MachineCodeEmitter> *Emit;
917
918 public:
919   X86MCCodeEmitter(X86TargetMachine &_TM) : TM(_TM) {
920     // Verily, thou shouldst avert thine eyes.
921     const llvm::FunctionType *FTy =
922       FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), false);
923     DummyF = Function::Create(FTy, GlobalValue::InternalLinkage);
924     DummyTD = new TargetData("");
925     DummyMF = new MachineFunction(DummyF, TM);
926     DummyMBB = DummyMF->CreateMachineBasicBlock();
927
928     InstrEmitter = new MCSingleInstructionCodeEmitter();
929     Emit = new Emitter<MachineCodeEmitter>(TM, *InstrEmitter, 
930                                            *TM.getInstrInfo(),
931                                            *DummyTD, false);
932   }
933   ~X86MCCodeEmitter() {
934     delete Emit;
935     delete InstrEmitter;
936     delete DummyMF;
937     delete DummyF;
938   }
939
940   bool AddRegToInstr(const MCInst &MI, MachineInstr *Instr,
941                      unsigned Start) const {
942     if (Start + 1 > MI.getNumOperands())
943       return false;
944
945     const MCOperand &Op = MI.getOperand(Start);
946     if (!Op.isReg()) return false;
947
948     Instr->addOperand(MachineOperand::CreateReg(Op.getReg(), false));
949     return true;
950   }
951
952   bool AddImmToInstr(const MCInst &MI, MachineInstr *Instr,
953                      unsigned Start) const {
954     if (Start + 1 > MI.getNumOperands())
955       return false;
956
957     const MCOperand &Op = MI.getOperand(Start);
958     if (Op.isImm()) {
959       Instr->addOperand(MachineOperand::CreateImm(Op.getImm()));
960       return true;
961     }
962     if (!Op.isExpr())
963       return false;
964
965     const MCExpr *Expr = Op.getExpr();
966     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) {
967       Instr->addOperand(MachineOperand::CreateImm(CE->getValue()));
968       return true;
969     }
970
971     // FIXME: Relocation / fixup.
972     Instr->addOperand(MachineOperand::CreateImm(0));
973     return true;
974   }
975
976   bool AddLMemToInstr(const MCInst &MI, MachineInstr *Instr,
977                      unsigned Start) const {
978     return (AddRegToInstr(MI, Instr, Start + 0) &&
979             AddImmToInstr(MI, Instr, Start + 1) &&
980             AddRegToInstr(MI, Instr, Start + 2) &&
981             AddImmToInstr(MI, Instr, Start + 3));
982   }
983
984   bool AddMemToInstr(const MCInst &MI, MachineInstr *Instr,
985                      unsigned Start) const {
986     return (AddRegToInstr(MI, Instr, Start + 0) &&
987             AddImmToInstr(MI, Instr, Start + 1) &&
988             AddRegToInstr(MI, Instr, Start + 2) &&
989             AddImmToInstr(MI, Instr, Start + 3) &&
990             AddRegToInstr(MI, Instr, Start + 4));
991   }
992
993   void EncodeInstruction(const MCInst &MI, raw_ostream &OS) const {
994     // Don't look yet!
995
996     // Convert the MCInst to a MachineInstr so we can (ab)use the regular
997     // emitter.
998     const X86InstrInfo &II = *TM.getInstrInfo();
999     const TargetInstrDesc &Desc = II.get(MI.getOpcode());    
1000     MachineInstr *Instr = DummyMF->CreateMachineInstr(Desc, DebugLoc());
1001     DummyMBB->push_back(Instr);
1002
1003     unsigned Opcode = MI.getOpcode();
1004     unsigned NumOps = MI.getNumOperands();
1005     unsigned CurOp = 0;
1006     if (NumOps > 1 && Desc.getOperandConstraint(1, TOI::TIED_TO) != -1) {
1007       Instr->addOperand(MachineOperand::CreateReg(0, false));
1008       ++CurOp;
1009     } else if (NumOps > 2 && 
1010              Desc.getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
1011       // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
1012       --NumOps;
1013
1014     bool OK = true;
1015     switch (Desc.TSFlags & X86II::FormMask) {
1016     case X86II::MRMDestReg:
1017     case X86II::MRMSrcReg:
1018       // Matching doesn't fill this in completely, we have to choose operand 0
1019       // for a tied register.
1020       OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1021       OK &= AddRegToInstr(MI, Instr, CurOp++);
1022       if (CurOp < NumOps)
1023         OK &= AddImmToInstr(MI, Instr, CurOp);
1024       break;
1025
1026     case X86II::RawFrm:
1027       if (CurOp < NumOps) {
1028         // Hack to make branches work.
1029         if (!(Desc.TSFlags & X86II::ImmMask) &&
1030             MI.getOperand(0).isExpr() &&
1031             isa<MCSymbolRefExpr>(MI.getOperand(0).getExpr()))
1032           Instr->addOperand(MachineOperand::CreateMBB(DummyMBB));
1033         else
1034           OK &= AddImmToInstr(MI, Instr, CurOp);
1035       }
1036       break;
1037
1038     case X86II::AddRegFrm:
1039       OK &= AddRegToInstr(MI, Instr, CurOp++);
1040       if (CurOp < NumOps)
1041         OK &= AddImmToInstr(MI, Instr, CurOp);
1042       break;
1043
1044     case X86II::MRM0r: case X86II::MRM1r:
1045     case X86II::MRM2r: case X86II::MRM3r:
1046     case X86II::MRM4r: case X86II::MRM5r:
1047     case X86II::MRM6r: case X86II::MRM7r:
1048       // Matching doesn't fill this in completely, we have to choose operand 0
1049       // for a tied register.
1050       OK &= AddRegToInstr(MI, Instr, 0); CurOp++;
1051       if (CurOp < NumOps)
1052         OK &= AddImmToInstr(MI, Instr, CurOp);
1053       break;
1054       
1055     case X86II::MRM0m: case X86II::MRM1m:
1056     case X86II::MRM2m: case X86II::MRM3m:
1057     case X86II::MRM4m: case X86II::MRM5m:
1058     case X86II::MRM6m: case X86II::MRM7m:
1059       OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1060       if (CurOp < NumOps)
1061         OK &= AddImmToInstr(MI, Instr, CurOp);
1062       break;
1063
1064     case X86II::MRMSrcMem:
1065       OK &= AddRegToInstr(MI, Instr, CurOp++);
1066       if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r ||
1067           Opcode == X86::LEA16r || Opcode == X86::LEA32r)
1068         OK &= AddLMemToInstr(MI, Instr, CurOp);
1069       else
1070         OK &= AddMemToInstr(MI, Instr, CurOp);
1071       break;
1072
1073     case X86II::MRMDestMem:
1074       OK &= AddMemToInstr(MI, Instr, CurOp); CurOp += 5;
1075       OK &= AddRegToInstr(MI, Instr, CurOp);
1076       break;
1077
1078     default:
1079     case X86II::MRMInitReg:
1080     case X86II::Pseudo:
1081       OK = false;
1082       break;
1083     }
1084
1085     if (!OK) {
1086       errs() << "couldn't convert inst '";
1087       MI.dump();
1088       errs() << "' to machine instr:\n";
1089       Instr->dump();
1090     }
1091
1092     InstrEmitter->reset();
1093     if (OK)
1094       Emit->emitInstruction(*Instr, &Desc);
1095     OS << InstrEmitter->str();
1096
1097     Instr->eraseFromParent();
1098   }
1099 };
1100 }
1101
1102 // Ok, now you can look.
1103 MCCodeEmitter *llvm::createX86MCCodeEmitter(const Target &,
1104                                             TargetMachine &TM) {
1105   return new X86MCCodeEmitter(static_cast<X86TargetMachine&>(TM));
1106 }