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