2585605f0e7ee58efa9de0c31824b19e1040a00e
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86IntelAsmPrinter.h"
18 #include "X86InstrInfo.h"
19 #include "X86MCAsmInfo.h"
20 #include "X86.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Mangler.h"
36 using namespace llvm;
37
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39
40 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
41                                                     const TargetData *TD) {
42   X86MachineFunctionInfo Info;
43   uint64_t Size = 0;
44
45   switch (F->getCallingConv()) {
46   case CallingConv::X86_StdCall:
47     Info.setDecorationStyle(StdCall);
48     break;
49   case CallingConv::X86_FastCall:
50     Info.setDecorationStyle(FastCall);
51     break;
52   default:
53     return Info;
54   }
55
56   unsigned argNum = 1;
57   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
58        AI != AE; ++AI, ++argNum) {
59     const Type* Ty = AI->getType();
60
61     // 'Dereference' type in case of byval parameter attribute
62     if (F->paramHasAttr(argNum, Attribute::ByVal))
63       Ty = cast<PointerType>(Ty)->getElementType();
64
65     // Size should be aligned to DWORD boundary
66     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
67   }
68
69   // We're not supporting tooooo huge arguments :)
70   Info.setBytesToPopOnReturn((unsigned int)Size);
71   return Info;
72 }
73
74
75 /// decorateName - Query FunctionInfoMap and use this information for various
76 /// name decoration.
77 void X86IntelAsmPrinter::decorateName(std::string &Name,
78                                       const GlobalValue *GV) {
79   const Function *F = dyn_cast<Function>(GV);
80   if (!F) return;
81
82   // We don't want to decorate non-stdcall or non-fastcall functions right now
83   CallingConv::ID CC = F->getCallingConv();
84   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
85     return;
86
87   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
88
89   const X86MachineFunctionInfo *Info;
90   if (info_item == FunctionInfoMap.end()) {
91     // Calculate apropriate function info and populate map
92     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
93     Info = &FunctionInfoMap[F];
94   } else {
95     Info = &info_item->second;
96   }
97
98   const FunctionType *FT = F->getFunctionType();
99   switch (Info->getDecorationStyle()) {
100   case None:
101     break;
102   case StdCall:
103     // "Pure" variadic functions do not receive @0 suffix.
104     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
105         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
106       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
107     break;
108   case FastCall:
109     // "Pure" variadic functions do not receive @0 suffix.
110     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
111         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
112       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
113
114     if (Name[0] == '_')
115       Name[0] = '@';
116     else
117       Name = '@' + Name;
118
119     break;
120   default:
121     llvm_unreachable("Unsupported DecorationStyle");
122   }
123 }
124
125 /// runOnMachineFunction - This uses the printMachineInstruction()
126 /// method to print assembly for each instruction.
127 ///
128 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
129   this->MF = &MF;
130   SetupMachineFunction(MF);
131   O << "\n\n";
132
133   // Print out constants referenced by the function
134   EmitConstantPool(MF.getConstantPool());
135
136   // Print out labels for the function.
137   const Function *F = MF.getFunction();
138   CallingConv::ID CC = F->getCallingConv();
139   unsigned FnAlign = MF.getAlignment();
140
141   // Populate function information map.  Actually, We don't want to populate
142   // non-stdcall or non-fastcall functions' information right now.
143   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
144     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
145
146   decorateName(CurrentFnName, F);
147
148   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
149
150   switch (F->getLinkage()) {
151   default: llvm_unreachable("Unsupported linkage type!");
152   case Function::LinkOnceAnyLinkage:
153   case Function::LinkOnceODRLinkage:
154   case Function::WeakAnyLinkage:
155   case Function::WeakODRLinkage:
156       
157   case Function::PrivateLinkage:
158   case Function::LinkerPrivateLinkage:
159   case Function::InternalLinkage:
160     EmitAlignment(FnAlign);
161     break;
162   case Function::DLLExportLinkage:
163     DLLExportedFns.insert(CurrentFnName);
164     //FALLS THROUGH
165   case Function::ExternalLinkage:
166     O << "\tpublic " << CurrentFnName << "\n";
167     EmitAlignment(FnAlign);
168     break;
169   }
170
171   O << CurrentFnName << "\tproc near\n";
172
173   // Print out code for the function.
174   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
175        I != E; ++I) {
176     // Print a label for the basic block if there are any predecessors.
177     if (!I->pred_empty()) {
178       EmitBasicBlockStart(I);
179       O << '\n';
180     }
181     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
182          II != E; ++II) {
183       // Print the assembly for the instruction.
184       printMachineInstruction(II);
185     }
186   }
187
188   // Print out jump tables referenced by the function.
189   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
190
191   O << CurrentFnName << "\tendp\n";
192
193   // We didn't modify anything.
194   return false;
195 }
196
197 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
198   unsigned char value = MI->getOperand(Op).getImm();
199   assert(value <= 7 && "Invalid ssecc argument!");
200   switch (value) {
201   case 0: O << "eq"; break;
202   case 1: O << "lt"; break;
203   case 2: O << "le"; break;
204   case 3: O << "unord"; break;
205   case 4: O << "neq"; break;
206   case 5: O << "nlt"; break;
207   case 6: O << "nle"; break;
208   case 7: O << "ord"; break;
209   }
210 }
211
212 static void PrintRegName(raw_ostream &O, StringRef RegName) {
213   for (unsigned i = 0, e = RegName.size(); i != e; ++i)
214     O << (char)toupper(RegName[i]);
215 }
216
217 void X86IntelAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
218                                       const char *Modifier) {
219   printOp(MI->getOperand(OpNo), Modifier);
220 }
221
222 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
223                                  const char *Modifier) {
224   switch (MO.getType()) {
225   case MachineOperand::MO_Register: {
226     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
227     unsigned Reg = MO.getReg();
228     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
229       EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
230         MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
231                     ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
232       Reg = getX86SubSuperRegister(Reg, VT);
233     }
234     PrintRegName(O, getRegisterName(Reg));
235     return;
236   }
237   case MachineOperand::MO_Immediate:
238     O << MO.getImm();
239     return;
240   case MachineOperand::MO_JumpTableIndex: {
241     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
242     if (!isMemOp) O << "OFFSET ";
243     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
244       << "_" << MO.getIndex();
245     return;
246   }
247   case MachineOperand::MO_ConstantPoolIndex: {
248     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
249     if (!isMemOp) O << "OFFSET ";
250     O << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
251       << getFunctionNumber() << "_" << MO.getIndex();
252     printOffset(MO.getOffset());
253     O << "]";
254     return;
255   }
256   case MachineOperand::MO_GlobalAddress: {
257     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
258     GlobalValue *GV = MO.getGlobal();
259     std::string Name = Mang->getMangledName(GV);
260     decorateName(Name, GV);
261
262     if (!isMemOp) O << "OFFSET ";
263     
264     // Handle dllimport linkage.
265     // FIXME: This should be fixed with full support of stdcall & fastcall
266     // CC's
267     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
268       O << "__imp_";
269     
270     O << Name;
271     printOffset(MO.getOffset());
272     return;
273   }
274   case MachineOperand::MO_ExternalSymbol: {
275     O << MAI->getGlobalPrefix() << MO.getSymbolName();
276     return;
277   }
278   default:
279     O << "<unknown operand type>"; return;
280   }
281 }
282
283 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
284   const MachineOperand &MO = MI->getOperand(OpNo);
285   switch (MO.getType()) {
286   default: llvm_unreachable("Unknown pcrel immediate operand");
287   case MachineOperand::MO_Immediate:
288     O << MO.getImm();
289     return;
290   case MachineOperand::MO_MachineBasicBlock:
291     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
292     return;
293     
294   case MachineOperand::MO_GlobalAddress: {
295     GlobalValue *GV = MO.getGlobal();
296     std::string Name = Mang->getMangledName(GV);
297     decorateName(Name, GV);
298     
299     // Handle dllimport linkage.
300     // FIXME: This should be fixed with full support of stdcall & fastcall
301     // CC's
302     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
303       O << "__imp_";
304     O << Name;
305     printOffset(MO.getOffset());
306     return;
307   }
308
309   case MachineOperand::MO_ExternalSymbol:
310     O << MAI->getGlobalPrefix() << MO.getSymbolName();
311     return;
312   }
313 }
314
315
316 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
317                                               unsigned Op,
318                                               const char *Modifier) {
319   const MachineOperand &BaseReg  = MI->getOperand(Op);
320   int ScaleVal                   = MI->getOperand(Op+1).getImm();
321   const MachineOperand &IndexReg = MI->getOperand(Op+2);
322   const MachineOperand &DispSpec = MI->getOperand(Op+3);
323
324   O << "[";
325   bool NeedPlus = false;
326   if (BaseReg.getReg()) {
327     printOp(BaseReg, Modifier);
328     NeedPlus = true;
329   }
330
331   if (IndexReg.getReg()) {
332     if (NeedPlus) O << " + ";
333     if (ScaleVal != 1)
334       O << ScaleVal << "*";
335     printOp(IndexReg, Modifier);
336     NeedPlus = true;
337   }
338
339   if (DispSpec.isGlobal() || DispSpec.isCPI() ||
340       DispSpec.isJTI()) {
341     if (NeedPlus)
342       O << " + ";
343     printOp(DispSpec, "mem");
344   } else {
345     int DispVal = DispSpec.getImm();
346     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
347       if (NeedPlus) {
348         if (DispVal > 0)
349           O << " + ";
350         else {
351           O << " - ";
352           DispVal = -DispVal;
353         }
354       }
355       O << DispVal;
356     }
357   }
358   O << "]";
359 }
360
361 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
362                                            const char *Modifier) {
363   assert(isMem(MI, Op) && "Invalid memory reference!");
364   MachineOperand Segment = MI->getOperand(Op+4);
365   if (Segment.getReg()) {
366       printOperand(MI, Op+4, Modifier);
367       O << ':';
368     }
369   printLeaMemReference(MI, Op, Modifier);
370 }
371
372 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
373                                            const MachineBasicBlock *MBB) const {
374   if (!MAI->getSetDirective())
375     return;
376
377   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
378     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
379   GetMBBSymbol(MBB->getNumber())->print(O, MAI);
380   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
381 }
382
383 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
384   O << "L" << getFunctionNumber() << "$pb\n";
385   O << "L" << getFunctionNumber() << "$pb:";
386 }
387
388 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
389                                            const char Mode) {
390   unsigned Reg = MO.getReg();
391   switch (Mode) {
392   default: return true;  // Unknown mode.
393   case 'b': // Print QImode register
394     Reg = getX86SubSuperRegister(Reg, MVT::i8);
395     break;
396   case 'h': // Print QImode high register
397     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
398     break;
399   case 'w': // Print HImode register
400     Reg = getX86SubSuperRegister(Reg, MVT::i16);
401     break;
402   case 'k': // Print SImode register
403     Reg = getX86SubSuperRegister(Reg, MVT::i32);
404     break;
405   }
406
407   PrintRegName(O, getRegisterName(Reg));
408   return false;
409 }
410
411 /// PrintAsmOperand - Print out an operand for an inline asm expression.
412 ///
413 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
414                                          unsigned AsmVariant,
415                                          const char *ExtraCode) {
416   // Does this asm operand have a single letter operand modifier?
417   if (ExtraCode && ExtraCode[0]) {
418     if (ExtraCode[1] != 0) return true; // Unknown modifier.
419
420     switch (ExtraCode[0]) {
421     default: return true;  // Unknown modifier.
422     case 'b': // Print QImode register
423     case 'h': // Print QImode high register
424     case 'w': // Print HImode register
425     case 'k': // Print SImode register
426       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
427     }
428   }
429
430   printOperand(MI, OpNo);
431   return false;
432 }
433
434 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
435                                                unsigned OpNo,
436                                                unsigned AsmVariant,
437                                                const char *ExtraCode) {
438   if (ExtraCode && ExtraCode[0])
439     return true; // Unknown modifier.
440   printMemReference(MI, OpNo);
441   return false;
442 }
443
444 /// printMachineInstruction -- Print out a single X86 LLVM instruction
445 /// MI in Intel syntax to the current output stream.
446 ///
447 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
448   ++EmittedInsts;
449
450   processDebugLoc(MI->getDebugLoc());
451
452   // Call the autogenerated instruction printer routines.
453   printInstruction(MI);
454   
455   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
456     EmitComments(*MI);
457   O << '\n';
458 }
459
460 bool X86IntelAsmPrinter::doInitialization(Module &M) {
461   bool Result = AsmPrinter::doInitialization(M);
462
463   O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
464
465   // Emit declarations for external functions.
466   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
467     if (I->isDeclaration()) {
468       std::string Name = Mang->getMangledName(I);
469       decorateName(Name, I);
470
471       O << "\tEXTERN " ;
472       if (I->hasDLLImportLinkage()) {
473         O << "__imp_";
474       }
475       O << Name << ":near\n";
476     }
477
478   // Emit declarations for external globals.  Note that VC++ always declares
479   // external globals to have type byte, and if that's good enough for VC++...
480   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
481        I != E; ++I) {
482     if (I->isDeclaration()) {
483       std::string Name = Mang->getMangledName(I);
484
485       O << "\tEXTERN " ;
486       if (I->hasDLLImportLinkage()) {
487         O << "__imp_";
488       }
489       O << Name << ":byte\n";
490     }
491   }
492
493   return Result;
494 }
495
496 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
497   // Check to see if this is a special global used by LLVM, if so, emit it.
498   if (GV->isDeclaration() ||
499       EmitSpecialLLVMGlobal(GV))
500     return;
501   
502   const TargetData *TD = TM.getTargetData();
503
504   std::string name = Mang->getMangledName(GV);
505   Constant *C = GV->getInitializer();
506   unsigned Align = TD->getPreferredAlignmentLog(GV);
507   bool bCustomSegment = false;
508   
509   switch (GV->getLinkage()) {
510   case GlobalValue::CommonLinkage:
511   case GlobalValue::LinkOnceAnyLinkage:
512   case GlobalValue::LinkOnceODRLinkage:
513   case GlobalValue::WeakAnyLinkage:
514   case GlobalValue::WeakODRLinkage:
515     // FIXME: make a MCSection.
516     O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
517     bCustomSegment = true;
518     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
519     // are also available.
520     break;
521   case GlobalValue::AppendingLinkage:
522     // FIXME: make a MCSection.
523     O << name << "?\tSEGMENT PARA public 'DATA'\n";
524     bCustomSegment = true;
525     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
526     // are also available.
527     break;
528   case GlobalValue::DLLExportLinkage:
529     DLLExportedGVs.insert(name);
530     // FALL THROUGH
531   case GlobalValue::ExternalLinkage:
532     O << "\tpublic " << name << "\n";
533     // FALL THROUGH
534   case GlobalValue::InternalLinkage:
535     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
536     break;
537   default:
538     llvm_unreachable("Unknown linkage type!");
539   }
540   
541   if (!bCustomSegment)
542     EmitAlignment(Align, GV);
543   
544   O << name << ":";
545   if (VerboseAsm)
546     O.PadToColumn(MAI->getCommentColumn());
547     O << MAI->getCommentString()
548     << " " << GV->getName();
549   O << '\n';
550   
551   EmitGlobalConstant(C);
552   
553   if (bCustomSegment)
554     O << name << "?\tends\n";
555 }
556
557 bool X86IntelAsmPrinter::doFinalization(Module &M) {
558   // Output linker support code for dllexported globals
559   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
560     O << "; WARNING: The following code is valid only with MASM v8.x"
561       << "and (possible) higher\n"
562       << "; This version of MASM is usually shipped with Microsoft "
563       << "Visual Studio 2005\n"
564       << "; or (possible) further versions. Unfortunately, there is no "
565       << "way to support\n"
566       << "; dllexported symbols in the earlier versions of MASM in fully "
567       << "automatic way\n\n";
568     O << "_drectve\t segment info alias('.drectve')\n";
569
570     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
571            e = DLLExportedGVs.end();
572            i != e; ++i)
573       O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
574
575     for (StringSet<>::iterator i = DLLExportedFns.begin(),
576            e = DLLExportedFns.end();
577            i != e; ++i)
578       O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
579
580     O << "_drectve\t ends\n";
581   }
582
583   // Bypass X86SharedAsmPrinter::doFinalization().
584   bool Result = AsmPrinter::doFinalization(M);
585   O << "\tend\n";
586   return Result;
587 }
588
589 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
590   unsigned NumElts = CVA->getNumOperands();
591   if (NumElts == 0) return;
592   
593   // ML does not have escape sequences except '' for '.  It also has a maximum
594   // string length of 255.
595   unsigned len = 0;
596   bool inString = false;
597   for (unsigned i = 0; i < NumElts; i++) {
598     int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
599     if (len == 0)
600       O << "\tdb ";
601
602     if (n >= 32 && n <= 127) {
603       if (!inString) {
604         if (len > 0) {
605           O << ",'";
606           len += 2;
607         } else {
608           O << "'";
609           len++;
610         }
611         inString = true;
612       }
613       if (n == '\'') {
614         O << "'";
615         len++;
616       }
617       O << char(n);
618     } else {
619       if (inString) {
620         O << "'";
621         len++;
622         inString = false;
623       }
624       if (len > 0) {
625         O << ",";
626         len++;
627       }
628       O << n;
629       len += 1 + (n > 9) + (n > 99);
630     }
631
632     if (len > 60) {
633       if (inString) {
634         O << "'";
635         inString = false;
636       }
637       O << "\n";
638       len = 0;
639     }
640   }
641
642   if (len > 0) {
643     if (inString)
644       O << "'";
645     O << "\n";
646   }
647 }
648
649 // Include the auto-generated portion of the assembly writer.
650 #include "X86GenAsmWriter1.inc"