blob: 0b8c31cc7f6c9e84c12d7fc29bb4609c1056a14f [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"
Anton Korobeynikovab46ce62008-01-20 14:00:07 +000028#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#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"
34using namespace llvm;
35
36static 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
Anton Korobeynikovab46ce62008-01-20 14:00:07 +000052 unsigned argNum = 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
Anton Korobeynikovab46ce62008-01-20 14:00:07 +000054 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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 // Size should be aligned to DWORD boundary
Anton Korobeynikovab46ce62008-01-20 14:00:07 +000062 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
63 }
64
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 // 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.
73void 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) ||
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000105 (FT->getNumParams() == 1 && F->isStructReturn()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 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) ||
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000111 (FT->getNumParams() == 1 && F->isStructReturn()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 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
126bool X86SharedAsmPrinter::doInitialization(Module &M) {
127 if (TAI->doesSupportDebugInformation()) {
128 // Emit initial debug information.
129 DW.BeginModule(&M);
130 }
131
Dan Gohman4a558a32007-07-25 19:33:14 +0000132 bool Result = AsmPrinter::doInitialization(M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134 // Darwin wants symbols to be quoted if they have complex names.
135 if (Subtarget->isTargetDarwin())
136 Mang->setUseQuotes(true);
137
Dan Gohman4a558a32007-07-25 19:33:14 +0000138 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139}
140
141bool 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();
Duncan Sands8157ef42007-11-05 00:04:43 +0000168 unsigned Size = TD->getABITypeSize(Type);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 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())
Dan Gohman721e6582007-07-30 15:08:02 +0000180 O << "\t.type\t" << name << ",@object\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181
Evan Cheng65c0fbc2007-09-21 00:41:19 +0000182 if (C->isNullValue() && !I->hasSection()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 if (I->hasExternalLinkage()) {
184 if (const char *Directive = TAI->getZeroFillDirective()) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000185 O << "\t.globl " << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 O << Directive << "__DATA__, __common, " << name << ", "
187 << Size << ", " << Align << "\n";
188 continue;
189 }
190 }
191
Evan Cheng65c0fbc2007-09-21 00:41:19 +0000192 if (!I->isThreadLocal() &&
Dale Johannesen50085da2008-01-17 23:04:07 +0000193 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
194 I->hasLinkOnceLinkage())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 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;
Chris Lattner93a2d432008-01-02 19:44:55 +0000205 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 O << TAI->getCOMMDirective() << name << "," << Size;
Chris Lattner93a2d432008-01-02 19:44:55 +0000207
208 // Leopard and above support aligned common symbols.
209 if (Subtarget->getDarwinVers() >= 9)
210 O << "," << Align;
211 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 } 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()) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000230 O << "\t.globl " << name << "\n"
Dale Johannesenfb3ac732007-11-20 23:24:42 +0000231 << TAI->getWeakDefDirective() << name << "\n";
Dale Johannesen3c788322008-01-11 00:54:37 +0000232 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 } else if (Subtarget->isTargetCygMing()) {
234 std::string SectionName(".section\t.data$linkonce." +
235 name +
236 ",\"aw\"");
237 SwitchToDataSection(SectionName.c_str(), I);
Dan Gohman52443a82007-10-05 15:58:41 +0000238 O << "\t.globl\t" << name << "\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 << "\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);
Dan Gohman721e6582007-07-30 15:08:02 +0000245 O << "\t.weak\t" << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 case GlobalValue::DLLExportLinkage:
249 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
250 // FALL THROUGH
Chris Lattner2f8ba292007-08-13 18:42:37 +0000251 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 case GlobalValue::ExternalLinkage:
255 // If external or appending, declare as a global symbol
Dale Johannesen3c788322008-01-11 00:54:37 +0000256 O << "\t.globl " << name << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 // 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 }
Dale Johannesenae4f62f2008-01-23 00:58:14 +0000278 SwitchToDataSection(SectionName.c_str());
279 } else if (I->hasSection() && Subtarget->isTargetDarwin()) {
280 // Honor all section names on Darwin; ObjC uses this
281 std::string SectionName = ".section " + I->getSection();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 SwitchToDataSection(SectionName.c_str());
283 } else {
284 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
285 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
286 TAI->getBSSSection(), I);
287 else if (!I->isConstant())
288 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
289 TAI->getDataSection(), I);
290 else if (I->isThreadLocal())
291 SwitchToDataSection(TAI->getTLSDataSection());
292 else {
293 // Read-only data.
294 bool HasReloc = C->ContainsRelocations();
295 if (HasReloc &&
296 Subtarget->isTargetDarwin() &&
297 TM.getRelocationModel() != Reloc::Static)
298 SwitchToDataSection("\t.const_data\n");
299 else if (!HasReloc && Size == 4 &&
300 TAI->getFourByteConstantSection())
301 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
302 else if (!HasReloc && Size == 8 &&
303 TAI->getEightByteConstantSection())
304 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
305 else if (!HasReloc && Size == 16 &&
306 TAI->getSixteenByteConstantSection())
307 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
308 else if (TAI->getReadOnlySection())
309 SwitchToDataSection(TAI->getReadOnlySection(), I);
310 else
311 SwitchToDataSection(TAI->getDataSection(), I);
312 }
313 }
314
315 break;
316 }
317 default:
318 assert(0 && "Unknown linkage type!");
319 }
320
321 EmitAlignment(Align, I);
322 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
323 << "\n";
324 if (TAI->hasDotTypeDotSizeDirective())
Dan Gohman721e6582007-07-30 15:08:02 +0000325 O << "\t.size\t" << name << ", " << Size << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 // If the initializer is a extern weak symbol, remember to emit the weak
327 // reference!
328 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
329 if (GV->hasExternalWeakLinkage())
330 ExtWeakSymbols.insert(GV);
331
332 EmitGlobalConstant(C);
333 }
334
335 // Output linker support code for dllexported globals
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000336 if (!DLLExportedGVs.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 SwitchToDataSection(".section .drectve");
338 }
339
340 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
341 e = DLLExportedGVs.end();
342 i != e; ++i) {
343 O << "\t.ascii \" -export:" << *i << ",data\"\n";
344 }
345
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000346 if (!DLLExportedFns.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 SwitchToDataSection(".section .drectve");
348 }
349
350 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
351 e = DLLExportedFns.end();
352 i != e; ++i) {
353 O << "\t.ascii \" -export:" << *i << "\"\n";
354 }
355
356 if (Subtarget->isTargetDarwin()) {
357 SwitchToDataSection("");
358
359 // Output stubs for dynamically-linked functions
360 unsigned j = 1;
361 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
362 i != e; ++i, ++j) {
Dale Johannesen3c788322008-01-11 00:54:37 +0000363 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 "self_modifying_code+pure_instructions,5", 0);
365 O << "L" << *i << "$stub:\n";
366 O << "\t.indirect_symbol " << *i << "\n";
367 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
368 }
369
370 O << "\n";
371
Dale Johannesen4670be42008-01-15 23:24:56 +0000372 if (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI &&
373 !Subtarget->is64Bit()) {
Bill Wendlingd1bda4f2007-09-11 08:27:17 +0000374 // Add the (possibly multiple) personalities to the set of global values.
375 const std::vector<Function *>& Personalities = MMI->getPersonalities();
376
377 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
378 E = Personalities.end(); I != E; ++I)
379 if (*I) GVStubs.insert("_" + (*I)->getName());
380 }
381
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 // Output stubs for external and common global variables.
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000383 if (!GVStubs.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 SwitchToDataSection(
Dale Johannesen3c788322008-01-11 00:54:37 +0000385 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
387 i != e; ++i) {
388 O << "L" << *i << "$non_lazy_ptr:\n";
389 O << "\t.indirect_symbol " << *i << "\n";
390 O << "\t.long\t0\n";
391 }
392
393 // Emit final debug information.
394 DW.EndModule();
395
396 // Funny Darwin hack: This flag tells the linker that no global symbols
397 // contain code that falls through to other global symbols (e.g. the obvious
398 // implementation of multiple entry points). If this doesn't occur, the
399 // linker can safely perform dead code stripping. Since LLVM never
400 // generates code that does this, it is always safe to set.
401 O << "\t.subsections_via_symbols\n";
402 } else if (Subtarget->isTargetCygMing()) {
403 // Emit type information for external functions
404 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
405 i != e; ++i) {
406 O << "\t.def\t " << *i
407 << ";\t.scl\t" << COFF::C_EXT
408 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
409 << ";\t.endef\n";
410 }
411
412 // Emit final debug information.
413 DW.EndModule();
414 } else if (Subtarget->isTargetELF()) {
415 // Emit final debug information.
416 DW.EndModule();
417 }
418
Dan Gohman4a558a32007-07-25 19:33:14 +0000419 return AsmPrinter::doFinalization(M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420}
421
422/// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
423/// for a MachineFunction to the given output stream, using the given target
424/// machine description.
425///
426FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
427 X86TargetMachine &tm) {
428 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
429
430 if (Subtarget->isFlavorIntel()) {
431 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
432 } else {
433 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
434 }
435}