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