X86AsmPrinter.cpp revision 2a07e2f4df8010bbb07591a097b5e55101ed4a96
1//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file the shared super class printer that converts from our internal
11// representation of machine-dependent LLVM code to Intel and AT&T format
12// assembly language.
13// This printer is the output mechanism used by `llc'.
14//
15//===----------------------------------------------------------------------===//
16
17#include "X86AsmPrinter.h"
18#include "X86ATTAsmPrinter.h"
19#include "X86COFF.h"
20#include "X86IntelAsmPrinter.h"
21#include "X86MachineFunctionInfo.h"
22#include "X86Subtarget.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/CallingConv.h"
25#include "llvm/Constants.h"
26#include "llvm/Module.h"
27#include "llvm/DerivedTypes.h"
28#include "llvm/Type.h"
29#include "llvm/Assembly/Writer.h"
30#include "llvm/Support/Mangler.h"
31#include "llvm/Target/TargetAsmInfo.h"
32#include "llvm/Target/TargetOptions.h"
33using namespace llvm;
34
35static 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  for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
52       AI != AE; ++AI)
53    // Size should be aligned to DWORD boundary
54    Size += ((TD->getTypeSize(AI->getType()) + 3)/4)*4;
55
56  // We're not supporting tooooo huge arguments :)
57  Info.setBytesToPopOnReturn((unsigned int)Size);
58  return Info;
59}
60
61
62/// decorateName - Query FunctionInfoMap and use this information for various
63/// name decoration.
64void X86SharedAsmPrinter::decorateName(std::string &Name,
65                                       const GlobalValue *GV) {
66  const Function *F = dyn_cast<Function>(GV);
67  if (!F) return;
68
69  // We don't want to decorate non-stdcall or non-fastcall functions right now
70  unsigned CC = F->getCallingConv();
71  if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
72    return;
73
74  // Decorate names only when we're targeting Cygwin/Mingw32 targets
75  if (!Subtarget->isTargetCygMing())
76    return;
77
78  FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
79
80  const X86MachineFunctionInfo *Info;
81  if (info_item == FunctionInfoMap.end()) {
82    // Calculate apropriate function info and populate map
83    FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
84    Info = &FunctionInfoMap[F];
85  } else {
86    Info = &info_item->second;
87  }
88
89  const FunctionType *FT = F->getFunctionType();
90  switch (Info->getDecorationStyle()) {
91  case None:
92    break;
93  case StdCall:
94    // "Pure" variadic functions do not receive @0 suffix.
95    if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
96        (FT->getNumParams() == 1 && FT->isStructReturn()))
97      Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
98    break;
99  case FastCall:
100    // "Pure" variadic functions do not receive @0 suffix.
101    if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
102        (FT->getNumParams() == 1 && FT->isStructReturn()))
103      Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
104
105    if (Name[0] == '_') {
106      Name[0] = '@';
107    } else {
108      Name = '@' + Name;
109    }
110    break;
111  default:
112    assert(0 && "Unsupported DecorationStyle");
113  }
114}
115
116/// doInitialization
117bool X86SharedAsmPrinter::doInitialization(Module &M) {
118  if (TAI->doesSupportDebugInformation()) {
119    // Emit initial debug information.
120    DW.BeginModule(&M);
121  }
122
123  return AsmPrinter::doInitialization(M);
124}
125
126bool X86SharedAsmPrinter::doFinalization(Module &M) {
127  // Note: this code is not shared by the Intel printer as it is too different
128  // from how MASM does things.  When making changes here don't forget to look
129  // at X86IntelAsmPrinter::doFinalization().
130  const TargetData *TD = TM.getTargetData();
131
132  // Print out module-level global variables here.
133  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
134       I != E; ++I) {
135    if (!I->hasInitializer())
136      continue;   // External global require no code
137
138    // Check to see if this is a special global used by LLVM, if so, emit it.
139    if (EmitSpecialLLVMGlobal(I)) {
140      if (Subtarget->isTargetDarwin() &&
141          TM.getRelocationModel() == Reloc::Static) {
142        if (I->getName() == "llvm.global_ctors")
143          O << ".reference .constructors_used\n";
144        else if (I->getName() == "llvm.global_dtors")
145          O << ".reference .destructors_used\n";
146      }
147      continue;
148    }
149
150    std::string name = Mang->getValueName(I);
151    Constant *C = I->getInitializer();
152    const Type *Type = C->getType();
153    unsigned Size = TD->getTypeSize(Type);
154    unsigned Align = TD->getPreferredAlignmentLog(I);
155
156    if (I->hasHiddenVisibility()) {
157      if (const char *Directive = TAI->getHiddenDirective())
158        O << Directive << name << "\n";
159    } else if (I->hasProtectedVisibility()) {
160      if (const char *Directive = TAI->getProtectedDirective())
161        O << Directive << name << "\n";
162    }
163
164    if (Subtarget->isTargetELF())
165      O << "\t.type " << name << ",@object\n";
166
167    if (C->isNullValue()) {
168      if (I->hasExternalLinkage()) {
169        if (const char *Directive = TAI->getZeroFillDirective()) {
170          O << "\t.globl\t" << name << "\n";
171          O << Directive << "__DATA__, __common, " << name << ", "
172            << Size << ", " << Align << "\n";
173          continue;
174        }
175      }
176
177      if (!I->hasSection() && !I->isThreadLocal() &&
178          (I->hasInternalLinkage() || I->hasWeakLinkage() ||
179           I->hasLinkOnceLinkage())) {
180        if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
181        if (!NoZerosInBSS && TAI->getBSSSection())
182          SwitchToDataSection(TAI->getBSSSection(), I);
183        else
184          SwitchToDataSection(TAI->getDataSection(), I);
185        if (TAI->getLCOMMDirective() != NULL) {
186          if (I->hasInternalLinkage()) {
187            O << TAI->getLCOMMDirective() << name << "," << Size;
188            if (Subtarget->isTargetDarwin())
189              O << "," << Align;
190          } else
191            O << TAI->getCOMMDirective()  << name << "," << Size;
192        } else {
193          if (!Subtarget->isTargetCygMing()) {
194            if (I->hasInternalLinkage())
195              O << "\t.local\t" << name << "\n";
196          }
197          O << TAI->getCOMMDirective()  << name << "," << Size;
198          if (TAI->getCOMMDirectiveTakesAlignment())
199            O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
200        }
201        O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
202        continue;
203      }
204    }
205
206    switch (I->getLinkage()) {
207    case GlobalValue::LinkOnceLinkage:
208    case GlobalValue::WeakLinkage:
209      if (Subtarget->isTargetDarwin()) {
210        O << "\t.globl " << name << "\n"
211          << "\t.weak_definition " << name << "\n";
212        SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
213      } else if (Subtarget->isTargetCygMing()) {
214        std::string SectionName(".section\t.data$linkonce." +
215                                name +
216                                ",\"aw\"");
217        SwitchToDataSection(SectionName.c_str(), I);
218        O << "\t.globl " << name << "\n"
219          << "\t.linkonce same_size\n";
220      } else {
221        std::string SectionName("\t.section\t.llvm.linkonce.d." +
222                                name +
223                                ",\"aw\",@progbits");
224        SwitchToDataSection(SectionName.c_str(), I);
225        O << "\t.weak " << name << "\n";
226      }
227      break;
228    case GlobalValue::AppendingLinkage:
229      // FIXME: appending linkage variables should go into a section of
230      // their name or something.  For now, just emit them as external.
231    case GlobalValue::DLLExportLinkage:
232      DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
233      // FALL THROUGH
234    case GlobalValue::ExternalLinkage:
235      // If external or appending, declare as a global symbol
236      O << "\t.globl " << name << "\n";
237      // FALL THROUGH
238    case GlobalValue::InternalLinkage: {
239      if (I->isConstant()) {
240        const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
241        if (TAI->getCStringSection() && CVA && CVA->isCString()) {
242          SwitchToDataSection(TAI->getCStringSection(), I);
243          break;
244        }
245      }
246      // FIXME: special handling for ".ctors" & ".dtors" sections
247      if (I->hasSection() &&
248          (I->getSection() == ".ctors" ||
249           I->getSection() == ".dtors")) {
250        std::string SectionName = ".section " + I->getSection();
251
252        if (Subtarget->isTargetCygMing()) {
253          SectionName += ",\"aw\"";
254        } else {
255          assert(!Subtarget->isTargetDarwin());
256          SectionName += ",\"aw\",@progbits";
257        }
258
259        SwitchToDataSection(SectionName.c_str());
260      } else {
261        if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
262          SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
263                              TAI->getBSSSection(), I);
264        else if (!I->isConstant())
265          SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
266                              TAI->getDataSection(), I);
267        else if (I->isThreadLocal())
268          SwitchToDataSection(TAI->getTLSDataSection());
269        else {
270          // Read-only data.
271          bool HasReloc = C->ContainsRelocations();
272          if (HasReloc &&
273              Subtarget->isTargetDarwin() &&
274              TM.getRelocationModel() != Reloc::Static)
275            SwitchToDataSection("\t.const_data\n");
276          else if (!HasReloc && Size == 4 &&
277                   TAI->getFourByteConstantSection())
278            SwitchToDataSection(TAI->getFourByteConstantSection(), I);
279          else if (!HasReloc && Size == 8 &&
280                   TAI->getEightByteConstantSection())
281            SwitchToDataSection(TAI->getEightByteConstantSection(), I);
282          else if (!HasReloc && Size == 16 &&
283                   TAI->getSixteenByteConstantSection())
284            SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
285          else if (TAI->getReadOnlySection())
286            SwitchToDataSection(TAI->getReadOnlySection(), I);
287          else
288            SwitchToDataSection(TAI->getDataSection(), I);
289        }
290      }
291
292      break;
293    }
294    default:
295      assert(0 && "Unknown linkage type!");
296    }
297
298    EmitAlignment(Align, I);
299    O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
300      << "\n";
301    if (TAI->hasDotTypeDotSizeDirective())
302      O << "\t.size " << name << ", " << Size << "\n";
303    // If the initializer is a extern weak symbol, remember to emit the weak
304    // reference!
305    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
306      if (GV->hasExternalWeakLinkage())
307        ExtWeakSymbols.insert(GV);
308
309    EmitGlobalConstant(C);
310    O << '\n';
311  }
312
313  // Output linker support code for dllexported globals
314  if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
315    SwitchToDataSection(".section .drectve");
316  }
317
318  for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
319         e = DLLExportedGVs.end();
320         i != e; ++i) {
321    O << "\t.ascii \" -export:" << *i << ",data\"\n";
322  }
323
324  if (DLLExportedFns.begin() != DLLExportedFns.end()) {
325    SwitchToDataSection(".section .drectve");
326  }
327
328  for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
329         e = DLLExportedFns.end();
330         i != e; ++i) {
331    O << "\t.ascii \" -export:" << *i << "\"\n";
332  }
333
334  if (Subtarget->isTargetDarwin()) {
335    SwitchToDataSection("");
336
337    // Output stubs for dynamically-linked functions
338    unsigned j = 1;
339    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
340         i != e; ++i, ++j) {
341      SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
342                          "self_modifying_code+pure_instructions,5", 0);
343      O << "L" << *i << "$stub:\n";
344      O << "\t.indirect_symbol " << *i << "\n";
345      O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
346    }
347
348    O << "\n";
349
350    // Output stubs for external and common global variables.
351    if (GVStubs.begin() != GVStubs.end())
352      SwitchToDataSection(
353                    ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
354    for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
355         i != e; ++i) {
356      O << "L" << *i << "$non_lazy_ptr:\n";
357      O << "\t.indirect_symbol " << *i << "\n";
358      O << "\t.long\t0\n";
359    }
360
361    // Emit final debug information.
362    DW.EndModule();
363
364    // Funny Darwin hack: This flag tells the linker that no global symbols
365    // contain code that falls through to other global symbols (e.g. the obvious
366    // implementation of multiple entry points).  If this doesn't occur, the
367    // linker can safely perform dead code stripping.  Since LLVM never
368    // generates code that does this, it is always safe to set.
369    O << "\t.subsections_via_symbols\n";
370  } else if (Subtarget->isTargetCygMing()) {
371    // Emit type information for external functions
372    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
373         i != e; ++i) {
374      O << "\t.def\t " << *i
375        << ";\t.scl\t" << COFF::C_EXT
376        << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
377        << ";\t.endef\n";
378    }
379
380    // Emit final debug information.
381    DW.EndModule();
382  } else if (Subtarget->isTargetELF()) {
383    // Emit final debug information.
384    DW.EndModule();
385  }
386
387  AsmPrinter::doFinalization(M);
388  return false; // success
389}
390
391/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
392/// for a MachineFunction to the given output stream, using the given target
393/// machine description.
394///
395FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
396                                             X86TargetMachine &tm) {
397  const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
398
399  if (Subtarget->isFlavorIntel()) {
400    return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
401  } else {
402    return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
403  }
404}
405