Add Initialization and Finalization methods for the Printer pass,
[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/Function.h"
11 #include "llvm/Constant.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineConstantPool.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "Support/Statistic.h"
17
18 namespace {
19   struct Printer : public MachineFunctionPass {
20     std::ostream &O;
21     unsigned ConstIdx;
22     Printer(std::ostream &o) : O(o), ConstIdx(0) {}
23
24     virtual const char *getPassName() const {
25       return "X86 Assembly Printer";
26     }
27
28     void printConstantPool(MachineConstantPool *MCP, const TargetData &TD);
29     bool runOnMachineFunction(MachineFunction &F);
30     
31     bool doInitialization(Module &M);
32     bool doFinalization(Module &M);
33
34   };
35 }
36
37 /// createX86CodePrinterPass - Print out the specified machine code function to
38 /// the specified stream.  This function should work regardless of whether or
39 /// not the function is in SSA form or not.
40 ///
41 Pass *createX86CodePrinterPass(std::ostream &O) {
42   return new Printer(O);
43 }
44
45
46 // printConstantPool - Print out any constants which have been spilled to
47 // memory...
48 void Printer::printConstantPool(MachineConstantPool *MCP, const TargetData &TD){
49   const std::vector<Constant*> &CP = MCP->getConstants();
50   if (CP.empty()) return;
51
52   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
53     O << "\t.section .rodata\n";
54     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType()) << "\n";
55     O << ".CPI" << i+ConstIdx << ":\t\t\t\t\t;" << *CP[i] << "\n";
56     O << "\t*Constant output not implemented yet!*\n\n";
57   }
58   ConstIdx += CP.size();  // Don't recycle constant pool index numbers
59 }
60
61 /// runOnFunction - This uses the X86InstructionInfo::print method
62 /// to print assembly for each instruction.
63 bool Printer::runOnMachineFunction(MachineFunction &MF) {
64   static unsigned BBNumber = 0;
65   const TargetMachine &TM = MF.getTarget();
66   const TargetInstrInfo &TII = TM.getInstrInfo();
67
68   // Print out constants referenced by the function
69   printConstantPool(MF.getConstantPool(), TM.getTargetData());
70
71   // Print out labels for the function.
72   O << "\t.text\n";
73   O << "\t.align 16\n";
74   O << "\t.globl\t" << MF.getFunction()->getName() << "\n";
75   O << "\t.type\t" << MF.getFunction()->getName() << ", @function\n";
76   O << MF.getFunction()->getName() << ":\n";
77
78   // Print out code for the function.
79   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
80        I != E; ++I) {
81     // Print a label for the basic block.
82     O << ".BB" << BBNumber++ << ":\n";
83     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
84          II != E; ++II) {
85       // Print the assembly for the instruction.
86       O << "\t";
87       TII.print(*II, O, TM);
88     }
89   }
90
91   // We didn't modify anything.
92   return false;
93 }
94
95 static bool isScale(const MachineOperand &MO) {
96   return MO.isImmediate() &&
97            (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
98             MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
99 }
100
101 static bool isMem(const MachineInstr *MI, unsigned Op) {
102   if (MI->getOperand(Op).isFrameIndex()) return true;
103   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
104   return Op+4 <= MI->getNumOperands() &&
105          MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
106          MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
107 }
108
109 static void printOp(std::ostream &O, const MachineOperand &MO,
110                     const MRegisterInfo &RI) {
111   switch (MO.getType()) {
112   case MachineOperand::MO_VirtualRegister:
113     if (Value *V = MO.getVRegValueOrNull()) {
114       O << "<" << V->getName() << ">";
115       return;
116     }
117     // FALLTHROUGH
118   case MachineOperand::MO_MachineRegister:
119     if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
120       O << RI.get(MO.getReg()).Name;
121     else
122       O << "%reg" << MO.getReg();
123     return;
124
125   case MachineOperand::MO_SignExtendedImmed:
126   case MachineOperand::MO_UnextendedImmed:
127     O << (int)MO.getImmedValue();
128     return;
129   case MachineOperand::MO_PCRelativeDisp:
130     O << MO.getVRegValue()->getName();
131     return;
132   case MachineOperand::MO_GlobalAddress:
133     O << MO.getGlobal()->getName();
134     return;
135   case MachineOperand::MO_ExternalSymbol:
136     O << MO.getSymbolName();
137     return;
138   default:
139     O << "<unknown op ty>"; return;    
140   }
141 }
142
143 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
144   switch (Desc.TSFlags & X86II::ArgMask) {
145     default: assert(0 && "Unknown arg size!");
146     case X86II::Arg8:   return "BYTE PTR"; 
147     case X86II::Arg16:  return "WORD PTR"; 
148     case X86II::Arg32:  return "DWORD PTR"; 
149     case X86II::Arg64:  return "QWORD PTR"; 
150     case X86II::ArgF32:  return "DWORD PTR"; 
151     case X86II::ArgF64:  return "QWORD PTR"; 
152     case X86II::ArgF80:  return "XWORD PTR"; 
153   }
154 }
155
156 static void printMemReference(std::ostream &O, const MachineInstr *MI,
157                               unsigned Op, const MRegisterInfo &RI) {
158   assert(isMem(MI, Op) && "Invalid memory reference!");
159
160   if (MI->getOperand(Op).isFrameIndex()) {
161     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
162     if (MI->getOperand(Op+3).getImmedValue())
163       O << " + " << MI->getOperand(Op+3).getImmedValue();
164     O << "]";
165     return;
166   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
167     O << "[.CPI" << MI->getOperand(Op).getConstantPoolIndex();
168     if (MI->getOperand(Op+3).getImmedValue())
169       O << " + " << MI->getOperand(Op+3).getImmedValue();
170     O << "]";
171     return;
172   }
173
174   const MachineOperand &BaseReg  = MI->getOperand(Op);
175   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
176   const MachineOperand &IndexReg = MI->getOperand(Op+2);
177   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
178
179   O << "[";
180   bool NeedPlus = false;
181   if (BaseReg.getReg()) {
182     printOp(O, BaseReg, RI);
183     NeedPlus = true;
184   }
185
186   if (IndexReg.getReg()) {
187     if (NeedPlus) O << " + ";
188     if (ScaleVal != 1)
189       O << ScaleVal << "*";
190     printOp(O, IndexReg, RI);
191     NeedPlus = true;
192   }
193
194   if (DispVal) {
195     if (NeedPlus)
196       if (DispVal > 0)
197         O << " + ";
198       else {
199         O << " - ";
200         DispVal = -DispVal;
201       }
202     O << DispVal;
203   }
204   O << "]";
205 }
206
207 // print - Print out an x86 instruction in intel syntax
208 void X86InstrInfo::print(const MachineInstr *MI, std::ostream &O,
209                          const TargetMachine &TM) const {
210   unsigned Opcode = MI->getOpcode();
211   const TargetInstrDescriptor &Desc = get(Opcode);
212
213   switch (Desc.TSFlags & X86II::FormMask) {
214   case X86II::Pseudo:
215     // Print pseudo-instructions as comments; either they should have been
216     // turned into real instructions by now, or they don't need to be
217     // seen by the assembler (e.g., IMPLICIT_USEs.)
218     O << "# ";
219     if (Opcode == X86::PHI) {
220       printOp(O, MI->getOperand(0), RI);
221       O << " = phi ";
222       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
223         if (i != 1) O << ", ";
224         O << "[";
225         printOp(O, MI->getOperand(i), RI);
226         O << ", ";
227         printOp(O, MI->getOperand(i+1), RI);
228         O << "]";
229       }
230     } else {
231       unsigned i = 0;
232       if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() || 
233                                    MI->getOperand(0).opIsDefAndUse())) {
234         printOp(O, MI->getOperand(0), RI);
235         O << " = ";
236         ++i;
237       }
238       O << getName(MI->getOpcode());
239
240       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
241         O << " ";
242         if (MI->getOperand(i).opIsDefOnly() || 
243             MI->getOperand(i).opIsDefAndUse()) O << "*";
244         printOp(O, MI->getOperand(i), RI);
245         if (MI->getOperand(i).opIsDefOnly() || 
246             MI->getOperand(i).opIsDefAndUse()) O << "*";
247       }
248     }
249     O << "\n";
250     return;
251
252   case X86II::RawFrm:
253     // The accepted forms of Raw instructions are:
254     //   1. nop     - No operand required
255     //   2. jmp foo - PC relative displacement operand
256     //   3. call bar - GlobalAddress Operand or External Symbol Operand
257     //
258     assert(MI->getNumOperands() == 0 ||
259            (MI->getNumOperands() == 1 &&
260             (MI->getOperand(0).isPCRelativeDisp() ||
261              MI->getOperand(0).isGlobalAddress() ||
262              MI->getOperand(0).isExternalSymbol())) &&
263            "Illegal raw instruction!");
264     O << getName(MI->getOpcode()) << " ";
265
266     if (MI->getNumOperands() == 1) {
267       printOp(O, MI->getOperand(0), RI);
268     }
269     O << "\n";
270     return;
271
272   case X86II::AddRegFrm: {
273     // There are currently two forms of acceptable AddRegFrm instructions.
274     // Either the instruction JUST takes a single register (like inc, dec, etc),
275     // or it takes a register and an immediate of the same size as the register
276     // (move immediate f.e.).  Note that this immediate value might be stored as
277     // an LLVM value, to represent, for example, loading the address of a global
278     // into a register.  The initial register might be duplicated if this is a
279     // M_2_ADDR_REG instruction
280     //
281     assert(MI->getOperand(0).isRegister() &&
282            (MI->getNumOperands() == 1 || 
283             (MI->getNumOperands() == 2 &&
284              (MI->getOperand(1).getVRegValueOrNull() ||
285               MI->getOperand(1).isImmediate() ||
286               MI->getOperand(1).isRegister() ||
287               MI->getOperand(1).isGlobalAddress() ||
288               MI->getOperand(1).isExternalSymbol()))) &&
289            "Illegal form for AddRegFrm instruction!");
290
291     unsigned Reg = MI->getOperand(0).getReg();
292     
293     O << getName(MI->getOpCode()) << " ";
294     printOp(O, MI->getOperand(0), RI);
295     if (MI->getNumOperands() == 2 &&
296         (!MI->getOperand(1).isRegister() ||
297          MI->getOperand(1).getVRegValueOrNull() ||
298          MI->getOperand(1).isGlobalAddress() ||
299          MI->getOperand(1).isExternalSymbol())) {
300       O << ", ";
301       printOp(O, MI->getOperand(1), RI);
302     }
303     O << "\n";
304     return;
305   }
306   case X86II::MRMDestReg: {
307     // There are two acceptable forms of MRMDestReg instructions, those with 2,
308     // 3 and 4 operands:
309     //
310     // 2 Operands: this is for things like mov that do not read a second input
311     //
312     // 3 Operands: in this form, the first two registers (the destination, and
313     // the first operand) should be the same, post register allocation.  The 3rd
314     // operand is an additional input.  This should be for things like add
315     // instructions.
316     //
317     // 4 Operands: This form is for instructions which are 3 operands forms, but
318     // have a constant argument as well.
319     //
320     bool isTwoAddr = isTwoAddrInstr(Opcode);
321     assert(MI->getOperand(0).isRegister() &&
322            (MI->getNumOperands() == 2 ||
323             (isTwoAddr && MI->getOperand(1).isRegister() &&
324              MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
325              (MI->getNumOperands() == 3 ||
326               (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
327            && "Bad format for MRMDestReg!");
328
329     O << getName(MI->getOpCode()) << " ";
330     printOp(O, MI->getOperand(0), RI);
331     O << ", ";
332     printOp(O, MI->getOperand(1+isTwoAddr), RI);
333     if (MI->getNumOperands() == 4) {
334       O << ", ";
335       printOp(O, MI->getOperand(3), RI);
336     }
337     O << "\n";
338     return;
339   }
340
341   case X86II::MRMDestMem: {
342     // These instructions are the same as MRMDestReg, but instead of having a
343     // register reference for the mod/rm field, it's a memory reference.
344     //
345     assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
346            MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
347
348     O << getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
349     printMemReference(O, MI, 0, RI);
350     O << ", ";
351     printOp(O, MI->getOperand(4), RI);
352     O << "\n";
353     return;
354   }
355
356   case X86II::MRMSrcReg: {
357     // There is a two forms that are acceptable for MRMSrcReg instructions,
358     // those with 3 and 2 operands:
359     //
360     // 3 Operands: in this form, the last register (the second input) is the
361     // ModR/M input.  The first two operands should be the same, post register
362     // allocation.  This is for things like: add r32, r/m32
363     //
364     // 2 Operands: this is for things like mov that do not read a second input
365     //
366     assert(MI->getOperand(0).isRegister() &&
367            MI->getOperand(1).isRegister() &&
368            (MI->getNumOperands() == 2 || 
369             (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
370            && "Bad format for MRMSrcReg!");
371     if (MI->getNumOperands() == 3 &&
372         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
373       O << "**";
374
375     O << getName(MI->getOpCode()) << " ";
376     printOp(O, MI->getOperand(0), RI);
377     O << ", ";
378     printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
379     O << "\n";
380     return;
381   }
382
383   case X86II::MRMSrcMem: {
384     // These instructions are the same as MRMSrcReg, but instead of having a
385     // register reference for the mod/rm field, it's a memory reference.
386     //
387     assert(MI->getOperand(0).isRegister() &&
388            (MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
389            (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() && 
390             isMem(MI, 2))
391            && "Bad format for MRMDestReg!");
392     if (MI->getNumOperands() == 2+4 &&
393         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
394       O << "**";
395
396     O << getName(MI->getOpCode()) << " ";
397     printOp(O, MI->getOperand(0), RI);
398     O << ", " << sizePtr(Desc) << " ";
399     printMemReference(O, MI, MI->getNumOperands()-4, RI);
400     O << "\n";
401     return;
402   }
403
404   case X86II::MRMS0r: case X86II::MRMS1r:
405   case X86II::MRMS2r: case X86II::MRMS3r:
406   case X86II::MRMS4r: case X86II::MRMS5r:
407   case X86II::MRMS6r: case X86II::MRMS7r: {
408     // In this form, the following are valid formats:
409     //  1. sete r
410     //  2. cmp reg, immediate
411     //  2. shl rdest, rinput  <implicit CL or 1>
412     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
413     //    
414     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
415            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
416     assert((MI->getNumOperands() != 2 ||
417             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
418            "Bad MRMSxR format!");
419     assert((MI->getNumOperands() < 3 ||
420         (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
421            "Bad MRMSxR format!");
422
423     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
424         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
425       O << "**";
426
427     O << getName(MI->getOpCode()) << " ";
428     printOp(O, MI->getOperand(0), RI);
429     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
430       O << ", ";
431       printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
432     }
433     O << "\n";
434
435     return;
436   }
437
438   case X86II::MRMS0m: case X86II::MRMS1m:
439   case X86II::MRMS2m: case X86II::MRMS3m:
440   case X86II::MRMS4m: case X86II::MRMS5m:
441   case X86II::MRMS6m: case X86II::MRMS7m: {
442     // In this form, the following are valid formats:
443     //  1. sete [m]
444     //  2. cmp [m], immediate
445     //  2. shl [m], rinput  <implicit CL or 1>
446     //  3. sbb [m], immediate
447     //    
448     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
449            isMem(MI, 0) && "Bad MRMSxM format!");
450     assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
451            "Bad MRMSxM format!");
452
453     O << getName(MI->getOpCode()) << " ";
454     O << sizePtr(Desc) << " ";
455     printMemReference(O, MI, 0, RI);
456     if (MI->getNumOperands() == 5) {
457       O << ", ";
458       printOp(O, MI->getOperand(4), RI);
459     }
460     O << "\n";
461     return;
462   }
463
464   default:
465     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
466   }
467 }
468
469 bool Printer::doInitialization(Module &M)
470 {
471   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
472   // with no % decorations on register names.
473   O << "\t.intel_syntax noprefix\n";
474   return false; // success
475 }
476
477 bool Printer::doFinalization(Module &M)
478 {
479   // FIXME: We may have to print out constants here.
480   return false; // success
481 }
482