4ab72eef8ef167d6473961a2f900af1eb87ed04c
[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 "X86IntelAsmPrinter.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86Subtarget.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30
31 using namespace llvm;
32
33 Statistic<> llvm::EmittedInsts("asm-printer",
34                                "Number of machine instrs printed");
35
36 static X86FunctionInfo calculateFunctionInfo(const Function *F,
37                                              const TargetData *TD) {
38   X86FunctionInfo 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   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
53        AI != AE; ++AI)
54     Size += TD->getTypeSize(AI->getType());
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->isTargetDarwin()) {
110     const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
111     if (!Subtarget->is64Bit())
112       X86PICStyle = PICStyle::Stub;
113
114     // Emit initial debug information.
115     DW.BeginModule(&M);
116   }
117
118   return AsmPrinter::doInitialization(M);
119 }
120
121 bool X86SharedAsmPrinter::doFinalization(Module &M) {
122   // Note: this code is not shared by the Intel printer as it is too different
123   // from how MASM does things.  When making changes here don't forget to look
124   // at X86IntelAsmPrinter::doFinalization().
125   const TargetData *TD = TM.getTargetData();
126
127   // Print out module-level global variables here.
128   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
129        I != E; ++I) {
130     if (!I->hasInitializer()) 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 = getPreferredAlignmentLog(I);
140
141     if (C->isNullValue() && /* FIXME: Verify correct */
142         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
143          I->hasLinkOnceLinkage() ||
144          (Subtarget->isTargetDarwin() && 
145           I->hasExternalLinkage() && !I->hasSection()))) {
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->isTargetCygwin()) {
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->isTargetCygwin()) {
180           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
181             << "\t.weak " << name << "\n";
182         } else {
183           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
184             << "\t.weak " << name << "\n";
185         }
186         break;
187       case GlobalValue::AppendingLinkage:
188         // FIXME: appending linkage variables should go into a section of
189         // their name or something.  For now, just emit them as external.
190       case GlobalValue::DLLExportLinkage:
191         DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
192         // FALL THROUGH
193       case GlobalValue::ExternalLinkage:
194         // If external or appending, declare as a global symbol
195         O << "\t.globl " << name << "\n";
196         // FALL THROUGH
197       case GlobalValue::InternalLinkage:
198         SwitchToDataSection(TAI->getDataSection(), I);
199         break;
200       default:
201         assert(0 && "Unknown linkage type!");
202       }
203
204       EmitAlignment(Align, I);
205       O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
206         << "\n";
207       if (TAI->hasDotTypeDotSizeDirective())
208         O << "\t.size " << name << ", " << Size << "\n";
209
210       EmitGlobalConstant(C);
211       O << '\n';
212     }
213   }
214   
215   // Output linker support code for dllexported globals
216   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
217     SwitchToDataSection(".section .drectve", 0);    
218   }
219
220   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
221          e = DLLExportedGVs.end();
222          i != e; ++i) {
223     O << "\t.ascii \" -export:" << *i << ",data\"\n";
224   }    
225
226   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
227     SwitchToDataSection(".section .drectve", 0);    
228   }
229
230   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
231          e = DLLExportedFns.end();
232          i != e; ++i) {
233     O << "\t.ascii \" -export:" << *i << "\"\n";
234   }    
235  
236   if (Subtarget->isTargetDarwin()) {
237     SwitchToDataSection("", 0);
238
239     // Output stubs for dynamically-linked functions
240     unsigned j = 1;
241     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
242          i != e; ++i, ++j) {
243       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
244                           "self_modifying_code+pure_instructions,5", 0);
245       O << "L" << *i << "$stub:\n";
246       O << "\t.indirect_symbol " << *i << "\n";
247       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
248     }
249
250     O << "\n";
251
252     // Output stubs for external and common global variables.
253     if (GVStubs.begin() != GVStubs.end())
254       SwitchToDataSection(
255                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
256     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
257          i != e; ++i) {
258       O << "L" << *i << "$non_lazy_ptr:\n";
259       O << "\t.indirect_symbol " << *i << "\n";
260       O << "\t.long\t0\n";
261     }
262
263     // Emit initial debug information.
264     DW.EndModule();
265
266     // Funny Darwin hack: This flag tells the linker that no global symbols
267     // contain code that falls through to other global symbols (e.g. the obvious
268     // implementation of multiple entry points).  If this doesn't occur, the
269     // linker can safely perform dead code stripping.  Since LLVM never
270     // generates code that does this, it is always safe to set.
271     O << "\t.subsections_via_symbols\n";
272   }
273
274   AsmPrinter::doFinalization(M);
275   return false; // success
276 }
277
278 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
279 /// for a MachineFunction to the given output stream, using the given target
280 /// machine description.
281 ///
282 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
283                                              X86TargetMachine &tm) {
284   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
285
286   if (Subtarget->isFlavorIntel()) {
287     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
288   } else {
289     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
290   }
291 }