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"
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';
186 if (F->hasHiddenVisibility()) {
187 if (const char *Directive = TAI->getHiddenDirective())
188 O << Directive << CurrentFnName << '\n';
189 } else if (F->hasProtectedVisibility()) {
190 if (const char *Directive = TAI->getProtectedDirective())
191 O << Directive << CurrentFnName << '\n';
194 if (Subtarget->isTargetELF())
195 O << "\t.type\t" << CurrentFnName << ",@function\n";
196 else if (Subtarget->isTargetCygMing()) {
197 O << "\t.def\t " << CurrentFnName
199 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
200 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
204 O << CurrentFnName << ":\n";
205 // Add some workaround for linkonce linkage on Cygwin\MinGW
206 if (Subtarget->isTargetCygMing() &&
207 (F->getLinkage() == Function::LinkOnceLinkage ||
208 F->getLinkage() == Function::WeakLinkage))
209 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 /// runOnMachineFunction - This uses the printMachineInstruction()
213 /// method to print assembly for each instruction.
215 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
216 const Function *F = MF.getFunction();
217 unsigned CC = F->getCallingConv();
219 SetupMachineFunction(MF);
222 // Populate function information map. Actually, We don't want to populate
223 // non-stdcall or non-fastcall functions' information right now.
224 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
225 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
227 // Print out constants referenced by the function
228 EmitConstantPool(MF.getConstantPool());
230 if (F->hasDLLExportLinkage())
231 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
233 // Print the 'header' of function
234 emitFunctionHeader(MF);
236 // Emit pre-function debug and/or EH information.
237 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
238 DW.BeginFunction(&MF);
240 // Print out code for the function.
241 bool hasAnyRealCode = false;
242 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
244 // Print a label for the basic block.
245 if (!I->pred_empty()) {
246 printBasicBlockLabel(I, true, true);
249 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
251 // Print the assembly for the instruction.
253 hasAnyRealCode = true;
254 printMachineInstruction(II);
258 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
259 // If the function is empty, then we need to emit *something*. Otherwise,
260 // the function's label might be associated with something that it wasn't
261 // meant to be associated with. We emit a noop in this situation.
262 // We are assuming inline asms are code.
266 if (TAI->hasDotTypeDotSizeDirective())
267 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
269 // Emit post-function debug information.
270 if (TAI->doesSupportDebugInformation())
273 // Print out jump tables referenced by the function.
274 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
276 // We didn't modify anything.
280 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
281 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
284 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
285 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
286 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
289 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
290 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
293 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
294 const char *Modifier, bool NotRIPRel) {
295 const MachineOperand &MO = MI->getOperand(OpNo);
296 switch (MO.getType()) {
297 case MachineOperand::MO_Register: {
298 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
299 "Virtual registers should not make it this far!");
301 unsigned Reg = MO.getReg();
302 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
303 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
304 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
305 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
306 Reg = getX86SubSuperRegister(Reg, VT);
308 O << TRI->getAsmName(Reg);
312 case MachineOperand::MO_Immediate:
314 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
318 case MachineOperand::MO_MachineBasicBlock:
319 printBasicBlockLabel(MO.getMBB());
321 case MachineOperand::MO_JumpTableIndex: {
322 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
323 if (!isMemOp) O << '$';
324 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
327 if (TM.getRelocationModel() == Reloc::PIC_) {
328 if (Subtarget->isPICStyleStub())
329 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
331 else if (Subtarget->isPICStyleGOT())
335 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
339 case MachineOperand::MO_ConstantPoolIndex: {
340 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
341 if (!isMemOp) O << '$';
342 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
345 if (TM.getRelocationModel() == Reloc::PIC_) {
346 if (Subtarget->isPICStyleStub())
347 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
349 else if (Subtarget->isPICStyleGOT())
353 int Offset = MO.getOffset();
359 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
363 case MachineOperand::MO_GlobalAddress: {
364 bool isCallOp = Modifier && !strcmp(Modifier, "call");
365 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
366 bool needCloseParen = false;
368 const GlobalValue *GV = MO.getGlobal();
369 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
371 // If GV is an alias then use the aliasee for determining
373 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
374 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
377 bool isThreadLocal = GVar && GVar->isThreadLocal();
379 std::string Name = Mang->getValueName(GV);
380 decorateName(Name, GV);
382 if (!isMemOp && !isCallOp)
384 else if (Name[0] == '$') {
385 // The name begins with a dollar-sign. In order to avoid having it look
386 // like an integer immediate to the assembler, enclose it in parens.
388 needCloseParen = true;
391 if (shouldPrintStub(TM, Subtarget)) {
392 // Link-once, declaration, or Weakly-linked global variables need
393 // non-lazily-resolved stubs
394 if (GV->isDeclaration() || GV->isWeakForLinker()) {
395 // Dynamically-resolved functions need a stub for the function.
396 if (isCallOp && isa<Function>(GV)) {
397 FnStubs.insert(Name);
398 printSuffixedName(Name, "$stub");
400 GVStubs.insert(Name);
401 printSuffixedName(Name, "$non_lazy_ptr");
404 if (GV->hasDLLImportLinkage())
409 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
410 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
412 if (GV->hasDLLImportLinkage()) {
418 if (shouldPrintPLT(TM, Subtarget)) {
419 // Assemble call via PLT for externally visible symbols
420 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
421 !GV->hasInternalLinkage())
424 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
425 // Save function name for later type emission
426 FnStubs.insert(Name);
430 if (GV->hasExternalWeakLinkage())
431 ExtWeakSymbols.insert(GV);
433 int Offset = MO.getOffset();
440 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
441 O << "@TLSGD"; // general dynamic TLS model
443 if (GV->isDeclaration())
444 O << "@INDNTPOFF"; // initial exec TLS model
446 O << "@NTPOFF"; // local exec TLS model
447 } else if (isMemOp) {
448 if (shouldPrintGOT(TM, Subtarget)) {
449 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
453 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
454 TM.getRelocationModel() != Reloc::Static) {
455 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
458 if (needCloseParen) {
459 needCloseParen = false;
463 // Use rip when possible to reduce code size, except when
464 // index or base register are also part of the address. e.g.
465 // foo(%rip)(%rcx,%rax,4) is not legal
475 case MachineOperand::MO_ExternalSymbol: {
476 bool isCallOp = Modifier && !strcmp(Modifier, "call");
477 bool needCloseParen = false;
478 std::string Name(TAI->getGlobalPrefix());
479 Name += MO.getSymbolName();
480 if (isCallOp && shouldPrintStub(TM, Subtarget)) {
481 FnStubs.insert(Name);
482 printSuffixedName(Name, "$stub");
487 else if (Name[0] == '$') {
488 // The name begins with a dollar-sign. In order to avoid having it look
489 // like an integer immediate to the assembler, enclose it in parens.
491 needCloseParen = true;
496 if (shouldPrintPLT(TM, Subtarget)) {
497 std::string GOTName(TAI->getGlobalPrefix());
498 GOTName+="_GLOBAL_OFFSET_TABLE_";
500 // HACK! Emit extra offset to PC during printing GOT offset to
501 // compensate for the size of popl instruction. The resulting code
505 // popl %some_register
506 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
508 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
517 if (!isCallOp && Subtarget->isPICStyleRIPRel())
523 O << "<unknown operand type>"; return;
527 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
528 unsigned char value = MI->getOperand(Op).getImm();
529 assert(value <= 7 && "Invalid ssecc argument!");
531 case 0: O << "eq"; break;
532 case 1: O << "lt"; break;
533 case 2: O << "le"; break;
534 case 3: O << "unord"; break;
535 case 4: O << "neq"; break;
536 case 5: O << "nlt"; break;
537 case 6: O << "nle"; break;
538 case 7: O << "ord"; break;
542 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
543 const char *Modifier){
544 assert(isMem(MI, Op) && "Invalid memory reference!");
545 MachineOperand BaseReg = MI->getOperand(Op);
546 MachineOperand IndexReg = MI->getOperand(Op+2);
547 const MachineOperand &DispSpec = MI->getOperand(Op+3);
549 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
550 if (DispSpec.isGlobalAddress() ||
551 DispSpec.isConstantPoolIndex() ||
552 DispSpec.isJumpTableIndex()) {
553 printOperand(MI, Op+3, "mem", NotRIPRel);
555 int DispVal = DispSpec.getImm();
556 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
560 if (IndexReg.getReg() || BaseReg.getReg()) {
561 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
562 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
564 // There are cases where we can end up with ESP/RSP in the indexreg slot.
565 // If this happens, swap the base/index register to support assemblers that
566 // don't work when the index is *SP.
567 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
568 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
569 std::swap(BaseReg, IndexReg);
570 std::swap(BaseRegOperand, IndexRegOperand);
574 if (BaseReg.getReg())
575 printOperand(MI, Op+BaseRegOperand, Modifier);
577 if (IndexReg.getReg()) {
579 printOperand(MI, Op+IndexRegOperand, Modifier);
581 O << ',' << ScaleVal;
587 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
588 const MachineBasicBlock *MBB) const {
589 if (!TAI->getSetDirective())
592 // We don't need .set machinery if we have GOT-style relocations
593 if (Subtarget->isPICStyleGOT())
596 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
597 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
598 printBasicBlockLabel(MBB, false, false, false);
599 if (Subtarget->isPICStyleRIPRel())
600 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
601 << '_' << uid << '\n';
603 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
606 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
607 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
608 O << label << '\n' << label << ':';
612 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
613 const MachineBasicBlock *MBB,
616 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
617 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
619 O << JTEntryDirective << ' ';
621 if (TM.getRelocationModel() == Reloc::PIC_) {
622 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
623 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
624 << '_' << uid << "_set_" << MBB->getNumber();
625 } else if (Subtarget->isPICStyleGOT()) {
626 printBasicBlockLabel(MBB, false, false, false);
629 assert(0 && "Don't know how to print MBB label for this PIC mode");
631 printBasicBlockLabel(MBB, false, false, false);
634 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
636 unsigned Reg = MO.getReg();
638 default: return true; // Unknown mode.
639 case 'b': // Print QImode register
640 Reg = getX86SubSuperRegister(Reg, MVT::i8);
642 case 'h': // Print QImode high register
643 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
645 case 'w': // Print HImode register
646 Reg = getX86SubSuperRegister(Reg, MVT::i16);
648 case 'k': // Print SImode register
649 Reg = getX86SubSuperRegister(Reg, MVT::i32);
651 case 'q': // Print DImode register
652 Reg = getX86SubSuperRegister(Reg, MVT::i64);
656 O << '%'<< TRI->getAsmName(Reg);
660 /// PrintAsmOperand - Print out an operand for an inline asm expression.
662 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
664 const char *ExtraCode) {
665 // Does this asm operand have a single letter operand modifier?
666 if (ExtraCode && ExtraCode[0]) {
667 if (ExtraCode[1] != 0) return true; // Unknown modifier.
669 switch (ExtraCode[0]) {
670 default: return true; // Unknown modifier.
671 case 'c': // Don't print "$" before a global var name or constant.
672 printOperand(MI, OpNo, "mem");
674 case 'b': // Print QImode register
675 case 'h': // Print QImode high register
676 case 'w': // Print HImode register
677 case 'k': // Print SImode register
678 case 'q': // Print DImode register
679 if (MI->getOperand(OpNo).isRegister())
680 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
681 printOperand(MI, OpNo);
684 case 'P': // Don't print @PLT, but do print as memory.
685 printOperand(MI, OpNo, "mem");
690 printOperand(MI, OpNo);
694 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
697 const char *ExtraCode) {
698 if (ExtraCode && ExtraCode[0]) {
699 if (ExtraCode[1] != 0) return true; // Unknown modifier.
701 switch (ExtraCode[0]) {
702 default: return true; // Unknown modifier.
703 case 'b': // Print QImode register
704 case 'h': // Print QImode high register
705 case 'w': // Print HImode register
706 case 'k': // Print SImode register
707 case 'q': // Print SImode register
708 // These only apply to registers, ignore on mem.
712 printMemReference(MI, OpNo);
716 /// printMachineInstruction -- Print out a single X86 LLVM instruction
717 /// MI in AT&T syntax to the current output stream.
719 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
722 // Call the autogenerated instruction printer routines.
723 printInstruction(MI);
727 bool X86ATTAsmPrinter::doInitialization(Module &M) {
728 if (TAI->doesSupportDebugInformation()) {
729 // Emit initial debug information.
733 bool Result = AsmPrinter::doInitialization(M);
735 if (TAI->doesSupportDebugInformation()) {
736 // Let PassManager know we need debug information and relay
737 // the MachineModuleInfo address on to DwarfWriter.
738 // AsmPrinter::doInitialization did this analysis.
739 MMI = getAnalysisToUpdate<MachineModuleInfo>();
740 DW.SetModuleInfo(MMI);
743 // Darwin wants symbols to be quoted if they have complex names.
744 if (Subtarget->isTargetDarwin())
745 Mang->setUseQuotes(true);
751 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
752 const TargetData *TD = TM.getTargetData();
754 if (!GVar->hasInitializer())
755 return; // External global require no code
757 std::string SectionName = TAI->SectionForGlobal(GVar);
759 // Check to see if this is a special global used by LLVM, if so, emit it.
760 if (EmitSpecialLLVMGlobal(GVar)) {
761 if (Subtarget->isTargetDarwin() &&
762 TM.getRelocationModel() == Reloc::Static) {
763 if (GVar->getName() == "llvm.global_ctors")
764 O << ".reference .constructors_used\n";
765 else if (GVar->getName() == "llvm.global_dtors")
766 O << ".reference .destructors_used\n";
771 std::string name = Mang->getValueName(GVar);
772 Constant *C = GVar->getInitializer();
773 const Type *Type = C->getType();
774 unsigned Size = TD->getABITypeSize(Type);
775 unsigned Align = TD->getPreferredAlignmentLog(GVar);
777 if (GVar->hasHiddenVisibility()) {
778 if (const char *Directive = TAI->getHiddenDirective())
779 O << Directive << name << '\n';
780 } else if (GVar->hasProtectedVisibility()) {
781 if (const char *Directive = TAI->getProtectedDirective())
782 O << Directive << name << '\n';
785 if (Subtarget->isTargetELF())
786 O << "\t.type\t" << name << ",@object\n";
788 SwitchToDataSection(SectionName.c_str());
790 if (C->isNullValue() && !GVar->hasSection()) {
791 // FIXME: This seems to be pretty darwin-specific
792 if (GVar->hasExternalLinkage()) {
793 if (const char *Directive = TAI->getZeroFillDirective()) {
794 O << "\t.globl " << name << '\n';
795 O << Directive << "__DATA, __common, " << name << ", "
796 << Size << ", " << Align << '\n';
801 if (!GVar->isThreadLocal() &&
802 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
803 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
805 if (TAI->getLCOMMDirective() != NULL) {
806 if (GVar->hasInternalLinkage()) {
807 O << TAI->getLCOMMDirective() << name << ',' << Size;
808 if (Subtarget->isTargetDarwin())
810 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
811 O << "\t.globl " << name << '\n'
812 << TAI->getWeakDefDirective() << name << '\n';
813 EmitAlignment(Align, GVar);
814 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
815 PrintUnmangledNameSafely(GVar, O);
817 EmitGlobalConstant(C);
820 O << TAI->getCOMMDirective() << name << ',' << Size;
822 // Leopard and above support aligned common symbols.
823 if (Subtarget->getDarwinVers() >= 9)
827 if (!Subtarget->isTargetCygMing()) {
828 if (GVar->hasInternalLinkage())
829 O << "\t.local\t" << name << '\n';
831 O << TAI->getCOMMDirective() << name << ',' << Size;
832 if (TAI->getCOMMDirectiveTakesAlignment())
833 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
835 O << "\t\t" << TAI->getCommentString() << ' ';
836 PrintUnmangledNameSafely(GVar, O);
842 switch (GVar->getLinkage()) {
843 case GlobalValue::CommonLinkage:
844 case GlobalValue::LinkOnceLinkage:
845 case GlobalValue::WeakLinkage:
846 if (Subtarget->isTargetDarwin()) {
847 O << "\t.globl " << name << '\n'
848 << TAI->getWeakDefDirective() << name << '\n';
849 } else if (Subtarget->isTargetCygMing()) {
850 O << "\t.globl\t" << name << "\n"
851 "\t.linkonce same_size\n";
853 O << "\t.weak\t" << name << '\n';
856 case GlobalValue::DLLExportLinkage:
857 case GlobalValue::AppendingLinkage:
858 // FIXME: appending linkage variables should go into a section of
859 // their name or something. For now, just emit them as external.
860 case GlobalValue::ExternalLinkage:
861 // If external or appending, declare as a global symbol
862 O << "\t.globl " << name << '\n';
864 case GlobalValue::InternalLinkage:
867 assert(0 && "Unknown linkage type!");
870 EmitAlignment(Align, GVar);
871 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
872 PrintUnmangledNameSafely(GVar, O);
874 if (TAI->hasDotTypeDotSizeDirective())
875 O << "\t.size\t" << name << ", " << Size << '\n';
877 // If the initializer is a extern weak symbol, remember to emit the weak
879 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
880 if (GV->hasExternalWeakLinkage())
881 ExtWeakSymbols.insert(GV);
883 EmitGlobalConstant(C);
886 /// printGVStub - Print stub for a global value.
888 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
889 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
890 O << ":\n\t.indirect_symbol ";
891 if (Prefix) O << Prefix;
892 O << GV << "\n\t.long\t0\n";
896 bool X86ATTAsmPrinter::doFinalization(Module &M) {
897 // Print out module-level global variables here.
898 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
900 printModuleLevelGV(I);
902 if (I->hasDLLExportLinkage())
903 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
906 // Output linker support code for dllexported globals
907 if (!DLLExportedGVs.empty())
908 SwitchToDataSection(".section .drectve");
910 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
911 e = DLLExportedGVs.end();
913 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
915 if (!DLLExportedFns.empty()) {
916 SwitchToDataSection(".section .drectve");
919 for (StringSet<>::iterator i = DLLExportedFns.begin(),
920 e = DLLExportedFns.end();
922 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
924 if (Subtarget->isTargetDarwin()) {
925 SwitchToDataSection("");
927 // Output stubs for dynamically-linked functions
929 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
931 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
932 "self_modifying_code+pure_instructions,5", 0);
933 const char *p = i->getKeyData();
934 printSuffixedName(p, "$stub");
936 "\t.indirect_symbol " << p << "\n"
937 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
942 // Print global value stubs.
943 bool InStubSection = false;
944 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
945 // Add the (possibly multiple) personalities to the set of global values.
946 // Only referenced functions get into the Personalities list.
947 const std::vector<Function *>& Personalities = MMI->getPersonalities();
948 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
949 E = Personalities.end(); I != E; ++I) {
952 if (!InStubSection) {
954 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
955 InStubSection = true;
957 printGVStub((*I)->getNameStart(), "_");
961 // Output stubs for external and common global variables.
962 if (!InStubSection && !GVStubs.empty())
964 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
965 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
967 printGVStub(i->getKeyData());
969 // Emit final debug information.
972 // Funny Darwin hack: This flag tells the linker that no global symbols
973 // contain code that falls through to other global symbols (e.g. the obvious
974 // implementation of multiple entry points). If this doesn't occur, the
975 // linker can safely perform dead code stripping. Since LLVM never
976 // generates code that does this, it is always safe to set.
977 O << "\t.subsections_via_symbols\n";
978 } else if (Subtarget->isTargetCygMing()) {
979 // Emit type information for external functions
980 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
982 O << "\t.def\t " << i->getKeyData()
983 << ";\t.scl\t" << COFF::C_EXT
984 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
988 // Emit final debug information.
990 } else if (Subtarget->isTargetELF()) {
991 // Emit final debug information.
995 return AsmPrinter::doFinalization(M);
998 // Include the auto-generated portion of the assembly writer.
999 #include "X86GenAsmWriter.inc"