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