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/MC/MCInst.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetOptions.h"
39 STATISTIC(EmittedInsts, "Number of machine instrs printed");
41 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
44 static std::string getPICLabelString(unsigned FnNum,
45 const TargetAsmInfo *TAI,
46 const X86Subtarget* Subtarget) {
48 if (Subtarget->isTargetDarwin())
49 label = "\"L" + utostr_32(FnNum) + "$pb\"";
50 else if (Subtarget->isTargetELF())
51 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
53 assert(0 && "Don't know how to print PIC label!\n");
58 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
59 const TargetData *TD) {
60 X86MachineFunctionInfo Info;
63 switch (F->getCallingConv()) {
64 case CallingConv::X86_StdCall:
65 Info.setDecorationStyle(StdCall);
67 case CallingConv::X86_FastCall:
68 Info.setDecorationStyle(FastCall);
75 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
76 AI != AE; ++AI, ++argNum) {
77 const Type* Ty = AI->getType();
79 // 'Dereference' type in case of byval parameter attribute
80 if (F->paramHasAttr(argNum, Attribute::ByVal))
81 Ty = cast<PointerType>(Ty)->getElementType();
83 // Size should be aligned to DWORD boundary
84 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
87 // We're not supporting tooooo huge arguments :)
88 Info.setBytesToPopOnReturn((unsigned int)Size);
92 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
93 /// Don't print things like \\n or \\0.
94 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
95 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
101 /// decorateName - Query FunctionInfoMap and use this information for various
103 void X86ATTAsmPrinter::decorateName(std::string &Name,
104 const GlobalValue *GV) {
105 const Function *F = dyn_cast<Function>(GV);
108 // We don't want to decorate non-stdcall or non-fastcall functions right now
109 unsigned CC = F->getCallingConv();
110 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
113 // Decorate names only when we're targeting Cygwin/Mingw32 targets
114 if (!Subtarget->isTargetCygMing())
117 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
119 const X86MachineFunctionInfo *Info;
120 if (info_item == FunctionInfoMap.end()) {
121 // Calculate apropriate function info and populate map
122 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
123 Info = &FunctionInfoMap[F];
125 Info = &info_item->second;
128 const FunctionType *FT = F->getFunctionType();
129 switch (Info->getDecorationStyle()) {
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());
139 // "Pure" variadic functions do not receive @0 suffix.
140 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
141 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
142 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
144 if (Name[0] == '_') {
151 assert(0 && "Unsupported DecorationStyle");
155 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
156 const Function *F = MF.getFunction();
158 decorateName(CurrentFnName, F);
160 SwitchToSection(TAI->SectionForGlobal(F));
162 unsigned FnAlign = 4;
163 if (F->hasFnAttr(Attribute::OptimizeForSize))
165 switch (F->getLinkage()) {
166 default: assert(0 && "Unknown linkage type!");
167 case Function::InternalLinkage: // Symbols default to internal.
168 case Function::PrivateLinkage:
169 EmitAlignment(FnAlign, F);
171 case Function::DLLExportLinkage:
172 case Function::ExternalLinkage:
173 EmitAlignment(FnAlign, F);
174 O << "\t.globl\t" << CurrentFnName << '\n';
176 case Function::LinkOnceAnyLinkage:
177 case Function::LinkOnceODRLinkage:
178 case Function::WeakAnyLinkage:
179 case Function::WeakODRLinkage:
180 EmitAlignment(FnAlign, F);
181 if (Subtarget->isTargetDarwin()) {
182 O << "\t.globl\t" << CurrentFnName << '\n';
183 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
184 } else if (Subtarget->isTargetCygMing()) {
185 O << "\t.globl\t" << CurrentFnName << "\n"
186 "\t.linkonce discard\n";
188 O << "\t.weak\t" << CurrentFnName << '\n';
193 printVisibility(CurrentFnName, F->getVisibility());
195 if (Subtarget->isTargetELF())
196 O << "\t.type\t" << CurrentFnName << ",@function\n";
197 else if (Subtarget->isTargetCygMing()) {
198 O << "\t.def\t " << CurrentFnName
200 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
201 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
205 O << CurrentFnName << ":\n";
206 // Add some workaround for linkonce linkage on Cygwin\MinGW
207 if (Subtarget->isTargetCygMing() &&
208 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
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();
218 unsigned CC = F->getCallingConv();
220 SetupMachineFunction(MF);
223 // Populate function information map. Actually, We don't want to populate
224 // non-stdcall or non-fastcall functions' information right now.
225 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
226 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
228 // Print out constants referenced by the function
229 EmitConstantPool(MF.getConstantPool());
231 if (F->hasDLLExportLinkage())
232 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
234 // Print the 'header' of function
235 emitFunctionHeader(MF);
237 // Emit pre-function debug and/or EH information.
238 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
239 DW->BeginFunction(&MF);
241 // Print out code for the function.
242 bool hasAnyRealCode = false;
243 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
245 // Print a label for the basic block.
246 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
247 // This is an entry block or a block that's only reachable via a
248 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
250 printBasicBlockLabel(I, true, true, VerboseAsm);
253 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
255 // Print the assembly for the instruction.
257 hasAnyRealCode = true;
258 printMachineInstruction(II);
262 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
263 // If the function is empty, then we need to emit *something*. Otherwise,
264 // the function's label might be associated with something that it wasn't
265 // meant to be associated with. We emit a noop in this situation.
266 // We are assuming inline asms are code.
270 if (TAI->hasDotTypeDotSizeDirective())
271 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
273 // Emit post-function debug information.
274 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
275 DW->EndFunction(&MF);
277 // Print out jump tables referenced by the function.
278 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
282 // We didn't modify anything.
286 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
287 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
290 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
291 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
292 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
295 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
296 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
299 /// print_pcrel_imm - This is used to print an immediate value that ends up
300 /// being encoded as a pc-relative value. These print slightly differently, for
301 /// example, a $ is not emitted.
302 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
303 const MachineOperand &MO = MI->getOperand(OpNo);
304 switch (MO.getType()) {
305 default: assert(0 && "Unknown pcrel immediate operand");
306 case MachineOperand::MO_Immediate:
309 case MachineOperand::MO_MachineBasicBlock:
310 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
313 case MachineOperand::MO_GlobalAddress: {
314 const GlobalValue *GV = MO.getGlobal();
315 std::string Name = Mang->getValueName(GV);
316 decorateName(Name, GV);
318 bool needCloseParen = false;
319 if (Name[0] == '$') {
320 // The name begins with a dollar-sign. In order to avoid having it look
321 // like an integer immediate to the assembler, enclose it in parens.
323 needCloseParen = true;
326 if (shouldPrintStub(TM, Subtarget)) {
327 // Link-once, declaration, or Weakly-linked global variables need
328 // non-lazily-resolved stubs
329 if (GV->isDeclaration() || GV->isWeakForLinker()) {
330 // Dynamically-resolved functions need a stub for the function.
331 if (isa<Function>(GV)) {
332 // Function stubs are no longer needed for Mac OS X 10.5 and up.
333 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
336 FnStubs.insert(Name);
337 printSuffixedName(Name, "$stub");
339 } else if (GV->hasHiddenVisibility()) {
340 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
341 // Definition is not definitely in the current translation unit.
344 HiddenGVStubs.insert(Name);
345 printSuffixedName(Name, "$non_lazy_ptr");
348 GVStubs.insert(Name);
349 printSuffixedName(Name, "$non_lazy_ptr");
352 if (GV->hasDLLImportLinkage())
357 if (GV->hasDLLImportLinkage()) {
362 if (shouldPrintPLT(TM, Subtarget)) {
363 // Assemble call via PLT for externally visible symbols
364 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
365 !GV->hasLocalLinkage())
368 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
369 // Save function name for later type emission
370 FnStubs.insert(Name);
373 if (GV->hasExternalWeakLinkage())
374 ExtWeakSymbols.insert(GV);
376 printOffset(MO.getOffset());
383 case MachineOperand::MO_ExternalSymbol: {
384 bool needCloseParen = false;
385 std::string Name(TAI->getGlobalPrefix());
386 Name += MO.getSymbolName();
387 // Print function stub suffix unless it's Mac OS X 10.5 and up.
388 if (shouldPrintStub(TM, Subtarget) &&
389 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
390 FnStubs.insert(Name);
391 printSuffixedName(Name, "$stub");
395 if (Name[0] == '$') {
396 // The name begins with a dollar-sign. In order to avoid having it look
397 // like an integer immediate to the assembler, enclose it in parens.
399 needCloseParen = true;
404 if (shouldPrintPLT(TM, Subtarget)) {
405 std::string GOTName(TAI->getGlobalPrefix());
406 GOTName+="_GLOBAL_OFFSET_TABLE_";
408 // HACK! Emit extra offset to PC during printing GOT offset to
409 // compensate for the size of popl instruction. The resulting code
413 // popl %some_register
414 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
416 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
429 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
430 const char *Modifier, bool NotRIPRel) {
431 const MachineOperand &MO = MI->getOperand(OpNo);
432 switch (MO.getType()) {
433 case MachineOperand::MO_Register: {
434 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
435 "Virtual registers should not make it this far!");
437 unsigned Reg = MO.getReg();
438 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
439 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
440 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
441 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
442 Reg = getX86SubSuperRegister(Reg, VT);
444 O << TRI->getAsmName(Reg);
448 case MachineOperand::MO_Immediate:
449 if (!Modifier || (strcmp(Modifier, "debug") &&
450 strcmp(Modifier, "mem")))
454 case MachineOperand::MO_MachineBasicBlock:
456 assert(0 && "labels should only be used as pc-relative values");
457 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
459 case MachineOperand::MO_JumpTableIndex: {
460 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
461 if (!isMemOp) O << '$';
462 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
465 if (TM.getRelocationModel() == Reloc::PIC_) {
466 if (Subtarget->isPICStyleStub())
467 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
469 else if (Subtarget->isPICStyleGOT())
473 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
477 case MachineOperand::MO_ConstantPoolIndex: {
478 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
479 if (!isMemOp) O << '$';
480 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
483 if (TM.getRelocationModel() == Reloc::PIC_) {
484 if (Subtarget->isPICStyleStub())
485 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
487 else if (Subtarget->isPICStyleGOT())
491 printOffset(MO.getOffset());
493 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
497 case MachineOperand::MO_GlobalAddress: {
498 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
499 bool needCloseParen = false;
501 const GlobalValue *GV = MO.getGlobal();
502 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
504 // If GV is an alias then use the aliasee for determining
506 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
507 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
510 bool isThreadLocal = GVar && GVar->isThreadLocal();
512 std::string Name = Mang->getValueName(GV);
513 decorateName(Name, GV);
517 else if (Name[0] == '$') {
518 // The name begins with a dollar-sign. In order to avoid having it look
519 // like an integer immediate to the assembler, enclose it in parens.
521 needCloseParen = true;
524 if (shouldPrintStub(TM, Subtarget)) {
525 // Link-once, declaration, or Weakly-linked global variables need
526 // non-lazily-resolved stubs
527 if (GV->isDeclaration() || GV->isWeakForLinker()) {
528 // Dynamically-resolved functions need a stub for the function.
529 if (GV->hasHiddenVisibility()) {
530 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
531 // Definition is not definitely in the current translation unit.
534 HiddenGVStubs.insert(Name);
535 printSuffixedName(Name, "$non_lazy_ptr");
538 GVStubs.insert(Name);
539 printSuffixedName(Name, "$non_lazy_ptr");
542 if (GV->hasDLLImportLinkage())
547 if (TM.getRelocationModel() == Reloc::PIC_)
548 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
550 if (GV->hasDLLImportLinkage()) {
556 if (GV->hasExternalWeakLinkage())
557 ExtWeakSymbols.insert(GV);
559 printOffset(MO.getOffset());
562 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
564 case TLSModel::GeneralDynamic:
567 case TLSModel::LocalDynamic:
568 // O << "@TLSLD"; // local dynamic not implemented
571 case TLSModel::InitialExec:
572 if (Subtarget->is64Bit()) {
574 O << "@GOTTPOFF(%rip)";
579 case TLSModel::LocalExec:
580 if (Subtarget->is64Bit())
586 assert (0 && "Unknown TLS model");
588 } else if (isMemOp) {
589 if (shouldPrintGOT(TM, Subtarget)) {
590 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
594 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
595 if (TM.getRelocationModel() != Reloc::Static) {
596 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
599 if (needCloseParen) {
600 needCloseParen = false;
605 // Use rip when possible to reduce code size, except when
606 // index or base register are also part of the address. e.g.
607 // foo(%rip)(%rcx,%rax,4) is not legal
617 case MachineOperand::MO_ExternalSymbol: {
618 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
619 bool needCloseParen = false;
620 std::string Name(TAI->getGlobalPrefix());
621 Name += MO.getSymbolName();
623 // Print function stub suffix unless it's Mac OS X 10.5 and up.
626 else if (Name[0] == '$') {
627 // The name begins with a dollar-sign. In order to avoid having it look
628 // like an integer immediate to the assembler, enclose it in parens.
630 needCloseParen = true;
635 if (shouldPrintPLT(TM, Subtarget)) {
636 std::string GOTName(TAI->getGlobalPrefix());
637 GOTName+="_GLOBAL_OFFSET_TABLE_";
639 // HACK! Emit extra offset to PC during printing GOT offset to
640 // compensate for the size of popl instruction. The resulting code
644 // popl %some_register
645 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
647 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
653 if (Subtarget->isPICStyleRIPRel())
658 O << "<unknown operand type>"; return;
662 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
663 unsigned char value = MI->getOperand(Op).getImm();
664 assert(value <= 7 && "Invalid ssecc argument!");
666 case 0: O << "eq"; break;
667 case 1: O << "lt"; break;
668 case 2: O << "le"; break;
669 case 3: O << "unord"; break;
670 case 4: O << "neq"; break;
671 case 5: O << "nlt"; break;
672 case 6: O << "nle"; break;
673 case 7: O << "ord"; break;
677 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
678 const char *Modifier,
680 MachineOperand BaseReg = MI->getOperand(Op);
681 MachineOperand IndexReg = MI->getOperand(Op+2);
682 const MachineOperand &DispSpec = MI->getOperand(Op+3);
684 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
685 if (DispSpec.isGlobal() ||
688 DispSpec.isSymbol()) {
689 printOperand(MI, Op+3, "mem", NotRIPRel);
691 int DispVal = DispSpec.getImm();
692 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
696 if (IndexReg.getReg() || BaseReg.getReg()) {
697 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
698 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
700 // There are cases where we can end up with ESP/RSP in the indexreg slot.
701 // If this happens, swap the base/index register to support assemblers that
702 // don't work when the index is *SP.
703 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
704 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
705 std::swap(BaseReg, IndexReg);
706 std::swap(BaseRegOperand, IndexRegOperand);
710 if (BaseReg.getReg())
711 printOperand(MI, Op+BaseRegOperand, Modifier);
713 if (IndexReg.getReg()) {
715 printOperand(MI, Op+IndexRegOperand, Modifier);
717 O << ',' << ScaleVal;
723 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
724 const char *Modifier, bool NotRIPRel){
725 assert(isMem(MI, Op) && "Invalid memory reference!");
726 MachineOperand Segment = MI->getOperand(Op+4);
727 if (Segment.getReg()) {
728 printOperand(MI, Op+4, Modifier);
731 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
734 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
735 const MachineBasicBlock *MBB) const {
736 if (!TAI->getSetDirective())
739 // We don't need .set machinery if we have GOT-style relocations
740 if (Subtarget->isPICStyleGOT())
743 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
744 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
745 printBasicBlockLabel(MBB, false, false, false);
746 if (Subtarget->isPICStyleRIPRel())
747 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
748 << '_' << uid << '\n';
750 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
753 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
754 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
755 O << label << '\n' << label << ':';
759 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
760 const MachineBasicBlock *MBB,
763 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
764 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
766 O << JTEntryDirective << ' ';
768 if (TM.getRelocationModel() == Reloc::PIC_) {
769 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
770 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
771 << '_' << uid << "_set_" << MBB->getNumber();
772 } else if (Subtarget->isPICStyleGOT()) {
773 printBasicBlockLabel(MBB, false, false, false);
776 assert(0 && "Don't know how to print MBB label for this PIC mode");
778 printBasicBlockLabel(MBB, false, false, false);
781 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
782 unsigned Reg = MO.getReg();
784 default: return true; // Unknown mode.
785 case 'b': // Print QImode register
786 Reg = getX86SubSuperRegister(Reg, MVT::i8);
788 case 'h': // Print QImode high register
789 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
791 case 'w': // Print HImode register
792 Reg = getX86SubSuperRegister(Reg, MVT::i16);
794 case 'k': // Print SImode register
795 Reg = getX86SubSuperRegister(Reg, MVT::i32);
797 case 'q': // Print DImode register
798 Reg = getX86SubSuperRegister(Reg, MVT::i64);
802 O << '%'<< TRI->getAsmName(Reg);
806 /// PrintAsmOperand - Print out an operand for an inline asm expression.
808 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
810 const char *ExtraCode) {
811 // Does this asm operand have a single letter operand modifier?
812 if (ExtraCode && ExtraCode[0]) {
813 if (ExtraCode[1] != 0) return true; // Unknown modifier.
815 switch (ExtraCode[0]) {
816 default: return true; // Unknown modifier.
817 case 'c': // Don't print "$" before a global var name or constant.
818 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
820 case 'b': // Print QImode register
821 case 'h': // Print QImode high register
822 case 'w': // Print HImode register
823 case 'k': // Print SImode register
824 case 'q': // Print DImode register
825 if (MI->getOperand(OpNo).isReg())
826 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
827 printOperand(MI, OpNo);
830 case 'P': // Don't print @PLT, but do print as memory.
831 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
836 printOperand(MI, OpNo);
840 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
843 const char *ExtraCode) {
844 if (ExtraCode && ExtraCode[0]) {
845 if (ExtraCode[1] != 0) return true; // Unknown modifier.
847 switch (ExtraCode[0]) {
848 default: return true; // Unknown modifier.
849 case 'b': // Print QImode register
850 case 'h': // Print QImode high register
851 case 'w': // Print HImode register
852 case 'k': // Print SImode register
853 case 'q': // Print SImode register
854 // These only apply to registers, ignore on mem.
856 case 'P': // Don't print @PLT, but do print as memory.
857 printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
861 printMemReference(MI, OpNo);
865 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
866 // Convert registers in the addr mode according to subreg64.
867 for (unsigned i = 0; i != 4; ++i) {
868 if (!MI->getOperand(i).isReg()) continue;
870 unsigned Reg = MI->getOperand(i).getReg();
871 if (Reg == 0) continue;
873 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
877 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
878 /// AT&T syntax to the current output stream.
880 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
884 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
888 } else if (MI->isLabel()) {
891 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
894 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
895 printImplicitDef(MI);
902 TmpInst.setOpcode(MI->getOpcode());
904 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
905 const MachineOperand &MO = MI->getOperand(i);
909 MCOp.MakeReg(MO.getReg());
910 } else if (MO.isImm()) {
911 MCOp.MakeImm(MO.getImm());
912 } else if (MO.isMBB()) {
913 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
915 assert(0 && "Unimp");
918 TmpInst.addOperand(MCOp);
921 switch (TmpInst.getOpcode()) {
923 // Handle the 'subreg rewriting' for the lea64_32mem operand.
924 lower_lea64_32mem(&TmpInst, 1);
926 case X86::CALL64pcrel32:
927 case X86::CALLpcrel32:
929 // The target operand is pc-relative, not an absolute reference.
930 // FIXME: this should be an operand property, not an asm format modifier.
934 // FIXME: Convert TmpInst.
935 printInstruction(&TmpInst);
939 // Call the autogenerated instruction printer routines.
940 printInstruction(MI);
944 bool X86ATTAsmPrinter::doInitialization(Module &M) {
945 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
946 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
947 return AsmPrinter::doInitialization(M);
950 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
951 const TargetData *TD = TM.getTargetData();
953 if (!GVar->hasInitializer())
954 return; // External global require no code
956 // Check to see if this is a special global used by LLVM, if so, emit it.
957 if (EmitSpecialLLVMGlobal(GVar)) {
958 if (Subtarget->isTargetDarwin() &&
959 TM.getRelocationModel() == Reloc::Static) {
960 if (GVar->getName() == "llvm.global_ctors")
961 O << ".reference .constructors_used\n";
962 else if (GVar->getName() == "llvm.global_dtors")
963 O << ".reference .destructors_used\n";
968 std::string name = Mang->getValueName(GVar);
969 Constant *C = GVar->getInitializer();
970 const Type *Type = C->getType();
971 unsigned Size = TD->getTypeAllocSize(Type);
972 unsigned Align = TD->getPreferredAlignmentLog(GVar);
974 printVisibility(name, GVar->getVisibility());
976 if (Subtarget->isTargetELF())
977 O << "\t.type\t" << name << ",@object\n";
979 SwitchToSection(TAI->SectionForGlobal(GVar));
981 if (C->isNullValue() && !GVar->hasSection() &&
982 !(Subtarget->isTargetDarwin() &&
983 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
984 // FIXME: This seems to be pretty darwin-specific
985 if (GVar->hasExternalLinkage()) {
986 if (const char *Directive = TAI->getZeroFillDirective()) {
987 O << "\t.globl " << name << '\n';
988 O << Directive << "__DATA, __common, " << name << ", "
989 << Size << ", " << Align << '\n';
994 if (!GVar->isThreadLocal() &&
995 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
996 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
998 if (TAI->getLCOMMDirective() != NULL) {
999 if (GVar->hasLocalLinkage()) {
1000 O << TAI->getLCOMMDirective() << name << ',' << Size;
1001 if (Subtarget->isTargetDarwin())
1003 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1004 O << "\t.globl " << name << '\n'
1005 << TAI->getWeakDefDirective() << name << '\n';
1006 EmitAlignment(Align, GVar);
1009 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1010 PrintUnmangledNameSafely(GVar, O);
1013 EmitGlobalConstant(C);
1016 O << TAI->getCOMMDirective() << name << ',' << Size;
1017 if (TAI->getCOMMDirectiveTakesAlignment())
1018 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1021 if (!Subtarget->isTargetCygMing()) {
1022 if (GVar->hasLocalLinkage())
1023 O << "\t.local\t" << name << '\n';
1025 O << TAI->getCOMMDirective() << name << ',' << Size;
1026 if (TAI->getCOMMDirectiveTakesAlignment())
1027 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1030 O << "\t\t" << TAI->getCommentString() << ' ';
1031 PrintUnmangledNameSafely(GVar, O);
1038 switch (GVar->getLinkage()) {
1039 case GlobalValue::CommonLinkage:
1040 case GlobalValue::LinkOnceAnyLinkage:
1041 case GlobalValue::LinkOnceODRLinkage:
1042 case GlobalValue::WeakAnyLinkage:
1043 case GlobalValue::WeakODRLinkage:
1044 if (Subtarget->isTargetDarwin()) {
1045 O << "\t.globl " << name << '\n'
1046 << TAI->getWeakDefDirective() << name << '\n';
1047 } else if (Subtarget->isTargetCygMing()) {
1048 O << "\t.globl\t" << name << "\n"
1049 "\t.linkonce same_size\n";
1051 O << "\t.weak\t" << name << '\n';
1054 case GlobalValue::DLLExportLinkage:
1055 case GlobalValue::AppendingLinkage:
1056 // FIXME: appending linkage variables should go into a section of
1057 // their name or something. For now, just emit them as external.
1058 case GlobalValue::ExternalLinkage:
1059 // If external or appending, declare as a global symbol
1060 O << "\t.globl " << name << '\n';
1062 case GlobalValue::PrivateLinkage:
1063 case GlobalValue::InternalLinkage:
1066 assert(0 && "Unknown linkage type!");
1069 EmitAlignment(Align, GVar);
1072 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1073 PrintUnmangledNameSafely(GVar, O);
1076 if (TAI->hasDotTypeDotSizeDirective())
1077 O << "\t.size\t" << name << ", " << Size << '\n';
1079 EmitGlobalConstant(C);
1082 /// printGVStub - Print stub for a global value.
1084 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
1085 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
1086 O << ":\n\t.indirect_symbol ";
1087 if (Prefix) O << Prefix;
1088 O << GV << "\n\t.long\t0\n";
1091 /// printHiddenGVStub - Print stub for a hidden global value.
1093 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
1095 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
1096 if (Prefix) O << Prefix;
1097 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
1101 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1102 // Print out module-level global variables here.
1103 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1105 printModuleLevelGV(I);
1107 if (I->hasDLLExportLinkage())
1108 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1110 // If the global is a extern weak symbol, remember to emit the weak
1112 // FIXME: This is rather hacky, since we'll emit references to ALL weak
1113 // stuff, not used. But currently it's the only way to deal with extern weak
1114 // initializers hidden deep inside constant expressions.
1115 if (I->hasExternalWeakLinkage())
1116 ExtWeakSymbols.insert(I);
1119 for (Module::const_iterator I = M.begin(), E = M.end();
1121 // If the global is a extern weak symbol, remember to emit the weak
1123 // FIXME: This is rather hacky, since we'll emit references to ALL weak
1124 // stuff, not used. But currently it's the only way to deal with extern weak
1125 // initializers hidden deep inside constant expressions.
1126 if (I->hasExternalWeakLinkage())
1127 ExtWeakSymbols.insert(I);
1130 // Output linker support code for dllexported globals
1131 if (!DLLExportedGVs.empty())
1132 SwitchToDataSection(".section .drectve");
1134 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1135 e = DLLExportedGVs.end();
1137 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1139 if (!DLLExportedFns.empty()) {
1140 SwitchToDataSection(".section .drectve");
1143 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1144 e = DLLExportedFns.end();
1146 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1148 if (Subtarget->isTargetDarwin()) {
1149 SwitchToDataSection("");
1151 // Output stubs for dynamically-linked functions
1152 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1154 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1155 "self_modifying_code+pure_instructions,5", 0);
1156 const char *p = i->getKeyData();
1157 printSuffixedName(p, "$stub");
1159 "\t.indirect_symbol " << p << "\n"
1160 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1165 // Print global value stubs.
1166 bool InStubSection = false;
1167 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1168 // Add the (possibly multiple) personalities to the set of global values.
1169 // Only referenced functions get into the Personalities list.
1170 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1171 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1172 E = Personalities.end(); I != E; ++I) {
1175 if (!InStubSection) {
1176 SwitchToDataSection(
1177 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1178 InStubSection = true;
1180 printGVStub((*I)->getNameStart(), "_");
1184 // Output stubs for external and common global variables.
1185 if (!InStubSection && !GVStubs.empty())
1186 SwitchToDataSection(
1187 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1188 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1190 printGVStub(i->getKeyData());
1192 if (!HiddenGVStubs.empty()) {
1193 SwitchToSection(TAI->getDataSection());
1194 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1196 printHiddenGVStub(i->getKeyData());
1199 // Emit final debug information.
1200 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
1203 // Funny Darwin hack: This flag tells the linker that no global symbols
1204 // contain code that falls through to other global symbols (e.g. the obvious
1205 // implementation of multiple entry points). If this doesn't occur, the
1206 // linker can safely perform dead code stripping. Since LLVM never
1207 // generates code that does this, it is always safe to set.
1208 O << "\t.subsections_via_symbols\n";
1209 } else if (Subtarget->isTargetCygMing()) {
1210 // Emit type information for external functions
1211 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1213 O << "\t.def\t " << i->getKeyData()
1214 << ";\t.scl\t" << COFF::C_EXT
1215 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1219 // Emit final debug information.
1220 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
1222 } else if (Subtarget->isTargetELF()) {
1223 // Emit final debug information.
1224 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
1228 return AsmPrinter::doFinalization(M);
1231 // Include the auto-generated portion of the assembly writer.
1232 #include "X86GenAsmWriter.inc"