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/MCExpr.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegistry.h"
42 #include "llvm/ADT/SmallString.h"
45 //===----------------------------------------------------------------------===//
46 // Primitive Helper Functions.
47 //===----------------------------------------------------------------------===//
49 void X86AsmPrinter::PrintPICBaseSymbol() const {
50 const TargetLowering *TLI = TM.getTargetLowering();
51 O << *static_cast<const X86TargetLowering*>(TLI)->getPICBaseSymbol(MF,
55 /// runOnMachineFunction - Emit the function body.
57 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
58 SetupMachineFunction(MF);
60 // COFF and Cygwin specific mangling stuff. This should be moved out to the
61 // mangler or handled some other way?
62 if (Subtarget->isTargetCOFF()) {
63 X86COFFMachineModuleInfo &COFFMMI =
64 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
66 // Populate function information map. Don't want to populate
67 // non-stdcall or non-fastcall functions' information right now.
68 const Function *F = MF.getFunction();
69 CallingConv::ID CC = F->getCallingConv();
70 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
71 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
73 if (Subtarget->isTargetCygMing()) {
74 const Function *F = MF.getFunction();
75 X86COFFMachineModuleInfo &COFFMMI =
76 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
77 COFFMMI.DecorateCygMingName(CurrentFnSym, OutContext,F,*TM.getTargetData());
79 O << "\t.def\t " << *CurrentFnSym;
81 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
82 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
86 // Have common code print out the function header with linkage info etc.
89 // Emit the rest of the function body.
92 // We didn't modify anything.
96 /// printSymbolOperand - Print a raw symbol reference operand. This handles
97 /// jump tables, constant pools, global address and external symbols, all of
98 /// which print to a label with various suffixes for relocation types etc.
99 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
100 switch (MO.getType()) {
101 default: llvm_unreachable("unknown symbol type!");
102 case MachineOperand::MO_JumpTableIndex:
103 O << *GetJTISymbol(MO.getIndex());
105 case MachineOperand::MO_ConstantPoolIndex:
106 O << *GetCPISymbol(MO.getIndex());
107 printOffset(MO.getOffset());
109 case MachineOperand::MO_GlobalAddress: {
110 const GlobalValue *GV = MO.getGlobal();
113 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
114 GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
115 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
116 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
117 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
118 GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
120 GVSym = GetGlobalValueSymbol(GV);
122 if (Subtarget->isTargetCygMing()) {
123 X86COFFMachineModuleInfo &COFFMMI =
124 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
125 COFFMMI.DecorateCygMingName(GVSym, OutContext, GV, *TM.getTargetData());
128 // Handle dllimport linkage.
129 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
130 GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
132 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
133 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
134 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
137 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
139 StubSym = GetGlobalValueSymbol(GV);
141 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
142 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
144 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
146 StubSym = GetGlobalValueSymbol(GV);
147 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
148 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
150 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
152 StubSym = GetGlobalValueSymbol(GV);
155 // If the name begins with a dollar-sign, enclose it in parens. We do this
156 // to avoid having it look like an integer immediate to the assembler.
157 if (GVSym->getName()[0] != '$')
160 O << '(' << *GVSym << ')';
161 printOffset(MO.getOffset());
164 case MachineOperand::MO_ExternalSymbol: {
165 const MCSymbol *SymToPrint;
166 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
167 SmallString<128> TempNameStr;
168 TempNameStr += StringRef(MO.getSymbolName());
169 TempNameStr += StringRef("$stub");
171 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
173 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
175 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
176 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
178 SymToPrint = StubSym;
180 SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
183 // If the name begins with a dollar-sign, enclose it in parens. We do this
184 // to avoid having it look like an integer immediate to the assembler.
185 if (SymToPrint->getName()[0] != '$')
188 O << '(' << *SymToPrint << '(';
193 switch (MO.getTargetFlags()) {
195 llvm_unreachable("Unknown target flag on GV operand");
196 case X86II::MO_NO_FLAG: // No flag.
198 case X86II::MO_DARWIN_NONLAZY:
199 case X86II::MO_DLLIMPORT:
200 case X86II::MO_DARWIN_STUB:
201 // These affect the name of the symbol, not any suffix.
203 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
205 PrintPICBaseSymbol();
208 case X86II::MO_PIC_BASE_OFFSET:
209 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
210 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
212 PrintPICBaseSymbol();
214 case X86II::MO_TLSGD: O << "@TLSGD"; break;
215 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
216 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
217 case X86II::MO_TPOFF: O << "@TPOFF"; break;
218 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
219 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
220 case X86II::MO_GOT: O << "@GOT"; break;
221 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
222 case X86II::MO_PLT: O << "@PLT"; break;
226 /// print_pcrel_imm - This is used to print an immediate value that ends up
227 /// being encoded as a pc-relative value. These print slightly differently, for
228 /// example, a $ is not emitted.
229 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
230 const MachineOperand &MO = MI->getOperand(OpNo);
231 switch (MO.getType()) {
232 default: llvm_unreachable("Unknown pcrel immediate operand");
233 case MachineOperand::MO_Immediate:
236 case MachineOperand::MO_MachineBasicBlock:
237 O << *MO.getMBB()->getSymbol(OutContext);
239 case MachineOperand::MO_GlobalAddress:
240 case MachineOperand::MO_ExternalSymbol:
241 printSymbolOperand(MO);
247 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
248 const char *Modifier) {
249 const MachineOperand &MO = MI->getOperand(OpNo);
250 switch (MO.getType()) {
251 default: llvm_unreachable("unknown operand type!");
252 case MachineOperand::MO_Register: {
254 unsigned Reg = MO.getReg();
255 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
256 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
257 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
258 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
259 Reg = getX86SubSuperRegister(Reg, VT);
261 O << X86ATTInstPrinter::getRegisterName(Reg);
265 case MachineOperand::MO_Immediate:
266 O << '$' << MO.getImm();
269 case MachineOperand::MO_JumpTableIndex:
270 case MachineOperand::MO_ConstantPoolIndex:
271 case MachineOperand::MO_GlobalAddress:
272 case MachineOperand::MO_ExternalSymbol: {
274 printSymbolOperand(MO);
280 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
281 unsigned char value = MI->getOperand(Op).getImm();
282 assert(value <= 7 && "Invalid ssecc argument!");
284 case 0: O << "eq"; break;
285 case 1: O << "lt"; break;
286 case 2: O << "le"; break;
287 case 3: O << "unord"; break;
288 case 4: O << "neq"; break;
289 case 5: O << "nlt"; break;
290 case 6: O << "nle"; break;
291 case 7: O << "ord"; break;
295 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
296 const char *Modifier) {
297 const MachineOperand &BaseReg = MI->getOperand(Op);
298 const MachineOperand &IndexReg = MI->getOperand(Op+2);
299 const MachineOperand &DispSpec = MI->getOperand(Op+3);
301 // If we really don't want to print out (rip), don't.
302 bool HasBaseReg = BaseReg.getReg() != 0;
303 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
304 BaseReg.getReg() == X86::RIP)
307 // HasParenPart - True if we will print out the () part of the mem ref.
308 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
310 if (DispSpec.isImm()) {
311 int DispVal = DispSpec.getImm();
312 if (DispVal || !HasParenPart)
315 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
316 DispSpec.isJTI() || DispSpec.isSymbol());
317 printSymbolOperand(MI->getOperand(Op+3));
321 assert(IndexReg.getReg() != X86::ESP &&
322 "X86 doesn't allow scaling by ESP");
326 printOperand(MI, Op, Modifier);
328 if (IndexReg.getReg()) {
330 printOperand(MI, Op+2, Modifier);
331 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
333 O << ',' << ScaleVal;
339 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
340 const char *Modifier) {
341 assert(isMem(MI, Op) && "Invalid memory reference!");
342 const MachineOperand &Segment = MI->getOperand(Op+4);
343 if (Segment.getReg()) {
344 printOperand(MI, Op+4, Modifier);
347 printLeaMemReference(MI, Op, Modifier);
350 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
351 PrintPICBaseSymbol();
353 PrintPICBaseSymbol();
357 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
358 unsigned Reg = MO.getReg();
360 default: return true; // Unknown mode.
361 case 'b': // Print QImode register
362 Reg = getX86SubSuperRegister(Reg, MVT::i8);
364 case 'h': // Print QImode high register
365 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
367 case 'w': // Print HImode register
368 Reg = getX86SubSuperRegister(Reg, MVT::i16);
370 case 'k': // Print SImode register
371 Reg = getX86SubSuperRegister(Reg, MVT::i32);
373 case 'q': // Print DImode register
374 Reg = getX86SubSuperRegister(Reg, MVT::i64);
378 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
382 /// PrintAsmOperand - Print out an operand for an inline asm expression.
384 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
386 const char *ExtraCode) {
387 // Does this asm operand have a single letter operand modifier?
388 if (ExtraCode && ExtraCode[0]) {
389 if (ExtraCode[1] != 0) return true; // Unknown modifier.
391 const MachineOperand &MO = MI->getOperand(OpNo);
393 switch (ExtraCode[0]) {
394 default: return true; // Unknown modifier.
395 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
400 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
401 printSymbolOperand(MO);
406 printOperand(MI, OpNo);
412 case 'c': // Don't print "$" before a global var name or constant.
415 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
416 printSymbolOperand(MO);
418 printOperand(MI, OpNo);
421 case 'A': // Print '*' before a register (it must be a register)
424 printOperand(MI, OpNo);
429 case 'b': // Print QImode register
430 case 'h': // Print QImode high register
431 case 'w': // Print HImode register
432 case 'k': // Print SImode register
433 case 'q': // Print DImode register
435 return printAsmMRegister(MO, ExtraCode[0]);
436 printOperand(MI, OpNo);
439 case 'P': // This is the operand of a call, treat specially.
440 print_pcrel_imm(MI, OpNo);
443 case 'n': // Negate the immediate or print a '-' before the operand.
444 // Note: this is a temporary solution. It should be handled target
445 // independently as part of the 'MC' work.
454 printOperand(MI, OpNo);
458 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
459 unsigned OpNo, unsigned AsmVariant,
460 const char *ExtraCode) {
461 if (ExtraCode && ExtraCode[0]) {
462 if (ExtraCode[1] != 0) return true; // Unknown modifier.
464 switch (ExtraCode[0]) {
465 default: return true; // Unknown modifier.
466 case 'b': // Print QImode register
467 case 'h': // Print QImode high register
468 case 'w': // Print HImode register
469 case 'k': // Print SImode register
470 case 'q': // Print SImode register
471 // These only apply to registers, ignore on mem.
473 case 'P': // Don't print @PLT, but do print as memory.
474 printMemReference(MI, OpNo, "no-rip");
478 printMemReference(MI, OpNo);
483 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
484 if (Subtarget->isTargetDarwin()) {
485 // All darwin targets use mach-o.
486 TargetLoweringObjectFileMachO &TLOFMacho =
487 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
489 MachineModuleInfoMachO &MMIMacho =
490 MMI->getObjFileInfo<MachineModuleInfoMachO>();
492 // Output stubs for dynamically-linked functions.
493 MachineModuleInfoMachO::SymbolListTy Stubs;
495 Stubs = MMIMacho.GetFnStubList();
496 if (!Stubs.empty()) {
497 const MCSection *TheSection =
498 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
499 MCSectionMachO::S_SYMBOL_STUBS |
500 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
501 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
502 5, SectionKind::getMetadata());
503 OutStreamer.SwitchSection(TheSection);
505 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
507 OutStreamer.EmitLabel(Stubs[i].first);
508 // .indirect_symbol _foo
509 OutStreamer.EmitSymbolAttribute(Stubs[i].second, MCSA_IndirectSymbol);
510 // hlt; hlt; hlt; hlt; hlt hlt = 0xf4 = -12.
511 const char HltInsts[] = { -12, -12, -12, -12, -12 };
512 OutStreamer.EmitBytes(StringRef(HltInsts, 5), 0/*addrspace*/);
516 OutStreamer.AddBlankLine();
519 // Output stubs for external and common global variables.
520 Stubs = MMIMacho.GetGVStubList();
521 if (!Stubs.empty()) {
522 const MCSection *TheSection =
523 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
524 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
525 SectionKind::getMetadata());
526 OutStreamer.SwitchSection(TheSection);
528 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
529 // L_foo$non_lazy_ptr:
530 OutStreamer.EmitLabel(Stubs[i].first);
531 // .indirect_symbol _foo
532 OutStreamer.EmitSymbolAttribute(Stubs[i].second, MCSA_IndirectSymbol);
534 OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
537 OutStreamer.AddBlankLine();
540 Stubs = MMIMacho.GetHiddenGVStubList();
541 if (!Stubs.empty()) {
542 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
545 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
546 // L_foo$non_lazy_ptr:
547 OutStreamer.EmitLabel(Stubs[i].first);
549 OutStreamer.EmitValue(MCSymbolRefExpr::Create(Stubs[i].second,
551 4/*size*/, 0/*addrspace*/);
554 OutStreamer.AddBlankLine();
557 // Funny Darwin hack: This flag tells the linker that no global symbols
558 // contain code that falls through to other global symbols (e.g. the obvious
559 // implementation of multiple entry points). If this doesn't occur, the
560 // linker can safely perform dead code stripping. Since LLVM never
561 // generates code that does this, it is always safe to set.
562 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
565 if (Subtarget->isTargetCOFF()) {
566 X86COFFMachineModuleInfo &COFFMMI =
567 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
569 // Emit type information for external functions
570 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
571 E = COFFMMI.stub_end(); I != E; ++I) {
572 O << "\t.def\t " << I->getKeyData()
573 << ";\t.scl\t" << COFF::C_EXT
574 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
578 if (Subtarget->isTargetCygMing()) {
579 // Necessary for dllexport support
580 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
582 TargetLoweringObjectFileCOFF &TLOFCOFF =
583 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
585 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
586 if (I->hasDLLExportLinkage()) {
587 MCSymbol *Sym = GetGlobalValueSymbol(I);
588 COFFMMI.DecorateCygMingName(Sym, OutContext, I, *TM.getTargetData());
589 DLLExportedFns.push_back(Sym);
592 for (Module::const_global_iterator I = M.global_begin(),
593 E = M.global_end(); I != E; ++I)
594 if (I->hasDLLExportLinkage())
595 DLLExportedGlobals.push_back(GetGlobalValueSymbol(I));
597 // Output linker support code for dllexported globals on windows.
598 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
599 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
601 SectionKind::getMetadata()));
602 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
603 O << "\t.ascii \" -export:" << *DLLExportedGlobals[i] << ",data\"\n";
605 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
606 O << "\t.ascii \" -export:" << *DLLExportedFns[i] << "\"\n";
613 //===----------------------------------------------------------------------===//
614 // Target Registry Stuff
615 //===----------------------------------------------------------------------===//
617 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
618 unsigned SyntaxVariant,
619 const MCAsmInfo &MAI,
621 if (SyntaxVariant == 0)
622 return new X86ATTInstPrinter(O, MAI);
623 if (SyntaxVariant == 1)
624 return new X86IntelInstPrinter(O, MAI);
628 // Force static initialization.
629 extern "C" void LLVMInitializeX86AsmPrinter() {
630 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
631 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
633 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
634 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);