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"
18 #include "X86MCInstLower.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/Statistic.h"
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45 //===----------------------------------------------------------------------===//
46 // Primitive Helper Functions.
47 //===----------------------------------------------------------------------===//
49 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
50 // FIXME: Gross const cast hack.
51 X86ATTAsmPrinter *AP = const_cast<X86ATTAsmPrinter*>(this);
52 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
55 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
56 const TargetData *TD) {
57 X86MachineFunctionInfo Info;
60 switch (F->getCallingConv()) {
61 case CallingConv::X86_StdCall:
62 Info.setDecorationStyle(StdCall);
64 case CallingConv::X86_FastCall:
65 Info.setDecorationStyle(FastCall);
72 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
73 AI != AE; ++AI, ++argNum) {
74 const Type* Ty = AI->getType();
76 // 'Dereference' type in case of byval parameter attribute
77 if (F->paramHasAttr(argNum, Attribute::ByVal))
78 Ty = cast<PointerType>(Ty)->getElementType();
80 // Size should be aligned to DWORD boundary
81 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
84 // We're not supporting tooooo huge arguments :)
85 Info.setBytesToPopOnReturn((unsigned int)Size);
89 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
90 /// various name decorations for Cygwin and MingW.
91 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl<char> &Name,
92 const GlobalValue *GV) {
93 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
95 const Function *F = dyn_cast<Function>(GV);
98 // Save function name for later type emission.
99 if (F->isDeclaration())
100 CygMingStubs.insert(StringRef(Name.data(), Name.size()));
102 // We don't want to decorate non-stdcall or non-fastcall functions right now
103 CallingConv::ID CC = F->getCallingConv();
104 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
108 const X86MachineFunctionInfo *Info;
110 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
111 if (info_item == FunctionInfoMap.end()) {
112 // Calculate apropriate function info and populate map
113 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
114 Info = &FunctionInfoMap[F];
116 Info = &info_item->second;
119 if (Info->getDecorationStyle() == None) return;
120 const FunctionType *FT = F->getFunctionType();
122 // "Pure" variadic functions do not receive @0 suffix.
123 if (!FT->isVarArg() || FT->getNumParams() == 0 ||
124 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
125 raw_svector_ostream(Name) << '@' << Info->getBytesToPopOnReturn();
127 if (Info->getDecorationStyle() == FastCall) {
131 Name.insert(Name.begin(), '@');
135 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
136 /// various name decorations for Cygwin and MingW.
137 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
138 const GlobalValue *GV) {
139 SmallString<128> NameStr(Name.begin(), Name.end());
140 DecorateCygMingName(NameStr, GV);
141 Name.assign(NameStr.begin(), NameStr.end());
144 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
145 unsigned FnAlign = MF.getAlignment();
146 const Function *F = MF.getFunction();
148 if (Subtarget->isTargetCygMing())
149 DecorateCygMingName(CurrentFnName, F);
151 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
152 EmitAlignment(FnAlign, F);
154 switch (F->getLinkage()) {
155 default: llvm_unreachable("Unknown linkage type!");
156 case Function::InternalLinkage: // Symbols default to internal.
157 case Function::PrivateLinkage:
159 case Function::DLLExportLinkage:
160 case Function::ExternalLinkage:
161 O << "\t.globl\t" << CurrentFnName << '\n';
163 case Function::LinkerPrivateLinkage:
164 case Function::LinkOnceAnyLinkage:
165 case Function::LinkOnceODRLinkage:
166 case Function::WeakAnyLinkage:
167 case Function::WeakODRLinkage:
168 if (Subtarget->isTargetDarwin()) {
169 O << "\t.globl\t" << CurrentFnName << '\n';
170 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
171 } else if (Subtarget->isTargetCygMing()) {
172 O << "\t.globl\t" << CurrentFnName << "\n"
173 "\t.linkonce discard\n";
175 O << "\t.weak\t" << CurrentFnName << '\n';
180 printVisibility(CurrentFnName, F->getVisibility());
182 if (Subtarget->isTargetELF())
183 O << "\t.type\t" << CurrentFnName << ",@function\n";
184 else if (Subtarget->isTargetCygMing()) {
185 O << "\t.def\t " << CurrentFnName
187 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
188 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
192 O << CurrentFnName << ':';
194 O.PadToColumn(MAI->getCommentColumn());
195 O << MAI->getCommentString() << ' ';
196 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
200 // Add some workaround for linkonce linkage on Cygwin\MinGW
201 if (Subtarget->isTargetCygMing() &&
202 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
203 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
206 /// runOnMachineFunction - This uses the printMachineInstruction()
207 /// method to print assembly for each instruction.
209 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
210 const Function *F = MF.getFunction();
212 CallingConv::ID CC = F->getCallingConv();
214 SetupMachineFunction(MF);
217 // Populate function information map. Actually, We don't want to populate
218 // non-stdcall or non-fastcall functions' information right now.
219 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
220 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
222 // Print out constants referenced by the function
223 EmitConstantPool(MF.getConstantPool());
225 if (F->hasDLLExportLinkage())
226 DLLExportedFns.insert(Mang->getMangledName(F));
228 // Print the 'header' of function
229 emitFunctionHeader(MF);
231 // Emit pre-function debug and/or EH information.
232 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
233 DW->BeginFunction(&MF);
235 // Print out code for the function.
236 bool hasAnyRealCode = false;
237 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
239 // Print a label for the basic block.
240 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
241 // This is an entry block or a block that's only reachable via a
242 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
244 EmitBasicBlockStart(I);
247 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
249 // Print the assembly for the instruction.
251 hasAnyRealCode = true;
252 printMachineInstruction(II);
256 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
257 // If the function is empty, then we need to emit *something*. Otherwise,
258 // the function's label might be associated with something that it wasn't
259 // meant to be associated with. We emit a noop in this situation.
260 // We are assuming inline asms are code.
264 if (MAI->hasDotTypeDotSizeDirective())
265 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
267 // Emit post-function debug information.
268 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
269 DW->EndFunction(&MF);
271 // Print out jump tables referenced by the function.
272 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
274 // We didn't modify anything.
278 /// printSymbolOperand - Print a raw symbol reference operand. This handles
279 /// jump tables, constant pools, global address and external symbols, all of
280 /// which print to a label with various suffixes for relocation types etc.
281 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
282 switch (MO.getType()) {
283 default: llvm_unreachable("unknown symbol type!");
284 case MachineOperand::MO_JumpTableIndex:
285 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
288 case MachineOperand::MO_ConstantPoolIndex:
289 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
291 printOffset(MO.getOffset());
293 case MachineOperand::MO_GlobalAddress: {
294 const GlobalValue *GV = MO.getGlobal();
296 const char *Suffix = "";
297 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
299 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
300 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
301 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
302 Suffix = "$non_lazy_ptr";
304 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
305 if (Subtarget->isTargetCygMing())
306 DecorateCygMingName(Name, GV);
308 // Handle dllimport linkage.
309 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
310 Name = "__imp_" + Name;
312 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
313 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
314 SmallString<128> NameStr;
315 Mang->getNameWithPrefix(NameStr, GV, true);
316 NameStr += "$non_lazy_ptr";
317 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
318 MCSymbol *&StubSym = GVStubs[Sym];
321 Mang->getNameWithPrefix(NameStr, GV, false);
322 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
324 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
325 SmallString<128> NameStr;
326 Mang->getNameWithPrefix(NameStr, GV, true);
327 NameStr += "$non_lazy_ptr";
328 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
329 MCSymbol *&StubSym = HiddenGVStubs[Sym];
332 Mang->getNameWithPrefix(NameStr, GV, false);
333 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
335 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
336 SmallString<128> NameStr;
337 Mang->getNameWithPrefix(NameStr, GV, true);
339 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
340 MCSymbol *&StubSym = FnStubs[Sym];
343 Mang->getNameWithPrefix(NameStr, GV, false);
344 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
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) {
362 MCSymbol *&StubSym = FnStubs[OutContext.GetOrCreateSymbol(Name)];
364 Name.erase(Name.end()-5, Name.end());
365 StubSym = OutContext.GetOrCreateSymbol(Name);
369 // If the name begins with a dollar-sign, enclose it in parens. We do this
370 // to avoid having it look like an integer immediate to the assembler.
372 O << '(' << Name << ')';
379 switch (MO.getTargetFlags()) {
381 llvm_unreachable("Unknown target flag on GV operand");
382 case X86II::MO_NO_FLAG: // No flag.
384 case X86II::MO_DARWIN_NONLAZY:
385 case X86II::MO_DLLIMPORT:
386 case X86II::MO_DARWIN_STUB:
387 // These affect the name of the symbol, not any suffix.
389 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
391 PrintPICBaseSymbol();
394 case X86II::MO_PIC_BASE_OFFSET:
395 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
396 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
398 PrintPICBaseSymbol();
400 case X86II::MO_TLSGD: O << "@TLSGD"; break;
401 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
402 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
403 case X86II::MO_TPOFF: O << "@TPOFF"; break;
404 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
405 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
406 case X86II::MO_GOT: O << "@GOT"; break;
407 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
408 case X86II::MO_PLT: O << "@PLT"; break;
412 /// print_pcrel_imm - This is used to print an immediate value that ends up
413 /// being encoded as a pc-relative value. These print slightly differently, for
414 /// example, a $ is not emitted.
415 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
416 const MachineOperand &MO = MI->getOperand(OpNo);
417 switch (MO.getType()) {
418 default: llvm_unreachable("Unknown pcrel immediate operand");
419 case MachineOperand::MO_Immediate:
422 case MachineOperand::MO_MachineBasicBlock:
423 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
425 case MachineOperand::MO_GlobalAddress:
426 case MachineOperand::MO_ExternalSymbol:
427 printSymbolOperand(MO);
433 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
434 const char *Modifier) {
435 const MachineOperand &MO = MI->getOperand(OpNo);
436 switch (MO.getType()) {
437 default: llvm_unreachable("unknown operand type!");
438 case MachineOperand::MO_Register: {
439 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
440 "Virtual registers should not make it this far!");
442 unsigned Reg = MO.getReg();
443 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
444 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
445 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
446 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
447 Reg = getX86SubSuperRegister(Reg, VT);
449 O << TRI->getAsmName(Reg);
453 case MachineOperand::MO_Immediate:
454 O << '$' << MO.getImm();
457 case MachineOperand::MO_JumpTableIndex:
458 case MachineOperand::MO_ConstantPoolIndex:
459 case MachineOperand::MO_GlobalAddress:
460 case MachineOperand::MO_ExternalSymbol: {
462 printSymbolOperand(MO);
468 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
469 unsigned char value = MI->getOperand(Op).getImm();
470 assert(value <= 7 && "Invalid ssecc argument!");
472 case 0: O << "eq"; break;
473 case 1: O << "lt"; break;
474 case 2: O << "le"; break;
475 case 3: O << "unord"; break;
476 case 4: O << "neq"; break;
477 case 5: O << "nlt"; break;
478 case 6: O << "nle"; break;
479 case 7: O << "ord"; break;
483 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
484 const char *Modifier) {
485 const MachineOperand &BaseReg = MI->getOperand(Op);
486 const MachineOperand &IndexReg = MI->getOperand(Op+2);
487 const MachineOperand &DispSpec = MI->getOperand(Op+3);
489 // If we really don't want to print out (rip), don't.
490 bool HasBaseReg = BaseReg.getReg() != 0;
491 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
492 BaseReg.getReg() == X86::RIP)
495 // HasParenPart - True if we will print out the () part of the mem ref.
496 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
498 if (DispSpec.isImm()) {
499 int DispVal = DispSpec.getImm();
500 if (DispVal || !HasParenPart)
503 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
504 DispSpec.isJTI() || DispSpec.isSymbol());
505 printSymbolOperand(MI->getOperand(Op+3));
509 assert(IndexReg.getReg() != X86::ESP &&
510 "X86 doesn't allow scaling by ESP");
514 printOperand(MI, Op, Modifier);
516 if (IndexReg.getReg()) {
518 printOperand(MI, Op+2, Modifier);
519 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
521 O << ',' << ScaleVal;
527 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
528 const char *Modifier) {
529 assert(isMem(MI, Op) && "Invalid memory reference!");
530 const MachineOperand &Segment = MI->getOperand(Op+4);
531 if (Segment.getReg()) {
532 printOperand(MI, Op+4, Modifier);
535 printLeaMemReference(MI, Op, Modifier);
538 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
539 const MachineBasicBlock *MBB) const {
540 if (!MAI->getSetDirective())
543 // We don't need .set machinery if we have GOT-style relocations
544 if (Subtarget->isPICStyleGOT())
547 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
548 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
550 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
552 if (Subtarget->isPICStyleRIPRel())
553 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
554 << '_' << uid << '\n';
557 PrintPICBaseSymbol();
563 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
564 PrintPICBaseSymbol();
566 PrintPICBaseSymbol();
570 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
571 const MachineBasicBlock *MBB,
572 unsigned uid) const {
573 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
574 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
576 O << JTEntryDirective << ' ';
578 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
579 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
580 << '_' << uid << "_set_" << MBB->getNumber();
581 } else if (Subtarget->isPICStyleGOT()) {
582 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
585 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
588 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
589 unsigned Reg = MO.getReg();
591 default: return true; // Unknown mode.
592 case 'b': // Print QImode register
593 Reg = getX86SubSuperRegister(Reg, MVT::i8);
595 case 'h': // Print QImode high register
596 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
598 case 'w': // Print HImode register
599 Reg = getX86SubSuperRegister(Reg, MVT::i16);
601 case 'k': // Print SImode register
602 Reg = getX86SubSuperRegister(Reg, MVT::i32);
604 case 'q': // Print DImode register
605 Reg = getX86SubSuperRegister(Reg, MVT::i64);
609 O << '%'<< TRI->getAsmName(Reg);
613 /// PrintAsmOperand - Print out an operand for an inline asm expression.
615 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
617 const char *ExtraCode) {
618 // Does this asm operand have a single letter operand modifier?
619 if (ExtraCode && ExtraCode[0]) {
620 if (ExtraCode[1] != 0) return true; // Unknown modifier.
622 const MachineOperand &MO = MI->getOperand(OpNo);
624 switch (ExtraCode[0]) {
625 default: return true; // Unknown modifier.
626 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
631 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
632 printSymbolOperand(MO);
637 printOperand(MI, OpNo);
643 case 'c': // Don't print "$" before a global var name or constant.
646 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
647 printSymbolOperand(MO);
649 printOperand(MI, OpNo);
652 case 'A': // Print '*' before a register (it must be a register)
655 printOperand(MI, OpNo);
660 case 'b': // Print QImode register
661 case 'h': // Print QImode high register
662 case 'w': // Print HImode register
663 case 'k': // Print SImode register
664 case 'q': // Print DImode register
666 return printAsmMRegister(MO, ExtraCode[0]);
667 printOperand(MI, OpNo);
670 case 'P': // This is the operand of a call, treat specially.
671 print_pcrel_imm(MI, OpNo);
674 case 'n': // Negate the immediate or print a '-' before the operand.
675 // Note: this is a temporary solution. It should be handled target
676 // independently as part of the 'MC' work.
685 printOperand(MI, OpNo);
689 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
692 const char *ExtraCode) {
693 if (ExtraCode && ExtraCode[0]) {
694 if (ExtraCode[1] != 0) return true; // Unknown modifier.
696 switch (ExtraCode[0]) {
697 default: return true; // Unknown modifier.
698 case 'b': // Print QImode register
699 case 'h': // Print QImode high register
700 case 'w': // Print HImode register
701 case 'k': // Print SImode register
702 case 'q': // Print SImode register
703 // These only apply to registers, ignore on mem.
705 case 'P': // Don't print @PLT, but do print as memory.
706 printMemReference(MI, OpNo, "no-rip");
710 printMemReference(MI, OpNo);
716 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
717 /// AT&T syntax to the current output stream.
719 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
722 processDebugLoc(MI->getDebugLoc());
724 printInstructionThroughMCStreamer(MI);
726 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
731 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
732 const TargetData *TD = TM.getTargetData();
734 if (!GVar->hasInitializer())
735 return; // External global require no code
737 // Check to see if this is a special global used by LLVM, if so, emit it.
738 if (EmitSpecialLLVMGlobal(GVar)) {
739 if (Subtarget->isTargetDarwin() &&
740 TM.getRelocationModel() == Reloc::Static) {
741 if (GVar->getName() == "llvm.global_ctors")
742 O << ".reference .constructors_used\n";
743 else if (GVar->getName() == "llvm.global_dtors")
744 O << ".reference .destructors_used\n";
749 std::string name = Mang->getMangledName(GVar);
750 Constant *C = GVar->getInitializer();
751 const Type *Type = C->getType();
752 unsigned Size = TD->getTypeAllocSize(Type);
753 unsigned Align = TD->getPreferredAlignmentLog(GVar);
755 printVisibility(name, GVar->getVisibility());
757 if (Subtarget->isTargetELF())
758 O << "\t.type\t" << name << ",@object\n";
761 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
762 const MCSection *TheSection =
763 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
764 OutStreamer.SwitchSection(TheSection);
766 // FIXME: get this stuff from section kind flags.
767 if (C->isNullValue() && !GVar->hasSection() &&
768 // Don't put things that should go in the cstring section into "comm".
769 !TheSection->getKind().isMergeableCString()) {
770 if (GVar->hasExternalLinkage()) {
771 if (const char *Directive = MAI->getZeroFillDirective()) {
772 O << "\t.globl " << name << '\n';
773 O << Directive << "__DATA, __common, " << name << ", "
774 << Size << ", " << Align << '\n';
779 if (!GVar->isThreadLocal() &&
780 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
781 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
783 if (MAI->getLCOMMDirective() != NULL) {
784 if (GVar->hasLocalLinkage()) {
785 O << MAI->getLCOMMDirective() << name << ',' << Size;
786 if (Subtarget->isTargetDarwin())
788 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
789 O << "\t.globl " << name << '\n'
790 << MAI->getWeakDefDirective() << name << '\n';
791 EmitAlignment(Align, GVar);
794 O.PadToColumn(MAI->getCommentColumn());
795 O << MAI->getCommentString() << ' ';
796 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
799 EmitGlobalConstant(C);
802 O << MAI->getCOMMDirective() << name << ',' << Size;
803 if (MAI->getCOMMDirectiveTakesAlignment())
804 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
807 if (!Subtarget->isTargetCygMing()) {
808 if (GVar->hasLocalLinkage())
809 O << "\t.local\t" << name << '\n';
811 O << MAI->getCOMMDirective() << name << ',' << Size;
812 if (MAI->getCOMMDirectiveTakesAlignment())
813 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
816 O.PadToColumn(MAI->getCommentColumn());
817 O << MAI->getCommentString() << ' ';
818 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
825 switch (GVar->getLinkage()) {
826 case GlobalValue::CommonLinkage:
827 case GlobalValue::LinkOnceAnyLinkage:
828 case GlobalValue::LinkOnceODRLinkage:
829 case GlobalValue::WeakAnyLinkage:
830 case GlobalValue::WeakODRLinkage:
831 case GlobalValue::LinkerPrivateLinkage:
832 if (Subtarget->isTargetDarwin()) {
833 O << "\t.globl " << name << '\n'
834 << MAI->getWeakDefDirective() << name << '\n';
835 } else if (Subtarget->isTargetCygMing()) {
836 O << "\t.globl\t" << name << "\n"
837 "\t.linkonce same_size\n";
839 O << "\t.weak\t" << name << '\n';
842 case GlobalValue::DLLExportLinkage:
843 case GlobalValue::AppendingLinkage:
844 // FIXME: appending linkage variables should go into a section of
845 // their name or something. For now, just emit them as external.
846 case GlobalValue::ExternalLinkage:
847 // If external or appending, declare as a global symbol
848 O << "\t.globl " << name << '\n';
850 case GlobalValue::PrivateLinkage:
851 case GlobalValue::InternalLinkage:
854 llvm_unreachable("Unknown linkage type!");
857 EmitAlignment(Align, GVar);
860 O.PadToColumn(MAI->getCommentColumn());
861 O << MAI->getCommentString() << ' ';
862 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
866 EmitGlobalConstant(C);
868 if (MAI->hasDotTypeDotSizeDirective())
869 O << "\t.size\t" << name << ", " << Size << '\n';
872 static int SortSymbolPair(const void *LHS, const void *RHS) {
873 MCSymbol *LHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)LHS)->first;
874 MCSymbol *RHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)RHS)->first;
875 return LHSS->getName().compare(RHSS->getName());
878 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
880 static std::vector<std::pair<MCSymbol*, MCSymbol*> >
881 GetSortedStubs(const DenseMap<MCSymbol*, MCSymbol*> &Map) {
882 assert(!Map.empty());
883 std::vector<std::pair<MCSymbol*, MCSymbol*> > List(Map.begin(), Map.end());
884 qsort(&List[0], List.size(), sizeof(List[0]), SortSymbolPair);
888 bool X86ATTAsmPrinter::doFinalization(Module &M) {
889 // Print out module-level global variables here.
890 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
892 if (I->hasDLLExportLinkage())
893 DLLExportedGVs.insert(Mang->getMangledName(I));
896 if (Subtarget->isTargetDarwin()) {
897 // All darwin targets use mach-o.
898 TargetLoweringObjectFileMachO &TLOFMacho =
899 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
901 // Add the (possibly multiple) personalities to the set of global value
902 // stubs. Only referenced functions get into the Personalities list.
903 if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
904 const std::vector<Function*> &Personalities = MMI->getPersonalities();
905 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
906 if (Personalities[i] == 0)
909 SmallString<128> Name;
910 Mang->getNameWithPrefix(Name, Personalities[i], true /*private label*/);
911 Name += "$non_lazy_ptr";
912 MCSymbol *NLPName = OutContext.GetOrCreateSymbol(Name.str());
914 MCSymbol *&StubName = GVStubs[NLPName];
915 if (StubName != 0) continue;
919 Mang->getNameWithPrefix(Name, Personalities[i], false);
920 StubName = OutContext.GetOrCreateSymbol(Name.str());
924 // Output stubs for dynamically-linked functions
925 if (!FnStubs.empty()) {
926 const MCSection *TheSection =
927 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
928 MCSectionMachO::S_SYMBOL_STUBS |
929 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
930 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
931 5, SectionKind::getMetadata());
932 OutStreamer.SwitchSection(TheSection);
934 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
935 = GetSortedStubs(FnStubs);
936 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
937 Stubs[i].first->print(O, MAI);
938 O << ":\n" << "\t.indirect_symbol ";
939 // Get the MCSymbol without the $stub suffix.
940 Stubs[i].second->print(O, MAI);
941 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
946 // Output stubs for external and common global variables.
947 if (!GVStubs.empty()) {
948 const MCSection *TheSection =
949 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
950 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
951 SectionKind::getMetadata());
952 OutStreamer.SwitchSection(TheSection);
954 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
955 = GetSortedStubs(GVStubs);
956 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
957 Stubs[i].first->print(O, MAI);
958 O << ":\n\t.indirect_symbol ";
959 Stubs[i].second->print(O, MAI);
960 O << "\n\t.long\t0\n";
964 if (!HiddenGVStubs.empty()) {
965 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
968 std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
969 = GetSortedStubs(HiddenGVStubs);
970 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
971 Stubs[i].first->print(O, MAI);
972 O << ":\n" << MAI->getData32bitsDirective();
973 Stubs[i].second->print(O, MAI);
978 // Funny Darwin hack: This flag tells the linker that no global symbols
979 // contain code that falls through to other global symbols (e.g. the obvious
980 // implementation of multiple entry points). If this doesn't occur, the
981 // linker can safely perform dead code stripping. Since LLVM never
982 // generates code that does this, it is always safe to set.
983 O << "\t.subsections_via_symbols\n";
984 } else if (Subtarget->isTargetCygMing()) {
985 // Emit type information for external functions
986 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
988 O << "\t.def\t " << i->getKeyData()
989 << ";\t.scl\t" << COFF::C_EXT
990 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
996 // Output linker support code for dllexported globals on windows.
997 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
998 // dllexport symbols only exist on coff targets.
999 TargetLoweringObjectFileCOFF &TLOFMacho =
1000 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
1002 OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
1003 SectionKind::getMetadata()));
1005 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1006 e = DLLExportedGVs.end(); i != e; ++i)
1007 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1009 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1010 e = DLLExportedFns.end();
1012 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1015 // Do common shutdown.
1016 return AsmPrinter::doFinalization(M);