ff85828c5a52473e447c2a880861a1ca4ba2bce1
[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       continue;
139     
140     std::string name = Mang->getValueName(I);
141     Constant *C = I->getInitializer();
142     unsigned Size = TD->getTypeSize(C->getType());
143     unsigned Align = TD->getPreferredAlignmentLog(I);
144
145     if (I->hasHiddenVisibility())
146       if (const char *Directive = TAI->getHiddenDirective())
147         O << Directive << name << "\n";
148     if (Subtarget->isTargetELF())
149       O << "\t.type " << name << ",@object\n";
150     
151     if (C->isNullValue()) {
152       if (I->hasExternalLinkage()) {
153         if (const char *Directive = TAI->getZeroFillDirective()) {
154           O << "\t.globl\t" << name << "\n";
155           O << Directive << "__DATA__, __common, " << name << ", "
156             << Size << ", " << Align << "\n";
157           continue;
158         }
159       }
160       
161       if (!I->hasSection() &&
162           (I->hasInternalLinkage() || I->hasWeakLinkage() ||
163            I->hasLinkOnceLinkage())) {
164         if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
165         if (!NoZerosInBSS && TAI->getBSSSection())
166           SwitchToDataSection(TAI->getBSSSection(), I);
167         else
168           SwitchToDataSection(TAI->getDataSection(), I);
169         if (TAI->getLCOMMDirective() != NULL) {
170           if (I->hasInternalLinkage()) {
171             O << TAI->getLCOMMDirective() << name << "," << Size;
172             if (Subtarget->isTargetDarwin())
173               O << "," << Align;
174           } else
175             O << TAI->getCOMMDirective()  << name << "," << Size;
176         } else {
177           if (!Subtarget->isTargetCygMing()) {
178             if (I->hasInternalLinkage())
179               O << "\t.local\t" << name << "\n";
180           }
181           O << TAI->getCOMMDirective()  << name << "," << Size;
182           if (TAI->getCOMMDirectiveTakesAlignment())
183             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
184         }
185         O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
186         continue;
187       }
188     }
189
190     switch (I->getLinkage()) {
191     case GlobalValue::LinkOnceLinkage:
192     case GlobalValue::WeakLinkage:
193       if (Subtarget->isTargetDarwin()) {
194         O << "\t.globl " << name << "\n"
195           << "\t.weak_definition " << name << "\n";
196         SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
197       } else if (Subtarget->isTargetCygMing()) {
198         std::string SectionName(".section\t.data$linkonce." +
199                                 name +
200                                 ",\"aw\"");
201         SwitchToDataSection(SectionName.c_str(), I);
202         O << "\t.globl " << name << "\n"
203           << "\t.linkonce same_size\n";
204       } else {
205         std::string SectionName("\t.section\t.llvm.linkonce.d." +
206                                 name +
207                                 ",\"aw\",@progbits");
208         SwitchToDataSection(SectionName.c_str(), I);
209         O << "\t.weak " << name << "\n";
210       }
211       break;
212     case GlobalValue::AppendingLinkage:
213       // FIXME: appending linkage variables should go into a section of
214       // their name or something.  For now, just emit them as external.
215     case GlobalValue::DLLExportLinkage:
216       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
217       // FALL THROUGH
218     case GlobalValue::ExternalLinkage:
219       // If external or appending, declare as a global symbol
220       O << "\t.globl " << name << "\n";
221       // FALL THROUGH
222     case GlobalValue::InternalLinkage: {
223       if (I->isConstant()) {
224         const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
225         if (TAI->getCStringSection() && CVA && CVA->isCString()) {
226           SwitchToDataSection(TAI->getCStringSection(), I);
227           break;
228         }
229       }
230       // FIXME: special handling for ".ctors" & ".dtors" sections
231       if (I->hasSection() &&
232           (I->getSection() == ".ctors" ||
233            I->getSection() == ".dtors")) {
234         std::string SectionName = ".section " + I->getSection();
235         
236         if (Subtarget->isTargetCygMing()) {
237           SectionName += ",\"aw\"";
238         } else {
239           assert(!Subtarget->isTargetDarwin());
240           SectionName += ",\"aw\",@progbits";
241         }
242
243         SwitchToDataSection(SectionName.c_str());
244       } else {
245         if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
246           SwitchToDataSection(TAI->getBSSSection(), I);
247         else
248           SwitchToDataSection(TAI->getDataSection(), I);
249       }
250       
251       break;
252     }
253     default:
254       assert(0 && "Unknown linkage type!");
255     }
256
257     EmitAlignment(Align, I);
258     O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
259       << "\n";
260     if (TAI->hasDotTypeDotSizeDirective())
261       O << "\t.size " << name << ", " << Size << "\n";
262     // If the initializer is a extern weak symbol, remember to emit the weak
263     // reference!
264     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
265       if (GV->hasExternalWeakLinkage())
266         ExtWeakSymbols.insert(GV);
267
268     EmitGlobalConstant(C);
269     O << '\n';
270   }
271   
272   // Output linker support code for dllexported globals
273   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
274     SwitchToDataSection(".section .drectve");
275   }
276
277   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
278          e = DLLExportedGVs.end();
279          i != e; ++i) {
280     O << "\t.ascii \" -export:" << *i << ",data\"\n";
281   }    
282
283   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
284     SwitchToDataSection(".section .drectve");
285   }
286
287   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
288          e = DLLExportedFns.end();
289          i != e; ++i) {
290     O << "\t.ascii \" -export:" << *i << "\"\n";
291   }    
292
293   if (Subtarget->isTargetDarwin()) {
294     SwitchToDataSection("");
295
296     // Output stubs for dynamically-linked functions
297     unsigned j = 1;
298     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
299          i != e; ++i, ++j) {
300       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
301                           "self_modifying_code+pure_instructions,5", 0);
302       O << "L" << *i << "$stub:\n";
303       O << "\t.indirect_symbol " << *i << "\n";
304       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
305     }
306
307     O << "\n";
308
309     // Output stubs for external and common global variables.
310     if (GVStubs.begin() != GVStubs.end())
311       SwitchToDataSection(
312                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
313     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
314          i != e; ++i) {
315       O << "L" << *i << "$non_lazy_ptr:\n";
316       O << "\t.indirect_symbol " << *i << "\n";
317       O << "\t.long\t0\n";
318     }
319
320     // Emit final debug information.
321     DW.EndModule();
322
323     // Funny Darwin hack: This flag tells the linker that no global symbols
324     // contain code that falls through to other global symbols (e.g. the obvious
325     // implementation of multiple entry points).  If this doesn't occur, the
326     // linker can safely perform dead code stripping.  Since LLVM never
327     // generates code that does this, it is always safe to set.
328     O << "\t.subsections_via_symbols\n";
329   } else if (Subtarget->isTargetCygMing()) {
330     // Emit type information for external functions
331     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
332          i != e; ++i) {
333       O << "\t.def\t " << *i
334         << ";\t.scl\t" << COFF::C_EXT
335         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
336         << ";\t.endef\n";
337     }
338     
339     // Emit final debug information.
340     DW.EndModule();    
341   } else if (Subtarget->isTargetELF()) {
342     // Emit final debug information.
343     DW.EndModule();
344   }
345
346   AsmPrinter::doFinalization(M);
347   return false; // success
348 }
349
350 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
351 /// for a MachineFunction to the given output stream, using the given target
352 /// machine description.
353 ///
354 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
355                                              X86TargetMachine &tm) {
356   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
357
358   if (Subtarget->isFlavorIntel()) {
359     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
360   } else {
361     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
362   }
363 }