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"
19 #include "../X86COFF.h"
20 #include "../X86MachineFunctionInfo.h"
21 #include "../X86TargetMachine.h"
22 #include "../X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetOptions.h"
35 STATISTIC(EmittedInsts, "Number of machine instrs printed");
37 static std::string getPICLabelString(unsigned FnNum,
38 const TargetAsmInfo *TAI,
39 const X86Subtarget* Subtarget) {
41 if (Subtarget->isTargetDarwin())
42 label = "\"L" + utostr_32(FnNum) + "$pb\"";
43 else if (Subtarget->isTargetELF())
44 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
46 assert(0 && "Don't know how to print PIC label!\n");
51 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
52 const TargetData *TD) {
53 X86MachineFunctionInfo Info;
56 switch (F->getCallingConv()) {
57 case CallingConv::X86_StdCall:
58 Info.setDecorationStyle(StdCall);
60 case CallingConv::X86_FastCall:
61 Info.setDecorationStyle(FastCall);
68 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
69 AI != AE; ++AI, ++argNum) {
70 const Type* Ty = AI->getType();
72 // 'Dereference' type in case of byval parameter attribute
73 if (F->paramHasAttr(argNum, ParamAttr::ByVal))
74 Ty = cast<PointerType>(Ty)->getElementType();
76 // Size should be aligned to DWORD boundary
77 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
80 // We're not supporting tooooo huge arguments :)
81 Info.setBytesToPopOnReturn((unsigned int)Size);
85 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
86 /// Don't print things like \n or \0.
87 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
88 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
94 /// decorateName - Query FunctionInfoMap and use this information for various
96 void X86ATTAsmPrinter::decorateName(std::string &Name,
97 const GlobalValue *GV) {
98 const Function *F = dyn_cast<Function>(GV);
101 // We don't want to decorate non-stdcall or non-fastcall functions right now
102 unsigned CC = F->getCallingConv();
103 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
106 // Decorate names only when we're targeting Cygwin/Mingw32 targets
107 if (!Subtarget->isTargetCygMing())
110 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
112 const X86MachineFunctionInfo *Info;
113 if (info_item == FunctionInfoMap.end()) {
114 // Calculate apropriate function info and populate map
115 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
116 Info = &FunctionInfoMap[F];
118 Info = &info_item->second;
121 const FunctionType *FT = F->getFunctionType();
122 switch (Info->getDecorationStyle()) {
126 // "Pure" variadic functions do not receive @0 suffix.
127 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
128 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
129 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
132 // "Pure" variadic functions do not receive @0 suffix.
133 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
134 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
135 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
137 if (Name[0] == '_') {
144 assert(0 && "Unsupported DecorationStyle");
148 // Substitute old hook with new one temporary
149 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
150 return TAI->SectionForGlobal(&F);
153 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
154 const Function *F = MF.getFunction();
155 std::string SectionName = TAI->SectionForGlobal(F);
157 decorateName(CurrentFnName, F);
159 SwitchToTextSection(SectionName.c_str());
161 unsigned FnAlign = OptimizeForSize ? 1 : 4;
162 switch (F->getLinkage()) {
163 default: assert(0 && "Unknown linkage type!");
164 case Function::InternalLinkage: // Symbols default to internal.
165 EmitAlignment(FnAlign, F);
167 case Function::DLLExportLinkage:
168 case Function::ExternalLinkage:
169 EmitAlignment(FnAlign, F);
170 O << "\t.globl\t" << CurrentFnName << '\n';
172 case Function::LinkOnceLinkage:
173 case Function::WeakLinkage:
174 EmitAlignment(FnAlign, F);
175 if (Subtarget->isTargetDarwin()) {
176 O << "\t.globl\t" << CurrentFnName << '\n';
177 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
178 } else if (Subtarget->isTargetCygMing()) {
179 O << "\t.globl\t" << CurrentFnName << "\n"
180 "\t.linkonce discard\n";
182 O << "\t.weak\t" << CurrentFnName << '\n';
187 printVisibility(CurrentFnName, F->getVisibility());
189 if (Subtarget->isTargetELF())
190 O << "\t.type\t" << CurrentFnName << ",@function\n";
191 else if (Subtarget->isTargetCygMing()) {
192 O << "\t.def\t " << CurrentFnName
194 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
195 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
199 O << CurrentFnName << ":\n";
200 // Add some workaround for linkonce linkage on Cygwin\MinGW
201 if (Subtarget->isTargetCygMing() &&
202 (F->getLinkage() == Function::LinkOnceLinkage ||
203 F->getLinkage() == Function::WeakLinkage))
204 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
207 /// runOnMachineFunction - This uses the printMachineInstruction()
208 /// method to print assembly for each instruction.
210 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
211 const Function *F = MF.getFunction();
212 unsigned CC = F->getCallingConv();
214 SetupMachineFunction(MF);
217 // Populate function information map. Actually, We don't want to populate
218 // non-stdcall or non-fastcall functions' information right now.
219 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
220 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
222 // Print out constants referenced by the function
223 EmitConstantPool(MF.getConstantPool());
225 if (F->hasDLLExportLinkage())
226 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
228 // Print the 'header' of function
229 emitFunctionHeader(MF);
231 // Emit pre-function debug and/or EH information.
232 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
233 DW.BeginFunction(&MF);
235 // Print out code for the function.
236 bool hasAnyRealCode = false;
237 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
239 // Print a label for the basic block.
240 if (!I->pred_empty()) {
241 printBasicBlockLabel(I, true, true);
244 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
246 // Print the assembly for the instruction.
248 hasAnyRealCode = true;
249 printMachineInstruction(II);
253 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
254 // If the function is empty, then we need to emit *something*. Otherwise,
255 // the function's label might be associated with something that it wasn't
256 // meant to be associated with. We emit a noop in this situation.
257 // We are assuming inline asms are code.
261 if (TAI->hasDotTypeDotSizeDirective())
262 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
264 // Emit post-function debug information.
265 if (TAI->doesSupportDebugInformation())
268 // Print out jump tables referenced by the function.
269 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
271 // We didn't modify anything.
275 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
276 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
279 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
280 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
281 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
284 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
285 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
288 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
289 const char *Modifier, bool NotRIPRel) {
290 const MachineOperand &MO = MI->getOperand(OpNo);
291 switch (MO.getType()) {
292 case MachineOperand::MO_Register: {
293 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
294 "Virtual registers should not make it this far!");
296 unsigned Reg = MO.getReg();
297 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
298 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
299 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
300 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
301 Reg = getX86SubSuperRegister(Reg, VT);
303 O << TRI->getAsmName(Reg);
307 case MachineOperand::MO_Immediate:
309 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
313 case MachineOperand::MO_MachineBasicBlock:
314 printBasicBlockLabel(MO.getMBB());
316 case MachineOperand::MO_JumpTableIndex: {
317 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
318 if (!isMemOp) O << '$';
319 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
322 if (TM.getRelocationModel() == Reloc::PIC_) {
323 if (Subtarget->isPICStyleStub())
324 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
326 else if (Subtarget->isPICStyleGOT())
330 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
334 case MachineOperand::MO_ConstantPoolIndex: {
335 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
336 if (!isMemOp) O << '$';
337 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
340 if (TM.getRelocationModel() == Reloc::PIC_) {
341 if (Subtarget->isPICStyleStub())
342 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
344 else if (Subtarget->isPICStyleGOT())
348 int Offset = MO.getOffset();
354 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
358 case MachineOperand::MO_GlobalAddress: {
359 bool isCallOp = Modifier && !strcmp(Modifier, "call");
360 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
361 bool needCloseParen = false;
363 const GlobalValue *GV = MO.getGlobal();
364 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
366 // If GV is an alias then use the aliasee for determining
368 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
369 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
372 bool isThreadLocal = GVar && GVar->isThreadLocal();
374 std::string Name = Mang->getValueName(GV);
375 decorateName(Name, GV);
377 if (!isMemOp && !isCallOp)
379 else if (Name[0] == '$') {
380 // The name begins with a dollar-sign. In order to avoid having it look
381 // like an integer immediate to the assembler, enclose it in parens.
383 needCloseParen = true;
386 if (shouldPrintStub(TM, Subtarget)) {
387 // Link-once, declaration, or Weakly-linked global variables need
388 // non-lazily-resolved stubs
389 if (GV->isDeclaration() || GV->isWeakForLinker()) {
390 // Dynamically-resolved functions need a stub for the function.
391 if (isCallOp && isa<Function>(GV)) {
392 FnStubs.insert(Name);
393 printSuffixedName(Name, "$stub");
395 GVStubs.insert(Name);
396 printSuffixedName(Name, "$non_lazy_ptr");
399 if (GV->hasDLLImportLinkage())
404 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
405 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
407 if (GV->hasDLLImportLinkage()) {
413 if (shouldPrintPLT(TM, Subtarget)) {
414 // Assemble call via PLT for externally visible symbols
415 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
416 !GV->hasInternalLinkage())
419 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
420 // Save function name for later type emission
421 FnStubs.insert(Name);
425 if (GV->hasExternalWeakLinkage())
426 ExtWeakSymbols.insert(GV);
428 int Offset = MO.getOffset();
435 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
436 O << "@TLSGD"; // general dynamic TLS model
438 if (GV->isDeclaration())
439 O << "@INDNTPOFF"; // initial exec TLS model
441 O << "@NTPOFF"; // local exec TLS model
442 } else if (isMemOp) {
443 if (shouldPrintGOT(TM, Subtarget)) {
444 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
448 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
449 TM.getRelocationModel() != Reloc::Static) {
450 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
453 if (needCloseParen) {
454 needCloseParen = false;
458 // Use rip when possible to reduce code size, except when
459 // index or base register are also part of the address. e.g.
460 // foo(%rip)(%rcx,%rax,4) is not legal
470 case MachineOperand::MO_ExternalSymbol: {
471 bool isCallOp = Modifier && !strcmp(Modifier, "call");
472 bool needCloseParen = false;
473 std::string Name(TAI->getGlobalPrefix());
474 Name += MO.getSymbolName();
475 if (isCallOp && shouldPrintStub(TM, Subtarget)) {
476 FnStubs.insert(Name);
477 printSuffixedName(Name, "$stub");
482 else if (Name[0] == '$') {
483 // The name begins with a dollar-sign. In order to avoid having it look
484 // like an integer immediate to the assembler, enclose it in parens.
486 needCloseParen = true;
491 if (shouldPrintPLT(TM, Subtarget)) {
492 std::string GOTName(TAI->getGlobalPrefix());
493 GOTName+="_GLOBAL_OFFSET_TABLE_";
495 // HACK! Emit extra offset to PC during printing GOT offset to
496 // compensate for the size of popl instruction. The resulting code
500 // popl %some_register
501 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
503 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
512 if (!isCallOp && Subtarget->isPICStyleRIPRel())
518 O << "<unknown operand type>"; return;
522 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
523 unsigned char value = MI->getOperand(Op).getImm();
524 assert(value <= 7 && "Invalid ssecc argument!");
526 case 0: O << "eq"; break;
527 case 1: O << "lt"; break;
528 case 2: O << "le"; break;
529 case 3: O << "unord"; break;
530 case 4: O << "neq"; break;
531 case 5: O << "nlt"; break;
532 case 6: O << "nle"; break;
533 case 7: O << "ord"; break;
537 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
538 const char *Modifier){
539 assert(isMem(MI, Op) && "Invalid memory reference!");
540 MachineOperand BaseReg = MI->getOperand(Op);
541 MachineOperand IndexReg = MI->getOperand(Op+2);
542 const MachineOperand &DispSpec = MI->getOperand(Op+3);
544 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
545 if (DispSpec.isGlobalAddress() ||
546 DispSpec.isConstantPoolIndex() ||
547 DispSpec.isJumpTableIndex()) {
548 printOperand(MI, Op+3, "mem", NotRIPRel);
550 int DispVal = DispSpec.getImm();
551 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
555 if (IndexReg.getReg() || BaseReg.getReg()) {
556 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
557 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
559 // There are cases where we can end up with ESP/RSP in the indexreg slot.
560 // If this happens, swap the base/index register to support assemblers that
561 // don't work when the index is *SP.
562 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
563 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
564 std::swap(BaseReg, IndexReg);
565 std::swap(BaseRegOperand, IndexRegOperand);
569 if (BaseReg.getReg())
570 printOperand(MI, Op+BaseRegOperand, Modifier);
572 if (IndexReg.getReg()) {
574 printOperand(MI, Op+IndexRegOperand, Modifier);
576 O << ',' << ScaleVal;
582 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
583 const MachineBasicBlock *MBB) const {
584 if (!TAI->getSetDirective())
587 // We don't need .set machinery if we have GOT-style relocations
588 if (Subtarget->isPICStyleGOT())
591 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
592 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
593 printBasicBlockLabel(MBB, false, false, false);
594 if (Subtarget->isPICStyleRIPRel())
595 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
596 << '_' << uid << '\n';
598 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
601 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
602 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
603 O << label << '\n' << label << ':';
607 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
608 const MachineBasicBlock *MBB,
611 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
612 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
614 O << JTEntryDirective << ' ';
616 if (TM.getRelocationModel() == Reloc::PIC_) {
617 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
618 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
619 << '_' << uid << "_set_" << MBB->getNumber();
620 } else if (Subtarget->isPICStyleGOT()) {
621 printBasicBlockLabel(MBB, false, false, false);
624 assert(0 && "Don't know how to print MBB label for this PIC mode");
626 printBasicBlockLabel(MBB, false, false, false);
629 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
631 unsigned Reg = MO.getReg();
633 default: return true; // Unknown mode.
634 case 'b': // Print QImode register
635 Reg = getX86SubSuperRegister(Reg, MVT::i8);
637 case 'h': // Print QImode high register
638 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
640 case 'w': // Print HImode register
641 Reg = getX86SubSuperRegister(Reg, MVT::i16);
643 case 'k': // Print SImode register
644 Reg = getX86SubSuperRegister(Reg, MVT::i32);
646 case 'q': // Print DImode register
647 Reg = getX86SubSuperRegister(Reg, MVT::i64);
651 O << '%'<< TRI->getAsmName(Reg);
655 /// PrintAsmOperand - Print out an operand for an inline asm expression.
657 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
659 const char *ExtraCode) {
660 // Does this asm operand have a single letter operand modifier?
661 if (ExtraCode && ExtraCode[0]) {
662 if (ExtraCode[1] != 0) return true; // Unknown modifier.
664 switch (ExtraCode[0]) {
665 default: return true; // Unknown modifier.
666 case 'c': // Don't print "$" before a global var name or constant.
667 printOperand(MI, OpNo, "mem");
669 case 'b': // Print QImode register
670 case 'h': // Print QImode high register
671 case 'w': // Print HImode register
672 case 'k': // Print SImode register
673 case 'q': // Print DImode register
674 if (MI->getOperand(OpNo).isRegister())
675 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
676 printOperand(MI, OpNo);
679 case 'P': // Don't print @PLT, but do print as memory.
680 printOperand(MI, OpNo, "mem");
685 printOperand(MI, OpNo);
689 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
692 const char *ExtraCode) {
693 if (ExtraCode && ExtraCode[0]) {
694 if (ExtraCode[1] != 0) return true; // Unknown modifier.
696 switch (ExtraCode[0]) {
697 default: return true; // Unknown modifier.
698 case 'b': // Print QImode register
699 case 'h': // Print QImode high register
700 case 'w': // Print HImode register
701 case 'k': // Print SImode register
702 case 'q': // Print SImode register
703 // These only apply to registers, ignore on mem.
707 printMemReference(MI, OpNo);
711 /// printMachineInstruction -- Print out a single X86 LLVM instruction
712 /// MI in AT&T syntax to the current output stream.
714 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
717 // Call the autogenerated instruction printer routines.
718 printInstruction(MI);
722 bool X86ATTAsmPrinter::doInitialization(Module &M) {
723 if (TAI->doesSupportDebugInformation()) {
724 // Emit initial debug information.
728 bool Result = AsmPrinter::doInitialization(M);
730 if (TAI->doesSupportDebugInformation()) {
731 // Let PassManager know we need debug information and relay
732 // the MachineModuleInfo address on to DwarfWriter.
733 // AsmPrinter::doInitialization did this analysis.
734 MMI = getAnalysisToUpdate<MachineModuleInfo>();
735 DW.SetModuleInfo(MMI);
738 // Darwin wants symbols to be quoted if they have complex names.
739 if (Subtarget->isTargetDarwin())
740 Mang->setUseQuotes(true);
746 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
747 const TargetData *TD = TM.getTargetData();
749 if (!GVar->hasInitializer())
750 return; // External global require no code
752 // Check to see if this is a special global used by LLVM, if so, emit it.
753 if (EmitSpecialLLVMGlobal(GVar)) {
754 if (Subtarget->isTargetDarwin() &&
755 TM.getRelocationModel() == Reloc::Static) {
756 if (GVar->getName() == "llvm.global_ctors")
757 O << ".reference .constructors_used\n";
758 else if (GVar->getName() == "llvm.global_dtors")
759 O << ".reference .destructors_used\n";
764 std::string SectionName = TAI->SectionForGlobal(GVar);
765 std::string name = Mang->getValueName(GVar);
766 Constant *C = GVar->getInitializer();
767 const Type *Type = C->getType();
768 unsigned Size = TD->getABITypeSize(Type);
769 unsigned Align = TD->getPreferredAlignmentLog(GVar);
771 printVisibility(name, GVar->getVisibility());
773 if (Subtarget->isTargetELF())
774 O << "\t.type\t" << name << ",@object\n";
776 SwitchToDataSection(SectionName.c_str());
778 if (C->isNullValue() && !GVar->hasSection()) {
779 // FIXME: This seems to be pretty darwin-specific
780 if (GVar->hasExternalLinkage()) {
781 if (const char *Directive = TAI->getZeroFillDirective()) {
782 O << "\t.globl " << name << '\n';
783 O << Directive << "__DATA, __common, " << name << ", "
784 << Size << ", " << Align << '\n';
789 if (!GVar->isThreadLocal() &&
790 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
791 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
793 if (TAI->getLCOMMDirective() != NULL) {
794 if (GVar->hasInternalLinkage()) {
795 O << TAI->getLCOMMDirective() << name << ',' << Size;
796 if (Subtarget->isTargetDarwin())
798 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
799 O << "\t.globl " << name << '\n'
800 << TAI->getWeakDefDirective() << name << '\n';
801 EmitAlignment(Align, GVar);
802 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
803 PrintUnmangledNameSafely(GVar, O);
805 EmitGlobalConstant(C);
808 O << TAI->getCOMMDirective() << name << ',' << Size;
809 if (TAI->getCOMMDirectiveTakesAlignment())
810 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
813 if (!Subtarget->isTargetCygMing()) {
814 if (GVar->hasInternalLinkage())
815 O << "\t.local\t" << name << '\n';
817 O << TAI->getCOMMDirective() << name << ',' << Size;
818 if (TAI->getCOMMDirectiveTakesAlignment())
819 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
821 O << "\t\t" << TAI->getCommentString() << ' ';
822 PrintUnmangledNameSafely(GVar, O);
828 switch (GVar->getLinkage()) {
829 case GlobalValue::CommonLinkage:
830 case GlobalValue::LinkOnceLinkage:
831 case GlobalValue::WeakLinkage:
832 if (Subtarget->isTargetDarwin()) {
833 O << "\t.globl " << name << '\n'
834 << TAI->getWeakDefDirective() << name << '\n';
835 } else if (Subtarget->isTargetCygMing()) {
836 O << "\t.globl\t" << name << "\n"
837 "\t.linkonce same_size\n";
839 O << "\t.weak\t" << name << '\n';
842 case GlobalValue::DLLExportLinkage:
843 case GlobalValue::AppendingLinkage:
844 // FIXME: appending linkage variables should go into a section of
845 // their name or something. For now, just emit them as external.
846 case GlobalValue::ExternalLinkage:
847 // If external or appending, declare as a global symbol
848 O << "\t.globl " << name << '\n';
850 case GlobalValue::InternalLinkage:
853 assert(0 && "Unknown linkage type!");
856 EmitAlignment(Align, GVar);
857 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
858 PrintUnmangledNameSafely(GVar, O);
860 if (TAI->hasDotTypeDotSizeDirective())
861 O << "\t.size\t" << name << ", " << Size << '\n';
863 // If the initializer is a extern weak symbol, remember to emit the weak
865 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
866 if (GV->hasExternalWeakLinkage())
867 ExtWeakSymbols.insert(GV);
869 EmitGlobalConstant(C);
872 /// printGVStub - Print stub for a global value.
874 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
875 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
876 O << ":\n\t.indirect_symbol ";
877 if (Prefix) O << Prefix;
878 O << GV << "\n\t.long\t0\n";
882 bool X86ATTAsmPrinter::doFinalization(Module &M) {
883 // Print out module-level global variables here.
884 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
886 printModuleLevelGV(I);
888 if (I->hasDLLExportLinkage())
889 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
892 // Output linker support code for dllexported globals
893 if (!DLLExportedGVs.empty())
894 SwitchToDataSection(".section .drectve");
896 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
897 e = DLLExportedGVs.end();
899 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
901 if (!DLLExportedFns.empty()) {
902 SwitchToDataSection(".section .drectve");
905 for (StringSet<>::iterator i = DLLExportedFns.begin(),
906 e = DLLExportedFns.end();
908 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
910 if (Subtarget->isTargetDarwin()) {
911 SwitchToDataSection("");
913 // Output stubs for dynamically-linked functions
915 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
917 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
918 "self_modifying_code+pure_instructions,5", 0);
919 const char *p = i->getKeyData();
920 printSuffixedName(p, "$stub");
922 "\t.indirect_symbol " << p << "\n"
923 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
928 // Print global value stubs.
929 bool InStubSection = false;
930 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
931 // Add the (possibly multiple) personalities to the set of global values.
932 // Only referenced functions get into the Personalities list.
933 const std::vector<Function *>& Personalities = MMI->getPersonalities();
934 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
935 E = Personalities.end(); I != E; ++I) {
938 if (!InStubSection) {
940 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
941 InStubSection = true;
943 printGVStub((*I)->getNameStart(), "_");
947 // Output stubs for external and common global variables.
948 if (!InStubSection && !GVStubs.empty())
950 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
951 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
953 printGVStub(i->getKeyData());
955 // Emit final debug information.
958 // Funny Darwin hack: This flag tells the linker that no global symbols
959 // contain code that falls through to other global symbols (e.g. the obvious
960 // implementation of multiple entry points). If this doesn't occur, the
961 // linker can safely perform dead code stripping. Since LLVM never
962 // generates code that does this, it is always safe to set.
963 O << "\t.subsections_via_symbols\n";
964 } else if (Subtarget->isTargetCygMing()) {
965 // Emit type information for external functions
966 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
968 O << "\t.def\t " << i->getKeyData()
969 << ";\t.scl\t" << COFF::C_EXT
970 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
974 // Emit final debug information.
976 } else if (Subtarget->isTargetELF()) {
977 // Emit final debug information.
981 return AsmPrinter::doFinalization(M);
984 // Include the auto-generated portion of the assembly writer.
985 #include "X86GenAsmWriter.inc"