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/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetOptions.h"
36 STATISTIC(EmittedInsts, "Number of machine instrs printed");
38 static std::string getPICLabelString(unsigned FnNum,
39 const TargetAsmInfo *TAI,
40 const X86Subtarget* Subtarget) {
42 if (Subtarget->isTargetDarwin())
43 label = "\"L" + utostr_32(FnNum) + "$pb\"";
44 else if (Subtarget->isTargetELF())
45 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
47 assert(0 && "Don't know how to print PIC label!\n");
52 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
53 const TargetData *TD) {
54 X86MachineFunctionInfo Info;
57 switch (F->getCallingConv()) {
58 case CallingConv::X86_StdCall:
59 Info.setDecorationStyle(StdCall);
61 case CallingConv::X86_FastCall:
62 Info.setDecorationStyle(FastCall);
69 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
70 AI != AE; ++AI, ++argNum) {
71 const Type* Ty = AI->getType();
73 // 'Dereference' type in case of byval parameter attribute
74 if (F->paramHasAttr(argNum, ParamAttr::ByVal))
75 Ty = cast<PointerType>(Ty)->getElementType();
77 // Size should be aligned to DWORD boundary
78 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
81 // We're not supporting tooooo huge arguments :)
82 Info.setBytesToPopOnReturn((unsigned int)Size);
86 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
87 /// Don't print things like \n or \0.
88 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
89 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
95 /// decorateName - Query FunctionInfoMap and use this information for various
97 void X86ATTAsmPrinter::decorateName(std::string &Name,
98 const GlobalValue *GV) {
99 const Function *F = dyn_cast<Function>(GV);
102 // We don't want to decorate non-stdcall or non-fastcall functions right now
103 unsigned CC = F->getCallingConv();
104 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
107 // Decorate names only when we're targeting Cygwin/Mingw32 targets
108 if (!Subtarget->isTargetCygMing())
111 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
113 const X86MachineFunctionInfo *Info;
114 if (info_item == FunctionInfoMap.end()) {
115 // Calculate apropriate function info and populate map
116 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
117 Info = &FunctionInfoMap[F];
119 Info = &info_item->second;
122 const FunctionType *FT = F->getFunctionType();
123 switch (Info->getDecorationStyle()) {
127 // "Pure" variadic functions do not receive @0 suffix.
128 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
129 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
130 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
133 // "Pure" variadic functions do not receive @0 suffix.
134 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
135 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
136 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
138 if (Name[0] == '_') {
145 assert(0 && "Unsupported DecorationStyle");
149 // Substitute old hook with new one temporary
150 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
151 return TAI->SectionForGlobal(&F);
154 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
155 const Function *F = MF.getFunction();
156 std::string SectionName = TAI->SectionForGlobal(F);
158 decorateName(CurrentFnName, F);
160 SwitchToTextSection(SectionName.c_str());
162 unsigned FnAlign = OptimizeForSize ? 1 : 4;
163 switch (F->getLinkage()) {
164 default: assert(0 && "Unknown linkage type!");
165 case Function::InternalLinkage: // Symbols default to internal.
166 EmitAlignment(FnAlign, F);
168 case Function::DLLExportLinkage:
169 case Function::ExternalLinkage:
170 EmitAlignment(FnAlign, F);
171 O << "\t.globl\t" << CurrentFnName << '\n';
173 case Function::LinkOnceLinkage:
174 case Function::WeakLinkage:
175 EmitAlignment(FnAlign, F);
176 if (Subtarget->isTargetDarwin()) {
177 O << "\t.globl\t" << CurrentFnName << '\n';
178 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
179 } else if (Subtarget->isTargetCygMing()) {
180 O << "\t.globl\t" << CurrentFnName << "\n"
181 "\t.linkonce discard\n";
183 O << "\t.weak\t" << CurrentFnName << '\n';
188 printVisibility(CurrentFnName, F->getVisibility());
190 if (Subtarget->isTargetELF())
191 O << "\t.type\t" << CurrentFnName << ",@function\n";
192 else if (Subtarget->isTargetCygMing()) {
193 O << "\t.def\t " << CurrentFnName
195 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
196 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
200 O << CurrentFnName << ":\n";
201 // Add some workaround for linkonce linkage on Cygwin\MinGW
202 if (Subtarget->isTargetCygMing() &&
203 (F->getLinkage() == Function::LinkOnceLinkage ||
204 F->getLinkage() == Function::WeakLinkage))
205 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
208 /// runOnMachineFunction - This uses the printMachineInstruction()
209 /// method to print assembly for each instruction.
211 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
212 const Function *F = MF.getFunction();
213 unsigned CC = F->getCallingConv();
215 SetupMachineFunction(MF);
218 // Populate function information map. Actually, We don't want to populate
219 // non-stdcall or non-fastcall functions' information right now.
220 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
221 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
223 // Print out constants referenced by the function
224 EmitConstantPool(MF.getConstantPool());
226 if (F->hasDLLExportLinkage())
227 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
229 // Print the 'header' of function
230 emitFunctionHeader(MF);
232 // Emit pre-function debug and/or EH information.
233 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
234 DW.BeginFunction(&MF);
236 // Print out code for the function.
237 bool hasAnyRealCode = false;
238 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
240 // Print a label for the basic block.
241 if (!I->pred_empty()) {
242 printBasicBlockLabel(I, true, true);
245 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
247 // Print the assembly for the instruction.
249 hasAnyRealCode = true;
250 printMachineInstruction(II);
254 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
255 // If the function is empty, then we need to emit *something*. Otherwise,
256 // the function's label might be associated with something that it wasn't
257 // meant to be associated with. We emit a noop in this situation.
258 // We are assuming inline asms are code.
262 if (TAI->hasDotTypeDotSizeDirective())
263 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
265 // Emit post-function debug information.
266 if (TAI->doesSupportDebugInformation())
269 // Print out jump tables referenced by the function.
270 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
272 // We didn't modify anything.
276 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
277 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
280 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
281 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
282 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
285 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
286 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
289 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
290 const char *Modifier, bool NotRIPRel) {
291 const MachineOperand &MO = MI->getOperand(OpNo);
292 switch (MO.getType()) {
293 case MachineOperand::MO_Register: {
294 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
295 "Virtual registers should not make it this far!");
297 unsigned Reg = MO.getReg();
298 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
299 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
300 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
301 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
302 Reg = getX86SubSuperRegister(Reg, VT);
304 O << TRI->getAsmName(Reg);
308 case MachineOperand::MO_Immediate:
310 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
314 case MachineOperand::MO_MachineBasicBlock:
315 printBasicBlockLabel(MO.getMBB());
317 case MachineOperand::MO_JumpTableIndex: {
318 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
319 if (!isMemOp) O << '$';
320 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
323 if (TM.getRelocationModel() == Reloc::PIC_) {
324 if (Subtarget->isPICStyleStub())
325 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
327 else if (Subtarget->isPICStyleGOT())
331 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
335 case MachineOperand::MO_ConstantPoolIndex: {
336 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
337 if (!isMemOp) O << '$';
338 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
341 if (TM.getRelocationModel() == Reloc::PIC_) {
342 if (Subtarget->isPICStyleStub())
343 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
345 else if (Subtarget->isPICStyleGOT())
349 int Offset = MO.getOffset();
355 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
359 case MachineOperand::MO_GlobalAddress: {
360 bool isCallOp = Modifier && !strcmp(Modifier, "call");
361 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
362 bool needCloseParen = false;
364 const GlobalValue *GV = MO.getGlobal();
365 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
367 // If GV is an alias then use the aliasee for determining
369 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
370 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
373 bool isThreadLocal = GVar && GVar->isThreadLocal();
375 std::string Name = Mang->getValueName(GV);
376 decorateName(Name, GV);
378 if (!isMemOp && !isCallOp)
380 else if (Name[0] == '$') {
381 // The name begins with a dollar-sign. In order to avoid having it look
382 // like an integer immediate to the assembler, enclose it in parens.
384 needCloseParen = true;
387 if (shouldPrintStub(TM, Subtarget)) {
388 // Link-once, declaration, or Weakly-linked global variables need
389 // non-lazily-resolved stubs
390 if (GV->isDeclaration() || GV->isWeakForLinker()) {
391 // Dynamically-resolved functions need a stub for the function.
392 if (isCallOp && isa<Function>(GV)) {
393 FnStubs.insert(Name);
394 printSuffixedName(Name, "$stub");
396 GVStubs.insert(Name);
397 printSuffixedName(Name, "$non_lazy_ptr");
400 if (GV->hasDLLImportLinkage())
405 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
406 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
408 if (GV->hasDLLImportLinkage()) {
414 if (shouldPrintPLT(TM, Subtarget)) {
415 // Assemble call via PLT for externally visible symbols
416 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
417 !GV->hasInternalLinkage())
420 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
421 // Save function name for later type emission
422 FnStubs.insert(Name);
426 if (GV->hasExternalWeakLinkage())
427 ExtWeakSymbols.insert(GV);
429 int Offset = MO.getOffset();
436 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
437 O << "@TLSGD"; // general dynamic TLS model
439 if (GV->isDeclaration())
440 O << "@INDNTPOFF"; // initial exec TLS model
442 O << "@NTPOFF"; // local exec TLS model
443 } else if (isMemOp) {
444 if (shouldPrintGOT(TM, Subtarget)) {
445 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
449 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
450 TM.getRelocationModel() != Reloc::Static) {
451 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
454 if (needCloseParen) {
455 needCloseParen = false;
459 // Use rip when possible to reduce code size, except when
460 // index or base register are also part of the address. e.g.
461 // foo(%rip)(%rcx,%rax,4) is not legal
471 case MachineOperand::MO_ExternalSymbol: {
472 bool isCallOp = Modifier && !strcmp(Modifier, "call");
473 bool needCloseParen = false;
474 std::string Name(TAI->getGlobalPrefix());
475 Name += MO.getSymbolName();
476 if (isCallOp && shouldPrintStub(TM, Subtarget)) {
477 FnStubs.insert(Name);
478 printSuffixedName(Name, "$stub");
483 else if (Name[0] == '$') {
484 // The name begins with a dollar-sign. In order to avoid having it look
485 // like an integer immediate to the assembler, enclose it in parens.
487 needCloseParen = true;
492 if (shouldPrintPLT(TM, Subtarget)) {
493 std::string GOTName(TAI->getGlobalPrefix());
494 GOTName+="_GLOBAL_OFFSET_TABLE_";
496 // HACK! Emit extra offset to PC during printing GOT offset to
497 // compensate for the size of popl instruction. The resulting code
501 // popl %some_register
502 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
504 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
513 if (!isCallOp && Subtarget->isPICStyleRIPRel())
519 O << "<unknown operand type>"; return;
523 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
524 unsigned char value = MI->getOperand(Op).getImm();
525 assert(value <= 7 && "Invalid ssecc argument!");
527 case 0: O << "eq"; break;
528 case 1: O << "lt"; break;
529 case 2: O << "le"; break;
530 case 3: O << "unord"; break;
531 case 4: O << "neq"; break;
532 case 5: O << "nlt"; break;
533 case 6: O << "nle"; break;
534 case 7: O << "ord"; break;
538 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
539 const char *Modifier){
540 assert(isMem(MI, Op) && "Invalid memory reference!");
541 MachineOperand BaseReg = MI->getOperand(Op);
542 MachineOperand IndexReg = MI->getOperand(Op+2);
543 const MachineOperand &DispSpec = MI->getOperand(Op+3);
545 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
546 if (DispSpec.isGlobalAddress() ||
547 DispSpec.isConstantPoolIndex() ||
548 DispSpec.isJumpTableIndex()) {
549 printOperand(MI, Op+3, "mem", NotRIPRel);
551 int DispVal = DispSpec.getImm();
552 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
556 if (IndexReg.getReg() || BaseReg.getReg()) {
557 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
558 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
560 // There are cases where we can end up with ESP/RSP in the indexreg slot.
561 // If this happens, swap the base/index register to support assemblers that
562 // don't work when the index is *SP.
563 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
564 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
565 std::swap(BaseReg, IndexReg);
566 std::swap(BaseRegOperand, IndexRegOperand);
570 if (BaseReg.getReg())
571 printOperand(MI, Op+BaseRegOperand, Modifier);
573 if (IndexReg.getReg()) {
575 printOperand(MI, Op+IndexRegOperand, Modifier);
577 O << ',' << ScaleVal;
583 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
584 const MachineBasicBlock *MBB) const {
585 if (!TAI->getSetDirective())
588 // We don't need .set machinery if we have GOT-style relocations
589 if (Subtarget->isPICStyleGOT())
592 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
593 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
594 printBasicBlockLabel(MBB, false, false, false);
595 if (Subtarget->isPICStyleRIPRel())
596 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
597 << '_' << uid << '\n';
599 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
602 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
603 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
604 O << label << '\n' << label << ':';
608 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
609 const MachineBasicBlock *MBB,
612 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
613 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
615 O << JTEntryDirective << ' ';
617 if (TM.getRelocationModel() == Reloc::PIC_) {
618 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
619 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
620 << '_' << uid << "_set_" << MBB->getNumber();
621 } else if (Subtarget->isPICStyleGOT()) {
622 printBasicBlockLabel(MBB, false, false, false);
625 assert(0 && "Don't know how to print MBB label for this PIC mode");
627 printBasicBlockLabel(MBB, false, false, false);
630 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
632 unsigned Reg = MO.getReg();
634 default: return true; // Unknown mode.
635 case 'b': // Print QImode register
636 Reg = getX86SubSuperRegister(Reg, MVT::i8);
638 case 'h': // Print QImode high register
639 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
641 case 'w': // Print HImode register
642 Reg = getX86SubSuperRegister(Reg, MVT::i16);
644 case 'k': // Print SImode register
645 Reg = getX86SubSuperRegister(Reg, MVT::i32);
647 case 'q': // Print DImode register
648 Reg = getX86SubSuperRegister(Reg, MVT::i64);
652 O << '%'<< TRI->getAsmName(Reg);
656 /// PrintAsmOperand - Print out an operand for an inline asm expression.
658 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
660 const char *ExtraCode) {
661 // Does this asm operand have a single letter operand modifier?
662 if (ExtraCode && ExtraCode[0]) {
663 if (ExtraCode[1] != 0) return true; // Unknown modifier.
665 switch (ExtraCode[0]) {
666 default: return true; // Unknown modifier.
667 case 'c': // Don't print "$" before a global var name or constant.
668 printOperand(MI, OpNo, "mem");
670 case 'b': // Print QImode register
671 case 'h': // Print QImode high register
672 case 'w': // Print HImode register
673 case 'k': // Print SImode register
674 case 'q': // Print DImode register
675 if (MI->getOperand(OpNo).isRegister())
676 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
677 printOperand(MI, OpNo);
680 case 'P': // Don't print @PLT, but do print as memory.
681 printOperand(MI, OpNo, "mem");
686 printOperand(MI, OpNo);
690 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
693 const char *ExtraCode) {
694 if (ExtraCode && ExtraCode[0]) {
695 if (ExtraCode[1] != 0) return true; // Unknown modifier.
697 switch (ExtraCode[0]) {
698 default: return true; // Unknown modifier.
699 case 'b': // Print QImode register
700 case 'h': // Print QImode high register
701 case 'w': // Print HImode register
702 case 'k': // Print SImode register
703 case 'q': // Print SImode register
704 // These only apply to registers, ignore on mem.
708 printMemReference(MI, OpNo);
712 /// printMachineInstruction -- Print out a single X86 LLVM instruction
713 /// MI in AT&T syntax to the current output stream.
715 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
718 // Call the autogenerated instruction printer routines.
719 printInstruction(MI);
723 bool X86ATTAsmPrinter::doInitialization(Module &M) {
724 if (TAI->doesSupportDebugInformation()) {
725 // Emit initial debug information.
729 bool Result = AsmPrinter::doInitialization(M);
731 if (TAI->doesSupportDebugInformation()) {
732 // Let PassManager know we need debug information and relay
733 // the MachineModuleInfo address on to DwarfWriter.
734 // AsmPrinter::doInitialization did this analysis.
735 MMI = getAnalysisToUpdate<MachineModuleInfo>();
736 DW.SetModuleInfo(MMI);
739 // Darwin wants symbols to be quoted if they have complex names.
740 if (Subtarget->isTargetDarwin())
741 Mang->setUseQuotes(true);
747 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
748 const TargetData *TD = TM.getTargetData();
750 if (!GVar->hasInitializer())
751 return; // External global require no code
753 // Check to see if this is a special global used by LLVM, if so, emit it.
754 if (EmitSpecialLLVMGlobal(GVar)) {
755 if (Subtarget->isTargetDarwin() &&
756 TM.getRelocationModel() == Reloc::Static) {
757 if (GVar->getName() == "llvm.global_ctors")
758 O << ".reference .constructors_used\n";
759 else if (GVar->getName() == "llvm.global_dtors")
760 O << ".reference .destructors_used\n";
765 std::string SectionName = TAI->SectionForGlobal(GVar);
766 std::string name = Mang->getValueName(GVar);
767 Constant *C = GVar->getInitializer();
768 const Type *Type = C->getType();
769 unsigned Size = TD->getABITypeSize(Type);
770 unsigned Align = TD->getPreferredAlignmentLog(GVar);
772 printVisibility(name, GVar->getVisibility());
774 if (Subtarget->isTargetELF())
775 O << "\t.type\t" << name << ",@object\n";
777 SwitchToDataSection(SectionName.c_str());
779 if (C->isNullValue() && !GVar->hasSection()) {
780 // FIXME: This seems to be pretty darwin-specific
781 if (GVar->hasExternalLinkage()) {
782 if (const char *Directive = TAI->getZeroFillDirective()) {
783 O << "\t.globl " << name << '\n';
784 O << Directive << "__DATA, __common, " << name << ", "
785 << Size << ", " << Align << '\n';
790 if (!GVar->isThreadLocal() &&
791 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
792 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
794 if (TAI->getLCOMMDirective() != NULL) {
795 if (GVar->hasInternalLinkage()) {
796 O << TAI->getLCOMMDirective() << name << ',' << Size;
797 if (Subtarget->isTargetDarwin())
799 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
800 O << "\t.globl " << name << '\n'
801 << TAI->getWeakDefDirective() << name << '\n';
802 EmitAlignment(Align, GVar);
803 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
804 PrintUnmangledNameSafely(GVar, O);
806 EmitGlobalConstant(C);
809 O << TAI->getCOMMDirective() << name << ',' << Size;
810 if (TAI->getCOMMDirectiveTakesAlignment())
811 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
814 if (!Subtarget->isTargetCygMing()) {
815 if (GVar->hasInternalLinkage())
816 O << "\t.local\t" << name << '\n';
818 O << TAI->getCOMMDirective() << name << ',' << Size;
819 if (TAI->getCOMMDirectiveTakesAlignment())
820 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
822 O << "\t\t" << TAI->getCommentString() << ' ';
823 PrintUnmangledNameSafely(GVar, O);
829 switch (GVar->getLinkage()) {
830 case GlobalValue::CommonLinkage:
831 case GlobalValue::LinkOnceLinkage:
832 case GlobalValue::WeakLinkage:
833 if (Subtarget->isTargetDarwin()) {
834 O << "\t.globl " << name << '\n'
835 << TAI->getWeakDefDirective() << name << '\n';
836 } else if (Subtarget->isTargetCygMing()) {
837 O << "\t.globl\t" << name << "\n"
838 "\t.linkonce same_size\n";
840 O << "\t.weak\t" << name << '\n';
843 case GlobalValue::DLLExportLinkage:
844 case GlobalValue::AppendingLinkage:
845 // FIXME: appending linkage variables should go into a section of
846 // their name or something. For now, just emit them as external.
847 case GlobalValue::ExternalLinkage:
848 // If external or appending, declare as a global symbol
849 O << "\t.globl " << name << '\n';
851 case GlobalValue::InternalLinkage:
854 assert(0 && "Unknown linkage type!");
857 EmitAlignment(Align, GVar);
858 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
859 PrintUnmangledNameSafely(GVar, O);
861 if (TAI->hasDotTypeDotSizeDirective())
862 O << "\t.size\t" << name << ", " << Size << '\n';
864 // If the initializer is a extern weak symbol, remember to emit the weak
866 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
867 if (GV->hasExternalWeakLinkage())
868 ExtWeakSymbols.insert(GV);
870 EmitGlobalConstant(C);
873 /// printGVStub - Print stub for a global value.
875 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
876 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
877 O << ":\n\t.indirect_symbol ";
878 if (Prefix) O << Prefix;
879 O << GV << "\n\t.long\t0\n";
883 bool X86ATTAsmPrinter::doFinalization(Module &M) {
884 // Print out module-level global variables here.
885 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
887 printModuleLevelGV(I);
889 if (I->hasDLLExportLinkage())
890 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
893 // Output linker support code for dllexported globals
894 if (!DLLExportedGVs.empty())
895 SwitchToDataSection(".section .drectve");
897 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
898 e = DLLExportedGVs.end();
900 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
902 if (!DLLExportedFns.empty()) {
903 SwitchToDataSection(".section .drectve");
906 for (StringSet<>::iterator i = DLLExportedFns.begin(),
907 e = DLLExportedFns.end();
909 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
911 if (Subtarget->isTargetDarwin()) {
912 SwitchToDataSection("");
914 // Output stubs for dynamically-linked functions
916 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
918 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
919 "self_modifying_code+pure_instructions,5", 0);
920 const char *p = i->getKeyData();
921 printSuffixedName(p, "$stub");
923 "\t.indirect_symbol " << p << "\n"
924 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
929 // Print global value stubs.
930 bool InStubSection = false;
931 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
932 // Add the (possibly multiple) personalities to the set of global values.
933 // Only referenced functions get into the Personalities list.
934 const std::vector<Function *>& Personalities = MMI->getPersonalities();
935 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
936 E = Personalities.end(); I != E; ++I) {
939 if (!InStubSection) {
941 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
942 InStubSection = true;
944 printGVStub((*I)->getNameStart(), "_");
948 // Output stubs for external and common global variables.
949 if (!InStubSection && !GVStubs.empty())
951 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
952 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
954 printGVStub(i->getKeyData());
956 // Emit final debug information.
959 // Funny Darwin hack: This flag tells the linker that no global symbols
960 // contain code that falls through to other global symbols (e.g. the obvious
961 // implementation of multiple entry points). If this doesn't occur, the
962 // linker can safely perform dead code stripping. Since LLVM never
963 // generates code that does this, it is always safe to set.
964 O << "\t.subsections_via_symbols\n";
965 } else if (Subtarget->isTargetCygMing()) {
966 // Emit type information for external functions
967 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
969 O << "\t.def\t " << i->getKeyData()
970 << ";\t.scl\t" << COFF::C_EXT
971 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
975 // Emit final debug information.
977 } else if (Subtarget->isTargetELF()) {
978 // Emit final debug information.
982 return AsmPrinter::doFinalization(M);
985 // Include the auto-generated portion of the assembly writer.
986 #include "X86GenAsmWriter.inc"