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/MDNode.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/CodeGen/DwarfWriter.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/TargetOptions.h"
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
47 //===----------------------------------------------------------------------===//
48 // Primitive Helper Functions.
49 //===----------------------------------------------------------------------===//
51 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
52 if (Subtarget->isTargetDarwin())
53 O << "\"L" << getFunctionNumber() << "$pb\"";
54 else if (Subtarget->isTargetELF())
55 O << ".Lllvm$" << getFunctionNumber() << "." "$piclabel";
57 assert(0 && "Don't know how to print PIC label!\n");
60 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
61 /// Don't print things like \\n or \\0.
62 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
63 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
69 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
70 const TargetData *TD) {
71 X86MachineFunctionInfo Info;
74 switch (F->getCallingConv()) {
75 case CallingConv::X86_StdCall:
76 Info.setDecorationStyle(StdCall);
78 case CallingConv::X86_FastCall:
79 Info.setDecorationStyle(FastCall);
86 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
87 AI != AE; ++AI, ++argNum) {
88 const Type* Ty = AI->getType();
90 // 'Dereference' type in case of byval parameter attribute
91 if (F->paramHasAttr(argNum, Attribute::ByVal))
92 Ty = cast<PointerType>(Ty)->getElementType();
94 // Size should be aligned to DWORD boundary
95 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
98 // We're not supporting tooooo huge arguments :)
99 Info.setBytesToPopOnReturn((unsigned int)Size);
103 /// decorateName - Query FunctionInfoMap and use this information for various
105 void X86ATTAsmPrinter::decorateName(std::string &Name,
106 const GlobalValue *GV) {
107 const Function *F = dyn_cast<Function>(GV);
110 // We don't want to decorate non-stdcall or non-fastcall functions right now
111 unsigned CC = F->getCallingConv();
112 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
115 // Decorate names only when we're targeting Cygwin/Mingw32 targets
116 if (!Subtarget->isTargetCygMing())
119 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
121 const X86MachineFunctionInfo *Info;
122 if (info_item == FunctionInfoMap.end()) {
123 // Calculate apropriate function info and populate map
124 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
125 Info = &FunctionInfoMap[F];
127 Info = &info_item->second;
130 const FunctionType *FT = F->getFunctionType();
131 switch (Info->getDecorationStyle()) {
135 // "Pure" variadic functions do not receive @0 suffix.
136 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
137 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
138 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
141 // "Pure" variadic functions do not receive @0 suffix.
142 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
143 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
144 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
146 if (Name[0] == '_') {
153 assert(0 && "Unsupported DecorationStyle");
159 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
160 const Function *F = MF.getFunction();
162 decorateName(CurrentFnName, F);
164 SwitchToSection(TAI->SectionForGlobal(F));
166 // FIXME: A function's alignment should be part of MachineFunction. There
167 // shouldn't be a policy decision here.
168 unsigned FnAlign = 4;
169 if (F->hasFnAttr(Attribute::OptimizeForSize))
172 switch (F->getLinkage()) {
173 default: assert(0 && "Unknown linkage type!");
174 case Function::InternalLinkage: // Symbols default to internal.
175 case Function::PrivateLinkage:
176 EmitAlignment(FnAlign, F);
178 case Function::DLLExportLinkage:
179 case Function::ExternalLinkage:
180 EmitAlignment(FnAlign, F);
181 O << "\t.globl\t" << CurrentFnName << '\n';
183 case Function::LinkOnceAnyLinkage:
184 case Function::LinkOnceODRLinkage:
185 case Function::WeakAnyLinkage:
186 case Function::WeakODRLinkage:
187 EmitAlignment(FnAlign, F);
188 if (Subtarget->isTargetDarwin()) {
189 O << "\t.globl\t" << CurrentFnName << '\n';
190 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
191 } else if (Subtarget->isTargetCygMing()) {
192 O << "\t.globl\t" << CurrentFnName << "\n"
193 "\t.linkonce discard\n";
195 O << "\t.weak\t" << CurrentFnName << '\n';
200 printVisibility(CurrentFnName, F->getVisibility());
202 if (Subtarget->isTargetELF())
203 O << "\t.type\t" << CurrentFnName << ",@function\n";
204 else if (Subtarget->isTargetCygMing()) {
205 O << "\t.def\t " << CurrentFnName
207 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
208 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
212 O << CurrentFnName << ":\n";
213 // Add some workaround for linkonce linkage on Cygwin\MinGW
214 if (Subtarget->isTargetCygMing() &&
215 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
216 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
219 /// runOnMachineFunction - This uses the printMachineInstruction()
220 /// method to print assembly for each instruction.
222 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
223 const Function *F = MF.getFunction();
225 unsigned CC = F->getCallingConv();
227 SetupMachineFunction(MF);
230 // Populate function information map. Actually, We don't want to populate
231 // non-stdcall or non-fastcall functions' information right now.
232 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
233 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
235 // Print out constants referenced by the function
236 EmitConstantPool(MF.getConstantPool());
238 if (F->hasDLLExportLinkage())
239 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
241 // Print the 'header' of function
242 emitFunctionHeader(MF);
244 // Emit pre-function debug and/or EH information.
245 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
246 DW->BeginFunction(&MF);
248 // Print out code for the function.
249 bool hasAnyRealCode = false;
250 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
252 // Print a label for the basic block.
253 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
254 // This is an entry block or a block that's only reachable via a
255 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
257 printBasicBlockLabel(I, true, true, VerboseAsm);
260 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
262 // Print the assembly for the instruction.
264 hasAnyRealCode = true;
265 printMachineInstruction(II);
269 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
270 // If the function is empty, then we need to emit *something*. Otherwise,
271 // the function's label might be associated with something that it wasn't
272 // meant to be associated with. We emit a noop in this situation.
273 // We are assuming inline asms are code.
277 if (TAI->hasDotTypeDotSizeDirective())
278 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
280 // Emit post-function debug information.
281 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
282 DW->EndFunction(&MF);
284 // Print out jump tables referenced by the function.
285 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
289 // We didn't modify anything.
293 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
294 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_;
297 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
298 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
301 /// print_pcrel_imm - This is used to print an immediate value that ends up
302 /// being encoded as a pc-relative value. These print slightly differently, for
303 /// example, a $ is not emitted.
304 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
305 const MachineOperand &MO = MI->getOperand(OpNo);
306 switch (MO.getType()) {
307 default: assert(0 && "Unknown pcrel immediate operand");
308 case MachineOperand::MO_Immediate:
311 case MachineOperand::MO_MachineBasicBlock:
312 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
315 case MachineOperand::MO_GlobalAddress: {
316 const GlobalValue *GV = MO.getGlobal();
317 std::string Name = Mang->getValueName(GV);
318 decorateName(Name, GV);
320 bool needCloseParen = false;
321 if (Name[0] == '$') {
322 // The name begins with a dollar-sign. In order to avoid having it look
323 // like an integer immediate to the assembler, enclose it in parens.
325 needCloseParen = true;
328 if (shouldPrintStub(TM, Subtarget)) {
329 // DARWIN/X86-32 in != static mode.
331 // Link-once, declaration, or Weakly-linked global variables need
332 // non-lazily-resolved stubs
333 if (GV->isDeclaration() || GV->isWeakForLinker()) {
334 // Dynamically-resolved functions need a stub for the function.
335 if (isa<Function>(GV)) {
336 // Function stubs are no longer needed for Mac OS X 10.5 and up.
337 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
340 FnStubs.insert(Name);
341 printSuffixedName(Name, "$stub");
343 } else if (GV->hasHiddenVisibility()) {
344 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
345 // Definition is not definitely in the current translation unit.
348 HiddenGVStubs.insert(Name);
349 printSuffixedName(Name, "$non_lazy_ptr");
352 GVStubs.insert(Name);
353 printSuffixedName(Name, "$non_lazy_ptr");
356 if (GV->hasDLLImportLinkage())
361 if (GV->hasDLLImportLinkage())
365 if (shouldPrintPLT(TM, Subtarget)) {
366 // Assemble call via PLT for externally visible symbols
367 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
368 !GV->hasLocalLinkage())
371 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
372 // Save function name for later type emission
373 FnStubs.insert(Name);
376 printOffset(MO.getOffset());
383 case MachineOperand::MO_ExternalSymbol: {
384 bool needCloseParen = false;
385 std::string Name(TAI->getGlobalPrefix());
386 Name += MO.getSymbolName();
387 // Print function stub suffix unless it's Mac OS X 10.5 and up.
388 if (shouldPrintStub(TM, Subtarget) &&
389 // DARWIN/X86-32 in != static mode.
390 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
392 FnStubs.insert(Name);
393 printSuffixedName(Name, "$stub");
397 if (Name[0] == '$') {
398 // The name begins with a dollar-sign. In order to avoid having it look
399 // like an integer immediate to the assembler, enclose it in parens.
401 needCloseParen = true;
406 if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
408 PrintPICBaseSymbol();
412 if (shouldPrintPLT(TM, Subtarget))
423 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
424 const char *Modifier) {
425 const MachineOperand &MO = MI->getOperand(OpNo);
426 switch (MO.getType()) {
427 default: assert(0 && "unknown operand type!");
428 case MachineOperand::MO_Register: {
429 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
430 "Virtual registers should not make it this far!");
432 unsigned Reg = MO.getReg();
433 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
434 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
435 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
436 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
437 Reg = getX86SubSuperRegister(Reg, VT);
439 O << TRI->getAsmName(Reg);
443 case MachineOperand::MO_Immediate:
444 if (!Modifier || (strcmp(Modifier, "debug") &&
445 strcmp(Modifier, "mem")))
449 case MachineOperand::MO_JumpTableIndex: {
450 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
451 if (!isMemOp) O << '$';
452 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
456 case MachineOperand::MO_ConstantPoolIndex: {
457 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
458 if (!isMemOp) O << '$';
459 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
462 printOffset(MO.getOffset());
465 case MachineOperand::MO_GlobalAddress: {
466 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
468 const GlobalValue *GV = MO.getGlobal();
469 std::string Name = Mang->getValueName(GV);
470 decorateName(Name, GV);
472 bool needCloseParen = false;
475 else if (Name[0] == '$') {
476 // The name begins with a dollar-sign. In order to avoid having it look
477 // like an integer immediate to the assembler, enclose it in parens.
479 needCloseParen = true;
482 if (shouldPrintStub(TM, Subtarget)) {
483 // DARWIN/X86-32 in != static mode.
485 // Link-once, declaration, or Weakly-linked global variables need
486 // non-lazily-resolved stubs
487 if (GV->isDeclaration() || GV->isWeakForLinker()) {
488 // Dynamically-resolved functions need a stub for the function.
489 if (GV->hasHiddenVisibility()) {
490 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
491 // Definition is not definitely in the current translation unit.
494 HiddenGVStubs.insert(Name);
495 printSuffixedName(Name, "$non_lazy_ptr");
498 GVStubs.insert(Name);
499 printSuffixedName(Name, "$non_lazy_ptr");
502 if (GV->hasDLLImportLinkage())
507 if (TM.getRelocationModel() == Reloc::PIC_) {
509 PrintPICBaseSymbol();
512 if (GV->hasDLLImportLinkage())
517 printOffset(MO.getOffset());
524 case MachineOperand::MO_ExternalSymbol:
525 /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
526 /// by _GLOBAL_OFFSET_TABLE_ on X86-32. All others are call operands, which
528 assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
529 // These are never used as memory operands.
530 assert(!(Modifier && !strcmp(Modifier, "mem")));
533 O << TAI->getGlobalPrefix();
534 O << MO.getSymbolName();
538 switch (MO.getTargetFlags()) {
540 assert(0 && "Unknown target flag on GV operand");
541 case X86II::MO_NO_FLAG:
543 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
545 PrintPICBaseSymbol();
548 case X86II::MO_PIC_BASE_OFFSET:
550 PrintPICBaseSymbol();
552 case X86II::MO_TLSGD: O << "@TLSGD"; break;
553 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
554 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
555 case X86II::MO_TPOFF: O << "@TPOFF"; break;
556 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
557 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
558 case X86II::MO_GOT: O << "@GOT"; break;
559 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
563 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
564 unsigned char value = MI->getOperand(Op).getImm();
565 assert(value <= 7 && "Invalid ssecc argument!");
567 case 0: O << "eq"; break;
568 case 1: O << "lt"; break;
569 case 2: O << "le"; break;
570 case 3: O << "unord"; break;
571 case 4: O << "neq"; break;
572 case 5: O << "nlt"; break;
573 case 6: O << "nle"; break;
574 case 7: O << "ord"; break;
578 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
579 const char *Modifier) {
580 MachineOperand BaseReg = MI->getOperand(Op);
581 MachineOperand IndexReg = MI->getOperand(Op+2);
582 const MachineOperand &DispSpec = MI->getOperand(Op+3);
584 if (DispSpec.isGlobal() ||
587 DispSpec.isSymbol()) {
588 printOperand(MI, Op+3, "mem");
590 int DispVal = DispSpec.getImm();
591 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
595 if ((IndexReg.getReg() || BaseReg.getReg()) &&
596 (Modifier == 0 || strcmp(Modifier, "no-rip"))) {
597 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
598 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
600 // There are cases where we can end up with ESP/RSP in the indexreg slot.
601 // If this happens, swap the base/index register to support assemblers that
602 // don't work when the index is *SP.
603 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
604 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
605 std::swap(BaseReg, IndexReg);
606 std::swap(BaseRegOperand, IndexRegOperand);
610 if (BaseReg.getReg())
611 printOperand(MI, Op+BaseRegOperand, Modifier);
613 if (IndexReg.getReg()) {
615 printOperand(MI, Op+IndexRegOperand, Modifier);
617 O << ',' << ScaleVal;
623 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
624 const char *Modifier) {
625 assert(isMem(MI, Op) && "Invalid memory reference!");
626 MachineOperand Segment = MI->getOperand(Op+4);
627 if (Segment.getReg()) {
628 printOperand(MI, Op+4, Modifier);
631 printLeaMemReference(MI, Op, Modifier);
634 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
635 const MachineBasicBlock *MBB) const {
636 if (!TAI->getSetDirective())
639 // We don't need .set machinery if we have GOT-style relocations
640 if (Subtarget->isPICStyleGOT())
643 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
644 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
645 printBasicBlockLabel(MBB, false, false, false);
646 if (Subtarget->isPICStyleRIPRel())
647 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
648 << '_' << uid << '\n';
651 PrintPICBaseSymbol();
657 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
658 PrintPICBaseSymbol();
660 PrintPICBaseSymbol();
665 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
666 const MachineBasicBlock *MBB,
669 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
670 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
672 O << JTEntryDirective << ' ';
674 if (TM.getRelocationModel() == Reloc::PIC_) {
675 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
676 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
677 << '_' << uid << "_set_" << MBB->getNumber();
678 } else if (Subtarget->isPICStyleGOT()) {
679 printBasicBlockLabel(MBB, false, false, false);
682 assert(0 && "Don't know how to print MBB label for this PIC mode");
684 printBasicBlockLabel(MBB, false, false, false);
687 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
688 unsigned Reg = MO.getReg();
690 default: return true; // Unknown mode.
691 case 'b': // Print QImode register
692 Reg = getX86SubSuperRegister(Reg, MVT::i8);
694 case 'h': // Print QImode high register
695 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
697 case 'w': // Print HImode register
698 Reg = getX86SubSuperRegister(Reg, MVT::i16);
700 case 'k': // Print SImode register
701 Reg = getX86SubSuperRegister(Reg, MVT::i32);
703 case 'q': // Print DImode register
704 Reg = getX86SubSuperRegister(Reg, MVT::i64);
708 O << '%'<< TRI->getAsmName(Reg);
712 /// PrintAsmOperand - Print out an operand for an inline asm expression.
714 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
716 const char *ExtraCode) {
717 // Does this asm operand have a single letter operand modifier?
718 if (ExtraCode && ExtraCode[0]) {
719 if (ExtraCode[1] != 0) return true; // Unknown modifier.
721 switch (ExtraCode[0]) {
722 default: return true; // Unknown modifier.
723 case 'c': // Don't print "$" before a global var name or constant.
724 printOperand(MI, OpNo, "mem");
726 case 'b': // Print QImode register
727 case 'h': // Print QImode high register
728 case 'w': // Print HImode register
729 case 'k': // Print SImode register
730 case 'q': // Print DImode register
731 if (MI->getOperand(OpNo).isReg())
732 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
733 printOperand(MI, OpNo);
736 case 'P': // Don't print @PLT, but do print as memory.
737 printOperand(MI, OpNo, "mem");
740 case 'n': { // Negate the immediate or print a '-' before the operand.
741 // Note: this is a temporary solution. It should be handled target
742 // independently as part of the 'MC' work.
743 const MachineOperand &MO = MI->getOperand(OpNo);
753 printOperand(MI, OpNo);
757 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
760 const char *ExtraCode) {
761 if (ExtraCode && ExtraCode[0]) {
762 if (ExtraCode[1] != 0) return true; // Unknown modifier.
764 switch (ExtraCode[0]) {
765 default: return true; // Unknown modifier.
766 case 'b': // Print QImode register
767 case 'h': // Print QImode high register
768 case 'w': // Print HImode register
769 case 'k': // Print SImode register
770 case 'q': // Print SImode register
771 // These only apply to registers, ignore on mem.
773 case 'P': // Don't print @PLT, but do print as memory.
774 printMemReference(MI, OpNo, "no-rip");
778 printMemReference(MI, OpNo);
782 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
783 // Convert registers in the addr mode according to subreg64.
784 for (unsigned i = 0; i != 4; ++i) {
785 if (!MI->getOperand(i).isReg()) continue;
787 unsigned Reg = MI->getOperand(i).getReg();
788 if (Reg == 0) continue;
790 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
794 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
795 /// AT&T syntax to the current output stream.
797 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
801 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
805 } else if (MI->isLabel()) {
808 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
811 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
812 printImplicitDef(MI);
819 TmpInst.setOpcode(MI->getOpcode());
821 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
822 const MachineOperand &MO = MI->getOperand(i);
826 MCOp.MakeReg(MO.getReg());
827 } else if (MO.isImm()) {
828 MCOp.MakeImm(MO.getImm());
829 } else if (MO.isMBB()) {
830 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
832 assert(0 && "Unimp");
835 TmpInst.addOperand(MCOp);
838 switch (TmpInst.getOpcode()) {
840 // Handle the 'subreg rewriting' for the lea64_32mem operand.
841 lower_lea64_32mem(&TmpInst, 1);
845 // FIXME: Convert TmpInst.
846 printInstruction(&TmpInst);
850 // Call the autogenerated instruction printer routines.
851 printInstruction(MI);
855 bool X86ATTAsmPrinter::doInitialization(Module &M) {
857 Context = new MCContext();
858 // FIXME: Send this to "O" instead of outs(). For now, we force it to
859 // stdout to make it easy to compare.
860 Streamer = createAsmStreamer(*Context, outs());
863 return AsmPrinter::doInitialization(M);
866 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
867 const TargetData *TD = TM.getTargetData();
869 if (!GVar->hasInitializer())
870 return; // External global require no code
872 // Check to see if this is a special global used by LLVM, if so, emit it.
873 if (EmitSpecialLLVMGlobal(GVar)) {
874 if (Subtarget->isTargetDarwin() &&
875 TM.getRelocationModel() == Reloc::Static) {
876 if (GVar->getName() == "llvm.global_ctors")
877 O << ".reference .constructors_used\n";
878 else if (GVar->getName() == "llvm.global_dtors")
879 O << ".reference .destructors_used\n";
884 std::string name = Mang->getValueName(GVar);
885 Constant *C = GVar->getInitializer();
886 if (isa<MDNode>(C) || isa<MDString>(C))
888 const Type *Type = C->getType();
889 unsigned Size = TD->getTypeAllocSize(Type);
890 unsigned Align = TD->getPreferredAlignmentLog(GVar);
892 printVisibility(name, GVar->getVisibility());
894 if (Subtarget->isTargetELF())
895 O << "\t.type\t" << name << ",@object\n";
897 SwitchToSection(TAI->SectionForGlobal(GVar));
899 if (C->isNullValue() && !GVar->hasSection() &&
900 !(Subtarget->isTargetDarwin() &&
901 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
902 // FIXME: This seems to be pretty darwin-specific
903 if (GVar->hasExternalLinkage()) {
904 if (const char *Directive = TAI->getZeroFillDirective()) {
905 O << "\t.globl " << name << '\n';
906 O << Directive << "__DATA, __common, " << name << ", "
907 << Size << ", " << Align << '\n';
912 if (!GVar->isThreadLocal() &&
913 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
914 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
916 if (TAI->getLCOMMDirective() != NULL) {
917 if (GVar->hasLocalLinkage()) {
918 O << TAI->getLCOMMDirective() << name << ',' << Size;
919 if (Subtarget->isTargetDarwin())
921 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
922 O << "\t.globl " << name << '\n'
923 << TAI->getWeakDefDirective() << name << '\n';
924 EmitAlignment(Align, GVar);
927 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
928 PrintUnmangledNameSafely(GVar, O);
931 EmitGlobalConstant(C);
934 O << TAI->getCOMMDirective() << name << ',' << Size;
935 if (TAI->getCOMMDirectiveTakesAlignment())
936 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
939 if (!Subtarget->isTargetCygMing()) {
940 if (GVar->hasLocalLinkage())
941 O << "\t.local\t" << name << '\n';
943 O << TAI->getCOMMDirective() << name << ',' << Size;
944 if (TAI->getCOMMDirectiveTakesAlignment())
945 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
948 O << "\t\t" << TAI->getCommentString() << ' ';
949 PrintUnmangledNameSafely(GVar, O);
956 switch (GVar->getLinkage()) {
957 case GlobalValue::CommonLinkage:
958 case GlobalValue::LinkOnceAnyLinkage:
959 case GlobalValue::LinkOnceODRLinkage:
960 case GlobalValue::WeakAnyLinkage:
961 case GlobalValue::WeakODRLinkage:
962 if (Subtarget->isTargetDarwin()) {
963 O << "\t.globl " << name << '\n'
964 << TAI->getWeakDefDirective() << name << '\n';
965 } else if (Subtarget->isTargetCygMing()) {
966 O << "\t.globl\t" << name << "\n"
967 "\t.linkonce same_size\n";
969 O << "\t.weak\t" << name << '\n';
972 case GlobalValue::DLLExportLinkage:
973 case GlobalValue::AppendingLinkage:
974 // FIXME: appending linkage variables should go into a section of
975 // their name or something. For now, just emit them as external.
976 case GlobalValue::ExternalLinkage:
977 // If external or appending, declare as a global symbol
978 O << "\t.globl " << name << '\n';
980 case GlobalValue::PrivateLinkage:
981 case GlobalValue::InternalLinkage:
984 assert(0 && "Unknown linkage type!");
987 EmitAlignment(Align, GVar);
990 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
991 PrintUnmangledNameSafely(GVar, O);
994 if (TAI->hasDotTypeDotSizeDirective())
995 O << "\t.size\t" << name << ", " << Size << '\n';
997 EmitGlobalConstant(C);
1000 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1001 // Print out module-level global variables here.
1002 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1004 printModuleLevelGV(I);
1006 if (I->hasDLLExportLinkage())
1007 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1010 if (Subtarget->isTargetDarwin()) {
1011 SwitchToDataSection("");
1013 // Add the (possibly multiple) personalities to the set of global value
1014 // stubs. Only referenced functions get into the Personalities list.
1015 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1016 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1017 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1018 if (Personalities[i] == 0)
1020 std::string Name = Mang->getValueName(Personalities[i]);
1021 decorateName(Name, Personalities[i]);
1022 GVStubs.insert(Name);
1026 // Output stubs for dynamically-linked functions
1027 if (!FnStubs.empty()) {
1028 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1030 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1031 "self_modifying_code+pure_instructions,5", 0);
1032 const char *Name = I->getKeyData();
1033 printSuffixedName(Name, "$stub");
1035 "\t.indirect_symbol " << Name << "\n"
1036 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1041 // Output stubs for external and common global variables.
1042 if (!GVStubs.empty()) {
1043 SwitchToDataSection(
1044 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1045 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1047 const char *Name = I->getKeyData();
1048 printSuffixedName(Name, "$non_lazy_ptr");
1049 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1053 if (!HiddenGVStubs.empty()) {
1054 SwitchToSection(TAI->getDataSection());
1056 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1057 E = HiddenGVStubs.end(); I != E; ++I) {
1058 const char *Name = I->getKeyData();
1059 printSuffixedName(Name, "$non_lazy_ptr");
1060 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1064 // Funny Darwin hack: This flag tells the linker that no global symbols
1065 // contain code that falls through to other global symbols (e.g. the obvious
1066 // implementation of multiple entry points). If this doesn't occur, the
1067 // linker can safely perform dead code stripping. Since LLVM never
1068 // generates code that does this, it is always safe to set.
1069 O << "\t.subsections_via_symbols\n";
1070 } else if (Subtarget->isTargetCygMing()) {
1071 // Emit type information for external functions
1072 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1074 O << "\t.def\t " << i->getKeyData()
1075 << ";\t.scl\t" << COFF::C_EXT
1076 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1082 // Output linker support code for dllexported globals on windows.
1083 if (!DLLExportedGVs.empty()) {
1084 SwitchToDataSection(".section .drectve");
1086 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1087 e = DLLExportedGVs.end(); i != e; ++i)
1088 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1091 if (!DLLExportedFns.empty()) {
1092 SwitchToDataSection(".section .drectve");
1094 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1095 e = DLLExportedFns.end();
1097 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1100 // Do common shutdown.
1101 bool Changed = AsmPrinter::doFinalization(M);
1103 if (NewAsmPrinter) {
1115 // Include the auto-generated portion of the assembly writer.
1116 #include "X86GenAsmWriter.inc"