Implement protected visibility. This partly implements PR1363. Linker
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
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"
33 using namespace llvm;
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   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.
64 void 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
117 bool X86SharedAsmPrinter::doInitialization(Module &M) {
118   if (Subtarget->isTargetELF() ||
119       Subtarget->isTargetCygMing() ||
120       Subtarget->isTargetDarwin()) {
121     // Emit initial debug information.
122     DW.BeginModule(&M);
123   }
124
125   return AsmPrinter::doInitialization(M);
126 }
127
128 bool X86SharedAsmPrinter::doFinalization(Module &M) {
129   // Note: this code is not shared by the Intel printer as it is too different
130   // from how MASM does things.  When making changes here don't forget to look
131   // at X86IntelAsmPrinter::doFinalization().
132   const TargetData *TD = TM.getTargetData();
133   
134   // Print out module-level global variables here.
135   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
136        I != E; ++I) {
137     if (!I->hasInitializer())
138       continue;   // External global require no code
139     
140     // Check to see if this is a special global used by LLVM, if so, emit it.
141     if (EmitSpecialLLVMGlobal(I)) {
142       if (Subtarget->isTargetDarwin() &&
143           TM.getRelocationModel() == Reloc::Static) {
144         if (I->getName() == "llvm.global_ctors")
145           O << ".reference .constructors_used\n";
146         else if (I->getName() == "llvm.global_dtors")
147           O << ".reference .destructors_used\n";
148       }
149       continue;
150     }
151     
152     std::string name = Mang->getValueName(I);
153     Constant *C = I->getInitializer();
154     const Type *Type = C->getType();
155     unsigned Size = TD->getTypeSize(Type);
156     unsigned Align = TD->getPreferredAlignmentLog(I);
157
158     if (I->hasHiddenVisibility()) {
159       if (const char *Directive = TAI->getHiddenDirective())
160         O << Directive << name << "\n";
161     } else if (I->hasProtectedVisibility()) {
162       if (const char *Directive = TAI->getProtectedDirective())
163         O << Directive << name << "\n";
164     }
165     
166     if (Subtarget->isTargetELF())
167       O << "\t.type " << name << ",@object\n";
168     
169     if (C->isNullValue()) {
170       if (I->hasExternalLinkage()) {
171         if (const char *Directive = TAI->getZeroFillDirective()) {
172           O << "\t.globl\t" << name << "\n";
173           O << Directive << "__DATA__, __common, " << name << ", "
174             << Size << ", " << Align << "\n";
175           continue;
176         }
177       }
178       
179       if (!I->hasSection() && !I->isThreadLocal() &&
180           (I->hasInternalLinkage() || I->hasWeakLinkage() ||
181            I->hasLinkOnceLinkage())) {
182         if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
183         if (!NoZerosInBSS && TAI->getBSSSection())
184           SwitchToDataSection(TAI->getBSSSection(), I);
185         else
186           SwitchToDataSection(TAI->getDataSection(), I);
187         if (TAI->getLCOMMDirective() != NULL) {
188           if (I->hasInternalLinkage()) {
189             O << TAI->getLCOMMDirective() << name << "," << Size;
190             if (Subtarget->isTargetDarwin())
191               O << "," << Align;
192           } else
193             O << TAI->getCOMMDirective()  << name << "," << Size;
194         } else {
195           if (!Subtarget->isTargetCygMing()) {
196             if (I->hasInternalLinkage())
197               O << "\t.local\t" << name << "\n";
198           }
199           O << TAI->getCOMMDirective()  << name << "," << Size;
200           if (TAI->getCOMMDirectiveTakesAlignment())
201             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
202         }
203         O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
204         continue;
205       }
206     }
207
208     switch (I->getLinkage()) {
209     case GlobalValue::LinkOnceLinkage:
210     case GlobalValue::WeakLinkage:
211       if (Subtarget->isTargetDarwin()) {
212         O << "\t.globl " << name << "\n"
213           << "\t.weak_definition " << name << "\n";
214         SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
215       } else if (Subtarget->isTargetCygMing()) {
216         std::string SectionName(".section\t.data$linkonce." +
217                                 name +
218                                 ",\"aw\"");
219         SwitchToDataSection(SectionName.c_str(), I);
220         O << "\t.globl " << name << "\n"
221           << "\t.linkonce same_size\n";
222       } else {
223         std::string SectionName("\t.section\t.llvm.linkonce.d." +
224                                 name +
225                                 ",\"aw\",@progbits");
226         SwitchToDataSection(SectionName.c_str(), I);
227         O << "\t.weak " << name << "\n";
228       }
229       break;
230     case GlobalValue::AppendingLinkage:
231       // FIXME: appending linkage variables should go into a section of
232       // their name or something.  For now, just emit them as external.
233     case GlobalValue::DLLExportLinkage:
234       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
235       // FALL THROUGH
236     case GlobalValue::ExternalLinkage:
237       // If external or appending, declare as a global symbol
238       O << "\t.globl " << name << "\n";
239       // FALL THROUGH
240     case GlobalValue::InternalLinkage: {
241       if (I->isConstant()) {
242         const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
243         if (TAI->getCStringSection() && CVA && CVA->isCString()) {
244           SwitchToDataSection(TAI->getCStringSection(), I);
245           break;
246         }
247       }
248       // FIXME: special handling for ".ctors" & ".dtors" sections
249       if (I->hasSection() &&
250           (I->getSection() == ".ctors" ||
251            I->getSection() == ".dtors")) {
252         std::string SectionName = ".section " + I->getSection();
253         
254         if (Subtarget->isTargetCygMing()) {
255           SectionName += ",\"aw\"";
256         } else {
257           assert(!Subtarget->isTargetDarwin());
258           SectionName += ",\"aw\",@progbits";
259         }
260
261         SwitchToDataSection(SectionName.c_str());
262       } else {
263         if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
264           SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
265                               TAI->getBSSSection(), I);
266         else if (!I->isConstant())
267           SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
268                               TAI->getDataSection(), I);
269         else if (I->isThreadLocal())
270           SwitchToDataSection(TAI->getTLSDataSection());
271         else {
272           // Read-only data.
273           bool HasReloc = C->ContainsRelocations();
274           if (HasReloc &&
275               Subtarget->isTargetDarwin() &&
276               TM.getRelocationModel() != Reloc::Static)
277             SwitchToDataSection("\t.const_data\n");
278           else if (!HasReloc && Size == 4 &&
279                    TAI->getFourByteConstantSection())
280             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
281           else if (!HasReloc && Size == 8 &&
282                    TAI->getEightByteConstantSection())
283             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
284           else if (!HasReloc && Size == 16 &&
285                    TAI->getSixteenByteConstantSection())
286             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
287           else if (TAI->getReadOnlySection())
288             SwitchToDataSection(TAI->getReadOnlySection(), I);
289           else
290             SwitchToDataSection(TAI->getDataSection(), I);
291         }
292       }
293       
294       break;
295     }
296     default:
297       assert(0 && "Unknown linkage type!");
298     }
299
300     EmitAlignment(Align, I);
301     O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
302       << "\n";
303     if (TAI->hasDotTypeDotSizeDirective())
304       O << "\t.size " << name << ", " << Size << "\n";
305     // If the initializer is a extern weak symbol, remember to emit the weak
306     // reference!
307     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
308       if (GV->hasExternalWeakLinkage())
309         ExtWeakSymbols.insert(GV);
310
311     EmitGlobalConstant(C);
312     O << '\n';
313   }
314   
315   // Output linker support code for dllexported globals
316   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
317     SwitchToDataSection(".section .drectve");
318   }
319
320   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
321          e = DLLExportedGVs.end();
322          i != e; ++i) {
323     O << "\t.ascii \" -export:" << *i << ",data\"\n";
324   }    
325
326   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
327     SwitchToDataSection(".section .drectve");
328   }
329
330   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
331          e = DLLExportedFns.end();
332          i != e; ++i) {
333     O << "\t.ascii \" -export:" << *i << "\"\n";
334   }    
335
336   if (Subtarget->isTargetDarwin()) {
337     SwitchToDataSection("");
338
339     // Output stubs for dynamically-linked functions
340     unsigned j = 1;
341     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
342          i != e; ++i, ++j) {
343       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
344                           "self_modifying_code+pure_instructions,5", 0);
345       O << "L" << *i << "$stub:\n";
346       O << "\t.indirect_symbol " << *i << "\n";
347       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
348     }
349
350     O << "\n";
351
352     // Output stubs for external and common global variables.
353     if (GVStubs.begin() != GVStubs.end())
354       SwitchToDataSection(
355                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
356     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
357          i != e; ++i) {
358       O << "L" << *i << "$non_lazy_ptr:\n";
359       O << "\t.indirect_symbol " << *i << "\n";
360       O << "\t.long\t0\n";
361     }
362
363     // Emit final debug information.
364     DW.EndModule();
365
366     // Funny Darwin hack: This flag tells the linker that no global symbols
367     // contain code that falls through to other global symbols (e.g. the obvious
368     // implementation of multiple entry points).  If this doesn't occur, the
369     // linker can safely perform dead code stripping.  Since LLVM never
370     // generates code that does this, it is always safe to set.
371     O << "\t.subsections_via_symbols\n";
372   } else if (Subtarget->isTargetCygMing()) {
373     // Emit type information for external functions
374     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
375          i != e; ++i) {
376       O << "\t.def\t " << *i
377         << ";\t.scl\t" << COFF::C_EXT
378         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
379         << ";\t.endef\n";
380     }
381     
382     // Emit final debug information.
383     DW.EndModule();    
384   } else if (Subtarget->isTargetELF()) {
385     // Emit final debug information.
386     DW.EndModule();
387   }
388
389   AsmPrinter::doFinalization(M);
390   return false; // success
391 }
392
393 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
394 /// for a MachineFunction to the given output stream, using the given target
395 /// machine description.
396 ///
397 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
398                                              X86TargetMachine &tm) {
399   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
400
401   if (Subtarget->isFlavorIntel()) {
402     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
403   } else {
404     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
405   }
406 }