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 "X86MCAsmInfo.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/Assembly/Writer.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/CodeGen/DwarfWriter.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
45 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
50 //===----------------------------------------------------------------------===//
51 // Primitive Helper Functions.
52 //===----------------------------------------------------------------------===//
54 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
55 // FIXME: the actual label generated doesn't matter here! Just mangle in
56 // something unique (the function number) with Private prefix.
57 if (Subtarget->isTargetDarwin())
58 O << "\"L" << getFunctionNumber() << "$pb\"";
60 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
61 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
65 MCSymbol *X86ATTAsmPrinter::GetPICBaseSymbol() {
66 // FIXME: the actual label generated doesn't matter here! Just mangle in
67 // something unique (the function number) with Private prefix.
70 if (Subtarget->isTargetDarwin()) {
71 Name = "L" + utostr(getFunctionNumber())+"$pb";
73 assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
74 Name = ".Lllvm$" + utostr(getFunctionNumber())+".$piclabel";
76 return OutContext.GetOrCreateSymbol(Name);
79 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
80 const TargetData *TD) {
81 X86MachineFunctionInfo Info;
84 switch (F->getCallingConv()) {
85 case CallingConv::X86_StdCall:
86 Info.setDecorationStyle(StdCall);
88 case CallingConv::X86_FastCall:
89 Info.setDecorationStyle(FastCall);
96 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
97 AI != AE; ++AI, ++argNum) {
98 const Type* Ty = AI->getType();
100 // 'Dereference' type in case of byval parameter attribute
101 if (F->paramHasAttr(argNum, Attribute::ByVal))
102 Ty = cast<PointerType>(Ty)->getElementType();
104 // Size should be aligned to DWORD boundary
105 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
108 // We're not supporting tooooo huge arguments :)
109 Info.setBytesToPopOnReturn((unsigned int)Size);
113 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
114 /// various name decorations for Cygwin and MingW.
115 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
116 const GlobalValue *GV) {
117 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
119 const Function *F = dyn_cast<Function>(GV);
122 // Save function name for later type emission.
123 if (F->isDeclaration())
124 CygMingStubs.insert(Name);
126 // We don't want to decorate non-stdcall or non-fastcall functions right now
127 unsigned CC = F->getCallingConv();
128 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
132 const X86MachineFunctionInfo *Info;
134 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
135 if (info_item == FunctionInfoMap.end()) {
136 // Calculate apropriate function info and populate map
137 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
138 Info = &FunctionInfoMap[F];
140 Info = &info_item->second;
143 const FunctionType *FT = F->getFunctionType();
144 switch (Info->getDecorationStyle()) {
148 // "Pure" variadic functions do not receive @0 suffix.
149 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
150 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
151 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
154 // "Pure" variadic functions do not receive @0 suffix.
155 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
156 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
157 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
159 if (Name[0] == '_') {
166 llvm_unreachable("Unsupported DecorationStyle");
170 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
171 unsigned FnAlign = MF.getAlignment();
172 const Function *F = MF.getFunction();
174 if (Subtarget->isTargetCygMing())
175 DecorateCygMingName(CurrentFnName, F);
177 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
178 EmitAlignment(FnAlign, F);
180 switch (F->getLinkage()) {
181 default: llvm_unreachable("Unknown linkage type!");
182 case Function::InternalLinkage: // Symbols default to internal.
183 case Function::PrivateLinkage:
185 case Function::DLLExportLinkage:
186 case Function::ExternalLinkage:
187 O << "\t.globl\t" << CurrentFnName << '\n';
189 case Function::LinkerPrivateLinkage:
190 case Function::LinkOnceAnyLinkage:
191 case Function::LinkOnceODRLinkage:
192 case Function::WeakAnyLinkage:
193 case Function::WeakODRLinkage:
194 if (Subtarget->isTargetDarwin()) {
195 O << "\t.globl\t" << CurrentFnName << '\n';
196 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
197 } else if (Subtarget->isTargetCygMing()) {
198 O << "\t.globl\t" << CurrentFnName << "\n"
199 "\t.linkonce discard\n";
201 O << "\t.weak\t" << CurrentFnName << '\n';
206 printVisibility(CurrentFnName, F->getVisibility());
208 if (Subtarget->isTargetELF())
209 O << "\t.type\t" << CurrentFnName << ",@function\n";
210 else if (Subtarget->isTargetCygMing()) {
211 O << "\t.def\t " << CurrentFnName
213 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
214 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
218 O << CurrentFnName << ':';
220 O.PadToColumn(MAI->getCommentColumn());
221 O << MAI->getCommentString() << ' ';
222 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
226 // Add some workaround for linkonce linkage on Cygwin\MinGW
227 if (Subtarget->isTargetCygMing() &&
228 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
229 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
232 /// runOnMachineFunction - This uses the printMachineInstruction()
233 /// method to print assembly for each instruction.
235 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
236 const Function *F = MF.getFunction();
238 unsigned CC = F->getCallingConv();
240 SetupMachineFunction(MF);
243 // Populate function information map. Actually, We don't want to populate
244 // non-stdcall or non-fastcall functions' information right now.
245 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
246 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
248 // Print out constants referenced by the function
249 EmitConstantPool(MF.getConstantPool());
251 if (F->hasDLLExportLinkage())
252 DLLExportedFns.insert(Mang->getMangledName(F));
254 // Print the 'header' of function
255 emitFunctionHeader(MF);
257 // Emit pre-function debug and/or EH information.
258 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
259 DW->BeginFunction(&MF);
261 // Print out code for the function.
262 bool hasAnyRealCode = false;
263 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
265 // Print a label for the basic block.
266 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
267 // This is an entry block or a block that's only reachable via a
268 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
270 printBasicBlockLabel(I, true, true, VerboseAsm);
273 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
275 // Print the assembly for the instruction.
277 hasAnyRealCode = true;
278 printMachineInstruction(II);
282 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
283 // If the function is empty, then we need to emit *something*. Otherwise,
284 // the function's label might be associated with something that it wasn't
285 // meant to be associated with. We emit a noop in this situation.
286 // We are assuming inline asms are code.
290 if (MAI->hasDotTypeDotSizeDirective())
291 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
293 // Emit post-function debug information.
294 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
295 DW->EndFunction(&MF);
297 // Print out jump tables referenced by the function.
298 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
300 // We didn't modify anything.
304 /// printSymbolOperand - Print a raw symbol reference operand. This handles
305 /// jump tables, constant pools, global address and external symbols, all of
306 /// which print to a label with various suffixes for relocation types etc.
307 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
308 switch (MO.getType()) {
309 default: llvm_unreachable("unknown symbol type!");
310 case MachineOperand::MO_JumpTableIndex:
311 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
314 case MachineOperand::MO_ConstantPoolIndex:
315 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
317 printOffset(MO.getOffset());
319 case MachineOperand::MO_GlobalAddress: {
320 const GlobalValue *GV = MO.getGlobal();
322 const char *Suffix = "";
323 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
325 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
326 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
327 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
328 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
329 Suffix = "$non_lazy_ptr";
331 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
332 if (Subtarget->isTargetCygMing())
333 DecorateCygMingName(Name, GV);
335 // Handle dllimport linkage.
336 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
337 Name = "__imp_" + Name;
339 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
340 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
341 GVStubs[Name] = Mang->getMangledName(GV);
342 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
343 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
344 HiddenGVStubs[Name] = Mang->getMangledName(GV);
345 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
346 FnStubs[Name] = Mang->getMangledName(GV);
348 // If the name begins with a dollar-sign, enclose it in parens. We do this
349 // to avoid having it look like an integer immediate to the assembler.
351 O << '(' << Name << ')';
355 printOffset(MO.getOffset());
358 case MachineOperand::MO_ExternalSymbol: {
359 std::string Name = Mang->makeNameProper(MO.getSymbolName());
360 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
361 FnStubs[Name+"$stub"] = Name;
365 // If the name begins with a dollar-sign, enclose it in parens. We do this
366 // to avoid having it look like an integer immediate to the assembler.
368 O << '(' << Name << ')';
375 switch (MO.getTargetFlags()) {
377 llvm_unreachable("Unknown target flag on GV operand");
378 case X86II::MO_NO_FLAG: // No flag.
380 case X86II::MO_DARWIN_NONLAZY:
381 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
382 case X86II::MO_DLLIMPORT:
383 case X86II::MO_DARWIN_STUB:
384 // These affect the name of the symbol, not any suffix.
386 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
388 PrintPICBaseSymbol();
391 case X86II::MO_PIC_BASE_OFFSET:
392 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
393 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
395 PrintPICBaseSymbol();
397 case X86II::MO_TLSGD: O << "@TLSGD"; break;
398 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
399 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
400 case X86II::MO_TPOFF: O << "@TPOFF"; break;
401 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
402 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
403 case X86II::MO_GOT: O << "@GOT"; break;
404 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
405 case X86II::MO_PLT: O << "@PLT"; break;
409 /// print_pcrel_imm - This is used to print an immediate value that ends up
410 /// being encoded as a pc-relative value. These print slightly differently, for
411 /// example, a $ is not emitted.
412 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
413 const MachineOperand &MO = MI->getOperand(OpNo);
414 switch (MO.getType()) {
415 default: llvm_unreachable("Unknown pcrel immediate operand");
416 case MachineOperand::MO_Immediate:
419 case MachineOperand::MO_MachineBasicBlock:
420 printBasicBlockLabel(MO.getMBB(), false, false, false);
422 case MachineOperand::MO_GlobalAddress:
423 case MachineOperand::MO_ExternalSymbol:
424 printSymbolOperand(MO);
431 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
432 const char *Modifier) {
433 const MachineOperand &MO = MI->getOperand(OpNo);
434 switch (MO.getType()) {
435 default: llvm_unreachable("unknown operand type!");
436 case MachineOperand::MO_Register: {
437 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
438 "Virtual registers should not make it this far!");
440 unsigned Reg = MO.getReg();
441 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
442 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
443 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
444 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
445 Reg = getX86SubSuperRegister(Reg, VT);
447 O << TRI->getAsmName(Reg);
451 case MachineOperand::MO_Immediate:
452 O << '$' << MO.getImm();
455 case MachineOperand::MO_JumpTableIndex:
456 case MachineOperand::MO_ConstantPoolIndex:
457 case MachineOperand::MO_GlobalAddress:
458 case MachineOperand::MO_ExternalSymbol: {
460 printSymbolOperand(MO);
466 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
467 unsigned char value = MI->getOperand(Op).getImm();
468 assert(value <= 7 && "Invalid ssecc argument!");
470 case 0: O << "eq"; break;
471 case 1: O << "lt"; break;
472 case 2: O << "le"; break;
473 case 3: O << "unord"; break;
474 case 4: O << "neq"; break;
475 case 5: O << "nlt"; break;
476 case 6: O << "nle"; break;
477 case 7: O << "ord"; break;
481 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
482 const char *Modifier) {
483 const MachineOperand &BaseReg = MI->getOperand(Op);
484 const MachineOperand &IndexReg = MI->getOperand(Op+2);
485 const MachineOperand &DispSpec = MI->getOperand(Op+3);
487 // If we really don't want to print out (rip), don't.
488 bool HasBaseReg = BaseReg.getReg() != 0;
489 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
490 BaseReg.getReg() == X86::RIP)
493 // HasParenPart - True if we will print out the () part of the mem ref.
494 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
496 if (DispSpec.isImm()) {
497 int DispVal = DispSpec.getImm();
498 if (DispVal || !HasParenPart)
501 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
502 DispSpec.isJTI() || DispSpec.isSymbol());
503 printSymbolOperand(MI->getOperand(Op+3));
507 assert(IndexReg.getReg() != X86::ESP &&
508 "X86 doesn't allow scaling by ESP");
512 printOperand(MI, Op, Modifier);
514 if (IndexReg.getReg()) {
516 printOperand(MI, Op+2, Modifier);
517 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
519 O << ',' << ScaleVal;
525 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
526 const char *Modifier) {
527 assert(isMem(MI, Op) && "Invalid memory reference!");
528 const MachineOperand &Segment = MI->getOperand(Op+4);
529 if (Segment.getReg()) {
530 printOperand(MI, Op+4, Modifier);
533 printLeaMemReference(MI, Op, Modifier);
536 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
537 const MachineBasicBlock *MBB) const {
538 if (!MAI->getSetDirective())
541 // We don't need .set machinery if we have GOT-style relocations
542 if (Subtarget->isPICStyleGOT())
545 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
546 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
547 printBasicBlockLabel(MBB, false, false, false);
548 if (Subtarget->isPICStyleRIPRel())
549 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
550 << '_' << uid << '\n';
553 PrintPICBaseSymbol();
559 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
560 PrintPICBaseSymbol();
562 PrintPICBaseSymbol();
567 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
568 const MachineBasicBlock *MBB,
569 unsigned uid) const {
570 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
571 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
573 O << JTEntryDirective << ' ';
575 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
576 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
577 << '_' << uid << "_set_" << MBB->getNumber();
578 } else if (Subtarget->isPICStyleGOT()) {
579 printBasicBlockLabel(MBB, false, false, false);
582 printBasicBlockLabel(MBB, false, false, false);
585 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
586 unsigned Reg = MO.getReg();
588 default: return true; // Unknown mode.
589 case 'b': // Print QImode register
590 Reg = getX86SubSuperRegister(Reg, MVT::i8);
592 case 'h': // Print QImode high register
593 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
595 case 'w': // Print HImode register
596 Reg = getX86SubSuperRegister(Reg, MVT::i16);
598 case 'k': // Print SImode register
599 Reg = getX86SubSuperRegister(Reg, MVT::i32);
601 case 'q': // Print DImode register
602 Reg = getX86SubSuperRegister(Reg, MVT::i64);
606 O << '%'<< TRI->getAsmName(Reg);
610 /// PrintAsmOperand - Print out an operand for an inline asm expression.
612 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
614 const char *ExtraCode) {
615 // Does this asm operand have a single letter operand modifier?
616 if (ExtraCode && ExtraCode[0]) {
617 if (ExtraCode[1] != 0) return true; // Unknown modifier.
619 const MachineOperand &MO = MI->getOperand(OpNo);
621 switch (ExtraCode[0]) {
622 default: return true; // Unknown modifier.
623 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
628 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
629 printSymbolOperand(MO);
634 printOperand(MI, OpNo);
640 case 'c': // Don't print "$" before a global var name or constant.
643 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
644 printSymbolOperand(MO);
646 printOperand(MI, OpNo);
649 case 'A': // Print '*' before a register (it must be a register)
652 printOperand(MI, OpNo);
657 case 'b': // Print QImode register
658 case 'h': // Print QImode high register
659 case 'w': // Print HImode register
660 case 'k': // Print SImode register
661 case 'q': // Print DImode register
663 return printAsmMRegister(MO, ExtraCode[0]);
664 printOperand(MI, OpNo);
667 case 'P': // This is the operand of a call, treat specially.
668 print_pcrel_imm(MI, OpNo);
671 case 'n': // Negate the immediate or print a '-' before the operand.
672 // Note: this is a temporary solution. It should be handled target
673 // independently as part of the 'MC' work.
682 printOperand(MI, OpNo);
686 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
689 const char *ExtraCode) {
690 if (ExtraCode && ExtraCode[0]) {
691 if (ExtraCode[1] != 0) return true; // Unknown modifier.
693 switch (ExtraCode[0]) {
694 default: return true; // Unknown modifier.
695 case 'b': // Print QImode register
696 case 'h': // Print QImode high register
697 case 'w': // Print HImode register
698 case 'k': // Print SImode register
699 case 'q': // Print SImode register
700 // These only apply to registers, ignore on mem.
702 case 'P': // Don't print @PLT, but do print as memory.
703 printMemReference(MI, OpNo, "no-rip");
707 printMemReference(MI, OpNo);
711 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
712 // Convert registers in the addr mode according to subreg64.
713 for (unsigned i = 0; i != 4; ++i) {
714 if (!MI->getOperand(i).isReg()) continue;
716 unsigned Reg = MI->getOperand(i).getReg();
717 if (Reg == 0) continue;
719 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
723 /// LowerGlobalAddressOperand - Lower an MO_GlobalAddress operand to an
725 MCOperand X86ATTAsmPrinter::LowerGlobalAddressOperand(const MachineOperand &MO){
726 const GlobalValue *GV = MO.getGlobal();
728 const char *Suffix = "";
729 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
731 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
732 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
733 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
734 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
735 Suffix = "$non_lazy_ptr";
737 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
738 if (Subtarget->isTargetCygMing())
739 DecorateCygMingName(Name, GV);
741 // Handle dllimport linkage.
742 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
743 Name = "__imp_" + Name;
745 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
746 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
747 GVStubs[Name] = Mang->getMangledName(GV);
748 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
749 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
750 HiddenGVStubs[Name] = Mang->getMangledName(GV);
751 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
752 FnStubs[Name] = Mang->getMangledName(GV);
755 // Handle target operand flags.
756 // FIXME: This should be common between external symbols, constant pool etc.
757 MCSymbol *NegatedSymbol = 0;
759 switch (MO.getTargetFlags()) {
761 llvm_unreachable("Unknown target flag on GV operand");
762 case X86II::MO_NO_FLAG: // No flag.
764 case X86II::MO_DARWIN_NONLAZY:
765 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
766 case X86II::MO_DLLIMPORT:
767 case X86II::MO_DARWIN_STUB:
768 // These affect the name of the symbol, not any suffix.
770 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
771 assert(0 && "Reloc mode unimp!");
773 //PrintPICBaseSymbol();
776 case X86II::MO_PIC_BASE_OFFSET:
777 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
778 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
779 // Subtract the pic base.
780 NegatedSymbol = GetPICBaseSymbol();
783 // FIXME: These probably should be a modifier on the symbol or something??
784 case X86II::MO_TLSGD: Name += "@TLSGD"; break;
785 case X86II::MO_GOTTPOFF: Name += "@GOTTPOFF"; break;
786 case X86II::MO_INDNTPOFF: Name += "@INDNTPOFF"; break;
787 case X86II::MO_TPOFF: Name += "@TPOFF"; break;
788 case X86II::MO_NTPOFF: Name += "@NTPOFF"; break;
789 case X86II::MO_GOTPCREL: Name += "@GOTPCREL"; break;
790 case X86II::MO_GOT: Name += "@GOT"; break;
791 case X86II::MO_GOTOFF: Name += "@GOTOFF"; break;
792 case X86II::MO_PLT: Name += "@PLT"; break;
795 // Create a symbol for the name.
796 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
797 return MCOperand::CreateMCValue(MCValue::get(Sym, NegatedSymbol,
801 MCOperand X86ATTAsmPrinter::
802 LowerExternalSymbolOperand(const MachineOperand &MO){
803 std::string Name = Mang->makeNameProper(MO.getSymbolName());
804 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
805 FnStubs[Name+"$stub"] = Name;
809 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
810 return MCOperand::CreateMCValue(MCValue::get(Sym, 0, MO.getOffset()));
814 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
815 /// AT&T syntax to the current output stream.
817 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
820 if (!NewAsmPrinter) {
821 // Call the autogenerated instruction printer routines.
822 printInstruction(MI);
828 switch (MI->getOpcode()) {
829 case TargetInstrInfo::DBG_LABEL:
830 case TargetInstrInfo::EH_LABEL:
831 case TargetInstrInfo::GC_LABEL:
834 case TargetInstrInfo::INLINEASM:
838 case TargetInstrInfo::IMPLICIT_DEF:
839 printImplicitDef(MI);
841 case X86::MOVPC32r: {
842 // This is a pseudo op for a two instruction sequence with a label, which
849 MCSymbol *PICBase = GetPICBaseSymbol();
850 TmpInst.setOpcode(X86::CALLpcrel32);
851 TmpInst.addOperand(MCOperand::CreateMCValue(MCValue::get(PICBase)));
852 printInstruction(&TmpInst);
855 OutStreamer.EmitLabel(PICBase);
858 TmpInst.setOpcode(X86::POP32r);
859 TmpInst.getOperand(0) = MCOperand::CreateReg(MI->getOperand(0).getReg());
860 printInstruction(&TmpInst);
862 // Call the autogenerated instruction printer routines.
863 printInstruction(MI);
870 TmpInst.setOpcode(MI->getOpcode());
872 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
873 const MachineOperand &MO = MI->getOperand(i);
876 switch (MO.getType()) {
879 errs() << "Cannot lower operand #" << i << " of :" << *MI;
880 llvm_unreachable("Unimp");
881 case MachineOperand::MO_Register:
882 MCOp = MCOperand::CreateReg(MO.getReg());
884 case MachineOperand::MO_Immediate:
885 MCOp = MCOperand::CreateImm(MO.getImm());
887 case MachineOperand::MO_MachineBasicBlock:
888 MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(),
889 MO.getMBB()->getNumber());
891 case MachineOperand::MO_GlobalAddress:
892 MCOp = LowerGlobalAddressOperand(MO);
894 case MachineOperand::MO_ExternalSymbol:
895 MCOp = LowerExternalSymbolOperand(MO);
899 TmpInst.addOperand(MCOp);
902 switch (TmpInst.getOpcode()) {
904 // Handle the 'subreg rewriting' for the lea64_32mem operand.
905 lower_lea64_32mem(&TmpInst, 1);
909 // FIXME: Convert TmpInst.
910 printInstruction(&TmpInst);
913 // Call the autogenerated instruction printer routines.
914 printInstruction(MI);
917 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
918 const TargetData *TD = TM.getTargetData();
920 if (!GVar->hasInitializer())
921 return; // External global require no code
923 // Check to see if this is a special global used by LLVM, if so, emit it.
924 if (EmitSpecialLLVMGlobal(GVar)) {
925 if (Subtarget->isTargetDarwin() &&
926 TM.getRelocationModel() == Reloc::Static) {
927 if (GVar->getName() == "llvm.global_ctors")
928 O << ".reference .constructors_used\n";
929 else if (GVar->getName() == "llvm.global_dtors")
930 O << ".reference .destructors_used\n";
935 std::string name = Mang->getMangledName(GVar);
936 Constant *C = GVar->getInitializer();
937 const Type *Type = C->getType();
938 unsigned Size = TD->getTypeAllocSize(Type);
939 unsigned Align = TD->getPreferredAlignmentLog(GVar);
941 printVisibility(name, GVar->getVisibility());
943 if (Subtarget->isTargetELF())
944 O << "\t.type\t" << name << ",@object\n";
947 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
948 const MCSection *TheSection =
949 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
950 OutStreamer.SwitchSection(TheSection);
952 // FIXME: get this stuff from section kind flags.
953 if (C->isNullValue() && !GVar->hasSection() &&
954 // Don't put things that should go in the cstring section into "comm".
955 !TheSection->getKind().isMergeableCString()) {
956 if (GVar->hasExternalLinkage()) {
957 if (const char *Directive = MAI->getZeroFillDirective()) {
958 O << "\t.globl " << name << '\n';
959 O << Directive << "__DATA, __common, " << name << ", "
960 << Size << ", " << Align << '\n';
965 if (!GVar->isThreadLocal() &&
966 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
967 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
969 if (MAI->getLCOMMDirective() != NULL) {
970 if (GVar->hasLocalLinkage()) {
971 O << MAI->getLCOMMDirective() << name << ',' << Size;
972 if (Subtarget->isTargetDarwin())
974 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
975 O << "\t.globl " << name << '\n'
976 << MAI->getWeakDefDirective() << name << '\n';
977 EmitAlignment(Align, GVar);
980 O.PadToColumn(MAI->getCommentColumn());
981 O << MAI->getCommentString() << ' ';
982 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
985 EmitGlobalConstant(C);
988 O << MAI->getCOMMDirective() << name << ',' << Size;
989 if (MAI->getCOMMDirectiveTakesAlignment())
990 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
993 if (!Subtarget->isTargetCygMing()) {
994 if (GVar->hasLocalLinkage())
995 O << "\t.local\t" << name << '\n';
997 O << MAI->getCOMMDirective() << name << ',' << Size;
998 if (MAI->getCOMMDirectiveTakesAlignment())
999 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1002 O.PadToColumn(MAI->getCommentColumn());
1003 O << MAI->getCommentString() << ' ';
1004 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1011 switch (GVar->getLinkage()) {
1012 case GlobalValue::CommonLinkage:
1013 case GlobalValue::LinkOnceAnyLinkage:
1014 case GlobalValue::LinkOnceODRLinkage:
1015 case GlobalValue::WeakAnyLinkage:
1016 case GlobalValue::WeakODRLinkage:
1017 case GlobalValue::LinkerPrivateLinkage:
1018 if (Subtarget->isTargetDarwin()) {
1019 O << "\t.globl " << name << '\n'
1020 << MAI->getWeakDefDirective() << name << '\n';
1021 } else if (Subtarget->isTargetCygMing()) {
1022 O << "\t.globl\t" << name << "\n"
1023 "\t.linkonce same_size\n";
1025 O << "\t.weak\t" << name << '\n';
1028 case GlobalValue::DLLExportLinkage:
1029 case GlobalValue::AppendingLinkage:
1030 // FIXME: appending linkage variables should go into a section of
1031 // their name or something. For now, just emit them as external.
1032 case GlobalValue::ExternalLinkage:
1033 // If external or appending, declare as a global symbol
1034 O << "\t.globl " << name << '\n';
1036 case GlobalValue::PrivateLinkage:
1037 case GlobalValue::InternalLinkage:
1040 llvm_unreachable("Unknown linkage type!");
1043 EmitAlignment(Align, GVar);
1046 O.PadToColumn(MAI->getCommentColumn());
1047 O << MAI->getCommentString() << ' ';
1048 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1052 EmitGlobalConstant(C);
1054 if (MAI->hasDotTypeDotSizeDirective())
1055 O << "\t.size\t" << name << ", " << Size << '\n';
1058 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1059 // Print out module-level global variables here.
1060 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1062 if (I->hasDLLExportLinkage())
1063 DLLExportedGVs.insert(Mang->getMangledName(I));
1066 if (Subtarget->isTargetDarwin()) {
1067 // All darwin targets use mach-o.
1068 TargetLoweringObjectFileMachO &TLOFMacho =
1069 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1071 // Add the (possibly multiple) personalities to the set of global value
1072 // stubs. Only referenced functions get into the Personalities list.
1073 if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1074 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1075 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1076 if (Personalities[i])
1077 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
1078 true /*private label*/)] =
1079 Mang->getMangledName(Personalities[i]);
1083 // Output stubs for dynamically-linked functions
1084 if (!FnStubs.empty()) {
1085 const MCSection *TheSection =
1086 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
1087 MCSectionMachO::S_SYMBOL_STUBS |
1088 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
1089 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1090 5, SectionKind::getMetadata());
1091 OutStreamer.SwitchSection(TheSection);
1092 for (StringMap<std::string>::iterator I = FnStubs.begin(),
1093 E = FnStubs.end(); I != E; ++I)
1094 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
1095 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
1099 // Output stubs for external and common global variables.
1100 if (!GVStubs.empty()) {
1101 const MCSection *TheSection =
1102 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
1103 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
1104 SectionKind::getMetadata());
1105 OutStreamer.SwitchSection(TheSection);
1106 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1107 E = GVStubs.end(); I != E; ++I)
1108 O << I->getKeyData() << ":\n\t.indirect_symbol "
1109 << I->second << "\n\t.long\t0\n";
1112 if (!HiddenGVStubs.empty()) {
1113 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1115 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1116 E = HiddenGVStubs.end(); I != E; ++I)
1117 O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
1118 << I->second << '\n';
1121 // Funny Darwin hack: This flag tells the linker that no global symbols
1122 // contain code that falls through to other global symbols (e.g. the obvious
1123 // implementation of multiple entry points). If this doesn't occur, the
1124 // linker can safely perform dead code stripping. Since LLVM never
1125 // generates code that does this, it is always safe to set.
1126 O << "\t.subsections_via_symbols\n";
1127 } else if (Subtarget->isTargetCygMing()) {
1128 // Emit type information for external functions
1129 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
1131 O << "\t.def\t " << i->getKeyData()
1132 << ";\t.scl\t" << COFF::C_EXT
1133 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1139 // Output linker support code for dllexported globals on windows.
1140 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
1141 // dllexport symbols only exist on coff targets.
1142 TargetLoweringObjectFileCOFF &TLOFMacho =
1143 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
1145 OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
1146 SectionKind::getMetadata()));
1148 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1149 e = DLLExportedGVs.end(); i != e; ++i)
1150 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1152 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1153 e = DLLExportedFns.end();
1155 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1158 // Do common shutdown.
1159 return AsmPrinter::doFinalization(M);
1162 // Include the auto-generated portion of the assembly writer.
1163 #include "X86GenAsmWriter.inc"