d55edc5841c472e165b6a2a18dffe871e54bfa81
[oota-llvm.git] / lib / Target / X86 / X86CodeEmitter.cpp
1 //===-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86TargetMachine.h"
16 #include "X86Relocations.h"
17 #include "X86.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/MachineCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Function.h"
24 #include "llvm/ADT/Statistic.h"
25 using namespace llvm;
26
27 namespace {
28   Statistic<>
29   NumEmitted("x86-emitter", "Number of machine instructions emitted");
30 }
31
32 namespace {
33   class Emitter : public MachineFunctionPass {
34     const X86InstrInfo  *II;
35     MachineCodeEmitter  &MCE;
36     std::map<const MachineBasicBlock*, unsigned> BasicBlockAddrs;
37     std::vector<std::pair<const MachineBasicBlock *, unsigned> > BBRefs;
38   public:
39     explicit Emitter(MachineCodeEmitter &mce) : II(0), MCE(mce) {}
40     Emitter(MachineCodeEmitter &mce, const X86InstrInfo& ii)
41         : II(&ii), MCE(mce) {}
42
43     bool runOnMachineFunction(MachineFunction &MF);
44
45     virtual const char *getPassName() const {
46       return "X86 Machine Code Emitter";
47     }
48
49     void emitInstruction(const MachineInstr &MI);
50
51   private:
52     void emitBasicBlock(const MachineBasicBlock &MBB);
53
54     void emitPCRelativeBlockAddress(const MachineBasicBlock *BB);
55     void emitPCRelativeValue(unsigned Address);
56     void emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall);
57     void emitGlobalAddressForPtr(GlobalValue *GV, int Disp = 0);
58     void emitExternalSymbolAddress(const char *ES, bool isPCRelative,
59                                    bool isTailCall);
60
61     void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
62     void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
63     void emitConstant(unsigned Val, unsigned Size);
64
65     void emitMemModRMByte(const MachineInstr &MI,
66                           unsigned Op, unsigned RegOpcodeField);
67
68   };
69 }
70
71 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get
72 /// machine code emitted.  This uses a MachineCodeEmitter object to handle
73 /// actually outputting the machine code and resolving things like the address
74 /// of functions.  This method should returns true if machine code emission is
75 /// not supported.
76 ///
77 bool X86TargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,
78                                                   MachineCodeEmitter &MCE) {
79   PM.add(new Emitter(MCE));
80   // Delete machine code for this function
81   PM.add(createMachineCodeDeleter());
82   return false;
83 }
84
85 bool Emitter::runOnMachineFunction(MachineFunction &MF) {
86   II = ((X86TargetMachine&)MF.getTarget()).getInstrInfo();
87
88   MCE.startFunction(MF);
89   MCE.emitConstantPool(MF.getConstantPool());
90   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
91     emitBasicBlock(*I);
92   MCE.finishFunction(MF);
93
94   // Resolve all forward branches now...
95   for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) {
96     unsigned Location = BasicBlockAddrs[BBRefs[i].first];
97     unsigned Ref = BBRefs[i].second;
98     MCE.emitWordAt(Location-Ref-4, (unsigned*)(intptr_t)Ref);
99   }
100   BBRefs.clear();
101   BasicBlockAddrs.clear();
102   return false;
103 }
104
105 void Emitter::emitBasicBlock(const MachineBasicBlock &MBB) {
106   if (uint64_t Addr = MCE.getCurrentPCValue())
107     BasicBlockAddrs[&MBB] = Addr;
108
109   for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end();
110        I != E; ++I)
111     emitInstruction(*I);
112 }
113
114 /// emitPCRelativeValue - Emit a 32-bit PC relative address.
115 ///
116 void Emitter::emitPCRelativeValue(unsigned Address) {
117   MCE.emitWord(Address-MCE.getCurrentPCValue()-4);
118 }
119
120 /// emitPCRelativeBlockAddress - This method emits the PC relative address of
121 /// the specified basic block, or if the basic block hasn't been emitted yet
122 /// (because this is a forward branch), it keeps track of the information
123 /// necessary to resolve this address later (and emits a dummy value).
124 ///
125 void Emitter::emitPCRelativeBlockAddress(const MachineBasicBlock *MBB) {
126   // If this is a backwards branch, we already know the address of the target,
127   // so just emit the value.
128   std::map<const MachineBasicBlock*, unsigned>::iterator I =
129     BasicBlockAddrs.find(MBB);
130   if (I != BasicBlockAddrs.end()) {
131     emitPCRelativeValue(I->second);
132   } else {
133     // Otherwise, remember where this reference was and where it is to so we can
134     // deal with it later.
135     BBRefs.push_back(std::make_pair(MBB, MCE.getCurrentPCValue()));
136     MCE.emitWord(0);
137   }
138 }
139
140 /// emitGlobalAddressForCall - Emit the specified address to the code stream
141 /// assuming this is part of a function call, which is PC relative.
142 ///
143 void Emitter::emitGlobalAddressForCall(GlobalValue *GV, bool isTailCall) {
144   MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
145                                       X86::reloc_pcrel_word, GV, 0,
146                                       !isTailCall /*Doesn'tNeedStub*/));
147   MCE.emitWord(0);
148 }
149
150 /// emitGlobalAddress - Emit the specified address to the code stream assuming
151 /// this is part of a "take the address of a global" instruction, which is not
152 /// PC relative.
153 ///
154 void Emitter::emitGlobalAddressForPtr(GlobalValue *GV, int Disp /* = 0 */) {
155   MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
156                                       X86::reloc_absolute_word, GV));
157   MCE.emitWord(Disp);   // The relocated value will be added to the displacement
158 }
159
160 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
161 /// be emitted to the current location in the function, and allow it to be PC
162 /// relative.
163 void Emitter::emitExternalSymbolAddress(const char *ES, bool isPCRelative,
164                                         bool isTailCall) {
165   MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(),
166           isPCRelative ? X86::reloc_pcrel_word : X86::reloc_absolute_word, ES));
167   MCE.emitWord(0);
168 }
169
170 /// N86 namespace - Native X86 Register numbers... used by X86 backend.
171 ///
172 namespace N86 {
173   enum {
174     EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESP = 4, EBP = 5, ESI = 6, EDI = 7
175   };
176 }
177
178
179 // getX86RegNum - This function maps LLVM register identifiers to their X86
180 // specific numbering, which is used in various places encoding instructions.
181 //
182 static unsigned getX86RegNum(unsigned RegNo) {
183   switch(RegNo) {
184   case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
185   case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
186   case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
187   case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
188   case X86::ESP: case X86::SP: case X86::AH: return N86::ESP;
189   case X86::EBP: case X86::BP: case X86::CH: return N86::EBP;
190   case X86::ESI: case X86::SI: case X86::DH: return N86::ESI;
191   case X86::EDI: case X86::DI: case X86::BH: return N86::EDI;
192
193   case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
194   case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
195     return RegNo-X86::ST0;
196   default:
197     assert(MRegisterInfo::isVirtualRegister(RegNo) &&
198            "Unknown physical register!");
199     assert(0 && "Register allocator hasn't allocated reg correctly yet!");
200     return 0;
201   }
202 }
203
204 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
205                                       unsigned RM) {
206   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
207   return RM | (RegOpcode << 3) | (Mod << 6);
208 }
209
210 void Emitter::emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeFld){
211   MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
212 }
213
214 void Emitter::emitSIBByte(unsigned SS, unsigned Index, unsigned Base) {
215   // SIB byte is in the same format as the ModRMByte...
216   MCE.emitByte(ModRMByte(SS, Index, Base));
217 }
218
219 void Emitter::emitConstant(unsigned Val, unsigned Size) {
220   // Output the constant in little endian byte order...
221   for (unsigned i = 0; i != Size; ++i) {
222     MCE.emitByte(Val & 255);
223     Val >>= 8;
224   }
225 }
226
227 static bool isDisp8(int Value) {
228   return Value == (signed char)Value;
229 }
230
231 void Emitter::emitMemModRMByte(const MachineInstr &MI,
232                                unsigned Op, unsigned RegOpcodeField) {
233   const MachineOperand &Op3 = MI.getOperand(Op+3);
234   GlobalValue *GV = 0;
235   int DispVal = 0;
236
237   if (Op3.isGlobalAddress()) {
238     GV = Op3.getGlobal();
239     DispVal = Op3.getOffset();
240   } else {
241     DispVal = Op3.getImmedValue();
242   }
243
244   const MachineOperand &Base     = MI.getOperand(Op);
245   const MachineOperand &Scale    = MI.getOperand(Op+1);
246   const MachineOperand &IndexReg = MI.getOperand(Op+2);
247
248   unsigned BaseReg = 0;
249
250   if (Base.isConstantPoolIndex()) {
251     // Emit a direct address reference [disp32] where the displacement of the
252     // constant pool entry is controlled by the MCE.
253     assert(!GV && "Constant Pool reference cannot be relative to global!");
254     DispVal += MCE.getConstantPoolEntryAddress(Base.getConstantPoolIndex());
255   } else {
256     BaseReg = Base.getReg();
257   }
258
259   // Is a SIB byte needed?
260   if (IndexReg.getReg() == 0 && BaseReg != X86::ESP) {
261     if (BaseReg == 0) {  // Just a displacement?
262       // Emit special case [disp32] encoding
263       MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
264       if (GV)
265         emitGlobalAddressForPtr(GV, DispVal);
266       else
267         emitConstant(DispVal, 4);
268     } else {
269       unsigned BaseRegNo = getX86RegNum(BaseReg);
270       if (GV) {
271         // Emit the most general non-SIB encoding: [REG+disp32]
272         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
273         emitGlobalAddressForPtr(GV, DispVal);
274       } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
275         // Emit simple indirect register encoding... [EAX] f.e.
276         MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
277       } else if (isDisp8(DispVal)) {
278         // Emit the disp8 encoding... [REG+disp8]
279         MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
280         emitConstant(DispVal, 1);
281       } else {
282         // Emit the most general non-SIB encoding: [REG+disp32]
283         MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
284         emitConstant(DispVal, 4);
285       }
286     }
287
288   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
289     assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
290
291     bool ForceDisp32 = false;
292     bool ForceDisp8  = false;
293     if (BaseReg == 0) {
294       // If there is no base register, we emit the special case SIB byte with
295       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
296       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
297       ForceDisp32 = true;
298     } else if (GV) {
299       // Emit the normal disp32 encoding...
300       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
301       ForceDisp32 = true;
302     } else if (DispVal == 0 && BaseReg != X86::EBP) {
303       // Emit no displacement ModR/M byte
304       MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
305     } else if (isDisp8(DispVal)) {
306       // Emit the disp8 encoding...
307       MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
308       ForceDisp8 = true;           // Make sure to force 8 bit disp if Base=EBP
309     } else {
310       // Emit the normal disp32 encoding...
311       MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
312     }
313
314     // Calculate what the SS field value should be...
315     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
316     unsigned SS = SSTable[Scale.getImmedValue()];
317
318     if (BaseReg == 0) {
319       // Handle the SIB byte for the case where there is no base.  The
320       // displacement has already been output.
321       assert(IndexReg.getReg() && "Index register must be specified!");
322       emitSIBByte(SS, getX86RegNum(IndexReg.getReg()), 5);
323     } else {
324       unsigned BaseRegNo = getX86RegNum(BaseReg);
325       unsigned IndexRegNo;
326       if (IndexReg.getReg())
327         IndexRegNo = getX86RegNum(IndexReg.getReg());
328       else
329         IndexRegNo = 4;   // For example [ESP+1*<noreg>+4]
330       emitSIBByte(SS, IndexRegNo, BaseRegNo);
331     }
332
333     // Do we need to output a displacement?
334     if (DispVal != 0 || ForceDisp32 || ForceDisp8) {
335       if (!ForceDisp32 && isDisp8(DispVal))
336         emitConstant(DispVal, 1);
337       else if (GV)
338         emitGlobalAddressForPtr(GV, DispVal);
339       else
340         emitConstant(DispVal, 4);
341     }
342   }
343 }
344
345 static unsigned sizeOfImm(const TargetInstrDescriptor &Desc) {
346   switch (Desc.TSFlags & X86II::ImmMask) {
347   case X86II::Imm8:   return 1;
348   case X86II::Imm16:  return 2;
349   case X86II::Imm32:  return 4;
350   default: assert(0 && "Immediate size not set!");
351     return 0;
352   }
353 }
354
355 void Emitter::emitInstruction(const MachineInstr &MI) {
356   NumEmitted++;  // Keep track of the # of mi's emitted
357
358   unsigned Opcode = MI.getOpcode();
359   const TargetInstrDescriptor &Desc = II->get(Opcode);
360
361   // Emit the repeat opcode prefix as needed.
362   if ((Desc.TSFlags & X86II::Op0Mask) == X86II::REP) MCE.emitByte(0xF3);
363
364   // Emit instruction prefixes if necessary
365   if (Desc.TSFlags & X86II::OpSize) MCE.emitByte(0x66);// Operand size...
366
367   switch (Desc.TSFlags & X86II::Op0Mask) {
368   case X86II::TB:
369     MCE.emitByte(0x0F);   // Two-byte opcode prefix
370     break;
371   case X86II::REP: break; // already handled.
372   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
373   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
374     MCE.emitByte(0xD8+
375                  (((Desc.TSFlags & X86II::Op0Mask)-X86II::D8)
376                                    >> X86II::Op0Shift));
377     break; // Two-byte opcode prefix
378   default: assert(0 && "Invalid prefix!");
379   case 0: break;  // No prefix!
380   }
381
382   unsigned char BaseOpcode = II->getBaseOpcodeFor(Opcode);
383   switch (Desc.TSFlags & X86II::FormMask) {
384   default: assert(0 && "Unknown FormMask value in X86 MachineCodeEmitter!");
385   case X86II::Pseudo:
386     if (Opcode != X86::IMPLICIT_USE &&
387         Opcode != X86::IMPLICIT_DEF &&
388         Opcode != X86::FP_REG_KILL)
389       std::cerr << "X86 Machine Code Emitter: No 'form', not emitting: " << MI;
390     break;
391
392   case X86II::RawFrm:
393     MCE.emitByte(BaseOpcode);
394     if (MI.getNumOperands() == 1) {
395       const MachineOperand &MO = MI.getOperand(0);
396       if (MO.isMachineBasicBlock()) {
397         emitPCRelativeBlockAddress(MO.getMachineBasicBlock());
398       } else if (MO.isGlobalAddress()) {
399         assert(MO.isPCRelative() && "Call target is not PC Relative?");
400         bool isTailCall = Opcode == X86::TAILJMPd ||
401                           Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
402         emitGlobalAddressForCall(MO.getGlobal(), isTailCall);
403       } else if (MO.isExternalSymbol()) {
404         bool isTailCall = Opcode == X86::TAILJMPd ||
405                           Opcode == X86::TAILJMPr || Opcode == X86::TAILJMPm;
406         emitExternalSymbolAddress(MO.getSymbolName(), true, isTailCall);
407       } else if (MO.isImmediate()) {
408         emitConstant(MO.getImmedValue(), sizeOfImm(Desc));
409       } else {
410         assert(0 && "Unknown RawFrm operand!");
411       }
412     }
413     break;
414
415   case X86II::AddRegFrm:
416     MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(0).getReg()));
417     if (MI.getNumOperands() == 2) {
418       const MachineOperand &MO1 = MI.getOperand(1);
419       if (Value *V = MO1.getVRegValueOrNull()) {
420         assert(sizeOfImm(Desc) == 4 &&
421                "Don't know how to emit non-pointer values!");
422         emitGlobalAddressForPtr(cast<GlobalValue>(V));
423       } else if (MO1.isGlobalAddress()) {
424         assert(sizeOfImm(Desc) == 4 &&
425                "Don't know how to emit non-pointer values!");
426         assert(!MO1.isPCRelative() && "Function pointer ref is PC relative?");
427         emitGlobalAddressForPtr(MO1.getGlobal(), MO1.getOffset());
428       } else if (MO1.isExternalSymbol()) {
429         assert(sizeOfImm(Desc) == 4 &&
430                "Don't know how to emit non-pointer values!");
431         emitExternalSymbolAddress(MO1.getSymbolName(), false, false);
432       } else {
433         emitConstant(MO1.getImmedValue(), sizeOfImm(Desc));
434       }
435     }
436     break;
437
438   case X86II::MRMDestReg: {
439     MCE.emitByte(BaseOpcode);
440     emitRegModRMByte(MI.getOperand(0).getReg(),
441                      getX86RegNum(MI.getOperand(1).getReg()));
442     if (MI.getNumOperands() == 3)
443       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
444     break;
445   }
446   case X86II::MRMDestMem:
447     MCE.emitByte(BaseOpcode);
448     emitMemModRMByte(MI, 0, getX86RegNum(MI.getOperand(4).getReg()));
449     if (MI.getNumOperands() == 6)
450       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
451     break;
452
453   case X86II::MRMSrcReg:
454     MCE.emitByte(BaseOpcode);
455
456     emitRegModRMByte(MI.getOperand(1).getReg(),
457                      getX86RegNum(MI.getOperand(0).getReg()));
458     if (MI.getNumOperands() == 3)
459       emitConstant(MI.getOperand(2).getImmedValue(), sizeOfImm(Desc));
460     break;
461
462   case X86II::MRMSrcMem:
463     MCE.emitByte(BaseOpcode);
464     emitMemModRMByte(MI, 1, getX86RegNum(MI.getOperand(0).getReg()));
465     if (MI.getNumOperands() == 2+4)
466       emitConstant(MI.getOperand(5).getImmedValue(), sizeOfImm(Desc));
467     break;
468
469   case X86II::MRM0r: case X86II::MRM1r:
470   case X86II::MRM2r: case X86II::MRM3r:
471   case X86II::MRM4r: case X86II::MRM5r:
472   case X86II::MRM6r: case X86II::MRM7r:
473     MCE.emitByte(BaseOpcode);
474     emitRegModRMByte(MI.getOperand(0).getReg(),
475                      (Desc.TSFlags & X86II::FormMask)-X86II::MRM0r);
476
477     if (MI.getOperand(MI.getNumOperands()-1).isImmediate()) {
478       emitConstant(MI.getOperand(MI.getNumOperands()-1).getImmedValue(),
479                    sizeOfImm(Desc));
480     }
481     break;
482
483   case X86II::MRM0m: case X86II::MRM1m:
484   case X86II::MRM2m: case X86II::MRM3m:
485   case X86II::MRM4m: case X86II::MRM5m:
486   case X86II::MRM6m: case X86II::MRM7m:
487     MCE.emitByte(BaseOpcode);
488     emitMemModRMByte(MI, 0, (Desc.TSFlags & X86II::FormMask)-X86II::MRM0m);
489
490     if (MI.getNumOperands() == 5) {
491       if (MI.getOperand(4).isImmediate())
492         emitConstant(MI.getOperand(4).getImmedValue(), sizeOfImm(Desc));
493       else if (MI.getOperand(4).isGlobalAddress())
494         emitGlobalAddressForPtr(MI.getOperand(4).getGlobal(),
495                                 MI.getOperand(4).getOffset());
496       else
497         assert(0 && "Unknown operand!");
498     }
499     break;
500   }
501 }