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