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/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/Analysis/DebugInfo.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetOptions.h"
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
40 static std::string getPICLabelString(unsigned FnNum,
41 const TargetAsmInfo *TAI,
42 const X86Subtarget* Subtarget) {
44 if (Subtarget->isTargetDarwin())
45 label = "\"L" + utostr_32(FnNum) + "$pb\"";
46 else if (Subtarget->isTargetELF())
47 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
49 assert(0 && "Don't know how to print PIC label!\n");
54 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
55 const TargetData *TD) {
56 X86MachineFunctionInfo Info;
59 switch (F->getCallingConv()) {
60 case CallingConv::X86_StdCall:
61 Info.setDecorationStyle(StdCall);
63 case CallingConv::X86_FastCall:
64 Info.setDecorationStyle(FastCall);
71 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
72 AI != AE; ++AI, ++argNum) {
73 const Type* Ty = AI->getType();
75 // 'Dereference' type in case of byval parameter attribute
76 if (F->paramHasAttr(argNum, Attribute::ByVal))
77 Ty = cast<PointerType>(Ty)->getElementType();
79 // Size should be aligned to DWORD boundary
80 Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
83 // We're not supporting tooooo huge arguments :)
84 Info.setBytesToPopOnReturn((unsigned int)Size);
88 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
89 /// Don't print things like \\n or \\0.
90 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
91 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
97 /// decorateName - Query FunctionInfoMap and use this information for various
99 void X86ATTAsmPrinter::decorateName(std::string &Name,
100 const GlobalValue *GV) {
101 const Function *F = dyn_cast<Function>(GV);
104 // We don't want to decorate non-stdcall or non-fastcall functions right now
105 unsigned CC = F->getCallingConv();
106 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
109 // Decorate names only when we're targeting Cygwin/Mingw32 targets
110 if (!Subtarget->isTargetCygMing())
113 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
115 const X86MachineFunctionInfo *Info;
116 if (info_item == FunctionInfoMap.end()) {
117 // Calculate apropriate function info and populate map
118 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
119 Info = &FunctionInfoMap[F];
121 Info = &info_item->second;
124 const FunctionType *FT = F->getFunctionType();
125 switch (Info->getDecorationStyle()) {
129 // "Pure" variadic functions do not receive @0 suffix.
130 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
131 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
132 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
135 // "Pure" variadic functions do not receive @0 suffix.
136 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
137 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
138 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
140 if (Name[0] == '_') {
147 assert(0 && "Unsupported DecorationStyle");
151 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
152 const Function *F = MF.getFunction();
154 decorateName(CurrentFnName, F);
156 SwitchToSection(TAI->SectionForGlobal(F));
158 unsigned FnAlign = 4;
159 if (F->hasFnAttr(Attribute::OptimizeForSize))
161 switch (F->getLinkage()) {
162 default: assert(0 && "Unknown linkage type!");
163 case Function::InternalLinkage: // Symbols default to internal.
164 case Function::PrivateLinkage:
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::LinkOnceAnyLinkage:
173 case Function::LinkOnceODRLinkage:
174 case Function::WeakAnyLinkage:
175 case Function::WeakODRLinkage:
176 EmitAlignment(FnAlign, F);
177 if (Subtarget->isTargetDarwin()) {
178 O << "\t.globl\t" << CurrentFnName << '\n';
179 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
180 } else if (Subtarget->isTargetCygMing()) {
181 O << "\t.globl\t" << CurrentFnName << "\n"
182 "\t.linkonce discard\n";
184 O << "\t.weak\t" << CurrentFnName << '\n';
189 printVisibility(CurrentFnName, F->getVisibility());
191 if (Subtarget->isTargetELF())
192 O << "\t.type\t" << CurrentFnName << ",@function\n";
193 else if (Subtarget->isTargetCygMing()) {
194 O << "\t.def\t " << CurrentFnName
196 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
197 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
201 O << CurrentFnName << ":\n";
202 // Add some workaround for linkonce linkage on Cygwin\MinGW
203 if (Subtarget->isTargetCygMing() &&
204 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
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();
214 unsigned CC = F->getCallingConv();
216 SetupMachineFunction(MF);
219 // Populate function information map. Actually, We don't want to populate
220 // non-stdcall or non-fastcall functions' information right now.
221 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
222 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
224 // Print out constants referenced by the function
225 EmitConstantPool(MF.getConstantPool());
227 if (F->hasDLLExportLinkage())
228 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
230 // Print the 'header' of function
231 emitFunctionHeader(MF);
233 // Emit pre-function debug and/or EH information.
234 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
235 DW->BeginFunction(&MF);
237 // Print out code for the function.
238 bool hasAnyRealCode = false;
239 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
241 // Print a label for the basic block.
242 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
243 // This is an entry block or a block that's only reachable via a
244 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
246 printBasicBlockLabel(I, true, true, VerboseAsm);
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())
271 DW->EndFunction(&MF);
273 // Print out jump tables referenced by the function.
274 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
278 // We didn't modify anything.
282 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
283 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
286 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
287 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
288 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
291 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
292 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
295 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
296 const char *Modifier, bool NotRIPRel) {
297 const MachineOperand &MO = MI->getOperand(OpNo);
298 switch (MO.getType()) {
299 case MachineOperand::MO_Register: {
300 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
301 "Virtual registers should not make it this far!");
303 unsigned Reg = MO.getReg();
304 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
305 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
306 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
307 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
308 Reg = getX86SubSuperRegister(Reg, VT);
310 O << TRI->getAsmName(Reg);
314 case MachineOperand::MO_Immediate:
315 if (!Modifier || (strcmp(Modifier, "debug") &&
316 strcmp(Modifier, "mem") &&
317 strcmp(Modifier, "call")))
321 case MachineOperand::MO_MachineBasicBlock:
322 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
324 case MachineOperand::MO_JumpTableIndex: {
325 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
326 if (!isMemOp) O << '$';
327 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
330 if (TM.getRelocationModel() == Reloc::PIC_) {
331 if (Subtarget->isPICStyleStub())
332 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
334 else if (Subtarget->isPICStyleGOT())
338 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
342 case MachineOperand::MO_ConstantPoolIndex: {
343 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
344 if (!isMemOp) O << '$';
345 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
348 if (TM.getRelocationModel() == Reloc::PIC_) {
349 if (Subtarget->isPICStyleStub())
350 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
352 else if (Subtarget->isPICStyleGOT())
356 printOffset(MO.getOffset());
358 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
362 case MachineOperand::MO_GlobalAddress: {
363 bool isCallOp = Modifier && !strcmp(Modifier, "call");
364 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
365 bool needCloseParen = false;
367 const GlobalValue *GV = MO.getGlobal();
368 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
370 // If GV is an alias then use the aliasee for determining
372 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
373 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
376 bool isThreadLocal = GVar && GVar->isThreadLocal();
378 std::string Name = Mang->getValueName(GV);
379 decorateName(Name, GV);
381 if (!isMemOp && !isCallOp)
383 else if (Name[0] == '$') {
384 // The name begins with a dollar-sign. In order to avoid having it look
385 // like an integer immediate to the assembler, enclose it in parens.
387 needCloseParen = true;
390 if (shouldPrintStub(TM, Subtarget)) {
391 // Link-once, declaration, or Weakly-linked global variables need
392 // non-lazily-resolved stubs
393 if (GV->isDeclaration() || GV->isWeakForLinker()) {
394 // Dynamically-resolved functions need a stub for the function.
395 if (isCallOp && isa<Function>(GV)) {
396 // Function stubs are no longer needed for Mac OS X 10.5 and up.
397 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
400 FnStubs.insert(Name);
401 printSuffixedName(Name, "$stub");
403 } else if (GV->hasHiddenVisibility()) {
404 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
405 // Definition is not definitely in the current translation unit.
408 HiddenGVStubs.insert(Name);
409 printSuffixedName(Name, "$non_lazy_ptr");
412 GVStubs.insert(Name);
413 printSuffixedName(Name, "$non_lazy_ptr");
416 if (GV->hasDLLImportLinkage())
421 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
422 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
424 if (GV->hasDLLImportLinkage()) {
430 if (shouldPrintPLT(TM, Subtarget)) {
431 // Assemble call via PLT for externally visible symbols
432 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
433 !GV->hasLocalLinkage())
436 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
437 // Save function name for later type emission
438 FnStubs.insert(Name);
442 if (GV->hasExternalWeakLinkage())
443 ExtWeakSymbols.insert(GV);
445 printOffset(MO.getOffset());
448 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
450 case TLSModel::GeneralDynamic:
453 case TLSModel::LocalDynamic:
454 // O << "@TLSLD"; // local dynamic not implemented
457 case TLSModel::InitialExec:
458 if (Subtarget->is64Bit()) {
460 O << "@GOTTPOFF(%rip)";
465 case TLSModel::LocalExec:
466 if (Subtarget->is64Bit())
472 assert (0 && "Unknown TLS model");
474 } else if (isMemOp) {
475 if (shouldPrintGOT(TM, Subtarget)) {
476 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
480 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
481 if (TM.getRelocationModel() != Reloc::Static) {
482 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
485 if (needCloseParen) {
486 needCloseParen = false;
491 // Use rip when possible to reduce code size, except when
492 // index or base register are also part of the address. e.g.
493 // foo(%rip)(%rcx,%rax,4) is not legal
503 case MachineOperand::MO_ExternalSymbol: {
504 bool isCallOp = Modifier && !strcmp(Modifier, "call");
505 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
506 bool needCloseParen = false;
507 std::string Name(TAI->getGlobalPrefix());
508 Name += MO.getSymbolName();
509 // Print function stub suffix unless it's Mac OS X 10.5 and up.
510 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
511 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
512 FnStubs.insert(Name);
513 printSuffixedName(Name, "$stub");
516 if (!isMemOp && !isCallOp)
518 else if (Name[0] == '$') {
519 // The name begins with a dollar-sign. In order to avoid having it look
520 // like an integer immediate to the assembler, enclose it in parens.
522 needCloseParen = true;
527 if (shouldPrintPLT(TM, Subtarget)) {
528 std::string GOTName(TAI->getGlobalPrefix());
529 GOTName+="_GLOBAL_OFFSET_TABLE_";
531 // HACK! Emit extra offset to PC during printing GOT offset to
532 // compensate for the size of popl instruction. The resulting code
536 // popl %some_register
537 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
539 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
548 if (!isCallOp && Subtarget->isPICStyleRIPRel())
554 O << "<unknown operand type>"; return;
558 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
559 unsigned char value = MI->getOperand(Op).getImm();
560 assert(value <= 7 && "Invalid ssecc argument!");
562 case 0: O << "eq"; break;
563 case 1: O << "lt"; break;
564 case 2: O << "le"; break;
565 case 3: O << "unord"; break;
566 case 4: O << "neq"; break;
567 case 5: O << "nlt"; break;
568 case 6: O << "nle"; break;
569 case 7: O << "ord"; break;
573 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
574 const char *Modifier,
576 MachineOperand BaseReg = MI->getOperand(Op);
577 MachineOperand IndexReg = MI->getOperand(Op+2);
578 const MachineOperand &DispSpec = MI->getOperand(Op+3);
580 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
581 if (DispSpec.isGlobal() ||
584 DispSpec.isSymbol()) {
585 printOperand(MI, Op+3, "mem", NotRIPRel);
587 int DispVal = DispSpec.getImm();
588 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
592 if (IndexReg.getReg() || BaseReg.getReg()) {
593 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
594 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
596 // There are cases where we can end up with ESP/RSP in the indexreg slot.
597 // If this happens, swap the base/index register to support assemblers that
598 // don't work when the index is *SP.
599 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
600 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
601 std::swap(BaseReg, IndexReg);
602 std::swap(BaseRegOperand, IndexRegOperand);
606 if (BaseReg.getReg())
607 printOperand(MI, Op+BaseRegOperand, Modifier);
609 if (IndexReg.getReg()) {
611 printOperand(MI, Op+IndexRegOperand, Modifier);
613 O << ',' << ScaleVal;
619 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
620 const char *Modifier, bool NotRIPRel){
621 assert(isMem(MI, Op) && "Invalid memory reference!");
622 MachineOperand Segment = MI->getOperand(Op+4);
623 if (Segment.getReg()) {
624 printOperand(MI, Op+4, Modifier);
627 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
630 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
631 const MachineBasicBlock *MBB) const {
632 if (!TAI->getSetDirective())
635 // We don't need .set machinery if we have GOT-style relocations
636 if (Subtarget->isPICStyleGOT())
639 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
640 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
641 printBasicBlockLabel(MBB, false, false, false);
642 if (Subtarget->isPICStyleRIPRel())
643 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
644 << '_' << uid << '\n';
646 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
649 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
650 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
651 O << label << '\n' << label << ':';
655 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
656 const MachineBasicBlock *MBB,
659 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
660 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
662 O << JTEntryDirective << ' ';
664 if (TM.getRelocationModel() == Reloc::PIC_) {
665 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
666 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
667 << '_' << uid << "_set_" << MBB->getNumber();
668 } else if (Subtarget->isPICStyleGOT()) {
669 printBasicBlockLabel(MBB, false, false, false);
672 assert(0 && "Don't know how to print MBB label for this PIC mode");
674 printBasicBlockLabel(MBB, false, false, false);
677 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
679 unsigned Reg = MO.getReg();
681 default: return true; // Unknown mode.
682 case 'b': // Print QImode register
683 Reg = getX86SubSuperRegister(Reg, MVT::i8);
685 case 'h': // Print QImode high register
686 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
688 case 'w': // Print HImode register
689 Reg = getX86SubSuperRegister(Reg, MVT::i16);
691 case 'k': // Print SImode register
692 Reg = getX86SubSuperRegister(Reg, MVT::i32);
694 case 'q': // Print DImode register
695 Reg = getX86SubSuperRegister(Reg, MVT::i64);
699 O << '%'<< TRI->getAsmName(Reg);
703 /// PrintAsmOperand - Print out an operand for an inline asm expression.
705 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
707 const char *ExtraCode) {
708 // Does this asm operand have a single letter operand modifier?
709 if (ExtraCode && ExtraCode[0]) {
710 if (ExtraCode[1] != 0) return true; // Unknown modifier.
712 switch (ExtraCode[0]) {
713 default: return true; // Unknown modifier.
714 case 'c': // Don't print "$" before a global var name or constant.
715 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
717 case 'b': // Print QImode register
718 case 'h': // Print QImode high register
719 case 'w': // Print HImode register
720 case 'k': // Print SImode register
721 case 'q': // Print DImode register
722 if (MI->getOperand(OpNo).isReg())
723 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
724 printOperand(MI, OpNo);
727 case 'P': // Don't print @PLT, but do print as memory.
728 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
733 printOperand(MI, OpNo);
737 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
740 const char *ExtraCode) {
741 if (ExtraCode && ExtraCode[0]) {
742 if (ExtraCode[1] != 0) return true; // Unknown modifier.
744 switch (ExtraCode[0]) {
745 default: return true; // Unknown modifier.
746 case 'b': // Print QImode register
747 case 'h': // Print QImode high register
748 case 'w': // Print HImode register
749 case 'k': // Print SImode register
750 case 'q': // Print SImode register
751 // These only apply to registers, ignore on mem.
753 case 'P': // Don't print @PLT, but do print as memory.
754 printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
758 printMemReference(MI, OpNo);
762 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
763 /// AT&T syntax to the current output stream.
765 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
768 // Call the autogenerated instruction printer routines.
769 printInstruction(MI);
773 bool X86ATTAsmPrinter::doInitialization(Module &M) {
775 bool Result = AsmPrinter::doInitialization(M);
777 if (TAI->doesSupportDebugInformation()) {
778 // Let PassManager know we need debug information and relay
779 // the MachineModuleInfo address on to DwarfWriter.
780 // AsmPrinter::doInitialization did this analysis.
781 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
782 DW = getAnalysisIfAvailable<DwarfWriter>();
783 DW->BeginModule(&M, MMI, O, this, TAI);
786 // Darwin wants symbols to be quoted if they have complex names.
787 if (Subtarget->isTargetDarwin())
788 Mang->setUseQuotes(true);
794 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
795 const TargetData *TD = TM.getTargetData();
797 if (!GVar->hasInitializer())
798 return; // External global require no code
800 // Check to see if this is a special global used by LLVM, if so, emit it.
801 if (EmitSpecialLLVMGlobal(GVar)) {
802 if (Subtarget->isTargetDarwin() &&
803 TM.getRelocationModel() == Reloc::Static) {
804 if (GVar->getName() == "llvm.global_ctors")
805 O << ".reference .constructors_used\n";
806 else if (GVar->getName() == "llvm.global_dtors")
807 O << ".reference .destructors_used\n";
812 std::string name = Mang->getValueName(GVar);
813 Constant *C = GVar->getInitializer();
814 const Type *Type = C->getType();
815 unsigned Size = TD->getTypePaddedSize(Type);
816 unsigned Align = TD->getPreferredAlignmentLog(GVar);
818 printVisibility(name, GVar->getVisibility());
820 if (Subtarget->isTargetELF())
821 O << "\t.type\t" << name << ",@object\n";
823 SwitchToSection(TAI->SectionForGlobal(GVar));
825 if (C->isNullValue() && !GVar->hasSection() &&
826 !(Subtarget->isTargetDarwin() &&
827 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
828 // FIXME: This seems to be pretty darwin-specific
829 if (GVar->hasExternalLinkage()) {
830 if (const char *Directive = TAI->getZeroFillDirective()) {
831 O << "\t.globl " << name << '\n';
832 O << Directive << "__DATA, __common, " << name << ", "
833 << Size << ", " << Align << '\n';
838 if (!GVar->isThreadLocal() &&
839 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
840 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
842 if (TAI->getLCOMMDirective() != NULL) {
843 if (GVar->hasLocalLinkage()) {
844 O << TAI->getLCOMMDirective() << name << ',' << Size;
845 if (Subtarget->isTargetDarwin())
847 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
848 O << "\t.globl " << name << '\n'
849 << TAI->getWeakDefDirective() << name << '\n';
850 EmitAlignment(Align, GVar);
853 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
854 PrintUnmangledNameSafely(GVar, O);
857 EmitGlobalConstant(C);
860 O << TAI->getCOMMDirective() << name << ',' << Size;
861 if (TAI->getCOMMDirectiveTakesAlignment())
862 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
865 if (!Subtarget->isTargetCygMing()) {
866 if (GVar->hasLocalLinkage())
867 O << "\t.local\t" << name << '\n';
869 O << TAI->getCOMMDirective() << name << ',' << Size;
870 if (TAI->getCOMMDirectiveTakesAlignment())
871 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
874 O << "\t\t" << TAI->getCommentString() << ' ';
875 PrintUnmangledNameSafely(GVar, O);
882 switch (GVar->getLinkage()) {
883 case GlobalValue::CommonLinkage:
884 case GlobalValue::LinkOnceAnyLinkage:
885 case GlobalValue::LinkOnceODRLinkage:
886 case GlobalValue::WeakAnyLinkage:
887 case GlobalValue::WeakODRLinkage:
888 if (Subtarget->isTargetDarwin()) {
889 O << "\t.globl " << name << '\n'
890 << TAI->getWeakDefDirective() << name << '\n';
891 } else if (Subtarget->isTargetCygMing()) {
892 O << "\t.globl\t" << name << "\n"
893 "\t.linkonce same_size\n";
895 O << "\t.weak\t" << name << '\n';
898 case GlobalValue::DLLExportLinkage:
899 case GlobalValue::AppendingLinkage:
900 // FIXME: appending linkage variables should go into a section of
901 // their name or something. For now, just emit them as external.
902 case GlobalValue::ExternalLinkage:
903 // If external or appending, declare as a global symbol
904 O << "\t.globl " << name << '\n';
906 case GlobalValue::PrivateLinkage:
907 case GlobalValue::InternalLinkage:
910 assert(0 && "Unknown linkage type!");
913 EmitAlignment(Align, GVar);
916 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
917 PrintUnmangledNameSafely(GVar, O);
920 if (TAI->hasDotTypeDotSizeDirective())
921 O << "\t.size\t" << name << ", " << Size << '\n';
923 EmitGlobalConstant(C);
926 /// printGVStub - Print stub for a global value.
928 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
929 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
930 O << ":\n\t.indirect_symbol ";
931 if (Prefix) O << Prefix;
932 O << GV << "\n\t.long\t0\n";
935 /// printHiddenGVStub - Print stub for a hidden global value.
937 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
939 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
940 if (Prefix) O << Prefix;
941 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
945 bool X86ATTAsmPrinter::doFinalization(Module &M) {
946 // Print out module-level global variables here.
947 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
949 printModuleLevelGV(I);
951 if (I->hasDLLExportLinkage())
952 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
954 // If the global is a extern weak symbol, remember to emit the weak
956 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
957 // not used. But currently it's the only way to deal with extern weak
958 // initializers hidden deep inside constant expressions.
959 if (I->hasExternalWeakLinkage())
960 ExtWeakSymbols.insert(I);
963 for (Module::const_iterator I = M.begin(), E = M.end();
965 // If the global is a extern weak symbol, remember to emit the weak
967 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
968 // not used. But currently it's the only way to deal with extern weak
969 // initializers hidden deep inside constant expressions.
970 if (I->hasExternalWeakLinkage())
971 ExtWeakSymbols.insert(I);
974 // Output linker support code for dllexported globals
975 if (!DLLExportedGVs.empty())
976 SwitchToDataSection(".section .drectve");
978 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
979 e = DLLExportedGVs.end();
981 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
983 if (!DLLExportedFns.empty()) {
984 SwitchToDataSection(".section .drectve");
987 for (StringSet<>::iterator i = DLLExportedFns.begin(),
988 e = DLLExportedFns.end();
990 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
992 if (Subtarget->isTargetDarwin()) {
993 SwitchToDataSection("");
995 // Output stubs for dynamically-linked functions
996 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
998 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
999 "self_modifying_code+pure_instructions,5", 0);
1000 const char *p = i->getKeyData();
1001 printSuffixedName(p, "$stub");
1003 "\t.indirect_symbol " << p << "\n"
1004 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1009 // Print global value stubs.
1010 bool InStubSection = false;
1011 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1012 // Add the (possibly multiple) personalities to the set of global values.
1013 // Only referenced functions get into the Personalities list.
1014 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1015 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1016 E = Personalities.end(); I != E; ++I) {
1019 if (!InStubSection) {
1020 SwitchToDataSection(
1021 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1022 InStubSection = true;
1024 printGVStub((*I)->getNameStart(), "_");
1028 // Output stubs for external and common global variables.
1029 if (!InStubSection && !GVStubs.empty())
1030 SwitchToDataSection(
1031 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1032 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1034 printGVStub(i->getKeyData());
1036 if (!HiddenGVStubs.empty()) {
1037 SwitchToSection(TAI->getDataSection());
1038 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1040 printHiddenGVStub(i->getKeyData());
1043 // Emit final debug information.
1044 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1047 // Funny Darwin hack: This flag tells the linker that no global symbols
1048 // contain code that falls through to other global symbols (e.g. the obvious
1049 // implementation of multiple entry points). If this doesn't occur, the
1050 // linker can safely perform dead code stripping. Since LLVM never
1051 // generates code that does this, it is always safe to set.
1052 O << "\t.subsections_via_symbols\n";
1053 } else if (Subtarget->isTargetCygMing()) {
1054 // Emit type information for external functions
1055 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1057 O << "\t.def\t " << i->getKeyData()
1058 << ";\t.scl\t" << COFF::C_EXT
1059 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1063 // Emit final debug information.
1064 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1066 } else if (Subtarget->isTargetELF()) {
1067 // Emit final debug information.
1068 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1072 return AsmPrinter::doFinalization(M);
1075 // Include the auto-generated portion of the assembly writer.
1076 #include "X86GenAsmWriter.inc"