Add rawfrm flags
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86/Printer.cpp - Convert X86 code to human readable rep. ---------===//
2 //
3 // This file contains a printer that converts from our internal representation
4 // of LLVM code to a nice human readable form that is suitable for debuggging.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "X86.h"
9 #include "X86InstrInfo.h"
10 #include "llvm/Pass.h"
11 #include "llvm/Function.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "Support/Statistic.h"
16
17 namespace {
18   struct Printer : public FunctionPass {
19     TargetMachine &TM;
20     std::ostream &O;
21
22     Printer(TargetMachine &tm, std::ostream &o) : TM(tm), O(o) {}
23
24     bool runOnFunction(Function &F);
25   };
26 }
27
28 /// createX86CodePrinterPass - Print out the specified machine code function to
29 /// the specified stream.  This function should work regardless of whether or
30 /// not the function is in SSA form or not.
31 ///
32 Pass *createX86CodePrinterPass(TargetMachine &TM, std::ostream &O) {
33   return new Printer(TM, O);
34 }
35
36
37 /// runOnFunction - This uses the X86InstructionInfo::print method
38 /// to print assembly for each instruction.
39 bool Printer::runOnFunction (Function & F)
40 {
41   static unsigned bbnumber = 0;
42   MachineFunction & MF = MachineFunction::get (&F);
43   const MachineInstrInfo & MII = TM.getInstrInfo ();
44
45   O << "; x86 printing only sorta implemented so far!\n";
46
47   // Print out labels for the function.
48   O << "\t.globl\t" << F.getName () << "\n";
49   O << "\t.type\t" << F.getName () << ", @function\n";
50   O << F.getName () << ":\n";
51
52   // Print out code for the function.
53   for (MachineFunction::const_iterator bb_i = MF.begin (), bb_e = MF.end ();
54        bb_i != bb_e; ++bb_i)
55     {
56       // Print a label for the basic block.
57       O << ".BB" << bbnumber++ << ":\n";
58       for (MachineBasicBlock::const_iterator i_i = bb_i->begin (), i_e =
59            bb_i->end (); i_i != i_e; ++i_i)
60         {
61           // Print the assembly for the instruction.
62           O << "\t";
63           MII.print(*i_i, O, TM);
64         }
65     }
66
67   // We didn't modify anything.
68   return false;
69 }
70
71 static bool isReg(const MachineOperand &MO) {
72   return MO.getType() == MachineOperand::MO_VirtualRegister ||
73          MO.getType() == MachineOperand::MO_MachineRegister;
74 }
75
76 static bool isImmediate(const MachineOperand &MO) {
77   return MO.getType() == MachineOperand::MO_SignExtendedImmed ||
78          MO.getType() == MachineOperand::MO_UnextendedImmed;
79 }
80
81 static bool isPCRelativeDisp(const MachineOperand &MO) {
82   return MO.getType() == MachineOperand::MO_PCRelativeDisp;
83 }
84
85 static bool isScale(const MachineOperand &MO) {
86   return isImmediate(MO) &&
87            (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
88             MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
89 }
90
91 static bool isMem(const MachineInstr *MI, unsigned Op) {
92   return Op+4 <= MI->getNumOperands() &&
93          isReg(MI->getOperand(Op  )) && isScale(MI->getOperand(Op+1)) &&
94          isReg(MI->getOperand(Op+2)) && isImmediate(MI->getOperand(Op+3));
95 }
96
97 static void printOp(std::ostream &O, const MachineOperand &MO,
98                     const MRegisterInfo &RI) {
99   switch (MO.getType()) {
100   case MachineOperand::MO_VirtualRegister:
101   case MachineOperand::MO_MachineRegister:
102     if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
103       O << RI.get(MO.getReg()).Name;
104     else
105       O << "%reg" << MO.getReg();
106     return;
107
108   case MachineOperand::MO_SignExtendedImmed:
109   case MachineOperand::MO_UnextendedImmed:
110     O << (int)MO.getImmedValue();
111     return;
112   case MachineOperand::MO_PCRelativeDisp:
113     O << "< " << MO.getVRegValue()->getName() << ">";
114     return;
115   default:
116     O << "<unknown op ty>"; return;    
117   }
118 }
119
120 static void printMemReference(std::ostream &O, const MachineInstr *MI,
121                               unsigned Op, const MRegisterInfo &RI) {
122   assert(isMem(MI, Op) && "Invalid memory reference!");
123   const MachineOperand &BaseReg  = MI->getOperand(Op);
124   const MachineOperand &Scale    = MI->getOperand(Op+1);
125   const MachineOperand &IndexReg = MI->getOperand(Op+2);
126   const MachineOperand &Disp     = MI->getOperand(Op+3);
127
128   O << "[";
129   bool NeedPlus = false;
130   if (BaseReg.getReg()) {
131     printOp(O, BaseReg, RI);
132     NeedPlus = true;
133   }
134
135   if (IndexReg.getReg()) {
136     if (NeedPlus) O << " + ";
137     if (IndexReg.getImmedValue() != 1)
138       O << IndexReg.getImmedValue() << "*";
139     printOp(O, IndexReg, RI);
140     NeedPlus = true;
141   }
142
143   if (Disp.getImmedValue()) {
144     if (NeedPlus) O << " + ";
145     printOp(O, Disp, RI);
146   }
147   O << "]";
148 }
149
150 static inline void toHexDigit(std::ostream &O, unsigned char V) {
151   if (V >= 10)
152     O << (char)('A'+V-10);
153   else
154     O << (char)('0'+V);
155 }
156
157 static std::ostream &toHex(std::ostream &O, unsigned char V) {
158   toHexDigit(O, V >> 4);
159   toHexDigit(O, V & 0xF);
160   return O;
161 }
162
163 static std::ostream &emitConstant(std::ostream &O, unsigned Val, unsigned Size){
164   // Output the constant in little endian byte order...
165   for (unsigned i = 0; i != Size; ++i) {
166     toHex(O, Val) << " ";
167     Val >>= 8;
168   }
169   return O;
170 }
171
172 namespace N86 {  // Native X86 Register numbers...
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   default:
193     assert(RegNo >= MRegisterInfo::FirstVirtualRegister &&
194            "Unknown physical register!");
195     DEBUG(std::cerr << "Register allocator hasn't allocated " << RegNo
196                     << " correctly yet!\n");
197     return 0;
198   }
199 }
200
201 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
202                                       unsigned RM) {
203   assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
204   return RM | (RegOpcode << 3) | (Mod << 6);
205 }
206
207 static void emitRegModRMByte(std::ostream &O, unsigned ModRMReg,
208                              unsigned RegOpcodeField) {
209   toHex(O, ModRMByte(3, RegOpcodeField, getX86RegNum(ModRMReg))) << " ";
210 }
211
212 inline static void emitSIBByte(std::ostream &O, unsigned SS, unsigned Index,
213                                unsigned Base) {
214   // SIB byte is in the same format as the ModRMByte...
215   toHex(O, ModRMByte(SS, Index, Base));
216 }
217
218 static bool isDisp8(int Value) {
219   return Value == (signed char)Value;
220 }
221
222 static void emitMemModRMByte(std::ostream &O, const MachineInstr *MI,
223                              unsigned Op, unsigned RegOpcodeField) {
224   assert(isMem(MI, Op) && "Invalid memory reference!");
225   const MachineOperand &BaseReg  = MI->getOperand(Op);
226   const MachineOperand &Scale    = MI->getOperand(Op+1);
227   const MachineOperand &IndexReg = MI->getOperand(Op+2);
228   const MachineOperand &Disp     = MI->getOperand(Op+3);
229
230   // Is a SIB byte needed?
231   if (IndexReg.getReg() == 0 && BaseReg.getReg() != X86::ESP) {
232     if (BaseReg.getReg() == 0) {  // Just a displacement?
233       // Emit special case [disp32] encoding
234       toHex(O, ModRMByte(0, RegOpcodeField, 5));
235       emitConstant(O, Disp.getImmedValue(), 4);
236     } else {
237       unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
238       if (Disp.getImmedValue() == 0 && BaseRegNo != N86::EBP) {
239         // Emit simple indirect register encoding... [EAX] f.e.
240         toHex(O, ModRMByte(0, RegOpcodeField, BaseRegNo));
241       } else if (isDisp8(Disp.getImmedValue())) {
242         // Emit the disp8 encoding... [REG+disp8]
243         toHex(O, ModRMByte(1, RegOpcodeField, BaseRegNo));
244         emitConstant(O, Disp.getImmedValue(), 1);
245       } else {
246         // Emit the most general non-SIB encoding: [REG+disp32]
247         toHex(O, ModRMByte(1, RegOpcodeField, BaseRegNo));
248         emitConstant(O, Disp.getImmedValue(), 4);
249       }
250     }
251
252   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
253     assert(IndexReg.getReg() != X86::ESP && "Cannot use ESP as index reg!");
254
255     bool ForceDisp32 = false;
256     if (BaseReg.getReg() == 0) {
257       // If there is no base register, we emit the special case SIB byte with
258       // MOD=0, BASE=5, to JUST get the index, scale, and displacement.
259       toHex(O, ModRMByte(0, RegOpcodeField, 4));
260       ForceDisp32 = true;
261     } else if (Disp.getImmedValue() == 0) {
262       // Emit no displacement ModR/M byte
263       toHex(O, ModRMByte(0, RegOpcodeField, 4));
264     } else if (isDisp8(Disp.getImmedValue())) {
265       // Emit the disp8 encoding...
266       toHex(O, ModRMByte(1, RegOpcodeField, 4));
267     } else {
268       // Emit the normal disp32 encoding...
269       toHex(O, ModRMByte(2, RegOpcodeField, 4));
270     }
271
272     // Calculate what the SS field value should be...
273     static const unsigned SSTable[] = { ~0, 0, 1, ~0, 2, ~0, ~0, ~0, 3 };
274     unsigned SS = SSTable[Scale.getImmedValue()];
275
276     if (BaseReg.getReg() == 0) {
277       // Handle the SIB byte for the case where there is no base.  The
278       // displacement has already been output.
279       assert(IndexReg.getReg() && "Index register must be specified!");
280       emitSIBByte(O, SS, getX86RegNum(IndexReg.getReg()), 5);
281     } else {
282       unsigned BaseRegNo = getX86RegNum(BaseReg.getReg());
283       unsigned IndexRegNo = getX86RegNum(IndexReg.getReg());
284       emitSIBByte(O, SS, IndexRegNo, BaseRegNo);
285     }
286
287     // Do we need to output a displacement?
288     if (Disp.getImmedValue() != 0 || ForceDisp32) {
289       if (!ForceDisp32 && isDisp8(Disp.getImmedValue()))
290         emitConstant(O, Disp.getImmedValue(), 1);
291       else
292         emitConstant(O, Disp.getImmedValue(), 4);
293     }
294   }
295 }
296
297
298 // print - Print out an x86 instruction in intel syntax
299 void X86InstrInfo::print(const MachineInstr *MI, std::ostream &O,
300                          const TargetMachine &TM) const {
301   unsigned Opcode = MI->getOpcode();
302   const MachineInstrDescriptor &Desc = get(Opcode);
303
304   // Print instruction prefixes if neccesary
305   if (Desc.TSFlags & X86II::OpSize) O << "66 "; // Operand size...
306   if (Desc.TSFlags & X86II::TB) O << "0F ";     // Two-byte opcode prefix
307
308   switch (Desc.TSFlags & X86II::FormMask) {
309   case X86II::OtherFrm:
310     O << "\t\t\t";
311     O << "-"; MI->print(O, TM);
312     break;
313
314   case X86II::RawFrm:
315     // The accepted forms of Raw instructions are:
316     //   1. nop     - No operand required
317     //   2. jmp foo - PC relative displacement operand
318     //
319     assert(MI->getNumOperands() == 0 ||
320            (MI->getNumOperands() == 1 && isPCRelativeDisp(MI->getOperand(0))) &&
321            "Illegal raw instruction!");
322     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
323
324     if (MI->getNumOperands() == 1) {
325       Value *V = MI->getOperand(0).getVRegValue();
326       emitConstant(O, 0, 4);
327     }
328
329     O << "\n\t\t\t\t";
330     O << getName(MI->getOpCode()) << " ";
331
332     if (MI->getNumOperands() == 1) {
333       printOp(O, MI->getOperand(0), RI);
334     }
335     O << "\n";
336     return;
337
338   case X86II::AddRegFrm: {
339     // There are currently two forms of acceptable AddRegFrm instructions.
340     // Either the instruction JUST takes a single register (like inc, dec, etc),
341     // or it takes a register and an immediate of the same size as the register
342     // (move immediate f.e.).
343     //
344     assert(isReg(MI->getOperand(0)) &&
345            (MI->getNumOperands() == 1 || 
346             (MI->getNumOperands() == 2 && isImmediate(MI->getOperand(1)))) &&
347            "Illegal form for AddRegFrm instruction!");
348
349     unsigned Reg = MI->getOperand(0).getReg();
350     toHex(O, getBaseOpcodeFor(Opcode) + getX86RegNum(Reg)) << " ";
351
352     if (MI->getNumOperands() == 2) {
353       unsigned Size = 4;
354       emitConstant(O, MI->getOperand(1).getImmedValue(), Size);
355     }
356     
357     O << "\n\t\t\t\t";
358     O << getName(MI->getOpCode()) << " ";
359     printOp(O, MI->getOperand(0), RI);
360     if (MI->getNumOperands() == 2) {
361       O << ", ";
362       printOp(O, MI->getOperand(1), RI);
363     }
364     O << "\n";
365     return;
366   }
367   case X86II::MRMDestReg: {
368     // There are two acceptable forms of MRMDestReg instructions, those with 3
369     // and 2 operands:
370     //
371     // 3 Operands: in this form, the first two registers (the destination, and
372     // the first operand) should be the same, post register allocation.  The 3rd
373     // operand is an additional input.  This should be for things like add
374     // instructions.
375     //
376     // 2 Operands: this is for things like mov that do not read a second input
377     //
378     assert(isReg(MI->getOperand(0)) &&
379            (MI->getNumOperands() == 2 || 
380             (MI->getNumOperands() == 3 && isReg(MI->getOperand(1)))) &&
381            isReg(MI->getOperand(MI->getNumOperands()-1))
382            && "Bad format for MRMDestReg!");
383     if (MI->getNumOperands() == 3 &&
384         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
385       O << "**";
386
387     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
388     unsigned ModRMReg = MI->getOperand(0).getReg();
389     unsigned ExtraReg = MI->getOperand(MI->getNumOperands()-1).getReg();
390     emitRegModRMByte(O, ModRMReg, getX86RegNum(ExtraReg));
391
392     O << "\n\t\t\t\t";
393     O << getName(MI->getOpCode()) << " ";
394     printOp(O, MI->getOperand(0), RI);
395     O << ", ";
396     printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
397     O << "\n";
398     return;
399   }
400
401   case X86II::MRMDestMem: {
402     // These instructions are the same as MRMDestReg, but instead of having a
403     // register reference for the mod/rm field, it's a memory reference.
404     //
405     assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
406            isReg(MI->getOperand(4)) && "Bad format for MRMDestMem!");
407     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
408     emitMemModRMByte(O, MI, 0, getX86RegNum(MI->getOperand(4).getReg()));
409
410     O << "\n\t\t\t\t";
411     O << getName(MI->getOpCode()) << " <SIZE> PTR ";
412     printMemReference(O, MI, 0, RI);
413     O << ", ";
414     printOp(O, MI->getOperand(4), RI);
415     O << "\n";
416     return;
417   }
418
419   case X86II::MRMSrcReg: {
420     // There is a two forms that are acceptable for MRMSrcReg instructions,
421     // those with 3 and 2 operands:
422     //
423     // 3 Operands: in this form, the last register (the second input) is the
424     // ModR/M input.  The first two operands should be the same, post register
425     // allocation.  This is for things like: add r32, r/m32
426     //
427     // 2 Operands: this is for things like mov that do not read a second input
428     //
429     assert(isReg(MI->getOperand(0)) &&
430            isReg(MI->getOperand(1)) &&
431            (MI->getNumOperands() == 2 || 
432             (MI->getNumOperands() == 3 && isReg(MI->getOperand(2))))
433            && "Bad format for MRMDestReg!");
434     if (MI->getNumOperands() == 3 &&
435         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
436       O << "**";
437
438     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
439     unsigned ModRMReg = MI->getOperand(MI->getNumOperands()-1).getReg();
440     unsigned ExtraReg = MI->getOperand(0).getReg();
441     emitRegModRMByte(O, ModRMReg, getX86RegNum(ExtraReg));
442
443     O << "\n\t\t\t\t";
444     O << getName(MI->getOpCode()) << " ";
445     printOp(O, MI->getOperand(0), RI);
446     O << ", ";
447     printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
448     O << "\n";
449     return;
450   }
451
452   case X86II::MRMSrcMem: {
453     // These instructions are the same as MRMSrcReg, but instead of having a
454     // register reference for the mod/rm field, it's a memory reference.
455     //
456     assert(isReg(MI->getOperand(0)) &&
457            (MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
458            (MI->getNumOperands() == 2+4 && isReg(MI->getOperand(1)) && 
459             isMem(MI, 2))
460            && "Bad format for MRMDestReg!");
461     if (MI->getNumOperands() == 2+4 &&
462         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
463       O << "**";
464
465     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
466     unsigned ExtraReg = MI->getOperand(0).getReg();
467     emitMemModRMByte(O, MI, MI->getNumOperands()-4, getX86RegNum(ExtraReg));
468
469     O << "\n\t\t\t\t";
470     O << getName(MI->getOpCode()) << " ";
471     printOp(O, MI->getOperand(0), RI);
472     O << ", <SIZE> PTR ";
473     printMemReference(O, MI, MI->getNumOperands()-4, RI);
474     O << "\n";
475     return;
476   }
477
478   case X86II::MRMS0r: case X86II::MRMS1r:
479   case X86II::MRMS2r: case X86II::MRMS3r:
480   case X86II::MRMS4r: case X86II::MRMS5r:
481   case X86II::MRMS6r: case X86II::MRMS7r: {
482     // In this form, the following are valid formats:
483     //  1. sete r
484     //  2. cmp reg, immediate
485     //  2. shl rdest, rinput  <implicit CL or 1>
486     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
487     //    
488     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
489            isReg(MI->getOperand(0)) && "Bad MRMSxR format!");
490     assert((MI->getNumOperands() != 2 ||
491             isReg(MI->getOperand(1)) || isImmediate(MI->getOperand(1))) &&
492            "Bad MRMSxR format!");
493     assert((MI->getNumOperands() < 3 ||
494             (isReg(MI->getOperand(1)) && isImmediate(MI->getOperand(2)))) &&
495            "Bad MRMSxR format!");
496
497     if (MI->getNumOperands() > 1 && isReg(MI->getOperand(1)) && 
498         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
499       O << "**";
500
501     toHex(O, getBaseOpcodeFor(Opcode)) << " ";
502     unsigned ExtraField = (Desc.TSFlags & X86II::FormMask)-X86II::MRMS0r;
503     emitRegModRMByte(O, MI->getOperand(0).getReg(), ExtraField);
504
505     if (isImmediate(MI->getOperand(MI->getNumOperands()-1))) {
506       unsigned Size = 4;
507       emitConstant(O, MI->getOperand(MI->getNumOperands()-1).getImmedValue(),
508                    Size);
509     }
510
511     O << "\n\t\t\t\t";
512     O << getName(MI->getOpCode()) << " ";
513     printOp(O, MI->getOperand(0), RI);
514     if (isImmediate(MI->getOperand(MI->getNumOperands()-1))) {
515       O << ", ";
516       printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
517     }
518     O << "\n";
519
520     return;
521   }
522
523   default:
524     O << "\t\t\t-"; MI->print(O, TM); break;
525   }
526 }