93faa531ba4e30f661c0df5dfcc44e4720d4ebe6
[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     unsigned Reg = MO.getReg();
227     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
228       EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
229         MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
230                     ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
231       Reg = getX86SubSuperRegister(Reg, VT);
232     }
233     PrintRegName(O, getRegisterName(Reg));
234     return;
235   }
236   case MachineOperand::MO_Immediate:
237     O << MO.getImm();
238     return;
239   case MachineOperand::MO_JumpTableIndex: {
240     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
241     if (!isMemOp) O << "OFFSET ";
242     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
243       << "_" << MO.getIndex();
244     return;
245   }
246   case MachineOperand::MO_ConstantPoolIndex: {
247     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
248     if (!isMemOp) O << "OFFSET ";
249     O << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
250       << getFunctionNumber() << "_" << MO.getIndex();
251     printOffset(MO.getOffset());
252     O << "]";
253     return;
254   }
255   case MachineOperand::MO_GlobalAddress: {
256     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
257     GlobalValue *GV = MO.getGlobal();
258     std::string Name = Mang->getMangledName(GV);
259     decorateName(Name, GV);
260
261     if (!isMemOp) O << "OFFSET ";
262     
263     // Handle dllimport linkage.
264     // FIXME: This should be fixed with full support of stdcall & fastcall
265     // CC's
266     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
267       O << "__imp_";
268     
269     O << Name;
270     printOffset(MO.getOffset());
271     return;
272   }
273   case MachineOperand::MO_ExternalSymbol: {
274     O << MAI->getGlobalPrefix() << MO.getSymbolName();
275     return;
276   }
277   default:
278     O << "<unknown operand type>"; return;
279   }
280 }
281
282 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
283   const MachineOperand &MO = MI->getOperand(OpNo);
284   switch (MO.getType()) {
285   default: llvm_unreachable("Unknown pcrel immediate operand");
286   case MachineOperand::MO_Immediate:
287     O << MO.getImm();
288     return;
289   case MachineOperand::MO_MachineBasicBlock:
290     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
291     return;
292     
293   case MachineOperand::MO_GlobalAddress: {
294     GlobalValue *GV = MO.getGlobal();
295     std::string Name = Mang->getMangledName(GV);
296     decorateName(Name, GV);
297     
298     // Handle dllimport linkage.
299     // FIXME: This should be fixed with full support of stdcall & fastcall
300     // CC's
301     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
302       O << "__imp_";
303     O << Name;
304     printOffset(MO.getOffset());
305     return;
306   }
307
308   case MachineOperand::MO_ExternalSymbol:
309     O << MAI->getGlobalPrefix() << MO.getSymbolName();
310     return;
311   }
312 }
313
314
315 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
316                                               unsigned Op,
317                                               const char *Modifier) {
318   const MachineOperand &BaseReg  = MI->getOperand(Op);
319   int ScaleVal                   = MI->getOperand(Op+1).getImm();
320   const MachineOperand &IndexReg = MI->getOperand(Op+2);
321   const MachineOperand &DispSpec = MI->getOperand(Op+3);
322
323   O << "[";
324   bool NeedPlus = false;
325   if (BaseReg.getReg()) {
326     printOp(BaseReg, Modifier);
327     NeedPlus = true;
328   }
329
330   if (IndexReg.getReg()) {
331     if (NeedPlus) O << " + ";
332     if (ScaleVal != 1)
333       O << ScaleVal << "*";
334     printOp(IndexReg, Modifier);
335     NeedPlus = true;
336   }
337
338   if (DispSpec.isGlobal() || DispSpec.isCPI() ||
339       DispSpec.isJTI()) {
340     if (NeedPlus)
341       O << " + ";
342     printOp(DispSpec, "mem");
343   } else {
344     int DispVal = DispSpec.getImm();
345     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
346       if (NeedPlus) {
347         if (DispVal > 0)
348           O << " + ";
349         else {
350           O << " - ";
351           DispVal = -DispVal;
352         }
353       }
354       O << DispVal;
355     }
356   }
357   O << "]";
358 }
359
360 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
361                                            const char *Modifier) {
362   assert(isMem(MI, Op) && "Invalid memory reference!");
363   MachineOperand Segment = MI->getOperand(Op+4);
364   if (Segment.getReg()) {
365       printOperand(MI, Op+4, Modifier);
366       O << ':';
367     }
368   printLeaMemReference(MI, Op, Modifier);
369 }
370
371 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
372                                            const MachineBasicBlock *MBB) const {
373   if (!MAI->getSetDirective())
374     return;
375
376   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
377     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
378   GetMBBSymbol(MBB->getNumber())->print(O, MAI);
379   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
380 }
381
382 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
383   O << "L" << getFunctionNumber() << "$pb\n";
384   O << "L" << getFunctionNumber() << "$pb:";
385 }
386
387 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
388                                            const char Mode) {
389   unsigned Reg = MO.getReg();
390   switch (Mode) {
391   default: return true;  // Unknown mode.
392   case 'b': // Print QImode register
393     Reg = getX86SubSuperRegister(Reg, MVT::i8);
394     break;
395   case 'h': // Print QImode high register
396     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
397     break;
398   case 'w': // Print HImode register
399     Reg = getX86SubSuperRegister(Reg, MVT::i16);
400     break;
401   case 'k': // Print SImode register
402     Reg = getX86SubSuperRegister(Reg, MVT::i32);
403     break;
404   }
405
406   PrintRegName(O, getRegisterName(Reg));
407   return false;
408 }
409
410 /// PrintAsmOperand - Print out an operand for an inline asm expression.
411 ///
412 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
413                                          unsigned AsmVariant,
414                                          const char *ExtraCode) {
415   // Does this asm operand have a single letter operand modifier?
416   if (ExtraCode && ExtraCode[0]) {
417     if (ExtraCode[1] != 0) return true; // Unknown modifier.
418
419     switch (ExtraCode[0]) {
420     default: return true;  // Unknown modifier.
421     case 'b': // Print QImode register
422     case 'h': // Print QImode high register
423     case 'w': // Print HImode register
424     case 'k': // Print SImode register
425       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
426     }
427   }
428
429   printOperand(MI, OpNo);
430   return false;
431 }
432
433 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
434                                                unsigned OpNo,
435                                                unsigned AsmVariant,
436                                                const char *ExtraCode) {
437   if (ExtraCode && ExtraCode[0])
438     return true; // Unknown modifier.
439   printMemReference(MI, OpNo);
440   return false;
441 }
442
443 /// printMachineInstruction -- Print out a single X86 LLVM instruction
444 /// MI in Intel syntax to the current output stream.
445 ///
446 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
447   ++EmittedInsts;
448
449   processDebugLoc(MI->getDebugLoc());
450
451   // Call the autogenerated instruction printer routines.
452   printInstruction(MI);
453   
454   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
455     EmitComments(*MI);
456   O << '\n';
457 }
458
459 bool X86IntelAsmPrinter::doInitialization(Module &M) {
460   bool Result = AsmPrinter::doInitialization(M);
461
462   O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
463
464   // Emit declarations for external functions.
465   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
466     if (I->isDeclaration()) {
467       std::string Name = Mang->getMangledName(I);
468       decorateName(Name, I);
469
470       O << "\tEXTERN " ;
471       if (I->hasDLLImportLinkage()) {
472         O << "__imp_";
473       }
474       O << Name << ":near\n";
475     }
476
477   // Emit declarations for external globals.  Note that VC++ always declares
478   // external globals to have type byte, and if that's good enough for VC++...
479   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
480        I != E; ++I) {
481     if (I->isDeclaration()) {
482       std::string Name = Mang->getMangledName(I);
483
484       O << "\tEXTERN " ;
485       if (I->hasDLLImportLinkage()) {
486         O << "__imp_";
487       }
488       O << Name << ":byte\n";
489     }
490   }
491
492   return Result;
493 }
494
495 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
496   // Check to see if this is a special global used by LLVM, if so, emit it.
497   if (GV->isDeclaration() ||
498       EmitSpecialLLVMGlobal(GV))
499     return;
500   
501   const TargetData *TD = TM.getTargetData();
502
503   std::string name = Mang->getMangledName(GV);
504   Constant *C = GV->getInitializer();
505   unsigned Align = TD->getPreferredAlignmentLog(GV);
506   bool bCustomSegment = false;
507   
508   switch (GV->getLinkage()) {
509   case GlobalValue::CommonLinkage:
510   case GlobalValue::LinkOnceAnyLinkage:
511   case GlobalValue::LinkOnceODRLinkage:
512   case GlobalValue::WeakAnyLinkage:
513   case GlobalValue::WeakODRLinkage:
514     // FIXME: make a MCSection.
515     O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
516     bCustomSegment = true;
517     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
518     // are also available.
519     break;
520   case GlobalValue::AppendingLinkage:
521     // FIXME: make a MCSection.
522     O << name << "?\tSEGMENT PARA public 'DATA'\n";
523     bCustomSegment = true;
524     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
525     // are also available.
526     break;
527   case GlobalValue::DLLExportLinkage:
528     DLLExportedGVs.insert(name);
529     // FALL THROUGH
530   case GlobalValue::ExternalLinkage:
531     O << "\tpublic " << name << "\n";
532     // FALL THROUGH
533   case GlobalValue::InternalLinkage:
534     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
535     break;
536   default:
537     llvm_unreachable("Unknown linkage type!");
538   }
539   
540   if (!bCustomSegment)
541     EmitAlignment(Align, GV);
542   
543   O << name << ":";
544   if (VerboseAsm)
545     O.PadToColumn(MAI->getCommentColumn());
546     O << MAI->getCommentString()
547     << " " << GV->getName();
548   O << '\n';
549   
550   EmitGlobalConstant(C);
551   
552   if (bCustomSegment)
553     O << name << "?\tends\n";
554 }
555
556 bool X86IntelAsmPrinter::doFinalization(Module &M) {
557   // Output linker support code for dllexported globals
558   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
559     O << "; WARNING: The following code is valid only with MASM v8.x"
560       << "and (possible) higher\n"
561       << "; This version of MASM is usually shipped with Microsoft "
562       << "Visual Studio 2005\n"
563       << "; or (possible) further versions. Unfortunately, there is no "
564       << "way to support\n"
565       << "; dllexported symbols in the earlier versions of MASM in fully "
566       << "automatic way\n\n";
567     O << "_drectve\t segment info alias('.drectve')\n";
568
569     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
570            e = DLLExportedGVs.end();
571            i != e; ++i)
572       O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
573
574     for (StringSet<>::iterator i = DLLExportedFns.begin(),
575            e = DLLExportedFns.end();
576            i != e; ++i)
577       O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
578
579     O << "_drectve\t ends\n";
580   }
581
582   // Bypass X86SharedAsmPrinter::doFinalization().
583   bool Result = AsmPrinter::doFinalization(M);
584   O << "\tend\n";
585   return Result;
586 }
587
588 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
589   unsigned NumElts = CVA->getNumOperands();
590   if (NumElts == 0) return;
591   
592   // ML does not have escape sequences except '' for '.  It also has a maximum
593   // string length of 255.
594   unsigned len = 0;
595   bool inString = false;
596   for (unsigned i = 0; i < NumElts; i++) {
597     int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
598     if (len == 0)
599       O << "\tdb ";
600
601     if (n >= 32 && n <= 127) {
602       if (!inString) {
603         if (len > 0) {
604           O << ",'";
605           len += 2;
606         } else {
607           O << "'";
608           len++;
609         }
610         inString = true;
611       }
612       if (n == '\'') {
613         O << "'";
614         len++;
615       }
616       O << char(n);
617     } else {
618       if (inString) {
619         O << "'";
620         len++;
621         inString = false;
622       }
623       if (len > 0) {
624         O << ",";
625         len++;
626       }
627       O << n;
628       len += 1 + (n > 9) + (n > 99);
629     }
630
631     if (len > 60) {
632       if (inString) {
633         O << "'";
634         inString = false;
635       }
636       O << "\n";
637       len = 0;
638     }
639   }
640
641   if (len > 0) {
642     if (inString)
643       O << "'";
644     O << "\n";
645   }
646 }
647
648 // Include the auto-generated portion of the assembly writer.
649 #include "X86GenAsmWriter1.inc"