1 //===-- X86AsmPrinter.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 X86 machine code.
13 //===----------------------------------------------------------------------===//
15 #include "X86AsmPrinter.h"
16 #include "X86ATTInstPrinter.h"
17 #include "X86IntelInstPrinter.h"
18 #include "X86MCInstLower.h"
21 #include "X86COFFMachineModuleInfo.h"
22 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/ADT/SmallString.h"
44 //===----------------------------------------------------------------------===//
45 // Primitive Helper Functions.
46 //===----------------------------------------------------------------------===//
48 void X86AsmPrinter::printMCInst(const MCInst *MI) {
49 if (MAI->getAssemblerDialect() == 0)
50 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
52 X86IntelInstPrinter(O, *MAI).printInstruction(MI);
55 void X86AsmPrinter::PrintPICBaseSymbol() const {
56 const TargetLowering *TLI = TM.getTargetLowering();
57 O << *static_cast<const X86TargetLowering*>(TLI)->getPICBaseSymbol(MF,
61 /// runOnMachineFunction - Emit the function body.
63 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
64 SetupMachineFunction(MF);
67 // COFF and Cygwin specific mangling stuff. This should be moved out to the
68 // mangler or handled some other way?
69 if (Subtarget->isTargetCOFF()) {
70 X86COFFMachineModuleInfo &COFFMMI =
71 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
73 // Populate function information map. Don't want to populate
74 // non-stdcall or non-fastcall functions' information right now.
75 const Function *F = MF.getFunction();
76 CallingConv::ID CC = F->getCallingConv();
77 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
78 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
80 if (Subtarget->isTargetCygMing()) {
81 const Function *F = MF.getFunction();
82 X86COFFMachineModuleInfo &COFFMMI =
83 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
84 COFFMMI.DecorateCygMingName(CurrentFnSym, OutContext,F,*TM.getTargetData());
86 O << "\t.def\t " << *CurrentFnSym;
88 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
89 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
93 // Have common code print out the function header with linkage info etc.
96 // Emit the rest of the function body.
99 // We didn't modify anything.
103 /// printSymbolOperand - Print a raw symbol reference operand. This handles
104 /// jump tables, constant pools, global address and external symbols, all of
105 /// which print to a label with various suffixes for relocation types etc.
106 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
107 switch (MO.getType()) {
108 default: llvm_unreachable("unknown symbol type!");
109 case MachineOperand::MO_JumpTableIndex:
110 O << *GetJTISymbol(MO.getIndex());
112 case MachineOperand::MO_ConstantPoolIndex:
113 O << *GetCPISymbol(MO.getIndex());
114 printOffset(MO.getOffset());
116 case MachineOperand::MO_GlobalAddress: {
117 const GlobalValue *GV = MO.getGlobal();
120 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
121 GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
122 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
123 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
124 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
125 GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
127 GVSym = GetGlobalValueSymbol(GV);
129 if (Subtarget->isTargetCygMing()) {
130 X86COFFMachineModuleInfo &COFFMMI =
131 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
132 COFFMMI.DecorateCygMingName(GVSym, OutContext, GV, *TM.getTargetData());
135 // Handle dllimport linkage.
136 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
137 GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
139 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
140 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
141 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
143 const MCSymbol *&StubSym =
144 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
146 StubSym = GetGlobalValueSymbol(GV);
148 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
149 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
150 const MCSymbol *&StubSym =
151 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
153 StubSym = GetGlobalValueSymbol(GV);
154 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
155 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
156 const MCSymbol *&StubSym =
157 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
159 StubSym = GetGlobalValueSymbol(GV);
162 // If the name begins with a dollar-sign, enclose it in parens. We do this
163 // to avoid having it look like an integer immediate to the assembler.
164 if (GVSym->getName()[0] != '$')
167 O << '(' << *GVSym << ')';
168 printOffset(MO.getOffset());
171 case MachineOperand::MO_ExternalSymbol: {
172 const MCSymbol *SymToPrint;
173 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
174 SmallString<128> TempNameStr;
175 TempNameStr += StringRef(MO.getSymbolName());
176 TempNameStr += StringRef("$stub");
178 const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
179 const MCSymbol *&StubSym =
180 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
182 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
183 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
185 SymToPrint = StubSym;
187 SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
190 // If the name begins with a dollar-sign, enclose it in parens. We do this
191 // to avoid having it look like an integer immediate to the assembler.
192 if (SymToPrint->getName()[0] != '$')
195 O << '(' << *SymToPrint << '(';
200 switch (MO.getTargetFlags()) {
202 llvm_unreachable("Unknown target flag on GV operand");
203 case X86II::MO_NO_FLAG: // No flag.
205 case X86II::MO_DARWIN_NONLAZY:
206 case X86II::MO_DLLIMPORT:
207 case X86II::MO_DARWIN_STUB:
208 // These affect the name of the symbol, not any suffix.
210 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
212 PrintPICBaseSymbol();
215 case X86II::MO_PIC_BASE_OFFSET:
216 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
217 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
219 PrintPICBaseSymbol();
221 case X86II::MO_TLSGD: O << "@TLSGD"; break;
222 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
223 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
224 case X86II::MO_TPOFF: O << "@TPOFF"; break;
225 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
226 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
227 case X86II::MO_GOT: O << "@GOT"; break;
228 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
229 case X86II::MO_PLT: O << "@PLT"; break;
233 /// print_pcrel_imm - This is used to print an immediate value that ends up
234 /// being encoded as a pc-relative value. These print slightly differently, for
235 /// example, a $ is not emitted.
236 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
237 const MachineOperand &MO = MI->getOperand(OpNo);
238 switch (MO.getType()) {
239 default: llvm_unreachable("Unknown pcrel immediate operand");
240 case MachineOperand::MO_Immediate:
243 case MachineOperand::MO_MachineBasicBlock:
244 O << *MO.getMBB()->getSymbol(OutContext);
246 case MachineOperand::MO_GlobalAddress:
247 case MachineOperand::MO_ExternalSymbol:
248 printSymbolOperand(MO);
254 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
255 const char *Modifier) {
256 const MachineOperand &MO = MI->getOperand(OpNo);
257 switch (MO.getType()) {
258 default: llvm_unreachable("unknown operand type!");
259 case MachineOperand::MO_Register: {
261 unsigned Reg = MO.getReg();
262 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
263 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
264 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
265 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
266 Reg = getX86SubSuperRegister(Reg, VT);
268 O << X86ATTInstPrinter::getRegisterName(Reg);
272 case MachineOperand::MO_Immediate:
273 O << '$' << MO.getImm();
276 case MachineOperand::MO_JumpTableIndex:
277 case MachineOperand::MO_ConstantPoolIndex:
278 case MachineOperand::MO_GlobalAddress:
279 case MachineOperand::MO_ExternalSymbol: {
281 printSymbolOperand(MO);
287 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
288 unsigned char value = MI->getOperand(Op).getImm();
289 assert(value <= 7 && "Invalid ssecc argument!");
291 case 0: O << "eq"; break;
292 case 1: O << "lt"; break;
293 case 2: O << "le"; break;
294 case 3: O << "unord"; break;
295 case 4: O << "neq"; break;
296 case 5: O << "nlt"; break;
297 case 6: O << "nle"; break;
298 case 7: O << "ord"; break;
302 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
303 const char *Modifier) {
304 const MachineOperand &BaseReg = MI->getOperand(Op);
305 const MachineOperand &IndexReg = MI->getOperand(Op+2);
306 const MachineOperand &DispSpec = MI->getOperand(Op+3);
308 // If we really don't want to print out (rip), don't.
309 bool HasBaseReg = BaseReg.getReg() != 0;
310 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
311 BaseReg.getReg() == X86::RIP)
314 // HasParenPart - True if we will print out the () part of the mem ref.
315 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
317 if (DispSpec.isImm()) {
318 int DispVal = DispSpec.getImm();
319 if (DispVal || !HasParenPart)
322 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
323 DispSpec.isJTI() || DispSpec.isSymbol());
324 printSymbolOperand(MI->getOperand(Op+3));
328 assert(IndexReg.getReg() != X86::ESP &&
329 "X86 doesn't allow scaling by ESP");
333 printOperand(MI, Op, Modifier);
335 if (IndexReg.getReg()) {
337 printOperand(MI, Op+2, Modifier);
338 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
340 O << ',' << ScaleVal;
346 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
347 const char *Modifier) {
348 assert(isMem(MI, Op) && "Invalid memory reference!");
349 const MachineOperand &Segment = MI->getOperand(Op+4);
350 if (Segment.getReg()) {
351 printOperand(MI, Op+4, Modifier);
354 printLeaMemReference(MI, Op, Modifier);
357 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
358 PrintPICBaseSymbol();
360 PrintPICBaseSymbol();
364 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
365 unsigned Reg = MO.getReg();
367 default: return true; // Unknown mode.
368 case 'b': // Print QImode register
369 Reg = getX86SubSuperRegister(Reg, MVT::i8);
371 case 'h': // Print QImode high register
372 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
374 case 'w': // Print HImode register
375 Reg = getX86SubSuperRegister(Reg, MVT::i16);
377 case 'k': // Print SImode register
378 Reg = getX86SubSuperRegister(Reg, MVT::i32);
380 case 'q': // Print DImode register
381 Reg = getX86SubSuperRegister(Reg, MVT::i64);
385 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
389 /// PrintAsmOperand - Print out an operand for an inline asm expression.
391 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
393 const char *ExtraCode) {
394 // Does this asm operand have a single letter operand modifier?
395 if (ExtraCode && ExtraCode[0]) {
396 if (ExtraCode[1] != 0) return true; // Unknown modifier.
398 const MachineOperand &MO = MI->getOperand(OpNo);
400 switch (ExtraCode[0]) {
401 default: return true; // Unknown modifier.
402 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
407 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
408 printSymbolOperand(MO);
413 printOperand(MI, OpNo);
419 case 'c': // Don't print "$" before a global var name or constant.
422 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
423 printSymbolOperand(MO);
425 printOperand(MI, OpNo);
428 case 'A': // Print '*' before a register (it must be a register)
431 printOperand(MI, OpNo);
436 case 'b': // Print QImode register
437 case 'h': // Print QImode high register
438 case 'w': // Print HImode register
439 case 'k': // Print SImode register
440 case 'q': // Print DImode register
442 return printAsmMRegister(MO, ExtraCode[0]);
443 printOperand(MI, OpNo);
446 case 'P': // This is the operand of a call, treat specially.
447 print_pcrel_imm(MI, OpNo);
450 case 'n': // Negate the immediate or print a '-' before the operand.
451 // Note: this is a temporary solution. It should be handled target
452 // independently as part of the 'MC' work.
461 printOperand(MI, OpNo);
465 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
466 unsigned OpNo, unsigned AsmVariant,
467 const char *ExtraCode) {
468 if (ExtraCode && ExtraCode[0]) {
469 if (ExtraCode[1] != 0) return true; // Unknown modifier.
471 switch (ExtraCode[0]) {
472 default: return true; // Unknown modifier.
473 case 'b': // Print QImode register
474 case 'h': // Print QImode high register
475 case 'w': // Print HImode register
476 case 'k': // Print SImode register
477 case 'q': // Print SImode register
478 // These only apply to registers, ignore on mem.
480 case 'P': // Don't print @PLT, but do print as memory.
481 printMemReference(MI, OpNo, "no-rip");
485 printMemReference(MI, OpNo);
490 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
491 if (Subtarget->isTargetDarwin()) {
492 // All darwin targets use mach-o.
493 TargetLoweringObjectFileMachO &TLOFMacho =
494 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
496 MachineModuleInfoMachO &MMIMacho =
497 MMI->getObjFileInfo<MachineModuleInfoMachO>();
499 // Output stubs for dynamically-linked functions.
500 MachineModuleInfoMachO::SymbolListTy Stubs;
502 Stubs = MMIMacho.GetFnStubList();
503 if (!Stubs.empty()) {
504 const MCSection *TheSection =
505 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
506 MCSectionMachO::S_SYMBOL_STUBS |
507 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
508 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
509 5, SectionKind::getMetadata());
510 OutStreamer.SwitchSection(TheSection);
512 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
513 O << *Stubs[i].first << ":\n";
514 // Get the MCSymbol without the $stub suffix.
515 O << "\t.indirect_symbol " << *Stubs[i].second;
516 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
523 // Output stubs for external and common global variables.
524 Stubs = MMIMacho.GetGVStubList();
525 if (!Stubs.empty()) {
526 const MCSection *TheSection =
527 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
528 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
529 SectionKind::getMetadata());
530 OutStreamer.SwitchSection(TheSection);
532 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
533 O << *Stubs[i].first << ":\n\t.indirect_symbol " << *Stubs[i].second;
534 O << "\n\t.long\t0\n";
539 Stubs = MMIMacho.GetHiddenGVStubList();
540 if (!Stubs.empty()) {
541 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
544 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
545 O << *Stubs[i].first << ":\n" << MAI->getData32bitsDirective();
546 O << *Stubs[i].second << '\n';
551 // Funny Darwin hack: This flag tells the linker that no global symbols
552 // contain code that falls through to other global symbols (e.g. the obvious
553 // implementation of multiple entry points). If this doesn't occur, the
554 // linker can safely perform dead code stripping. Since LLVM never
555 // generates code that does this, it is always safe to set.
556 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
559 if (Subtarget->isTargetCOFF()) {
560 X86COFFMachineModuleInfo &COFFMMI =
561 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
563 // Emit type information for external functions
564 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
565 E = COFFMMI.stub_end(); I != E; ++I) {
566 O << "\t.def\t " << I->getKeyData()
567 << ";\t.scl\t" << COFF::C_EXT
568 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
572 if (Subtarget->isTargetCygMing()) {
573 // Necessary for dllexport support
574 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
576 TargetLoweringObjectFileCOFF &TLOFCOFF =
577 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
579 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
580 if (I->hasDLLExportLinkage()) {
581 MCSymbol *Sym = GetGlobalValueSymbol(I);
582 COFFMMI.DecorateCygMingName(Sym, OutContext, I, *TM.getTargetData());
583 DLLExportedFns.push_back(Sym);
586 for (Module::const_global_iterator I = M.global_begin(),
587 E = M.global_end(); I != E; ++I)
588 if (I->hasDLLExportLinkage())
589 DLLExportedGlobals.push_back(GetGlobalValueSymbol(I));
591 // Output linker support code for dllexported globals on windows.
592 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
593 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
595 SectionKind::getMetadata()));
596 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
597 O << "\t.ascii \" -export:" << *DLLExportedGlobals[i] << ",data\"\n";
599 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
600 O << "\t.ascii \" -export:" << *DLLExportedFns[i] << "\"\n";
607 //===----------------------------------------------------------------------===//
608 // Target Registry Stuff
609 //===----------------------------------------------------------------------===//
611 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
612 unsigned SyntaxVariant,
613 const MCAsmInfo &MAI,
615 if (SyntaxVariant == 0)
616 return new X86ATTInstPrinter(O, MAI);
617 if (SyntaxVariant == 1)
618 return new X86IntelInstPrinter(O, MAI);
622 // Force static initialization.
623 extern "C" void LLVMInitializeX86AsmPrinter() {
624 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
625 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
627 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
628 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);