Support Cygwin assembly generation. The cygwin version of Gnu ASsembler
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to Intel assembly -------===//
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 a printer that converts from our internal representation
11 // of machine-dependent LLVM code to Intel and AT&T format assembly
12 // language. This printer is the output mechanism used by `llc' and `lli
13 // -print-machineinstrs' on X86.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/CommandLine.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
33   enum AsmWriterFlavor { att, intel };
34
35   cl::opt<AsmWriterFlavor>
36   AsmWriterFlavor("x86-asm-syntax",
37                   cl::desc("Choose style of code to emit from X86 backend:"),
38                   cl::values(
39                              clEnumVal(att,   "  Emit AT&T-style assembly"),
40                              clEnumVal(intel, "  Emit Intel-style assembly"),
41                              clEnumValEnd),
42                   cl::init(att));
43
44   struct X86SharedAsmPrinter : public AsmPrinter {
45     X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM)
46       : AsmPrinter(O, TM), forCygwin(false) { }
47
48     bool doInitialization(Module &M);
49     void printConstantPool(MachineConstantPool *MCP);
50     bool doFinalization(Module &M);
51     bool forCygwin;
52   };
53 }
54
55 static bool isScale(const MachineOperand &MO) {
56   return MO.isImmediate() &&
57     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
58      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
59 }
60
61 static bool isMem(const MachineInstr *MI, unsigned Op) {
62   if (MI->getOperand(Op).isFrameIndex()) return true;
63   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
64   return Op+4 <= MI->getNumOperands() &&
65     MI->getOperand(Op  ).isRegister() && isScale(MI->getOperand(Op+1)) &&
66     MI->getOperand(Op+2).isRegister() && (MI->getOperand(Op+3).isImmediate() ||
67         MI->getOperand(Op+3).isGlobalAddress());
68 }
69
70 // SwitchSection - Switch to the specified section of the executable if we are
71 // not already in it!
72 //
73 static void SwitchSection(std::ostream &OS, std::string &CurSection,
74                           const char *NewSection) {
75   if (CurSection != NewSection) {
76     CurSection = NewSection;
77     if (!CurSection.empty())
78       OS << "\t" << NewSection << "\n";
79   }
80 }
81
82 /// doInitialization - determine
83 bool X86SharedAsmPrinter::doInitialization(Module& M) {
84   forCygwin = false;
85   const std::string& TT = M.getTargetTriple();
86   if (TT.length() > 5)
87     forCygwin = TT.find("cygwin") != std::string::npos;
88   else if (TT.empty()) {
89 #ifdef __CYGWIN__
90     forCygwin = true;
91 #else
92     forCygwin = false;
93 #endif
94   }
95   if (forCygwin)
96     GlobalPrefix = "_";
97   return AsmPrinter::doInitialization(M);
98 }
99
100 /// printConstantPool - Print to the current output stream assembly
101 /// representations of the constants in the constant pool MCP. This is
102 /// used to print out constants which have been "spilled to memory" by
103 /// the code generator.
104 ///
105 void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
106   const std::vector<Constant*> &CP = MCP->getConstants();
107   const TargetData &TD = TM.getTargetData();
108  
109   if (CP.empty()) return;
110
111   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
112     O << "\t.section .rodata\n";
113     emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
114     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
115       << *CP[i] << "\n";
116     emitGlobalConstant(CP[i]);
117   }
118 }
119
120 bool X86SharedAsmPrinter::doFinalization(Module &M) {
121   const TargetData &TD = TM.getTargetData();
122   std::string CurSection;
123
124   // Print out module-level global variables here.
125   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
126     if (I->hasInitializer()) {   // External global require no code
127       O << "\n\n";
128       std::string name = Mang->getValueName(I);
129       Constant *C = I->getInitializer();
130       unsigned Size = TD.getTypeSize(C->getType());
131       unsigned Align = TD.getTypeAlignmentShift(C->getType());
132
133       if (C->isNullValue() && 
134           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
135            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
136         SwitchSection(O, CurSection, ".data");
137         if (!forCygwin && I->hasInternalLinkage())
138           O << "\t.local " << name << "\n";
139         
140         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
141         if (!forCygwin)
142           O << "," << (1 << Align);
143         O << "\t\t# ";
144         WriteAsOperand(O, I, true, true, &M);
145         O << "\n";
146       } else {
147         switch (I->getLinkage()) {
148         case GlobalValue::LinkOnceLinkage:
149         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
150           // Nonnull linkonce -> weak
151           O << "\t.weak " << name << "\n";
152           SwitchSection(O, CurSection, "");
153           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
154           break;
155         case GlobalValue::AppendingLinkage:
156           // FIXME: appending linkage variables should go into a section of
157           // their name or something.  For now, just emit them as external.
158         case GlobalValue::ExternalLinkage:
159           // If external or appending, declare as a global symbol
160           O << "\t.globl " << name << "\n";
161           // FALL THROUGH
162         case GlobalValue::InternalLinkage:
163           if (C->isNullValue())
164             SwitchSection(O, CurSection, ".bss");
165           else
166             SwitchSection(O, CurSection, ".data");
167           break;
168         case GlobalValue::GhostLinkage:
169           std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n";
170           abort();
171         }
172
173         emitAlignment(Align);
174         if (!forCygwin) {
175           O << "\t.type " << name << ",@object\n";
176           O << "\t.size " << name << "," << Size << "\n";
177         }
178         O << name << ":\t\t\t\t# ";
179         WriteAsOperand(O, I, true, true, &M);
180         O << " = ";
181         WriteAsOperand(O, C, false, false, &M);
182         O << "\n";
183         emitGlobalConstant(C);
184       }
185     }
186
187   AsmPrinter::doFinalization(M);
188   return false; // success
189 }
190
191 namespace {
192   struct X86IntelAsmPrinter : public X86SharedAsmPrinter {
193     X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM)
194       : X86SharedAsmPrinter(O, TM) { }
195
196     virtual const char *getPassName() const {
197       return "X86 Intel-Style Assembly Printer";
198     }
199
200     /// printInstruction - This method is automatically generated by tablegen
201     /// from the instruction set description.  This method returns true if the
202     /// machine instruction was sufficiently described to print it, otherwise it
203     /// returns false.
204     bool printInstruction(const MachineInstr *MI);
205
206     // This method is used by the tablegen'erated instruction printer.
207     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
208       const MachineOperand &MO = MI->getOperand(OpNo);
209       if (MO.getType() == MachineOperand::MO_MachineRegister) {
210         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
211         // Bug Workaround: See note in Printer::doInitialization about %.
212         O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
213       } else {
214         printOp(MO);
215       }
216     }
217
218     void printCallOperand(const MachineInstr *MI, unsigned OpNo,
219                           MVT::ValueType VT) {
220       printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
221     }
222
223     void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
224                             MVT::ValueType VT) {
225       switch (VT) {
226       default: assert(0 && "Unknown arg size!");
227       case MVT::i8:   O << "BYTE PTR "; break;
228       case MVT::i16:  O << "WORD PTR "; break;
229       case MVT::i32:
230       case MVT::f32:  O << "DWORD PTR "; break;
231       case MVT::i64:
232       case MVT::f64:  O << "QWORD PTR "; break;
233       case MVT::f80:  O << "XWORD PTR "; break;
234       }
235       printMemReference(MI, OpNo);
236     }
237
238     void printMachineInstruction(const MachineInstr *MI);
239     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
240     void printMemReference(const MachineInstr *MI, unsigned Op);
241     bool runOnMachineFunction(MachineFunction &F);    
242     bool doInitialization(Module &M);
243   };
244 } // end of anonymous namespace
245
246
247 // Include the auto-generated portion of the assembly writer.
248 #include "X86GenAsmWriter1.inc"
249
250
251 /// runOnMachineFunction - This uses the printMachineInstruction()
252 /// method to print assembly for each instruction.
253 ///
254 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
255   setupMachineFunction(MF);
256   O << "\n\n";
257
258   // Print out constants referenced by the function
259   printConstantPool(MF.getConstantPool());
260
261   // Print out labels for the function.
262   O << "\t.text\n";
263   emitAlignment(4);
264   O << "\t.globl\t" << CurrentFnName << "\n";
265   if (!forCygwin)
266     O << "\t.type\t" << CurrentFnName << ", @function\n";
267   O << CurrentFnName << ":\n";
268
269   // Print out code for the function.
270   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
271        I != E; ++I) {
272     // Print a label for the basic block if there are any predecessors.
273     if (I->pred_begin() != I->pred_end())
274       O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
275         << CommentString << " " << I->getBasicBlock()->getName() << "\n";
276     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
277          II != E; ++II) {
278       // Print the assembly for the instruction.
279       O << "\t";
280       printMachineInstruction(II);
281     }
282   }
283
284   // We didn't modify anything.
285   return false;
286 }
287
288 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
289                                  bool elideOffsetKeyword /* = false */) {
290   const MRegisterInfo &RI = *TM.getRegisterInfo();
291   switch (MO.getType()) {
292   case MachineOperand::MO_VirtualRegister:
293     if (Value *V = MO.getVRegValueOrNull()) {
294       O << "<" << V->getName() << ">";
295       return;
296     }
297     // FALLTHROUGH
298   case MachineOperand::MO_MachineRegister:
299     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
300       // Bug Workaround: See note in Printer::doInitialization about %.
301       O << "%" << RI.get(MO.getReg()).Name;
302     else
303       O << "%reg" << MO.getReg();
304     return;
305
306   case MachineOperand::MO_SignExtendedImmed:
307   case MachineOperand::MO_UnextendedImmed:
308     O << (int)MO.getImmedValue();
309     return;
310   case MachineOperand::MO_MachineBasicBlock: {
311     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
312     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
313       << "_" << MBBOp->getNumber () << "\t# "
314       << MBBOp->getBasicBlock ()->getName ();
315     return;
316   }
317   case MachineOperand::MO_PCRelativeDisp:
318     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
319     abort ();
320     return;
321   case MachineOperand::MO_GlobalAddress: {
322     if (!elideOffsetKeyword)
323       O << "OFFSET ";
324     O << Mang->getValueName(MO.getGlobal());
325     int Offset = MO.getOffset();
326     if (Offset > 0)
327       O << " + " << Offset;
328     else if (Offset < 0)
329       O << " - " << -Offset;
330     return;
331   }
332   case MachineOperand::MO_ExternalSymbol:
333     O << GlobalPrefix << MO.getSymbolName();
334     return;
335   default:
336     O << "<unknown operand type>"; return;    
337   }
338 }
339
340 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
341   assert(isMem(MI, Op) && "Invalid memory reference!");
342
343   const MachineOperand &BaseReg  = MI->getOperand(Op);
344   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
345   const MachineOperand &IndexReg = MI->getOperand(Op+2);
346   const MachineOperand &DispSpec = MI->getOperand(Op+3);
347
348   if (BaseReg.isFrameIndex()) {
349     O << "[frame slot #" << BaseReg.getFrameIndex();
350     if (DispSpec.getImmedValue())
351       O << " + " << DispSpec.getImmedValue();
352     O << "]";
353     return;
354   } else if (BaseReg.isConstantPoolIndex()) {
355     O << "[.CPI" << CurrentFnName << "_"
356       << BaseReg.getConstantPoolIndex();
357
358     if (IndexReg.getReg()) {
359       O << " + ";
360       if (ScaleVal != 1)
361         O << ScaleVal << "*";
362       printOp(IndexReg);
363     }
364     
365     if (DispSpec.getImmedValue())
366       O << " + " << DispSpec.getImmedValue();
367     O << "]";
368     return;
369   }
370
371   O << "[";
372   bool NeedPlus = false;
373   if (BaseReg.getReg()) {
374     printOp(BaseReg, true);
375     NeedPlus = true;
376   }
377
378   if (IndexReg.getReg()) {
379     if (NeedPlus) O << " + ";
380     if (ScaleVal != 1)
381       O << ScaleVal << "*";
382     printOp(IndexReg);
383     NeedPlus = true;
384   }
385
386   if (DispSpec.isGlobalAddress()) {
387     if (NeedPlus)
388       O << " + ";
389     printOp(DispSpec, true);
390   } else {
391     int DispVal = DispSpec.getImmedValue();
392     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
393       if (NeedPlus)
394         if (DispVal > 0)
395           O << " + ";
396         else {
397           O << " - ";
398           DispVal = -DispVal;
399         }
400       O << DispVal;
401     }
402   }
403   O << "]";
404 }
405
406
407 /// printMachineInstruction -- Print out a single X86 LLVM instruction
408 /// MI in Intel syntax to the current output stream.
409 ///
410 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
411   ++EmittedInsts;
412
413   // Call the autogenerated instruction printer routines.
414   printInstruction(MI);
415 }
416
417 bool X86IntelAsmPrinter::doInitialization(Module &M) {
418   AsmPrinter::doInitialization(M);
419   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
420   //
421   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
422   // instruction as a reference to the register named sp, and if you try to
423   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
424   // before being looked up in the symbol table. This creates spurious
425   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
426   // mode, and decorate all register names with percent signs.
427   O << "\t.intel_syntax\n";
428   return false;
429 }
430
431
432
433 namespace {
434   struct X86ATTAsmPrinter : public X86SharedAsmPrinter {
435     X86ATTAsmPrinter(std::ostream &O, TargetMachine &TM)
436       : X86SharedAsmPrinter(O, TM) { }
437
438     virtual const char *getPassName() const {
439       return "X86 AT&T-Style Assembly Printer";
440     }
441
442     /// printInstruction - This method is automatically generated by tablegen
443     /// from the instruction set description.  This method returns true if the
444     /// machine instruction was sufficiently described to print it, otherwise it
445     /// returns false.
446     bool printInstruction(const MachineInstr *MI);
447
448     // This method is used by the tablegen'erated instruction printer.
449     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
450       printOp(MI->getOperand(OpNo));
451     }
452
453     void printCallOperand(const MachineInstr *MI, unsigned OpNo,
454                           MVT::ValueType VT) {
455       printOp(MI->getOperand(OpNo), true); // Don't print '$' prefix.
456     }
457
458     void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
459                             MVT::ValueType VT) {
460       printMemReference(MI, OpNo);
461     }
462
463     void printMachineInstruction(const MachineInstr *MI);
464     void printOp(const MachineOperand &MO, bool isCallOperand = false);
465     void printMemReference(const MachineInstr *MI, unsigned Op);
466     bool runOnMachineFunction(MachineFunction &F);    
467   };
468 } // end of anonymous namespace
469
470
471 // Include the auto-generated portion of the assembly writer.
472 #include "X86GenAsmWriter.inc"
473
474
475 /// runOnMachineFunction - This uses the printMachineInstruction()
476 /// method to print assembly for each instruction.
477 ///
478 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
479   setupMachineFunction(MF);
480   O << "\n\n";
481
482   // Print out constants referenced by the function
483   printConstantPool(MF.getConstantPool());
484
485   // Print out labels for the function.
486   O << "\t.text\n";
487   emitAlignment(4);
488   O << "\t.globl\t" << CurrentFnName << "\n";
489   if (!forCygwin)
490     O << "\t.type\t" << CurrentFnName << ", @function\n";
491   O << CurrentFnName << ":\n";
492
493   // Print out code for the function.
494   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
495        I != E; ++I) {
496     // Print a label for the basic block.
497     if (I->pred_begin() != I->pred_end())
498       O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
499         << CommentString << " " << I->getBasicBlock()->getName() << "\n";
500     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
501          II != E; ++II) {
502       // Print the assembly for the instruction.
503       O << "\t";
504       printMachineInstruction(II);
505     }
506   }
507
508   // We didn't modify anything.
509   return false;
510 }
511
512 void X86ATTAsmPrinter::printOp(const MachineOperand &MO, bool isCallOp) {
513   const MRegisterInfo &RI = *TM.getRegisterInfo();
514   switch (MO.getType()) {
515   case MachineOperand::MO_VirtualRegister:
516   case MachineOperand::MO_MachineRegister:
517     assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
518            "Virtual registers should not make it this far!");
519     O << '%';
520     for (const char *Name = RI.get(MO.getReg()).Name; *Name; ++Name)
521       O << (char)tolower(*Name);
522     return;
523
524   case MachineOperand::MO_SignExtendedImmed:
525   case MachineOperand::MO_UnextendedImmed:
526     O << '$' << (int)MO.getImmedValue();
527     return;
528   case MachineOperand::MO_MachineBasicBlock: {
529     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
530     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
531       << "_" << MBBOp->getNumber () << "\t# "
532       << MBBOp->getBasicBlock ()->getName ();
533     return;
534   }
535   case MachineOperand::MO_PCRelativeDisp:
536     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
537     abort ();
538     return;
539   case MachineOperand::MO_GlobalAddress: {
540     if (!isCallOp) O << '$';
541     O << Mang->getValueName(MO.getGlobal());
542     int Offset = MO.getOffset();
543     if (Offset > 0)
544       O << "+" << Offset;
545     else if (Offset < 0)
546       O << Offset;
547     return;
548   }
549   case MachineOperand::MO_ExternalSymbol:
550     if (!isCallOp) O << '$';
551     O << GlobalPrefix << MO.getSymbolName();
552     return;
553   default:
554     O << "<unknown operand type>"; return;    
555   }
556 }
557
558 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
559   assert(isMem(MI, Op) && "Invalid memory reference!");
560
561   const MachineOperand &BaseReg  = MI->getOperand(Op);
562   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
563   const MachineOperand &IndexReg = MI->getOperand(Op+2);
564   const MachineOperand &DispSpec = MI->getOperand(Op+3);
565
566   if (BaseReg.isFrameIndex()) {
567     O << "[frame slot #" << BaseReg.getFrameIndex();
568     if (DispSpec.getImmedValue())
569       O << " + " << DispSpec.getImmedValue();
570     O << "]";
571     return;
572   } else if (BaseReg.isConstantPoolIndex()) {
573     O << ".CPI" << CurrentFnName << "_"
574       << BaseReg.getConstantPoolIndex();
575     if (DispSpec.getImmedValue())
576       O << "+" << DispSpec.getImmedValue();
577     if (IndexReg.getReg()) {
578       O << "(,";
579       printOp(IndexReg);
580       if (ScaleVal != 1)
581         O << "," << ScaleVal;
582       O << ")";
583     }
584     return;
585   }
586
587   if (DispSpec.isGlobalAddress()) {
588     printOp(DispSpec, true);
589   } else {
590     int DispVal = DispSpec.getImmedValue();
591     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
592       O << DispVal;
593   }
594
595   if (IndexReg.getReg() || BaseReg.getReg()) {
596     O << "(";
597     if (BaseReg.getReg())
598       printOp(BaseReg);
599
600     if (IndexReg.getReg()) {
601       O << ",";
602       printOp(IndexReg);
603       if (ScaleVal != 1)
604         O << "," << ScaleVal;
605     }
606
607     O << ")";
608   }
609 }
610
611
612 /// printMachineInstruction -- Print out a single X86 LLVM instruction
613 /// MI in Intel syntax to the current output stream.
614 ///
615 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
616   ++EmittedInsts;
617   // Call the autogenerated instruction printer routines.
618   printInstruction(MI);
619 }
620
621
622 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
623 /// for a MachineFunction to the given output stream, using the given target
624 /// machine description.
625 ///
626 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
627   switch (AsmWriterFlavor) {
628   default: 
629     assert(0 && "Unknown asm flavor!");
630   case intel:
631     return new X86IntelAsmPrinter(o, tm);
632   case att:
633     return new X86ATTAsmPrinter(o, tm);
634   }
635 }