1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86ATTInstPrinter.h"
19 #include "X86IntelInstPrinter.h"
20 #include "X86MCInstLower.h"
23 #include "X86COFFMachineModuleInfo.h"
24 #include "X86MachineFunctionInfo.h"
25 #include "X86TargetMachine.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/Type.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/Statistic.h"
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
49 //===----------------------------------------------------------------------===//
50 // Primitive Helper Functions.
51 //===----------------------------------------------------------------------===//
53 void X86AsmPrinter::printMCInst(const MCInst *MI) {
54 if (MAI->getAssemblerDialect() == 0)
55 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
57 X86IntelInstPrinter(O, *MAI).printInstruction(MI);
60 void X86AsmPrinter::PrintPICBaseSymbol() const {
61 // FIXME: Gross const cast hack.
62 X86AsmPrinter *AP = const_cast<X86AsmPrinter*>(this);
63 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
66 void X86AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
67 unsigned FnAlign = MF.getAlignment();
68 const Function *F = MF.getFunction();
70 if (Subtarget->isTargetCygMing()) {
71 X86COFFMachineModuleInfo &COFFMMI =
72 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
73 COFFMMI.DecorateCygMingName(CurrentFnName, F, *TM.getTargetData());
76 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
77 EmitAlignment(FnAlign, F);
79 switch (F->getLinkage()) {
80 default: llvm_unreachable("Unknown linkage type!");
81 case Function::InternalLinkage: // Symbols default to internal.
82 case Function::PrivateLinkage:
84 case Function::DLLExportLinkage:
85 case Function::ExternalLinkage:
86 O << "\t.globl\t" << CurrentFnName << '\n';
88 case Function::LinkerPrivateLinkage:
89 case Function::LinkOnceAnyLinkage:
90 case Function::LinkOnceODRLinkage:
91 case Function::WeakAnyLinkage:
92 case Function::WeakODRLinkage:
93 if (Subtarget->isTargetDarwin()) {
94 O << "\t.globl\t" << CurrentFnName << '\n';
95 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
96 } else if (Subtarget->isTargetCygMing()) {
97 O << "\t.globl\t" << CurrentFnName << "\n"
98 "\t.linkonce discard\n";
100 O << "\t.weak\t" << CurrentFnName << '\n';
105 printVisibility(CurrentFnName, F->getVisibility());
107 if (Subtarget->isTargetELF())
108 O << "\t.type\t" << CurrentFnName << ",@function\n";
109 else if (Subtarget->isTargetCygMing()) {
110 O << "\t.def\t " << CurrentFnName
112 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
113 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
117 O << CurrentFnName << ':';
119 O.PadToColumn(MAI->getCommentColumn());
120 O << MAI->getCommentString() << ' ';
121 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
125 // Add some workaround for linkonce linkage on Cygwin\MinGW
126 if (Subtarget->isTargetCygMing() &&
127 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
128 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
131 /// runOnMachineFunction - This uses the printMachineInstruction()
132 /// method to print assembly for each instruction.
134 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
135 const Function *F = MF.getFunction();
137 CallingConv::ID CC = F->getCallingConv();
139 SetupMachineFunction(MF);
142 if (Subtarget->isTargetCOFF()) {
143 X86COFFMachineModuleInfo &COFFMMI =
144 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
146 // Populate function information map. Don't want to populate
147 // non-stdcall or non-fastcall functions' information right now.
148 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
149 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
152 // Print out constants referenced by the function
153 EmitConstantPool(MF.getConstantPool());
155 // Print the 'header' of function
156 emitFunctionHeader(MF);
158 // Emit pre-function debug and/or EH information.
159 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
160 DW->BeginFunction(&MF);
162 // Print out code for the function.
163 bool hasAnyRealCode = false;
164 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166 // Print a label for the basic block.
167 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
168 // This is an entry block or a block that's only reachable via a
169 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
171 EmitBasicBlockStart(I);
174 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
176 // Print the assembly for the instruction.
178 hasAnyRealCode = true;
179 printMachineInstruction(II);
183 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
184 // If the function is empty, then we need to emit *something*. Otherwise,
185 // the function's label might be associated with something that it wasn't
186 // meant to be associated with. We emit a noop in this situation.
187 // We are assuming inline asms are code.
191 if (MAI->hasDotTypeDotSizeDirective())
192 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
194 // Emit post-function debug information.
195 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
196 DW->EndFunction(&MF);
198 // Print out jump tables referenced by the function.
199 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
201 // We didn't modify anything.
205 /// printSymbolOperand - Print a raw symbol reference operand. This handles
206 /// jump tables, constant pools, global address and external symbols, all of
207 /// which print to a label with various suffixes for relocation types etc.
208 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
209 switch (MO.getType()) {
210 default: llvm_unreachable("unknown symbol type!");
211 case MachineOperand::MO_JumpTableIndex:
212 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
215 case MachineOperand::MO_ConstantPoolIndex:
216 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
218 printOffset(MO.getOffset());
220 case MachineOperand::MO_GlobalAddress: {
221 const GlobalValue *GV = MO.getGlobal();
223 const char *Suffix = "";
224 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
226 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
227 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
228 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
229 Suffix = "$non_lazy_ptr";
231 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
232 if (Subtarget->isTargetCygMing()) {
233 X86COFFMachineModuleInfo &COFFMMI =
234 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
235 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
238 // Handle dllimport linkage.
239 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
240 Name = "__imp_" + Name;
242 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
243 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
244 SmallString<128> NameStr;
245 Mang->getNameWithPrefix(NameStr, GV, true);
246 NameStr += "$non_lazy_ptr";
247 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
249 const MCSymbol *&StubSym =
250 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
253 Mang->getNameWithPrefix(NameStr, GV, false);
254 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
256 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
257 SmallString<128> NameStr;
258 Mang->getNameWithPrefix(NameStr, GV, true);
259 NameStr += "$non_lazy_ptr";
260 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
261 const MCSymbol *&StubSym =
262 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
265 Mang->getNameWithPrefix(NameStr, GV, false);
266 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
268 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
269 SmallString<128> NameStr;
270 Mang->getNameWithPrefix(NameStr, GV, true);
272 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
273 const MCSymbol *&StubSym =
274 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
277 Mang->getNameWithPrefix(NameStr, GV, false);
278 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
282 // If the name begins with a dollar-sign, enclose it in parens. We do this
283 // to avoid having it look like an integer immediate to the assembler.
285 O << '(' << Name << ')';
289 printOffset(MO.getOffset());
292 case MachineOperand::MO_ExternalSymbol: {
293 std::string Name = Mang->makeNameProper(MO.getSymbolName());
294 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
296 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
297 const MCSymbol *&StubSym =
298 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
300 Name.erase(Name.end()-5, Name.end());
301 StubSym = OutContext.GetOrCreateSymbol(Name);
305 // If the name begins with a dollar-sign, enclose it in parens. We do this
306 // to avoid having it look like an integer immediate to the assembler.
308 O << '(' << Name << ')';
315 switch (MO.getTargetFlags()) {
317 llvm_unreachable("Unknown target flag on GV operand");
318 case X86II::MO_NO_FLAG: // No flag.
320 case X86II::MO_DARWIN_NONLAZY:
321 case X86II::MO_DLLIMPORT:
322 case X86II::MO_DARWIN_STUB:
323 // These affect the name of the symbol, not any suffix.
325 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
327 PrintPICBaseSymbol();
330 case X86II::MO_PIC_BASE_OFFSET:
331 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
332 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
334 PrintPICBaseSymbol();
336 case X86II::MO_TLSGD: O << "@TLSGD"; break;
337 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
338 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
339 case X86II::MO_TPOFF: O << "@TPOFF"; break;
340 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
341 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
342 case X86II::MO_GOT: O << "@GOT"; break;
343 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
344 case X86II::MO_PLT: O << "@PLT"; break;
348 /// print_pcrel_imm - This is used to print an immediate value that ends up
349 /// being encoded as a pc-relative value. These print slightly differently, for
350 /// example, a $ is not emitted.
351 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
352 const MachineOperand &MO = MI->getOperand(OpNo);
353 switch (MO.getType()) {
354 default: llvm_unreachable("Unknown pcrel immediate operand");
355 case MachineOperand::MO_Immediate:
358 case MachineOperand::MO_MachineBasicBlock:
359 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
361 case MachineOperand::MO_GlobalAddress:
362 case MachineOperand::MO_ExternalSymbol:
363 printSymbolOperand(MO);
369 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
370 const char *Modifier) {
371 const MachineOperand &MO = MI->getOperand(OpNo);
372 switch (MO.getType()) {
373 default: llvm_unreachable("unknown operand type!");
374 case MachineOperand::MO_Register: {
376 unsigned Reg = MO.getReg();
377 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
378 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
379 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
380 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
381 Reg = getX86SubSuperRegister(Reg, VT);
383 O << X86ATTInstPrinter::getRegisterName(Reg);
387 case MachineOperand::MO_Immediate:
388 O << '$' << MO.getImm();
391 case MachineOperand::MO_JumpTableIndex:
392 case MachineOperand::MO_ConstantPoolIndex:
393 case MachineOperand::MO_GlobalAddress:
394 case MachineOperand::MO_ExternalSymbol: {
396 printSymbolOperand(MO);
402 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
403 unsigned char value = MI->getOperand(Op).getImm();
404 assert(value <= 7 && "Invalid ssecc argument!");
406 case 0: O << "eq"; break;
407 case 1: O << "lt"; break;
408 case 2: O << "le"; break;
409 case 3: O << "unord"; break;
410 case 4: O << "neq"; break;
411 case 5: O << "nlt"; break;
412 case 6: O << "nle"; break;
413 case 7: O << "ord"; break;
417 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
418 const char *Modifier) {
419 const MachineOperand &BaseReg = MI->getOperand(Op);
420 const MachineOperand &IndexReg = MI->getOperand(Op+2);
421 const MachineOperand &DispSpec = MI->getOperand(Op+3);
423 // If we really don't want to print out (rip), don't.
424 bool HasBaseReg = BaseReg.getReg() != 0;
425 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
426 BaseReg.getReg() == X86::RIP)
429 // HasParenPart - True if we will print out the () part of the mem ref.
430 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
432 if (DispSpec.isImm()) {
433 int DispVal = DispSpec.getImm();
434 if (DispVal || !HasParenPart)
437 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
438 DispSpec.isJTI() || DispSpec.isSymbol());
439 printSymbolOperand(MI->getOperand(Op+3));
443 assert(IndexReg.getReg() != X86::ESP &&
444 "X86 doesn't allow scaling by ESP");
448 printOperand(MI, Op, Modifier);
450 if (IndexReg.getReg()) {
452 printOperand(MI, Op+2, Modifier);
453 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
455 O << ',' << ScaleVal;
461 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
462 const char *Modifier) {
463 assert(isMem(MI, Op) && "Invalid memory reference!");
464 const MachineOperand &Segment = MI->getOperand(Op+4);
465 if (Segment.getReg()) {
466 printOperand(MI, Op+4, Modifier);
469 printLeaMemReference(MI, Op, Modifier);
472 void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
473 const MachineBasicBlock *MBB) const {
474 if (!MAI->getSetDirective())
477 // We don't need .set machinery if we have GOT-style relocations
478 if (Subtarget->isPICStyleGOT())
481 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
482 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
484 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
486 if (Subtarget->isPICStyleRIPRel())
487 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
488 << '_' << uid << '\n';
491 PrintPICBaseSymbol();
497 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
498 PrintPICBaseSymbol();
500 PrintPICBaseSymbol();
504 void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
505 const MachineBasicBlock *MBB,
506 unsigned uid) const {
507 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
508 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
510 O << JTEntryDirective << ' ';
512 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
513 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
514 << '_' << uid << "_set_" << MBB->getNumber();
515 } else if (Subtarget->isPICStyleGOT()) {
516 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
519 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
522 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
523 unsigned Reg = MO.getReg();
525 default: return true; // Unknown mode.
526 case 'b': // Print QImode register
527 Reg = getX86SubSuperRegister(Reg, MVT::i8);
529 case 'h': // Print QImode high register
530 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
532 case 'w': // Print HImode register
533 Reg = getX86SubSuperRegister(Reg, MVT::i16);
535 case 'k': // Print SImode register
536 Reg = getX86SubSuperRegister(Reg, MVT::i32);
538 case 'q': // Print DImode register
539 Reg = getX86SubSuperRegister(Reg, MVT::i64);
543 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
547 /// PrintAsmOperand - Print out an operand for an inline asm expression.
549 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
551 const char *ExtraCode) {
552 // Does this asm operand have a single letter operand modifier?
553 if (ExtraCode && ExtraCode[0]) {
554 if (ExtraCode[1] != 0) return true; // Unknown modifier.
556 const MachineOperand &MO = MI->getOperand(OpNo);
558 switch (ExtraCode[0]) {
559 default: return true; // Unknown modifier.
560 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
565 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
566 printSymbolOperand(MO);
571 printOperand(MI, OpNo);
577 case 'c': // Don't print "$" before a global var name or constant.
580 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
581 printSymbolOperand(MO);
583 printOperand(MI, OpNo);
586 case 'A': // Print '*' before a register (it must be a register)
589 printOperand(MI, OpNo);
594 case 'b': // Print QImode register
595 case 'h': // Print QImode high register
596 case 'w': // Print HImode register
597 case 'k': // Print SImode register
598 case 'q': // Print DImode register
600 return printAsmMRegister(MO, ExtraCode[0]);
601 printOperand(MI, OpNo);
604 case 'P': // This is the operand of a call, treat specially.
605 print_pcrel_imm(MI, OpNo);
608 case 'n': // Negate the immediate or print a '-' before the operand.
609 // Note: this is a temporary solution. It should be handled target
610 // independently as part of the 'MC' work.
619 printOperand(MI, OpNo);
623 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
624 unsigned OpNo, unsigned AsmVariant,
625 const char *ExtraCode) {
626 if (ExtraCode && ExtraCode[0]) {
627 if (ExtraCode[1] != 0) return true; // Unknown modifier.
629 switch (ExtraCode[0]) {
630 default: return true; // Unknown modifier.
631 case 'b': // Print QImode register
632 case 'h': // Print QImode high register
633 case 'w': // Print HImode register
634 case 'k': // Print SImode register
635 case 'q': // Print SImode register
636 // These only apply to registers, ignore on mem.
638 case 'P': // Don't print @PLT, but do print as memory.
639 printMemReference(MI, OpNo, "no-rip");
643 printMemReference(MI, OpNo);
649 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
650 /// AT&T syntax to the current output stream.
652 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
655 processDebugLoc(MI->getDebugLoc());
657 printInstructionThroughMCStreamer(MI);
659 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
664 void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
665 if (!GVar->hasInitializer())
666 return; // External global require no code
668 // Check to see if this is a special global used by LLVM, if so, emit it.
669 if (EmitSpecialLLVMGlobal(GVar)) {
670 if (Subtarget->isTargetDarwin() &&
671 TM.getRelocationModel() == Reloc::Static) {
672 if (GVar->getName() == "llvm.global_ctors")
673 O << ".reference .constructors_used\n";
674 else if (GVar->getName() == "llvm.global_dtors")
675 O << ".reference .destructors_used\n";
680 const TargetData *TD = TM.getTargetData();
682 std::string name = Mang->getMangledName(GVar);
683 Constant *C = GVar->getInitializer();
684 const Type *Type = C->getType();
685 unsigned Size = TD->getTypeAllocSize(Type);
686 unsigned Align = TD->getPreferredAlignmentLog(GVar);
688 printVisibility(name, GVar->getVisibility());
690 if (Subtarget->isTargetELF())
691 O << "\t.type\t" << name << ",@object\n";
694 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
695 const MCSection *TheSection =
696 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
697 OutStreamer.SwitchSection(TheSection);
699 // FIXME: get this stuff from section kind flags.
700 if (C->isNullValue() && !GVar->hasSection() &&
701 // Don't put things that should go in the cstring section into "comm".
702 !TheSection->getKind().isMergeableCString()) {
703 if (GVar->hasExternalLinkage()) {
704 if (const char *Directive = MAI->getZeroFillDirective()) {
705 O << "\t.globl " << name << '\n';
706 O << Directive << "__DATA, __common, " << name << ", "
707 << Size << ", " << Align << '\n';
712 if (!GVar->isThreadLocal() &&
713 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
714 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
716 if (MAI->getLCOMMDirective() != NULL) {
717 if (GVar->hasLocalLinkage()) {
718 O << MAI->getLCOMMDirective() << name << ',' << Size;
719 if (Subtarget->isTargetDarwin())
721 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
722 O << "\t.globl " << name << '\n'
723 << MAI->getWeakDefDirective() << name << '\n';
724 EmitAlignment(Align, GVar);
727 O.PadToColumn(MAI->getCommentColumn());
728 O << MAI->getCommentString() << ' ';
729 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
732 EmitGlobalConstant(C);
735 O << MAI->getCOMMDirective() << name << ',' << Size;
736 if (MAI->getCOMMDirectiveTakesAlignment())
737 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
740 if (!Subtarget->isTargetCygMing()) {
741 if (GVar->hasLocalLinkage())
742 O << "\t.local\t" << name << '\n';
744 O << MAI->getCOMMDirective() << name << ',' << Size;
745 if (MAI->getCOMMDirectiveTakesAlignment())
746 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
749 O.PadToColumn(MAI->getCommentColumn());
750 O << MAI->getCommentString() << ' ';
751 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
758 switch (GVar->getLinkage()) {
759 case GlobalValue::CommonLinkage:
760 case GlobalValue::LinkOnceAnyLinkage:
761 case GlobalValue::LinkOnceODRLinkage:
762 case GlobalValue::WeakAnyLinkage:
763 case GlobalValue::WeakODRLinkage:
764 case GlobalValue::LinkerPrivateLinkage:
765 if (Subtarget->isTargetDarwin()) {
766 O << "\t.globl " << name << '\n'
767 << MAI->getWeakDefDirective() << name << '\n';
768 } else if (Subtarget->isTargetCygMing()) {
769 O << "\t.globl\t" << name << "\n"
770 "\t.linkonce same_size\n";
772 O << "\t.weak\t" << name << '\n';
775 case GlobalValue::DLLExportLinkage:
776 case GlobalValue::AppendingLinkage:
777 // FIXME: appending linkage variables should go into a section of
778 // their name or something. For now, just emit them as external.
779 case GlobalValue::ExternalLinkage:
780 // If external or appending, declare as a global symbol
781 O << "\t.globl " << name << '\n';
783 case GlobalValue::PrivateLinkage:
784 case GlobalValue::InternalLinkage:
787 llvm_unreachable("Unknown linkage type!");
790 EmitAlignment(Align, GVar);
793 O.PadToColumn(MAI->getCommentColumn());
794 O << MAI->getCommentString() << ' ';
795 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
799 EmitGlobalConstant(C);
801 if (MAI->hasDotTypeDotSizeDirective())
802 O << "\t.size\t" << name << ", " << Size << '\n';
805 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
806 if (Subtarget->isTargetDarwin()) {
807 // All darwin targets use mach-o.
808 TargetLoweringObjectFileMachO &TLOFMacho =
809 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
811 MachineModuleInfoMachO &MMIMacho =
812 MMI->getObjFileInfo<MachineModuleInfoMachO>();
814 // Output stubs for dynamically-linked functions.
815 MachineModuleInfoMachO::SymbolListTy Stubs;
817 Stubs = MMIMacho.GetFnStubList();
818 if (!Stubs.empty()) {
819 const MCSection *TheSection =
820 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
821 MCSectionMachO::S_SYMBOL_STUBS |
822 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
823 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
824 5, SectionKind::getMetadata());
825 OutStreamer.SwitchSection(TheSection);
827 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
828 Stubs[i].first->print(O, MAI);
829 O << ":\n" << "\t.indirect_symbol ";
830 // Get the MCSymbol without the $stub suffix.
831 Stubs[i].second->print(O, MAI);
832 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
839 // Output stubs for external and common global variables.
840 Stubs = MMIMacho.GetGVStubList();
841 if (!Stubs.empty()) {
842 const MCSection *TheSection =
843 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
844 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
845 SectionKind::getMetadata());
846 OutStreamer.SwitchSection(TheSection);
848 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
849 Stubs[i].first->print(O, MAI);
850 O << ":\n\t.indirect_symbol ";
851 Stubs[i].second->print(O, MAI);
852 O << "\n\t.long\t0\n";
857 Stubs = MMIMacho.GetHiddenGVStubList();
858 if (!Stubs.empty()) {
859 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
862 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
863 Stubs[i].first->print(O, MAI);
864 O << ":\n" << MAI->getData32bitsDirective();
865 Stubs[i].second->print(O, MAI);
871 // Funny Darwin hack: This flag tells the linker that no global symbols
872 // contain code that falls through to other global symbols (e.g. the obvious
873 // implementation of multiple entry points). If this doesn't occur, the
874 // linker can safely perform dead code stripping. Since LLVM never
875 // generates code that does this, it is always safe to set.
876 O << "\t.subsections_via_symbols\n";
879 if (Subtarget->isTargetCOFF()) {
880 // Necessary for dllexport support
881 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
883 X86COFFMachineModuleInfo &COFFMMI =
884 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
885 TargetLoweringObjectFileCOFF &TLOFCOFF =
886 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
888 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
889 if (I->hasDLLExportLinkage())
890 DLLExportedFns.push_back(Mang->getMangledName(I));
892 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
894 if (I->hasDLLExportLinkage())
895 DLLExportedGlobals.push_back(Mang->getMangledName(I));
897 if (Subtarget->isTargetCygMing()) {
898 // Emit type information for external functions
899 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
900 E = COFFMMI.stub_end(); I != E; ++I) {
901 O << "\t.def\t " << I->getKeyData()
902 << ";\t.scl\t" << COFF::C_EXT
903 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
908 // Output linker support code for dllexported globals on windows.
909 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
910 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
912 SectionKind::getMetadata()));
914 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
915 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
917 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
918 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";