1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
13 // This printer is the output mechanism used by `llc'.
15 //===----------------------------------------------------------------------===//
17 #include "X86AsmPrinter.h"
18 #include "X86ATTAsmPrinter.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"
34 static X86FunctionInfo calculateFunctionInfo(const Function *F,
35 const TargetData *TD) {
39 switch (F->getCallingConv()) {
40 case CallingConv::X86_StdCall:
41 Info.setDecorationStyle(StdCall);
43 case CallingConv::X86_FastCall:
44 Info.setDecorationStyle(FastCall);
50 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
52 // Size should be aligned to DWORD boundary
53 Size += ((TD->getTypeSize(AI->getType()) + 3)/4)*4;
55 // We're not supporting tooooo huge arguments :)
56 Info.setBytesToPopOnReturn((unsigned int)Size);
61 /// decorateName - Query FunctionInfoMap and use this information for various
63 void X86SharedAsmPrinter::decorateName(std::string &Name,
64 const GlobalValue *GV) {
65 const Function *F = dyn_cast<Function>(GV);
68 // We don't want to decorate non-stdcall or non-fastcall functions right now
69 unsigned CC = F->getCallingConv();
70 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
73 // Decorate names only when we're targeting Cygwin/Mingw32 targets
74 if (!Subtarget->isTargetCygMing())
77 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
79 const X86FunctionInfo *Info;
80 if (info_item == FunctionInfoMap.end()) {
81 // Calculate apropriate function info and populate map
82 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
83 Info = &FunctionInfoMap[F];
85 Info = &info_item->second;
88 switch (Info->getDecorationStyle()) {
92 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
93 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
96 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
97 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
106 assert(0 && "Unsupported DecorationStyle");
111 bool X86SharedAsmPrinter::doInitialization(Module &M) {
112 if (Subtarget->isTargetELF() ||
113 Subtarget->isTargetCygMing() ||
114 Subtarget->isTargetDarwin()) {
115 // Emit initial debug information.
119 return AsmPrinter::doInitialization(M);
122 bool X86SharedAsmPrinter::doFinalization(Module &M) {
123 // Note: this code is not shared by the Intel printer as it is too different
124 // from how MASM does things. When making changes here don't forget to look
125 // at X86IntelAsmPrinter::doFinalization().
126 const TargetData *TD = TM.getTargetData();
128 // Print out module-level global variables here.
129 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
131 if (!I->hasInitializer())
132 continue; // External global require no code
134 // Check to see if this is a special global used by LLVM, if so, emit it.
135 if (EmitSpecialLLVMGlobal(I)) {
136 if (Subtarget->isTargetDarwin() &&
137 TM.getRelocationModel() == Reloc::Static) {
138 if (I->getName() == "llvm.global_ctors")
139 O << ".reference .constructors_used\n";
140 else if (I->getName() == "llvm.global_dtors")
141 O << ".reference .destructors_used\n";
146 std::string name = Mang->getValueName(I);
147 Constant *C = I->getInitializer();
148 const Type *Type = C->getType();
149 unsigned Size = TD->getTypeSize(Type);
150 unsigned Align = TD->getPreferredAlignmentLog(I);
152 if (I->hasHiddenVisibility())
153 if (const char *Directive = TAI->getHiddenDirective())
154 O << Directive << name << "\n";
155 if (Subtarget->isTargetELF())
156 O << "\t.type " << name << ",@object\n";
158 if (C->isNullValue()) {
159 if (I->hasExternalLinkage()) {
160 if (const char *Directive = TAI->getZeroFillDirective()) {
161 O << "\t.globl\t" << name << "\n";
162 O << Directive << "__DATA__, __common, " << name << ", "
163 << Size << ", " << Align << "\n";
168 if (!I->hasSection() &&
169 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
170 I->hasLinkOnceLinkage())) {
171 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
172 if (!NoZerosInBSS && TAI->getBSSSection())
173 SwitchToDataSection(TAI->getBSSSection(), I);
175 SwitchToDataSection(TAI->getDataSection(), I);
176 if (TAI->getLCOMMDirective() != NULL) {
177 if (I->hasInternalLinkage()) {
178 O << TAI->getLCOMMDirective() << name << "," << Size;
179 if (Subtarget->isTargetDarwin())
182 O << TAI->getCOMMDirective() << name << "," << Size;
184 if (!Subtarget->isTargetCygMing()) {
185 if (I->hasInternalLinkage())
186 O << "\t.local\t" << name << "\n";
188 O << TAI->getCOMMDirective() << name << "," << Size;
189 if (TAI->getCOMMDirectiveTakesAlignment())
190 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
192 O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
197 switch (I->getLinkage()) {
198 case GlobalValue::LinkOnceLinkage:
199 case GlobalValue::WeakLinkage:
200 if (Subtarget->isTargetDarwin()) {
201 O << "\t.globl " << name << "\n"
202 << "\t.weak_definition " << name << "\n";
203 SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
204 } else if (Subtarget->isTargetCygMing()) {
205 std::string SectionName(".section\t.data$linkonce." +
208 SwitchToDataSection(SectionName.c_str(), I);
209 O << "\t.globl " << name << "\n"
210 << "\t.linkonce same_size\n";
212 std::string SectionName("\t.section\t.llvm.linkonce.d." +
214 ",\"aw\",@progbits");
215 SwitchToDataSection(SectionName.c_str(), I);
216 O << "\t.weak " << name << "\n";
219 case GlobalValue::AppendingLinkage:
220 // FIXME: appending linkage variables should go into a section of
221 // their name or something. For now, just emit them as external.
222 case GlobalValue::DLLExportLinkage:
223 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
225 case GlobalValue::ExternalLinkage:
226 // If external or appending, declare as a global symbol
227 O << "\t.globl " << name << "\n";
229 case GlobalValue::InternalLinkage: {
230 if (I->isConstant()) {
231 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
232 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
233 SwitchToDataSection(TAI->getCStringSection(), I);
237 // FIXME: special handling for ".ctors" & ".dtors" sections
238 if (I->hasSection() &&
239 (I->getSection() == ".ctors" ||
240 I->getSection() == ".dtors")) {
241 std::string SectionName = ".section " + I->getSection();
243 if (Subtarget->isTargetCygMing()) {
244 SectionName += ",\"aw\"";
246 assert(!Subtarget->isTargetDarwin());
247 SectionName += ",\"aw\",@progbits";
250 SwitchToDataSection(SectionName.c_str());
252 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
253 SwitchToDataSection(TAI->getBSSSection(), I);
254 else if (!I->isConstant())
255 SwitchToDataSection(TAI->getDataSection(), I);
258 bool isIntFPLiteral = Type->isInteger() || Type->isFloatingPoint();
259 if (C->ContainsRelocations() && Subtarget->isTargetDarwin() &&
260 TM.getRelocationModel() != Reloc::Static)
261 SwitchToDataSection("\t.const_data\n");
262 else if (isIntFPLiteral && Size == 4 &&
263 TAI->getFourByteConstantSection())
264 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
265 else if (isIntFPLiteral && Size == 8 &&
266 TAI->getEightByteConstantSection())
267 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
268 else if (isIntFPLiteral && Size == 16 &&
269 TAI->getSixteenByteConstantSection())
270 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
271 else if (TAI->getReadOnlySection())
272 SwitchToDataSection(TAI->getReadOnlySection(), I);
274 SwitchToDataSection(TAI->getDataSection(), I);
281 assert(0 && "Unknown linkage type!");
284 EmitAlignment(Align, I);
285 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
287 if (TAI->hasDotTypeDotSizeDirective())
288 O << "\t.size " << name << ", " << Size << "\n";
289 // If the initializer is a extern weak symbol, remember to emit the weak
291 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
292 if (GV->hasExternalWeakLinkage())
293 ExtWeakSymbols.insert(GV);
295 EmitGlobalConstant(C);
299 // Output linker support code for dllexported globals
300 if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
301 SwitchToDataSection(".section .drectve");
304 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
305 e = DLLExportedGVs.end();
307 O << "\t.ascii \" -export:" << *i << ",data\"\n";
310 if (DLLExportedFns.begin() != DLLExportedFns.end()) {
311 SwitchToDataSection(".section .drectve");
314 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
315 e = DLLExportedFns.end();
317 O << "\t.ascii \" -export:" << *i << "\"\n";
320 if (Subtarget->isTargetDarwin()) {
321 SwitchToDataSection("");
323 // Output stubs for dynamically-linked functions
325 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
327 SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
328 "self_modifying_code+pure_instructions,5", 0);
329 O << "L" << *i << "$stub:\n";
330 O << "\t.indirect_symbol " << *i << "\n";
331 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
336 // Output stubs for external and common global variables.
337 if (GVStubs.begin() != GVStubs.end())
339 ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
340 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
342 O << "L" << *i << "$non_lazy_ptr:\n";
343 O << "\t.indirect_symbol " << *i << "\n";
347 // Emit final debug information.
350 // Funny Darwin hack: This flag tells the linker that no global symbols
351 // contain code that falls through to other global symbols (e.g. the obvious
352 // implementation of multiple entry points). If this doesn't occur, the
353 // linker can safely perform dead code stripping. Since LLVM never
354 // generates code that does this, it is always safe to set.
355 O << "\t.subsections_via_symbols\n";
356 } else if (Subtarget->isTargetCygMing()) {
357 // Emit type information for external functions
358 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
360 O << "\t.def\t " << *i
361 << ";\t.scl\t" << COFF::C_EXT
362 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
366 // Emit final debug information.
368 } else if (Subtarget->isTargetELF()) {
369 // Emit final debug information.
373 AsmPrinter::doFinalization(M);
374 return false; // success
377 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
378 /// for a MachineFunction to the given output stream, using the given target
379 /// machine description.
381 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
382 X86TargetMachine &tm) {
383 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
385 if (Subtarget->isFlavorIntel()) {
386 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
388 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());