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/MCContext.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/CodeGen/DwarfWriter.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetAsmInfo.h"
38 #include "llvm/Target/TargetOptions.h"
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
47 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
48 if (Subtarget->isTargetDarwin())
49 O << "\"L" << getFunctionNumber() << "$pb\"";
50 else if (Subtarget->isTargetELF())
51 O << ".Lllvm$" << getFunctionNumber() << "." "$piclabel";
53 assert(0 && "Don't know how to print PIC label!\n");
57 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
58 const TargetData *TD) {
59 X86MachineFunctionInfo Info;
62 switch (F->getCallingConv()) {
63 case CallingConv::X86_StdCall:
64 Info.setDecorationStyle(StdCall);
66 case CallingConv::X86_FastCall:
67 Info.setDecorationStyle(FastCall);
74 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
75 AI != AE; ++AI, ++argNum) {
76 const Type* Ty = AI->getType();
78 // 'Dereference' type in case of byval parameter attribute
79 if (F->paramHasAttr(argNum, Attribute::ByVal))
80 Ty = cast<PointerType>(Ty)->getElementType();
82 // Size should be aligned to DWORD boundary
83 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
86 // We're not supporting tooooo huge arguments :)
87 Info.setBytesToPopOnReturn((unsigned int)Size);
91 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
92 /// Don't print things like \\n or \\0.
93 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
94 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
100 /// decorateName - Query FunctionInfoMap and use this information for various
102 void X86ATTAsmPrinter::decorateName(std::string &Name,
103 const GlobalValue *GV) {
104 const Function *F = dyn_cast<Function>(GV);
107 // We don't want to decorate non-stdcall or non-fastcall functions right now
108 unsigned CC = F->getCallingConv();
109 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
112 // Decorate names only when we're targeting Cygwin/Mingw32 targets
113 if (!Subtarget->isTargetCygMing())
116 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
118 const X86MachineFunctionInfo *Info;
119 if (info_item == FunctionInfoMap.end()) {
120 // Calculate apropriate function info and populate map
121 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
122 Info = &FunctionInfoMap[F];
124 Info = &info_item->second;
127 const FunctionType *FT = F->getFunctionType();
128 switch (Info->getDecorationStyle()) {
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());
138 // "Pure" variadic functions do not receive @0 suffix.
139 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
140 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
141 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
143 if (Name[0] == '_') {
150 assert(0 && "Unsupported DecorationStyle");
154 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
155 const Function *F = MF.getFunction();
157 decorateName(CurrentFnName, F);
159 SwitchToSection(TAI->SectionForGlobal(F));
161 unsigned FnAlign = 4;
162 if (F->hasFnAttr(Attribute::OptimizeForSize))
164 switch (F->getLinkage()) {
165 default: assert(0 && "Unknown linkage type!");
166 case Function::InternalLinkage: // Symbols default to internal.
167 case Function::PrivateLinkage:
168 EmitAlignment(FnAlign, F);
170 case Function::DLLExportLinkage:
171 case Function::ExternalLinkage:
172 EmitAlignment(FnAlign, F);
173 O << "\t.globl\t" << CurrentFnName << '\n';
175 case Function::LinkOnceAnyLinkage:
176 case Function::LinkOnceODRLinkage:
177 case Function::WeakAnyLinkage:
178 case Function::WeakODRLinkage:
179 EmitAlignment(FnAlign, F);
180 if (Subtarget->isTargetDarwin()) {
181 O << "\t.globl\t" << CurrentFnName << '\n';
182 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
183 } else if (Subtarget->isTargetCygMing()) {
184 O << "\t.globl\t" << CurrentFnName << "\n"
185 "\t.linkonce discard\n";
187 O << "\t.weak\t" << CurrentFnName << '\n';
192 printVisibility(CurrentFnName, F->getVisibility());
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->hasInternalLinkage() ? 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->hasLinkOnceLinkage() || F->hasWeakLinkage()))
208 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
211 /// runOnMachineFunction - This uses the printMachineInstruction()
212 /// method to print assembly for each instruction.
214 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
215 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 (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
246 // This is an entry block or a block that's only reachable via a
247 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
249 printBasicBlockLabel(I, true, true, VerboseAsm);
252 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
254 // Print the assembly for the instruction.
256 hasAnyRealCode = true;
257 printMachineInstruction(II);
261 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
262 // If the function is empty, then we need to emit *something*. Otherwise,
263 // the function's label might be associated with something that it wasn't
264 // meant to be associated with. We emit a noop in this situation.
265 // We are assuming inline asms are code.
269 if (TAI->hasDotTypeDotSizeDirective())
270 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
272 // Emit post-function debug information.
273 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
274 DW->EndFunction(&MF);
276 // Print out jump tables referenced by the function.
277 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
281 // We didn't modify anything.
285 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
286 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
289 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
290 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
291 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
294 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
295 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
298 /// print_pcrel_imm - This is used to print an immediate value that ends up
299 /// being encoded as a pc-relative value. These print slightly differently, for
300 /// example, a $ is not emitted.
301 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
302 const MachineOperand &MO = MI->getOperand(OpNo);
303 switch (MO.getType()) {
304 default: assert(0 && "Unknown pcrel immediate operand");
305 case MachineOperand::MO_Immediate:
308 case MachineOperand::MO_MachineBasicBlock:
309 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
312 case MachineOperand::MO_GlobalAddress: {
313 const GlobalValue *GV = MO.getGlobal();
314 std::string Name = Mang->getValueName(GV);
315 decorateName(Name, GV);
317 bool needCloseParen = false;
318 if (Name[0] == '$') {
319 // The name begins with a dollar-sign. In order to avoid having it look
320 // like an integer immediate to the assembler, enclose it in parens.
322 needCloseParen = true;
325 if (shouldPrintStub(TM, Subtarget)) {
326 // Link-once, declaration, or Weakly-linked global variables need
327 // non-lazily-resolved stubs
328 if (GV->isDeclaration() || GV->isWeakForLinker()) {
329 // Dynamically-resolved functions need a stub for the function.
330 if (isa<Function>(GV)) {
331 // Function stubs are no longer needed for Mac OS X 10.5 and up.
332 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
335 FnStubs.insert(Name);
336 printSuffixedName(Name, "$stub");
338 } else if (GV->hasHiddenVisibility()) {
339 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
340 // Definition is not definitely in the current translation unit.
343 HiddenGVStubs.insert(Name);
344 printSuffixedName(Name, "$non_lazy_ptr");
347 GVStubs.insert(Name);
348 printSuffixedName(Name, "$non_lazy_ptr");
351 if (GV->hasDLLImportLinkage())
356 if (GV->hasDLLImportLinkage()) {
361 if (shouldPrintPLT(TM, Subtarget)) {
362 // Assemble call via PLT for externally visible symbols
363 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
364 !GV->hasLocalLinkage())
367 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
368 // Save function name for later type emission
369 FnStubs.insert(Name);
372 printOffset(MO.getOffset());
379 case MachineOperand::MO_ExternalSymbol: {
380 bool needCloseParen = false;
381 std::string Name(TAI->getGlobalPrefix());
382 Name += MO.getSymbolName();
383 // Print function stub suffix unless it's Mac OS X 10.5 and up.
384 if (shouldPrintStub(TM, Subtarget) &&
385 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
386 FnStubs.insert(Name);
387 printSuffixedName(Name, "$stub");
391 if (Name[0] == '$') {
392 // The name begins with a dollar-sign. In order to avoid having it look
393 // like an integer immediate to the assembler, enclose it in parens.
395 needCloseParen = true;
400 if (shouldPrintPLT(TM, Subtarget)) {
401 std::string GOTName(TAI->getGlobalPrefix());
402 GOTName+="_GLOBAL_OFFSET_TABLE_";
403 if (Name == GOTName) {
404 // HACK! Emit extra offset to PC during printing GOT offset to
405 // compensate for the size of popl instruction. The resulting code
409 // popl %some_register
410 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
412 PrintPICBaseSymbol();
427 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
428 const char *Modifier, bool NotRIPRel) {
429 const MachineOperand &MO = MI->getOperand(OpNo);
430 switch (MO.getType()) {
431 case MachineOperand::MO_Register: {
432 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
433 "Virtual registers should not make it this far!");
435 unsigned Reg = MO.getReg();
436 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
437 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
438 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
439 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
440 Reg = getX86SubSuperRegister(Reg, VT);
442 O << TRI->getAsmName(Reg);
446 case MachineOperand::MO_Immediate:
447 if (!Modifier || (strcmp(Modifier, "debug") &&
448 strcmp(Modifier, "mem")))
452 case MachineOperand::MO_JumpTableIndex: {
453 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
454 if (!isMemOp) O << '$';
455 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
458 if (TM.getRelocationModel() == Reloc::PIC_) {
459 if (Subtarget->isPICStyleStub())
460 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
462 else if (Subtarget->isPICStyleGOT())
466 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
470 case MachineOperand::MO_ConstantPoolIndex: {
471 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
472 if (!isMemOp) O << '$';
473 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
476 if (TM.getRelocationModel() == Reloc::PIC_) {
477 if (Subtarget->isPICStyleStub())
478 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
480 else if (Subtarget->isPICStyleGOT())
484 printOffset(MO.getOffset());
486 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
490 case MachineOperand::MO_GlobalAddress: {
491 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
492 bool needCloseParen = false;
494 const GlobalValue *GV = MO.getGlobal();
495 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
497 // If GV is an alias then use the aliasee for determining
499 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
500 GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
503 bool isThreadLocal = GVar && GVar->isThreadLocal();
505 std::string Name = Mang->getValueName(GV);
506 decorateName(Name, GV);
510 else if (Name[0] == '$') {
511 // The name begins with a dollar-sign. In order to avoid having it look
512 // like an integer immediate to the assembler, enclose it in parens.
514 needCloseParen = true;
517 if (shouldPrintStub(TM, Subtarget)) {
518 // Link-once, declaration, or Weakly-linked global variables need
519 // non-lazily-resolved stubs
520 if (GV->isDeclaration() || GV->isWeakForLinker()) {
521 // Dynamically-resolved functions need a stub for the function.
522 if (GV->hasHiddenVisibility()) {
523 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
524 // Definition is not definitely in the current translation unit.
527 HiddenGVStubs.insert(Name);
528 printSuffixedName(Name, "$non_lazy_ptr");
531 GVStubs.insert(Name);
532 printSuffixedName(Name, "$non_lazy_ptr");
535 if (GV->hasDLLImportLinkage())
540 if (TM.getRelocationModel() == Reloc::PIC_) {
542 PrintPICBaseSymbol();
545 if (GV->hasDLLImportLinkage())
550 printOffset(MO.getOffset());
555 bool isRIPRelative = false;
557 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
559 case TLSModel::GeneralDynamic:
562 case TLSModel::LocalDynamic:
563 // O << "@TLSLD"; // local dynamic not implemented
566 case TLSModel::InitialExec:
567 if (Subtarget->is64Bit()) {
570 isRIPRelative = true;
575 case TLSModel::LocalExec:
576 if (Subtarget->is64Bit())
582 assert (0 && "Unknown TLS model");
584 } else if (isMemOp) {
585 if (shouldPrintGOT(TM, Subtarget)) {
586 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
590 } else if (Subtarget->isPICStyleRIPRel() &&
592 if (TM.getRelocationModel() != Reloc::Static) {
593 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
597 isRIPRelative = true;
601 // Use rip when possible to reduce code size, except when
602 // index or base register are also part of the address. e.g.
603 // foo(%rip)(%rcx,%rax,4) is not legal.
609 case MachineOperand::MO_ExternalSymbol: {
610 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
611 bool needCloseParen = false;
612 std::string Name(TAI->getGlobalPrefix());
613 Name += MO.getSymbolName();
615 // Print function stub suffix unless it's Mac OS X 10.5 and up.
618 else if (Name[0] == '$') {
619 // The name begins with a dollar-sign. In order to avoid having it look
620 // like an integer immediate to the assembler, enclose it in parens.
622 needCloseParen = true;
627 if (shouldPrintPLT(TM, Subtarget)) {
628 std::string GOTName(TAI->getGlobalPrefix());
629 GOTName+="_GLOBAL_OFFSET_TABLE_";
630 if (Name == GOTName) {
631 // HACK! Emit extra offset to PC during printing GOT offset to
632 // compensate for the size of popl instruction. The resulting code
636 // popl %some_register
637 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
639 PrintPICBaseSymbol();
647 if (Subtarget->isPICStyleRIPRel())
652 O << "<unknown operand type>"; return;
656 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
657 unsigned char value = MI->getOperand(Op).getImm();
658 assert(value <= 7 && "Invalid ssecc argument!");
660 case 0: O << "eq"; break;
661 case 1: O << "lt"; break;
662 case 2: O << "le"; break;
663 case 3: O << "unord"; break;
664 case 4: O << "neq"; break;
665 case 5: O << "nlt"; break;
666 case 6: O << "nle"; break;
667 case 7: O << "ord"; break;
671 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
672 const char *Modifier,
674 MachineOperand BaseReg = MI->getOperand(Op);
675 MachineOperand IndexReg = MI->getOperand(Op+2);
676 const MachineOperand &DispSpec = MI->getOperand(Op+3);
678 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
679 if (DispSpec.isGlobal() ||
682 DispSpec.isSymbol()) {
683 printOperand(MI, Op+3, "mem", NotRIPRel);
685 int DispVal = DispSpec.getImm();
686 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
690 if (IndexReg.getReg() || BaseReg.getReg()) {
691 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
692 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
694 // There are cases where we can end up with ESP/RSP in the indexreg slot.
695 // If this happens, swap the base/index register to support assemblers that
696 // don't work when the index is *SP.
697 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
698 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
699 std::swap(BaseReg, IndexReg);
700 std::swap(BaseRegOperand, IndexRegOperand);
704 if (BaseReg.getReg())
705 printOperand(MI, Op+BaseRegOperand, Modifier);
707 if (IndexReg.getReg()) {
709 printOperand(MI, Op+IndexRegOperand, Modifier);
711 O << ',' << ScaleVal;
717 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
718 const char *Modifier, bool NotRIPRel){
719 assert(isMem(MI, Op) && "Invalid memory reference!");
720 MachineOperand Segment = MI->getOperand(Op+4);
721 if (Segment.getReg()) {
722 printOperand(MI, Op+4, Modifier);
725 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
728 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
729 const MachineBasicBlock *MBB) const {
730 if (!TAI->getSetDirective())
733 // We don't need .set machinery if we have GOT-style relocations
734 if (Subtarget->isPICStyleGOT())
737 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
738 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
739 printBasicBlockLabel(MBB, false, false, false);
740 if (Subtarget->isPICStyleRIPRel())
741 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
742 << '_' << uid << '\n';
745 PrintPICBaseSymbol();
751 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
752 PrintPICBaseSymbol();
754 PrintPICBaseSymbol();
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);
928 // FIXME: Convert TmpInst.
929 printInstruction(&TmpInst);
933 // Call the autogenerated instruction printer routines.
934 printInstruction(MI);
938 bool X86ATTAsmPrinter::doInitialization(Module &M) {
940 Context = new MCContext();
941 // FIXME: Send this to "O" instead of outs(). For now, we force it to
942 // stdout to make it easy to compare.
943 Streamer = createAsmStreamer(*Context, outs());
946 return AsmPrinter::doInitialization(M);
949 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
950 const TargetData *TD = TM.getTargetData();
952 if (!GVar->hasInitializer())
953 return; // External global require no code
955 // Check to see if this is a special global used by LLVM, if so, emit it.
956 if (EmitSpecialLLVMGlobal(GVar)) {
957 if (Subtarget->isTargetDarwin() &&
958 TM.getRelocationModel() == Reloc::Static) {
959 if (GVar->getName() == "llvm.global_ctors")
960 O << ".reference .constructors_used\n";
961 else if (GVar->getName() == "llvm.global_dtors")
962 O << ".reference .destructors_used\n";
967 std::string name = Mang->getValueName(GVar);
968 Constant *C = GVar->getInitializer();
969 const Type *Type = C->getType();
970 unsigned Size = TD->getTypeAllocSize(Type);
971 unsigned Align = TD->getPreferredAlignmentLog(GVar);
973 printVisibility(name, GVar->getVisibility());
975 if (Subtarget->isTargetELF())
976 O << "\t.type\t" << name << ",@object\n";
978 SwitchToSection(TAI->SectionForGlobal(GVar));
980 if (C->isNullValue() && !GVar->hasSection() &&
981 !(Subtarget->isTargetDarwin() &&
982 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
983 // FIXME: This seems to be pretty darwin-specific
984 if (GVar->hasExternalLinkage()) {
985 if (const char *Directive = TAI->getZeroFillDirective()) {
986 O << "\t.globl " << name << '\n';
987 O << Directive << "__DATA, __common, " << name << ", "
988 << Size << ", " << Align << '\n';
993 if (!GVar->isThreadLocal() &&
994 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
995 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
997 if (TAI->getLCOMMDirective() != NULL) {
998 if (GVar->hasLocalLinkage()) {
999 O << TAI->getLCOMMDirective() << name << ',' << Size;
1000 if (Subtarget->isTargetDarwin())
1002 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1003 O << "\t.globl " << name << '\n'
1004 << TAI->getWeakDefDirective() << name << '\n';
1005 EmitAlignment(Align, GVar);
1008 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1009 PrintUnmangledNameSafely(GVar, O);
1012 EmitGlobalConstant(C);
1015 O << TAI->getCOMMDirective() << name << ',' << Size;
1016 if (TAI->getCOMMDirectiveTakesAlignment())
1017 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1020 if (!Subtarget->isTargetCygMing()) {
1021 if (GVar->hasLocalLinkage())
1022 O << "\t.local\t" << name << '\n';
1024 O << TAI->getCOMMDirective() << name << ',' << Size;
1025 if (TAI->getCOMMDirectiveTakesAlignment())
1026 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1029 O << "\t\t" << TAI->getCommentString() << ' ';
1030 PrintUnmangledNameSafely(GVar, O);
1037 switch (GVar->getLinkage()) {
1038 case GlobalValue::CommonLinkage:
1039 case GlobalValue::LinkOnceAnyLinkage:
1040 case GlobalValue::LinkOnceODRLinkage:
1041 case GlobalValue::WeakAnyLinkage:
1042 case GlobalValue::WeakODRLinkage:
1043 if (Subtarget->isTargetDarwin()) {
1044 O << "\t.globl " << name << '\n'
1045 << TAI->getWeakDefDirective() << name << '\n';
1046 } else if (Subtarget->isTargetCygMing()) {
1047 O << "\t.globl\t" << name << "\n"
1048 "\t.linkonce same_size\n";
1050 O << "\t.weak\t" << name << '\n';
1053 case GlobalValue::DLLExportLinkage:
1054 case GlobalValue::AppendingLinkage:
1055 // FIXME: appending linkage variables should go into a section of
1056 // their name or something. For now, just emit them as external.
1057 case GlobalValue::ExternalLinkage:
1058 // If external or appending, declare as a global symbol
1059 O << "\t.globl " << name << '\n';
1061 case GlobalValue::PrivateLinkage:
1062 case GlobalValue::InternalLinkage:
1065 assert(0 && "Unknown linkage type!");
1068 EmitAlignment(Align, GVar);
1071 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1072 PrintUnmangledNameSafely(GVar, O);
1075 if (TAI->hasDotTypeDotSizeDirective())
1076 O << "\t.size\t" << name << ", " << Size << '\n';
1078 EmitGlobalConstant(C);
1081 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1082 // Print out module-level global variables here.
1083 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1085 printModuleLevelGV(I);
1087 if (I->hasDLLExportLinkage())
1088 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1091 if (Subtarget->isTargetDarwin()) {
1092 SwitchToDataSection("");
1094 // Add the (possibly multiple) personalities to the set of global value
1095 // stubs. Only referenced functions get into the Personalities list.
1096 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1097 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1098 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1099 if (Personalities[i] == 0)
1101 std::string Name = Mang->getValueName(Personalities[i]);
1102 decorateName(Name, Personalities[i]);
1103 GVStubs.insert(Name);
1107 // Output stubs for dynamically-linked functions
1108 if (!FnStubs.empty()) {
1109 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1111 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1112 "self_modifying_code+pure_instructions,5", 0);
1113 const char *Name = I->getKeyData();
1114 printSuffixedName(Name, "$stub");
1116 "\t.indirect_symbol " << Name << "\n"
1117 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1122 // Output stubs for external and common global variables.
1123 if (!GVStubs.empty()) {
1124 SwitchToDataSection(
1125 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1126 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1128 const char *Name = I->getKeyData();
1129 printSuffixedName(Name, "$non_lazy_ptr");
1130 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1134 if (!HiddenGVStubs.empty()) {
1135 SwitchToSection(TAI->getDataSection());
1137 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1138 E = HiddenGVStubs.end(); I != E; ++I) {
1139 const char *Name = I->getKeyData();
1140 printSuffixedName(Name, "$non_lazy_ptr");
1141 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1145 // Funny Darwin hack: This flag tells the linker that no global symbols
1146 // contain code that falls through to other global symbols (e.g. the obvious
1147 // implementation of multiple entry points). If this doesn't occur, the
1148 // linker can safely perform dead code stripping. Since LLVM never
1149 // generates code that does this, it is always safe to set.
1150 O << "\t.subsections_via_symbols\n";
1151 } else if (Subtarget->isTargetCygMing()) {
1152 // Emit type information for external functions
1153 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1155 O << "\t.def\t " << i->getKeyData()
1156 << ";\t.scl\t" << COFF::C_EXT
1157 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1163 // Output linker support code for dllexported globals on windows.
1164 if (!DLLExportedGVs.empty()) {
1165 SwitchToDataSection(".section .drectve");
1167 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1168 e = DLLExportedGVs.end(); i != e; ++i)
1169 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1172 if (!DLLExportedFns.empty()) {
1173 SwitchToDataSection(".section .drectve");
1175 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1176 e = DLLExportedFns.end();
1178 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1181 // Do common shutdown.
1182 bool Changed = AsmPrinter::doFinalization(M);
1184 if (NewAsmPrinter) {
1196 // Include the auto-generated portion of the assembly writer.
1197 #include "X86GenAsmWriter.inc"