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