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