blob: b0e8165ad1c880b897728c862591185f8b129a2f [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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/Type.h"
29#include "llvm/Assembly/Writer.h"
30#include "llvm/Support/Mangler.h"
31#include "llvm/Target/TargetAsmInfo.h"
32#include "llvm/Target/TargetOptions.h"
33using namespace llvm;
34
35static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
36 const TargetData *TD) {
37 X86MachineFunctionInfo Info;
38 uint64_t Size = 0;
39
40 switch (F->getCallingConv()) {
41 case CallingConv::X86_StdCall:
42 Info.setDecorationStyle(StdCall);
43 break;
44 case CallingConv::X86_FastCall:
45 Info.setDecorationStyle(FastCall);
46 break;
47 default:
48 return Info;
49 }
50
51 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
52 AI != AE; ++AI)
53 // Size should be aligned to DWORD boundary
Duncan Sands8157ef42007-11-05 00:04:43 +000054 Size += ((TD->getABITypeSize(AI->getType()) + 3)/4)*4;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055
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.
64void 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 // Decorate names only when we're targeting Cygwin/Mingw32 targets
75 if (!Subtarget->isTargetCygMing())
76 return;
77
78 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
79
80 const X86MachineFunctionInfo *Info;
81 if (info_item == FunctionInfoMap.end()) {
82 // Calculate apropriate function info and populate map
83 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
84 Info = &FunctionInfoMap[F];
85 } else {
86 Info = &info_item->second;
87 }
88
89 const FunctionType *FT = F->getFunctionType();
90 switch (Info->getDecorationStyle()) {
91 case None:
92 break;
93 case StdCall:
94 // "Pure" variadic functions do not receive @0 suffix.
95 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
Duncan Sandsf5588dc2007-11-27 13:23:08 +000096 (FT->getNumParams() == 1 && F->isStructReturn()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
98 break;
99 case FastCall:
100 // "Pure" variadic functions do not receive @0 suffix.
101 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000102 (FT->getNumParams() == 1 && F->isStructReturn()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
104
105 if (Name[0] == '_') {
106 Name[0] = '@';
107 } else {
108 Name = '@' + Name;
109 }
110 break;
111 default:
112 assert(0 && "Unsupported DecorationStyle");
113 }
114}
115
116/// doInitialization
117bool X86SharedAsmPrinter::doInitialization(Module &M) {
118 if (TAI->doesSupportDebugInformation()) {
119 // Emit initial debug information.
120 DW.BeginModule(&M);
121 }
122
Dan Gohman4a558a32007-07-25 19:33:14 +0000123 bool Result = AsmPrinter::doInitialization(M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124
125 // Darwin wants symbols to be quoted if they have complex names.
126 if (Subtarget->isTargetDarwin())
127 Mang->setUseQuotes(true);
128
Dan Gohman4a558a32007-07-25 19:33:14 +0000129 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130}
131
132bool X86SharedAsmPrinter::doFinalization(Module &M) {
133 // Note: this code is not shared by the Intel printer as it is too different
134 // from how MASM does things. When making changes here don't forget to look
135 // at X86IntelAsmPrinter::doFinalization().
136 const TargetData *TD = TM.getTargetData();
137
138 // Print out module-level global variables here.
139 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
140 I != E; ++I) {
141 if (!I->hasInitializer())
142 continue; // External global require no code
143
144 // Check to see if this is a special global used by LLVM, if so, emit it.
145 if (EmitSpecialLLVMGlobal(I)) {
146 if (Subtarget->isTargetDarwin() &&
147 TM.getRelocationModel() == Reloc::Static) {
148 if (I->getName() == "llvm.global_ctors")
149 O << ".reference .constructors_used\n";
150 else if (I->getName() == "llvm.global_dtors")
151 O << ".reference .destructors_used\n";
152 }
153 continue;
154 }
155
156 std::string name = Mang->getValueName(I);
157 Constant *C = I->getInitializer();
158 const Type *Type = C->getType();
Duncan Sands8157ef42007-11-05 00:04:43 +0000159 unsigned Size = TD->getABITypeSize(Type);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 unsigned Align = TD->getPreferredAlignmentLog(I);
161
162 if (I->hasHiddenVisibility()) {
163 if (const char *Directive = TAI->getHiddenDirective())
164 O << Directive << name << "\n";
165 } else if (I->hasProtectedVisibility()) {
166 if (const char *Directive = TAI->getProtectedDirective())
167 O << Directive << name << "\n";
168 }
169
170 if (Subtarget->isTargetELF())
Dan Gohman721e6582007-07-30 15:08:02 +0000171 O << "\t.type\t" << name << ",@object\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172
Evan Cheng65c0fbc2007-09-21 00:41:19 +0000173 if (C->isNullValue() && !I->hasSection()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 if (I->hasExternalLinkage()) {
175 if (const char *Directive = TAI->getZeroFillDirective()) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000176 O << "\t.globl " << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 O << Directive << "__DATA__, __common, " << name << ", "
178 << Size << ", " << Align << "\n";
179 continue;
180 }
181 }
182
Evan Cheng65c0fbc2007-09-21 00:41:19 +0000183 if (!I->isThreadLocal() &&
Dale Johannesen3c788322008-01-11 00:54:37 +0000184 (I->hasInternalLinkage() ||
185 (!Subtarget->isTargetDarwin() &&
186 (I->hasWeakLinkage() || I->hasLinkOnceLinkage())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
188 if (!NoZerosInBSS && TAI->getBSSSection())
189 SwitchToDataSection(TAI->getBSSSection(), I);
190 else
191 SwitchToDataSection(TAI->getDataSection(), I);
192 if (TAI->getLCOMMDirective() != NULL) {
193 if (I->hasInternalLinkage()) {
194 O << TAI->getLCOMMDirective() << name << "," << Size;
195 if (Subtarget->isTargetDarwin())
196 O << "," << Align;
Chris Lattner93a2d432008-01-02 19:44:55 +0000197 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 O << TAI->getCOMMDirective() << name << "," << Size;
Chris Lattner93a2d432008-01-02 19:44:55 +0000199
200 // Leopard and above support aligned common symbols.
201 if (Subtarget->getDarwinVers() >= 9)
202 O << "," << Align;
203 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 } else {
205 if (!Subtarget->isTargetCygMing()) {
206 if (I->hasInternalLinkage())
207 O << "\t.local\t" << name << "\n";
208 }
209 O << TAI->getCOMMDirective() << name << "," << Size;
210 if (TAI->getCOMMDirectiveTakesAlignment())
211 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
212 }
213 O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
214 continue;
215 }
216 }
217
218 switch (I->getLinkage()) {
219 case GlobalValue::LinkOnceLinkage:
220 case GlobalValue::WeakLinkage:
221 if (Subtarget->isTargetDarwin()) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000222 O << "\t.globl " << name << "\n"
Dale Johannesenfb3ac732007-11-20 23:24:42 +0000223 << TAI->getWeakDefDirective() << name << "\n";
Dale Johannesen3c788322008-01-11 00:54:37 +0000224 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 } else if (Subtarget->isTargetCygMing()) {
226 std::string SectionName(".section\t.data$linkonce." +
227 name +
228 ",\"aw\"");
229 SwitchToDataSection(SectionName.c_str(), I);
Dan Gohman52443a82007-10-05 15:58:41 +0000230 O << "\t.globl\t" << name << "\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 << "\t.linkonce same_size\n";
232 } else {
233 std::string SectionName("\t.section\t.llvm.linkonce.d." +
234 name +
235 ",\"aw\",@progbits");
236 SwitchToDataSection(SectionName.c_str(), I);
Dan Gohman721e6582007-07-30 15:08:02 +0000237 O << "\t.weak\t" << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 }
239 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 case GlobalValue::DLLExportLinkage:
241 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
242 // FALL THROUGH
Chris Lattner2f8ba292007-08-13 18:42:37 +0000243 case GlobalValue::AppendingLinkage:
244 // FIXME: appending linkage variables should go into a section of
245 // their name or something. For now, just emit them as external.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 case GlobalValue::ExternalLinkage:
247 // If external or appending, declare as a global symbol
Dale Johannesen3c788322008-01-11 00:54:37 +0000248 O << "\t.globl " << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 // FALL THROUGH
250 case GlobalValue::InternalLinkage: {
251 if (I->isConstant()) {
252 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
253 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
254 SwitchToDataSection(TAI->getCStringSection(), I);
255 break;
256 }
257 }
258 // FIXME: special handling for ".ctors" & ".dtors" sections
259 if (I->hasSection() &&
260 (I->getSection() == ".ctors" ||
261 I->getSection() == ".dtors")) {
262 std::string SectionName = ".section " + I->getSection();
263
264 if (Subtarget->isTargetCygMing()) {
265 SectionName += ",\"aw\"";
266 } else {
267 assert(!Subtarget->isTargetDarwin());
268 SectionName += ",\"aw\",@progbits";
269 }
270
271 SwitchToDataSection(SectionName.c_str());
272 } else {
273 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
274 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
275 TAI->getBSSSection(), I);
276 else if (!I->isConstant())
277 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
278 TAI->getDataSection(), I);
279 else if (I->isThreadLocal())
280 SwitchToDataSection(TAI->getTLSDataSection());
281 else {
282 // Read-only data.
283 bool HasReloc = C->ContainsRelocations();
284 if (HasReloc &&
285 Subtarget->isTargetDarwin() &&
286 TM.getRelocationModel() != Reloc::Static)
287 SwitchToDataSection("\t.const_data\n");
288 else if (!HasReloc && Size == 4 &&
289 TAI->getFourByteConstantSection())
290 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
291 else if (!HasReloc && Size == 8 &&
292 TAI->getEightByteConstantSection())
293 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
294 else if (!HasReloc && Size == 16 &&
295 TAI->getSixteenByteConstantSection())
296 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
297 else if (TAI->getReadOnlySection())
298 SwitchToDataSection(TAI->getReadOnlySection(), I);
299 else
300 SwitchToDataSection(TAI->getDataSection(), I);
301 }
302 }
303
304 break;
305 }
306 default:
307 assert(0 && "Unknown linkage type!");
308 }
309
310 EmitAlignment(Align, I);
311 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
312 << "\n";
313 if (TAI->hasDotTypeDotSizeDirective())
Dan Gohman721e6582007-07-30 15:08:02 +0000314 O << "\t.size\t" << name << ", " << Size << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 // If the initializer is a extern weak symbol, remember to emit the weak
316 // reference!
317 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
318 if (GV->hasExternalWeakLinkage())
319 ExtWeakSymbols.insert(GV);
320
321 EmitGlobalConstant(C);
322 }
323
324 // Output linker support code for dllexported globals
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000325 if (!DLLExportedGVs.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 SwitchToDataSection(".section .drectve");
327 }
328
329 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
330 e = DLLExportedGVs.end();
331 i != e; ++i) {
332 O << "\t.ascii \" -export:" << *i << ",data\"\n";
333 }
334
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000335 if (!DLLExportedFns.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 SwitchToDataSection(".section .drectve");
337 }
338
339 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
340 e = DLLExportedFns.end();
341 i != e; ++i) {
342 O << "\t.ascii \" -export:" << *i << "\"\n";
343 }
344
345 if (Subtarget->isTargetDarwin()) {
346 SwitchToDataSection("");
347
348 // Output stubs for dynamically-linked functions
349 unsigned j = 1;
350 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
351 i != e; ++i, ++j) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000352 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 "self_modifying_code+pure_instructions,5", 0);
354 O << "L" << *i << "$stub:\n";
355 O << "\t.indirect_symbol " << *i << "\n";
356 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
357 }
358
359 O << "\n";
360
Dale Johannesen4670be42008-01-15 23:24:56 +0000361 if (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI &&
362 !Subtarget->is64Bit()) {
Bill Wendlingd1bda4f2007-09-11 08:27:17 +0000363 // Add the (possibly multiple) personalities to the set of global values.
364 const std::vector<Function *>& Personalities = MMI->getPersonalities();
365
366 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
367 E = Personalities.end(); I != E; ++I)
368 if (*I) GVStubs.insert("_" + (*I)->getName());
369 }
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 // Output stubs for external and common global variables.
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000372 if (!GVStubs.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 SwitchToDataSection(
Dale Johannesen3c788322008-01-11 00:54:37 +0000374 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
376 i != e; ++i) {
377 O << "L" << *i << "$non_lazy_ptr:\n";
378 O << "\t.indirect_symbol " << *i << "\n";
379 O << "\t.long\t0\n";
380 }
381
382 // Emit final debug information.
383 DW.EndModule();
384
385 // Funny Darwin hack: This flag tells the linker that no global symbols
386 // contain code that falls through to other global symbols (e.g. the obvious
387 // implementation of multiple entry points). If this doesn't occur, the
388 // linker can safely perform dead code stripping. Since LLVM never
389 // generates code that does this, it is always safe to set.
390 O << "\t.subsections_via_symbols\n";
391 } else if (Subtarget->isTargetCygMing()) {
392 // Emit type information for external functions
393 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
394 i != e; ++i) {
395 O << "\t.def\t " << *i
396 << ";\t.scl\t" << COFF::C_EXT
397 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
398 << ";\t.endef\n";
399 }
400
401 // Emit final debug information.
402 DW.EndModule();
403 } else if (Subtarget->isTargetELF()) {
404 // Emit final debug information.
405 DW.EndModule();
406 }
407
Dan Gohman4a558a32007-07-25 19:33:14 +0000408 return AsmPrinter::doFinalization(M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409}
410
411/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
412/// for a MachineFunction to the given output stream, using the given target
413/// machine description.
414///
415FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
416 X86TargetMachine &tm) {
417 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
418
419 if (Subtarget->isFlavorIntel()) {
420 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
421 } else {
422 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
423 }
424}