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