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 shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
294 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
297 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
298 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_;
301 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
302 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
305 /// print_pcrel_imm - This is used to print an immediate value that ends up
306 /// being encoded as a pc-relative value. These print slightly differently, for
307 /// example, a $ is not emitted.
308 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
309 const MachineOperand &MO = MI->getOperand(OpNo);
310 switch (MO.getType()) {
311 default: assert(0 && "Unknown pcrel immediate operand");
312 case MachineOperand::MO_Immediate:
315 case MachineOperand::MO_MachineBasicBlock:
316 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
319 case MachineOperand::MO_GlobalAddress: {
320 const GlobalValue *GV = MO.getGlobal();
321 std::string Name = Mang->getValueName(GV);
322 decorateName(Name, GV);
324 bool needCloseParen = false;
325 if (Name[0] == '$') {
326 // The name begins with a dollar-sign. In order to avoid having it look
327 // like an integer immediate to the assembler, enclose it in parens.
329 needCloseParen = true;
332 if (shouldPrintStub(TM, Subtarget)) {
333 // DARWIN/X86-32 in != static mode.
335 // Link-once, declaration, or Weakly-linked global variables need
336 // non-lazily-resolved stubs
337 if (GV->isDeclaration() || GV->isWeakForLinker()) {
338 // Dynamically-resolved functions need a stub for the function.
339 if (isa<Function>(GV)) {
340 // Function stubs are no longer needed for Mac OS X 10.5 and up.
341 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
344 FnStubs.insert(Name);
345 printSuffixedName(Name, "$stub");
347 } else if (GV->hasHiddenVisibility()) {
348 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
349 // Definition is not definitely in the current translation unit.
352 HiddenGVStubs.insert(Name);
353 printSuffixedName(Name, "$non_lazy_ptr");
356 GVStubs.insert(Name);
357 printSuffixedName(Name, "$non_lazy_ptr");
360 if (GV->hasDLLImportLinkage())
365 if (GV->hasDLLImportLinkage())
369 if (shouldPrintPLT(TM, Subtarget)) {
370 // Assemble call via PLT for externally visible symbols
371 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
372 !GV->hasLocalLinkage())
375 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
376 // Save function name for later type emission
377 FnStubs.insert(Name);
380 printOffset(MO.getOffset());
387 case MachineOperand::MO_ExternalSymbol: {
388 bool needCloseParen = false;
389 std::string Name(TAI->getGlobalPrefix());
390 Name += MO.getSymbolName();
391 // Print function stub suffix unless it's Mac OS X 10.5 and up.
392 if (shouldPrintStub(TM, Subtarget) &&
393 // DARWIN/X86-32 in != static mode.
394 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
396 FnStubs.insert(Name);
397 printSuffixedName(Name, "$stub");
401 if (Name[0] == '$') {
402 // The name begins with a dollar-sign. In order to avoid having it look
403 // like an integer immediate to the assembler, enclose it in parens.
405 needCloseParen = true;
410 if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
412 PrintPICBaseSymbol();
416 if (shouldPrintPLT(TM, Subtarget))
427 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
428 const char *Modifier, bool NotRIPRel) {
429 const MachineOperand &MO = MI->getOperand(OpNo);
430 switch (MO.getType()) {
431 case MachineOperand::MO_Register: {
432 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
433 "Virtual registers should not make it this far!");
435 unsigned Reg = MO.getReg();
436 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
437 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
438 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
439 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
440 Reg = getX86SubSuperRegister(Reg, VT);
442 O << TRI->getAsmName(Reg);
446 case MachineOperand::MO_Immediate:
447 if (!Modifier || (strcmp(Modifier, "debug") &&
448 strcmp(Modifier, "mem")))
452 case MachineOperand::MO_JumpTableIndex: {
453 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
454 if (!isMemOp) O << '$';
455 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
458 if (TM.getRelocationModel() == Reloc::PIC_) {
459 if (Subtarget->isPICStyleStub()) {
461 PrintPICBaseSymbol();
462 } else if (Subtarget->isPICStyleGOT()) {
467 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
471 case MachineOperand::MO_ConstantPoolIndex: {
472 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
473 if (!isMemOp) O << '$';
474 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
477 if (TM.getRelocationModel() == Reloc::PIC_) {
478 if (Subtarget->isPICStyleStub()) {
480 PrintPICBaseSymbol();
481 } else if (Subtarget->isPICStyleGOT())
485 printOffset(MO.getOffset());
487 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
491 case MachineOperand::MO_GlobalAddress: {
492 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
493 bool needCloseParen = false;
495 const GlobalValue *GV = MO.getGlobal();
496 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
498 // If GV is an alias then use the aliasee for determining
500 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
501 GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
504 bool isThreadLocal = GVar && GVar->isThreadLocal();
506 std::string Name = Mang->getValueName(GV);
507 decorateName(Name, GV);
511 else if (Name[0] == '$') {
512 // The name begins with a dollar-sign. In order to avoid having it look
513 // like an integer immediate to the assembler, enclose it in parens.
515 needCloseParen = true;
518 if (shouldPrintStub(TM, Subtarget)) {
519 // DARWIN/X86-32 in != static mode.
521 // Link-once, declaration, or Weakly-linked global variables need
522 // non-lazily-resolved stubs
523 if (GV->isDeclaration() || GV->isWeakForLinker()) {
524 // Dynamically-resolved functions need a stub for the function.
525 if (GV->hasHiddenVisibility()) {
526 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
527 // Definition is not definitely in the current translation unit.
530 HiddenGVStubs.insert(Name);
531 printSuffixedName(Name, "$non_lazy_ptr");
534 GVStubs.insert(Name);
535 printSuffixedName(Name, "$non_lazy_ptr");
538 if (GV->hasDLLImportLinkage())
543 if (TM.getRelocationModel() == Reloc::PIC_) {
545 PrintPICBaseSymbol();
548 if (GV->hasDLLImportLinkage())
553 printOffset(MO.getOffset());
558 bool isRIPRelative = false;
560 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
562 case TLSModel::GeneralDynamic:
565 case TLSModel::LocalDynamic:
566 // O << "@TLSLD"; // local dynamic not implemented
569 case TLSModel::InitialExec:
570 if (Subtarget->is64Bit()) {
573 isRIPRelative = true;
578 case TLSModel::LocalExec:
579 if (Subtarget->is64Bit())
585 assert (0 && "Unknown TLS model");
587 } else if (isMemOp) {
588 if (shouldPrintGOT(TM, Subtarget)) {
589 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
593 } else if (Subtarget->isPICStyleRIPRel() &&
595 if (TM.getRelocationModel() != Reloc::Static) {
596 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
600 isRIPRelative = true;
604 // Use rip when possible to reduce code size, except when
605 // index or base register are also part of the address. e.g.
606 // foo(%rip)(%rcx,%rax,4) is not legal.
612 case MachineOperand::MO_ExternalSymbol: {
613 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
614 bool needCloseParen = false;
615 std::string Name(TAI->getGlobalPrefix());
616 Name += MO.getSymbolName();
618 // Print function stub suffix unless it's Mac OS X 10.5 and up.
621 else if (Name[0] == '$') {
622 // The name begins with a dollar-sign. In order to avoid having it look
623 // like an integer immediate to the assembler, enclose it in parens.
625 needCloseParen = true;
630 if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
632 PrintPICBaseSymbol();
639 if (Subtarget->isPICStyleRIPRel())
644 O << "<unknown operand type>"; return;
648 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
649 unsigned char value = MI->getOperand(Op).getImm();
650 assert(value <= 7 && "Invalid ssecc argument!");
652 case 0: O << "eq"; break;
653 case 1: O << "lt"; break;
654 case 2: O << "le"; break;
655 case 3: O << "unord"; break;
656 case 4: O << "neq"; break;
657 case 5: O << "nlt"; break;
658 case 6: O << "nle"; break;
659 case 7: O << "ord"; break;
663 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
664 const char *Modifier,
666 MachineOperand BaseReg = MI->getOperand(Op);
667 MachineOperand IndexReg = MI->getOperand(Op+2);
668 const MachineOperand &DispSpec = MI->getOperand(Op+3);
670 NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
671 if (DispSpec.isGlobal() ||
674 DispSpec.isSymbol()) {
675 printOperand(MI, Op+3, "mem", NotRIPRel);
677 int DispVal = DispSpec.getImm();
678 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
682 if (IndexReg.getReg() || BaseReg.getReg()) {
683 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
684 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
686 // There are cases where we can end up with ESP/RSP in the indexreg slot.
687 // If this happens, swap the base/index register to support assemblers that
688 // don't work when the index is *SP.
689 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
690 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
691 std::swap(BaseReg, IndexReg);
692 std::swap(BaseRegOperand, IndexRegOperand);
696 if (BaseReg.getReg())
697 printOperand(MI, Op+BaseRegOperand, Modifier);
699 if (IndexReg.getReg()) {
701 printOperand(MI, Op+IndexRegOperand, Modifier);
703 O << ',' << ScaleVal;
709 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
710 const char *Modifier, bool NotRIPRel){
711 assert(isMem(MI, Op) && "Invalid memory reference!");
712 MachineOperand Segment = MI->getOperand(Op+4);
713 if (Segment.getReg()) {
714 printOperand(MI, Op+4, Modifier);
717 printLeaMemReference(MI, Op, Modifier, NotRIPRel);
720 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
721 const MachineBasicBlock *MBB) const {
722 if (!TAI->getSetDirective())
725 // We don't need .set machinery if we have GOT-style relocations
726 if (Subtarget->isPICStyleGOT())
729 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
730 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
731 printBasicBlockLabel(MBB, false, false, false);
732 if (Subtarget->isPICStyleRIPRel())
733 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
734 << '_' << uid << '\n';
737 PrintPICBaseSymbol();
743 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
744 PrintPICBaseSymbol();
746 PrintPICBaseSymbol();
751 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
752 const MachineBasicBlock *MBB,
755 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
756 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
758 O << JTEntryDirective << ' ';
760 if (TM.getRelocationModel() == Reloc::PIC_) {
761 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
762 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
763 << '_' << uid << "_set_" << MBB->getNumber();
764 } else if (Subtarget->isPICStyleGOT()) {
765 printBasicBlockLabel(MBB, false, false, false);
768 assert(0 && "Don't know how to print MBB label for this PIC mode");
770 printBasicBlockLabel(MBB, false, false, false);
773 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
774 unsigned Reg = MO.getReg();
776 default: return true; // Unknown mode.
777 case 'b': // Print QImode register
778 Reg = getX86SubSuperRegister(Reg, MVT::i8);
780 case 'h': // Print QImode high register
781 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
783 case 'w': // Print HImode register
784 Reg = getX86SubSuperRegister(Reg, MVT::i16);
786 case 'k': // Print SImode register
787 Reg = getX86SubSuperRegister(Reg, MVT::i32);
789 case 'q': // Print DImode register
790 Reg = getX86SubSuperRegister(Reg, MVT::i64);
794 O << '%'<< TRI->getAsmName(Reg);
798 /// PrintAsmOperand - Print out an operand for an inline asm expression.
800 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
802 const char *ExtraCode) {
803 // Does this asm operand have a single letter operand modifier?
804 if (ExtraCode && ExtraCode[0]) {
805 if (ExtraCode[1] != 0) return true; // Unknown modifier.
807 switch (ExtraCode[0]) {
808 default: return true; // Unknown modifier.
809 case 'c': // Don't print "$" before a global var name or constant.
810 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
812 case 'b': // Print QImode register
813 case 'h': // Print QImode high register
814 case 'w': // Print HImode register
815 case 'k': // Print SImode register
816 case 'q': // Print DImode register
817 if (MI->getOperand(OpNo).isReg())
818 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
819 printOperand(MI, OpNo);
822 case 'P': // Don't print @PLT, but do print as memory.
823 printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
828 printOperand(MI, OpNo);
832 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
835 const char *ExtraCode) {
836 if (ExtraCode && ExtraCode[0]) {
837 if (ExtraCode[1] != 0) return true; // Unknown modifier.
839 switch (ExtraCode[0]) {
840 default: return true; // Unknown modifier.
841 case 'b': // Print QImode register
842 case 'h': // Print QImode high register
843 case 'w': // Print HImode register
844 case 'k': // Print SImode register
845 case 'q': // Print SImode register
846 // These only apply to registers, ignore on mem.
848 case 'P': // Don't print @PLT, but do print as memory.
849 printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
853 printMemReference(MI, OpNo);
857 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
858 // Convert registers in the addr mode according to subreg64.
859 for (unsigned i = 0; i != 4; ++i) {
860 if (!MI->getOperand(i).isReg()) continue;
862 unsigned Reg = MI->getOperand(i).getReg();
863 if (Reg == 0) continue;
865 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
869 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
870 /// AT&T syntax to the current output stream.
872 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
876 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
880 } else if (MI->isLabel()) {
883 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
886 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
887 printImplicitDef(MI);
894 TmpInst.setOpcode(MI->getOpcode());
896 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
897 const MachineOperand &MO = MI->getOperand(i);
901 MCOp.MakeReg(MO.getReg());
902 } else if (MO.isImm()) {
903 MCOp.MakeImm(MO.getImm());
904 } else if (MO.isMBB()) {
905 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
907 assert(0 && "Unimp");
910 TmpInst.addOperand(MCOp);
913 switch (TmpInst.getOpcode()) {
915 // Handle the 'subreg rewriting' for the lea64_32mem operand.
916 lower_lea64_32mem(&TmpInst, 1);
920 // FIXME: Convert TmpInst.
921 printInstruction(&TmpInst);
925 // Call the autogenerated instruction printer routines.
926 printInstruction(MI);
930 bool X86ATTAsmPrinter::doInitialization(Module &M) {
932 Context = new MCContext();
933 // FIXME: Send this to "O" instead of outs(). For now, we force it to
934 // stdout to make it easy to compare.
935 Streamer = createAsmStreamer(*Context, outs());
938 return AsmPrinter::doInitialization(M);
941 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
942 const TargetData *TD = TM.getTargetData();
944 if (!GVar->hasInitializer())
945 return; // External global require no code
947 // Check to see if this is a special global used by LLVM, if so, emit it.
948 if (EmitSpecialLLVMGlobal(GVar)) {
949 if (Subtarget->isTargetDarwin() &&
950 TM.getRelocationModel() == Reloc::Static) {
951 if (GVar->getName() == "llvm.global_ctors")
952 O << ".reference .constructors_used\n";
953 else if (GVar->getName() == "llvm.global_dtors")
954 O << ".reference .destructors_used\n";
959 std::string name = Mang->getValueName(GVar);
960 Constant *C = GVar->getInitializer();
961 if (isa<MDNode>(C) || isa<MDString>(C))
963 const Type *Type = C->getType();
964 unsigned Size = TD->getTypeAllocSize(Type);
965 unsigned Align = TD->getPreferredAlignmentLog(GVar);
967 printVisibility(name, GVar->getVisibility());
969 if (Subtarget->isTargetELF())
970 O << "\t.type\t" << name << ",@object\n";
972 SwitchToSection(TAI->SectionForGlobal(GVar));
974 if (C->isNullValue() && !GVar->hasSection() &&
975 !(Subtarget->isTargetDarwin() &&
976 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
977 // FIXME: This seems to be pretty darwin-specific
978 if (GVar->hasExternalLinkage()) {
979 if (const char *Directive = TAI->getZeroFillDirective()) {
980 O << "\t.globl " << name << '\n';
981 O << Directive << "__DATA, __common, " << name << ", "
982 << Size << ", " << Align << '\n';
987 if (!GVar->isThreadLocal() &&
988 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
989 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
991 if (TAI->getLCOMMDirective() != NULL) {
992 if (GVar->hasLocalLinkage()) {
993 O << TAI->getLCOMMDirective() << name << ',' << Size;
994 if (Subtarget->isTargetDarwin())
996 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
997 O << "\t.globl " << name << '\n'
998 << TAI->getWeakDefDirective() << name << '\n';
999 EmitAlignment(Align, GVar);
1002 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1003 PrintUnmangledNameSafely(GVar, O);
1006 EmitGlobalConstant(C);
1009 O << TAI->getCOMMDirective() << name << ',' << Size;
1010 if (TAI->getCOMMDirectiveTakesAlignment())
1011 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1014 if (!Subtarget->isTargetCygMing()) {
1015 if (GVar->hasLocalLinkage())
1016 O << "\t.local\t" << name << '\n';
1018 O << TAI->getCOMMDirective() << name << ',' << Size;
1019 if (TAI->getCOMMDirectiveTakesAlignment())
1020 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1023 O << "\t\t" << TAI->getCommentString() << ' ';
1024 PrintUnmangledNameSafely(GVar, O);
1031 switch (GVar->getLinkage()) {
1032 case GlobalValue::CommonLinkage:
1033 case GlobalValue::LinkOnceAnyLinkage:
1034 case GlobalValue::LinkOnceODRLinkage:
1035 case GlobalValue::WeakAnyLinkage:
1036 case GlobalValue::WeakODRLinkage:
1037 if (Subtarget->isTargetDarwin()) {
1038 O << "\t.globl " << name << '\n'
1039 << TAI->getWeakDefDirective() << name << '\n';
1040 } else if (Subtarget->isTargetCygMing()) {
1041 O << "\t.globl\t" << name << "\n"
1042 "\t.linkonce same_size\n";
1044 O << "\t.weak\t" << name << '\n';
1047 case GlobalValue::DLLExportLinkage:
1048 case GlobalValue::AppendingLinkage:
1049 // FIXME: appending linkage variables should go into a section of
1050 // their name or something. For now, just emit them as external.
1051 case GlobalValue::ExternalLinkage:
1052 // If external or appending, declare as a global symbol
1053 O << "\t.globl " << name << '\n';
1055 case GlobalValue::PrivateLinkage:
1056 case GlobalValue::InternalLinkage:
1059 assert(0 && "Unknown linkage type!");
1062 EmitAlignment(Align, GVar);
1065 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1066 PrintUnmangledNameSafely(GVar, O);
1069 if (TAI->hasDotTypeDotSizeDirective())
1070 O << "\t.size\t" << name << ", " << Size << '\n';
1072 EmitGlobalConstant(C);
1075 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1076 // Print out module-level global variables here.
1077 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1079 printModuleLevelGV(I);
1081 if (I->hasDLLExportLinkage())
1082 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1085 if (Subtarget->isTargetDarwin()) {
1086 SwitchToDataSection("");
1088 // Add the (possibly multiple) personalities to the set of global value
1089 // stubs. Only referenced functions get into the Personalities list.
1090 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1091 const std::vector<Function*> &Personalities = MMI->getPersonalities();
1092 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1093 if (Personalities[i] == 0)
1095 std::string Name = Mang->getValueName(Personalities[i]);
1096 decorateName(Name, Personalities[i]);
1097 GVStubs.insert(Name);
1101 // Output stubs for dynamically-linked functions
1102 if (!FnStubs.empty()) {
1103 for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1105 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1106 "self_modifying_code+pure_instructions,5", 0);
1107 const char *Name = I->getKeyData();
1108 printSuffixedName(Name, "$stub");
1110 "\t.indirect_symbol " << Name << "\n"
1111 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1116 // Output stubs for external and common global variables.
1117 if (!GVStubs.empty()) {
1118 SwitchToDataSection(
1119 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1120 for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1122 const char *Name = I->getKeyData();
1123 printSuffixedName(Name, "$non_lazy_ptr");
1124 O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1128 if (!HiddenGVStubs.empty()) {
1129 SwitchToSection(TAI->getDataSection());
1131 for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1132 E = HiddenGVStubs.end(); I != E; ++I) {
1133 const char *Name = I->getKeyData();
1134 printSuffixedName(Name, "$non_lazy_ptr");
1135 O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1139 // Funny Darwin hack: This flag tells the linker that no global symbols
1140 // contain code that falls through to other global symbols (e.g. the obvious
1141 // implementation of multiple entry points). If this doesn't occur, the
1142 // linker can safely perform dead code stripping. Since LLVM never
1143 // generates code that does this, it is always safe to set.
1144 O << "\t.subsections_via_symbols\n";
1145 } else if (Subtarget->isTargetCygMing()) {
1146 // Emit type information for external functions
1147 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1149 O << "\t.def\t " << i->getKeyData()
1150 << ";\t.scl\t" << COFF::C_EXT
1151 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1157 // Output linker support code for dllexported globals on windows.
1158 if (!DLLExportedGVs.empty()) {
1159 SwitchToDataSection(".section .drectve");
1161 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1162 e = DLLExportedGVs.end(); i != e; ++i)
1163 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1166 if (!DLLExportedFns.empty()) {
1167 SwitchToDataSection(".section .drectve");
1169 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1170 e = DLLExportedFns.end();
1172 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1175 // Do common shutdown.
1176 bool Changed = AsmPrinter::doFinalization(M);
1178 if (NewAsmPrinter) {
1190 // Include the auto-generated portion of the assembly writer.
1191 #include "X86GenAsmWriter.inc"