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