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