Revert 74164. We'll want to use this method later.
[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/Mangler.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 using namespace llvm;
33
34 STATISTIC(EmittedInsts, "Number of machine instrs printed");
35
36 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
37                                                     const TargetData *TD) {
38   X86MachineFunctionInfo Info;
39   uint64_t Size = 0;
40
41   switch (F->getCallingConv()) {
42   case CallingConv::X86_StdCall:
43     Info.setDecorationStyle(StdCall);
44     break;
45   case CallingConv::X86_FastCall:
46     Info.setDecorationStyle(FastCall);
47     break;
48   default:
49     return Info;
50   }
51
52   unsigned argNum = 1;
53   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
54        AI != AE; ++AI, ++argNum) {
55     const Type* Ty = AI->getType();
56
57     // 'Dereference' type in case of byval parameter attribute
58     if (F->paramHasAttr(argNum, Attribute::ByVal))
59       Ty = cast<PointerType>(Ty)->getElementType();
60
61     // Size should be aligned to DWORD boundary
62     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
63   }
64
65   // We're not supporting tooooo huge arguments :)
66   Info.setBytesToPopOnReturn((unsigned int)Size);
67   return Info;
68 }
69
70
71 /// decorateName - Query FunctionInfoMap and use this information for various
72 /// name decoration.
73 void X86IntelAsmPrinter::decorateName(std::string &Name,
74                                       const GlobalValue *GV) {
75   const Function *F = dyn_cast<Function>(GV);
76   if (!F) return;
77
78   // We don't want to decorate non-stdcall or non-fastcall functions right now
79   unsigned CC = F->getCallingConv();
80   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
81     return;
82
83   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
84
85   const X86MachineFunctionInfo *Info;
86   if (info_item == FunctionInfoMap.end()) {
87     // Calculate apropriate function info and populate map
88     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
89     Info = &FunctionInfoMap[F];
90   } else {
91     Info = &info_item->second;
92   }
93
94   const FunctionType *FT = F->getFunctionType();
95   switch (Info->getDecorationStyle()) {
96   case None:
97     break;
98   case StdCall:
99     // "Pure" variadic functions do not receive @0 suffix.
100     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
101         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
102       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
103     break;
104   case FastCall:
105     // "Pure" variadic functions do not receive @0 suffix.
106     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
107         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
108       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
109
110     if (Name[0] == '_')
111       Name[0] = '@';
112     else
113       Name = '@' + Name;
114
115     break;
116   default:
117     assert(0 && "Unsupported DecorationStyle");
118   }
119 }
120
121 /// runOnMachineFunction - This uses the printMachineInstruction()
122 /// method to print assembly for each instruction.
123 ///
124 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
125   this->MF = &MF;
126   SetupMachineFunction(MF);
127   O << "\n\n";
128
129   // Print out constants referenced by the function
130   EmitConstantPool(MF.getConstantPool());
131
132   // Print out labels for the function.
133   const Function *F = MF.getFunction();
134   unsigned CC = F->getCallingConv();
135
136   // Populate function information map.  Actually, We don't want to populate
137   // non-stdcall or non-fastcall functions' information right now.
138   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
139     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
140
141   decorateName(CurrentFnName, F);
142
143   SwitchToTextSection("_text", F);
144
145   unsigned FnAlign = 4;
146   if (F->hasFnAttr(Attribute::OptimizeForSize))
147     FnAlign = 1;
148   switch (F->getLinkage()) {
149   default: assert(0 && "Unsupported linkage type!");
150   case Function::PrivateLinkage:
151   case Function::InternalLinkage:
152     EmitAlignment(FnAlign);
153     break;
154   case Function::DLLExportLinkage:
155     DLLExportedFns.insert(CurrentFnName);
156     //FALLS THROUGH
157   case Function::ExternalLinkage:
158     O << "\tpublic " << CurrentFnName << "\n";
159     EmitAlignment(FnAlign);
160     break;
161   }
162
163   O << CurrentFnName << "\tproc near\n";
164
165   // Print out code for the function.
166   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
167        I != E; ++I) {
168     // Print a label for the basic block if there are any predecessors.
169     if (!I->pred_empty()) {
170       printBasicBlockLabel(I, true, true);
171       O << '\n';
172     }
173     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
174          II != E; ++II) {
175       // Print the assembly for the instruction.
176       printMachineInstruction(II);
177     }
178   }
179
180   // Print out jump tables referenced by the function.
181   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
182
183   O << CurrentFnName << "\tendp\n";
184
185   O.flush();
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         MVT 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->getValueName(GV);
246
247     decorateName(Name, GV);
248
249     if (!isMemOp) O << "OFFSET ";
250     if (GV->hasDLLImportLinkage()) {
251       // FIXME: This should be fixed with full support of stdcall & fastcall
252       // CC's
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: assert(0 && "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->getValueName(GV);
282     decorateName(Name, GV);
283     
284     if (GV->hasDLLImportLinkage()) {
285       // FIXME: This should be fixed with full support of stdcall & fastcall
286       // CC's
287       O << "__imp_";
288     }
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->getValueName(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->getValueName(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 bool X86IntelAsmPrinter::doFinalization(Module &M) {
478   const TargetData *TD = TM.getTargetData();
479
480   // Print out module-level global variables here.
481   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
482        I != E; ++I) {
483     if (I->isDeclaration()) continue;   // External global require no code
484
485     // Check to see if this is a special global used by LLVM, if so, emit it.
486     if (EmitSpecialLLVMGlobal(I))
487       continue;
488
489     std::string name = Mang->getValueName(I);
490     Constant *C = I->getInitializer();
491     unsigned Align = TD->getPreferredAlignmentLog(I);
492     bool bCustomSegment = false;
493
494     switch (I->getLinkage()) {
495     case GlobalValue::CommonLinkage:
496     case GlobalValue::LinkOnceAnyLinkage:
497     case GlobalValue::LinkOnceODRLinkage:
498     case GlobalValue::WeakAnyLinkage:
499     case GlobalValue::WeakODRLinkage:
500       SwitchToDataSection("");
501       O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
502       bCustomSegment = true;
503       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
504       // are also available.
505       break;
506     case GlobalValue::AppendingLinkage:
507       SwitchToDataSection("");
508       O << name << "?\tSEGMENT PARA public 'DATA'\n";
509       bCustomSegment = true;
510       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
511       // are also available.
512       break;
513     case GlobalValue::DLLExportLinkage:
514       DLLExportedGVs.insert(name);
515       // FALL THROUGH
516     case GlobalValue::ExternalLinkage:
517       O << "\tpublic " << name << "\n";
518       // FALL THROUGH
519     case GlobalValue::InternalLinkage:
520       SwitchToSection(TAI->getDataSection());
521       break;
522     default:
523       assert(0 && "Unknown linkage type!");
524     }
525
526     if (!bCustomSegment)
527       EmitAlignment(Align, I);
528
529     O << name << ":";
530     if (VerboseAsm)
531       O << "\t\t\t\t" << TAI->getCommentString()
532         << " " << I->getName();
533     O << '\n';
534
535     EmitGlobalConstant(C);
536
537     if (bCustomSegment)
538       O << name << "?\tends\n";
539   }
540
541     // Output linker support code for dllexported globals
542   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
543     SwitchToDataSection("");
544     O << "; WARNING: The following code is valid only with MASM v8.x"
545       << "and (possible) higher\n"
546       << "; This version of MASM is usually shipped with Microsoft "
547       << "Visual Studio 2005\n"
548       << "; or (possible) further versions. Unfortunately, there is no "
549       << "way to support\n"
550       << "; dllexported symbols in the earlier versions of MASM in fully "
551       << "automatic way\n\n";
552     O << "_drectve\t segment info alias('.drectve')\n";
553   }
554
555   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
556          e = DLLExportedGVs.end();
557          i != e; ++i)
558     O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
559
560   for (StringSet<>::iterator i = DLLExportedFns.begin(),
561          e = DLLExportedFns.end();
562          i != e; ++i)
563     O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
564
565   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
566     O << "_drectve\t ends\n";
567
568   // Bypass X86SharedAsmPrinter::doFinalization().
569   bool Result = AsmPrinter::doFinalization(M);
570   SwitchToDataSection("");
571   O << "\tend\n";
572   return Result;
573 }
574
575 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
576   unsigned NumElts = CVA->getNumOperands();
577   if (NumElts) {
578     // ML does not have escape sequences except '' for '.  It also has a maximum
579     // string length of 255.
580     unsigned len = 0;
581     bool inString = false;
582     for (unsigned i = 0; i < NumElts; i++) {
583       int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
584       if (len == 0)
585         O << "\tdb ";
586
587       if (n >= 32 && n <= 127) {
588         if (!inString) {
589           if (len > 0) {
590             O << ",'";
591             len += 2;
592           } else {
593             O << "'";
594             len++;
595           }
596           inString = true;
597         }
598         if (n == '\'') {
599           O << "'";
600           len++;
601         }
602         O << char(n);
603       } else {
604         if (inString) {
605           O << "'";
606           len++;
607           inString = false;
608         }
609         if (len > 0) {
610           O << ",";
611           len++;
612         }
613         O << n;
614         len += 1 + (n > 9) + (n > 99);
615       }
616
617       if (len > 60) {
618         if (inString) {
619           O << "'";
620           inString = false;
621         }
622         O << "\n";
623         len = 0;
624       }
625     }
626
627     if (len > 0) {
628       if (inString)
629         O << "'";
630       O << "\n";
631     }
632   }
633 }
634
635 // Include the auto-generated portion of the assembly writer.
636 #include "X86GenAsmWriter1.inc"