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/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetOptions.h"
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39 static std::string getPICLabelString(unsigned FnNum,
40 const TargetAsmInfo *TAI,
41 const X86Subtarget* Subtarget) {
43 if (Subtarget->isTargetDarwin())
44 label = "\"L" + utostr_32(FnNum) + "$pb\"";
45 else if (Subtarget->isTargetELF())
46 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
48 assert(0 && "Don't know how to print PIC label!\n");
53 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
54 const TargetData *TD) {
55 X86MachineFunctionInfo Info;
58 switch (F->getCallingConv()) {
59 case CallingConv::X86_StdCall:
60 Info.setDecorationStyle(StdCall);
62 case CallingConv::X86_FastCall:
63 Info.setDecorationStyle(FastCall);
70 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
71 AI != AE; ++AI, ++argNum) {
72 const Type* Ty = AI->getType();
74 // 'Dereference' type in case of byval parameter attribute
75 if (F->paramHasAttr(argNum, Attribute::ByVal))
76 Ty = cast<PointerType>(Ty)->getElementType();
78 // Size should be aligned to DWORD boundary
79 Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
82 // We're not supporting tooooo huge arguments :)
83 Info.setBytesToPopOnReturn((unsigned int)Size);
87 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
88 /// Don't print things like \\n or \\0.
89 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
90 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
96 /// decorateName - Query FunctionInfoMap and use this information for various
98 void X86ATTAsmPrinter::decorateName(std::string &Name,
99 const GlobalValue *GV) {
100 const Function *F = dyn_cast<Function>(GV);
103 // We don't want to decorate non-stdcall or non-fastcall functions right now
104 unsigned CC = F->getCallingConv();
105 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
108 // Decorate names only when we're targeting Cygwin/Mingw32 targets
109 if (!Subtarget->isTargetCygMing())
112 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
114 const X86MachineFunctionInfo *Info;
115 if (info_item == FunctionInfoMap.end()) {
116 // Calculate apropriate function info and populate map
117 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
118 Info = &FunctionInfoMap[F];
120 Info = &info_item->second;
123 const FunctionType *FT = F->getFunctionType();
124 switch (Info->getDecorationStyle()) {
128 // "Pure" variadic functions do not receive @0 suffix.
129 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
130 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
131 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
134 // "Pure" variadic functions do not receive @0 suffix.
135 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
136 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
137 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
139 if (Name[0] == '_') {
146 assert(0 && "Unsupported DecorationStyle");
150 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
151 const Function *F = MF.getFunction();
153 decorateName(CurrentFnName, F);
155 SwitchToSection(TAI->SectionForGlobal(F));
157 unsigned FnAlign = 4;
158 if (F->hasFnAttr(Attribute::OptimizeForSize))
160 switch (F->getLinkage()) {
161 default: assert(0 && "Unknown linkage type!");
162 case Function::InternalLinkage: // Symbols default to internal.
163 case Function::PrivateLinkage:
164 EmitAlignment(FnAlign, F);
166 case Function::DLLExportLinkage:
167 case Function::ExternalLinkage:
168 EmitAlignment(FnAlign, F);
169 O << "\t.globl\t" << CurrentFnName << '\n';
171 case Function::LinkOnceAnyLinkage:
172 case Function::LinkOnceODRLinkage:
173 case Function::WeakAnyLinkage:
174 case Function::WeakODRLinkage:
175 EmitAlignment(FnAlign, F);
176 if (Subtarget->isTargetDarwin()) {
177 O << "\t.globl\t" << CurrentFnName << '\n';
178 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
179 } else if (Subtarget->isTargetCygMing()) {
180 O << "\t.globl\t" << CurrentFnName << "\n"
181 "\t.linkonce discard\n";
183 O << "\t.weak\t" << CurrentFnName << '\n';
188 printVisibility(CurrentFnName, F->getVisibility());
190 if (Subtarget->isTargetELF())
191 O << "\t.type\t" << CurrentFnName << ",@function\n";
192 else if (Subtarget->isTargetCygMing()) {
193 O << "\t.def\t " << CurrentFnName
195 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
196 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
200 O << CurrentFnName << ":\n";
201 // Add some workaround for linkonce linkage on Cygwin\MinGW
202 if (Subtarget->isTargetCygMing() &&
203 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
204 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
207 /// runOnMachineFunction - This uses the printMachineInstruction()
208 /// method to print assembly for each instruction.
210 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
211 const Function *F = MF.getFunction();
213 unsigned CC = F->getCallingConv();
215 SetupMachineFunction(MF);
218 // Populate function information map. Actually, We don't want to populate
219 // non-stdcall or non-fastcall functions' information right now.
220 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
221 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
223 // Print out constants referenced by the function
224 EmitConstantPool(MF.getConstantPool());
226 if (F->hasDLLExportLinkage())
227 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
229 // Print the 'header' of function
230 emitFunctionHeader(MF);
232 // Emit pre-function debug and/or EH information.
233 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
234 DW->BeginFunction(&MF);
236 // Print out code for the function.
237 bool hasAnyRealCode = false;
238 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
240 // Print a label for the basic block.
241 if (!I->pred_empty()) {
242 printBasicBlockLabel(I, true, true);
245 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
247 // Print the assembly for the instruction.
249 hasAnyRealCode = true;
250 printMachineInstruction(II);
254 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
255 // If the function is empty, then we need to emit *something*. Otherwise,
256 // the function's label might be associated with something that it wasn't
257 // meant to be associated with. We emit a noop in this situation.
258 // We are assuming inline asms are code.
262 if (TAI->hasDotTypeDotSizeDirective())
263 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
265 // Emit post-function debug information.
266 if (TAI->doesSupportDebugInformation())
267 DW->EndFunction(&MF);
269 // Print out jump tables referenced by the function.
270 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
274 // We didn't modify anything.
278 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
279 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
282 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
283 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
284 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
287 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
288 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
291 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
292 const char *Modifier, bool NotRIPRel) {
293 const MachineOperand &MO = MI->getOperand(OpNo);
294 switch (MO.getType()) {
295 case MachineOperand::MO_Register: {
296 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
297 "Virtual registers should not make it this far!");
299 unsigned Reg = MO.getReg();
300 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
301 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
302 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
303 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
304 Reg = getX86SubSuperRegister(Reg, VT);
306 O << TRI->getAsmName(Reg);
310 case MachineOperand::MO_Immediate:
312 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
316 case MachineOperand::MO_MachineBasicBlock:
317 printBasicBlockLabel(MO.getMBB());
319 case MachineOperand::MO_JumpTableIndex: {
320 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
321 if (!isMemOp) O << '$';
322 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
325 if (TM.getRelocationModel() == Reloc::PIC_) {
326 if (Subtarget->isPICStyleStub())
327 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
329 else if (Subtarget->isPICStyleGOT())
333 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
337 case MachineOperand::MO_ConstantPoolIndex: {
338 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
339 if (!isMemOp) O << '$';
340 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
343 if (TM.getRelocationModel() == Reloc::PIC_) {
344 if (Subtarget->isPICStyleStub())
345 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
347 else if (Subtarget->isPICStyleGOT())
351 printOffset(MO.getOffset());
353 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
357 case MachineOperand::MO_GlobalAddress: {
358 bool isCallOp = Modifier && !strcmp(Modifier, "call");
359 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
360 bool needCloseParen = false;
362 const GlobalValue *GV = MO.getGlobal();
363 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
365 // If GV is an alias then use the aliasee for determining
367 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
368 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
371 bool isThreadLocal = GVar && GVar->isThreadLocal();
373 std::string Name = Mang->getValueName(GV);
374 decorateName(Name, GV);
376 if (!isMemOp && !isCallOp)
378 else if (Name[0] == '$') {
379 // The name begins with a dollar-sign. In order to avoid having it look
380 // like an integer immediate to the assembler, enclose it in parens.
382 needCloseParen = true;
385 if (shouldPrintStub(TM, Subtarget)) {
386 // Link-once, declaration, or Weakly-linked global variables need
387 // non-lazily-resolved stubs
388 if (GV->isDeclaration() || GV->isWeakForLinker()) {
389 // Dynamically-resolved functions need a stub for the function.
390 if (isCallOp && isa<Function>(GV)) {
391 // Function stubs are no longer needed for Mac OS X 10.5 and up.
392 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
395 FnStubs.insert(Name);
396 printSuffixedName(Name, "$stub");
398 } else if (GV->hasHiddenVisibility()) {
399 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
400 // Definition is not definitely in the current translation unit.
403 HiddenGVStubs.insert(Name);
404 printSuffixedName(Name, "$non_lazy_ptr");
407 GVStubs.insert(Name);
408 printSuffixedName(Name, "$non_lazy_ptr");
411 if (GV->hasDLLImportLinkage())
416 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
417 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
419 if (GV->hasDLLImportLinkage()) {
425 if (shouldPrintPLT(TM, Subtarget)) {
426 // Assemble call via PLT for externally visible symbols
427 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
428 !GV->hasLocalLinkage())
431 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
432 // Save function name for later type emission
433 FnStubs.insert(Name);
437 if (GV->hasExternalWeakLinkage())
438 ExtWeakSymbols.insert(GV);
440 printOffset(MO.getOffset());
443 TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
445 case TLSModel::GeneralDynamic:
448 case TLSModel::LocalDynamic:
449 // O << "@TLSLD"; // local dynamic not implemented
452 case TLSModel::InitialExec:
453 if (Subtarget->is64Bit())
454 O << "@TLSGD"; // 64 bit intial exec not implemented
458 case TLSModel::LocalExec:
459 if (Subtarget->is64Bit())
460 O << "@TLSGD"; // 64 bit local exec not implemented
465 assert (0 && "Unknown TLS model");
467 } else if (isMemOp) {
468 if (shouldPrintGOT(TM, Subtarget)) {
469 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
473 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
474 TM.getRelocationModel() != Reloc::Static) {
475 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
478 if (needCloseParen) {
479 needCloseParen = false;
483 // Use rip when possible to reduce code size, except when
484 // index or base register are also part of the address. e.g.
485 // foo(%rip)(%rcx,%rax,4) is not legal
495 case MachineOperand::MO_ExternalSymbol: {
496 bool isCallOp = Modifier && !strcmp(Modifier, "call");
497 bool needCloseParen = false;
498 std::string Name(TAI->getGlobalPrefix());
499 Name += MO.getSymbolName();
500 // Print function stub suffix unless it's Mac OS X 10.5 and up.
501 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
502 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
503 FnStubs.insert(Name);
504 printSuffixedName(Name, "$stub");
509 else if (Name[0] == '$') {
510 // The name begins with a dollar-sign. In order to avoid having it look
511 // like an integer immediate to the assembler, enclose it in parens.
513 needCloseParen = true;
518 if (shouldPrintPLT(TM, Subtarget)) {
519 std::string GOTName(TAI->getGlobalPrefix());
520 GOTName+="_GLOBAL_OFFSET_TABLE_";
522 // HACK! Emit extra offset to PC during printing GOT offset to
523 // compensate for the size of popl instruction. The resulting code
527 // popl %some_register
528 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
530 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
539 if (!isCallOp && Subtarget->isPICStyleRIPRel())
545 O << "<unknown operand type>"; return;
549 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
550 unsigned char value = MI->getOperand(Op).getImm();
551 assert(value <= 7 && "Invalid ssecc argument!");
553 case 0: O << "eq"; break;
554 case 1: O << "lt"; break;
555 case 2: O << "le"; break;
556 case 3: O << "unord"; break;
557 case 4: O << "neq"; break;
558 case 5: O << "nlt"; break;
559 case 6: O << "nle"; break;
560 case 7: O << "ord"; break;
564 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
565 const char *Modifier){
566 assert(isMem(MI, Op) && "Invalid memory reference!");
567 MachineOperand BaseReg = MI->getOperand(Op);
568 MachineOperand IndexReg = MI->getOperand(Op+2);
569 const MachineOperand &DispSpec = MI->getOperand(Op+3);
571 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
572 if (DispSpec.isGlobal() ||
575 printOperand(MI, Op+3, "mem", NotRIPRel);
577 int DispVal = DispSpec.getImm();
578 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
582 if (IndexReg.getReg() || BaseReg.getReg()) {
583 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
584 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
586 // There are cases where we can end up with ESP/RSP in the indexreg slot.
587 // If this happens, swap the base/index register to support assemblers that
588 // don't work when the index is *SP.
589 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
590 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
591 std::swap(BaseReg, IndexReg);
592 std::swap(BaseRegOperand, IndexRegOperand);
596 if (BaseReg.getReg())
597 printOperand(MI, Op+BaseRegOperand, Modifier);
599 if (IndexReg.getReg()) {
601 printOperand(MI, Op+IndexRegOperand, Modifier);
603 O << ',' << ScaleVal;
609 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
610 const MachineBasicBlock *MBB) const {
611 if (!TAI->getSetDirective())
614 // We don't need .set machinery if we have GOT-style relocations
615 if (Subtarget->isPICStyleGOT())
618 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
619 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
620 printBasicBlockLabel(MBB, false, false, false);
621 if (Subtarget->isPICStyleRIPRel())
622 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
623 << '_' << uid << '\n';
625 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
628 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
629 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
630 O << label << '\n' << label << ':';
634 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
635 const MachineBasicBlock *MBB,
638 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
639 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
641 O << JTEntryDirective << ' ';
643 if (TM.getRelocationModel() == Reloc::PIC_) {
644 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
645 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
646 << '_' << uid << "_set_" << MBB->getNumber();
647 } else if (Subtarget->isPICStyleGOT()) {
648 printBasicBlockLabel(MBB, false, false, false);
651 assert(0 && "Don't know how to print MBB label for this PIC mode");
653 printBasicBlockLabel(MBB, false, false, false);
656 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
658 unsigned Reg = MO.getReg();
660 default: return true; // Unknown mode.
661 case 'b': // Print QImode register
662 Reg = getX86SubSuperRegister(Reg, MVT::i8);
664 case 'h': // Print QImode high register
665 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
667 case 'w': // Print HImode register
668 Reg = getX86SubSuperRegister(Reg, MVT::i16);
670 case 'k': // Print SImode register
671 Reg = getX86SubSuperRegister(Reg, MVT::i32);
673 case 'q': // Print DImode register
674 Reg = getX86SubSuperRegister(Reg, MVT::i64);
678 O << '%'<< TRI->getAsmName(Reg);
682 /// PrintAsmOperand - Print out an operand for an inline asm expression.
684 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
686 const char *ExtraCode) {
687 // Does this asm operand have a single letter operand modifier?
688 if (ExtraCode && ExtraCode[0]) {
689 if (ExtraCode[1] != 0) return true; // Unknown modifier.
691 switch (ExtraCode[0]) {
692 default: return true; // Unknown modifier.
693 case 'c': // Don't print "$" before a global var name or constant.
694 printOperand(MI, OpNo, "mem");
696 case 'b': // Print QImode register
697 case 'h': // Print QImode high register
698 case 'w': // Print HImode register
699 case 'k': // Print SImode register
700 case 'q': // Print DImode register
701 if (MI->getOperand(OpNo).isReg())
702 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
703 printOperand(MI, OpNo);
706 case 'P': // Don't print @PLT, but do print as memory.
707 printOperand(MI, OpNo, "mem");
712 printOperand(MI, OpNo);
716 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
719 const char *ExtraCode) {
720 if (ExtraCode && ExtraCode[0]) {
721 if (ExtraCode[1] != 0) return true; // Unknown modifier.
723 switch (ExtraCode[0]) {
724 default: return true; // Unknown modifier.
725 case 'b': // Print QImode register
726 case 'h': // Print QImode high register
727 case 'w': // Print HImode register
728 case 'k': // Print SImode register
729 case 'q': // Print SImode register
730 // These only apply to registers, ignore on mem.
732 case 'P': // Don't print @PLT, but do print as memory.
733 printOperand(MI, OpNo, "mem");
737 printMemReference(MI, OpNo);
741 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
742 /// AT&T syntax to the current output stream.
744 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
747 // Call the autogenerated instruction printer routines.
748 printInstruction(MI);
752 bool X86ATTAsmPrinter::doInitialization(Module &M) {
754 bool Result = AsmPrinter::doInitialization(M);
756 if (TAI->doesSupportDebugInformation()) {
757 // Let PassManager know we need debug information and relay
758 // the MachineModuleInfo address on to DwarfWriter.
759 // AsmPrinter::doInitialization did this analysis.
760 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
761 DW = getAnalysisIfAvailable<DwarfWriter>();
762 DW->BeginModule(&M, MMI, O, this, TAI);
765 // Darwin wants symbols to be quoted if they have complex names.
766 if (Subtarget->isTargetDarwin())
767 Mang->setUseQuotes(true);
773 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
774 const TargetData *TD = TM.getTargetData();
776 if (!GVar->hasInitializer())
777 return; // External global require no code
779 // Check to see if this is a special global used by LLVM, if so, emit it.
780 if (EmitSpecialLLVMGlobal(GVar)) {
781 if (Subtarget->isTargetDarwin() &&
782 TM.getRelocationModel() == Reloc::Static) {
783 if (GVar->getName() == "llvm.global_ctors")
784 O << ".reference .constructors_used\n";
785 else if (GVar->getName() == "llvm.global_dtors")
786 O << ".reference .destructors_used\n";
791 std::string name = Mang->getValueName(GVar);
792 Constant *C = GVar->getInitializer();
793 const Type *Type = C->getType();
794 unsigned Size = TD->getTypePaddedSize(Type);
795 unsigned Align = TD->getPreferredAlignmentLog(GVar);
797 printVisibility(name, GVar->getVisibility());
799 if (Subtarget->isTargetELF())
800 O << "\t.type\t" << name << ",@object\n";
802 SwitchToSection(TAI->SectionForGlobal(GVar));
804 if (C->isNullValue() && !GVar->hasSection() &&
805 !(Subtarget->isTargetDarwin() &&
806 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
807 // FIXME: This seems to be pretty darwin-specific
808 if (GVar->hasExternalLinkage()) {
809 if (const char *Directive = TAI->getZeroFillDirective()) {
810 O << "\t.globl " << name << '\n';
811 O << Directive << "__DATA, __common, " << name << ", "
812 << Size << ", " << Align << '\n';
817 if (!GVar->isThreadLocal() &&
818 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
819 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
821 if (TAI->getLCOMMDirective() != NULL) {
822 if (GVar->hasLocalLinkage()) {
823 O << TAI->getLCOMMDirective() << name << ',' << Size;
824 if (Subtarget->isTargetDarwin())
826 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
827 O << "\t.globl " << name << '\n'
828 << TAI->getWeakDefDirective() << name << '\n';
829 EmitAlignment(Align, GVar);
830 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
831 PrintUnmangledNameSafely(GVar, O);
833 EmitGlobalConstant(C);
836 O << TAI->getCOMMDirective() << name << ',' << Size;
837 if (TAI->getCOMMDirectiveTakesAlignment())
838 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
841 if (!Subtarget->isTargetCygMing()) {
842 if (GVar->hasLocalLinkage())
843 O << "\t.local\t" << name << '\n';
845 O << TAI->getCOMMDirective() << name << ',' << Size;
846 if (TAI->getCOMMDirectiveTakesAlignment())
847 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
849 O << "\t\t" << TAI->getCommentString() << ' ';
850 PrintUnmangledNameSafely(GVar, O);
856 switch (GVar->getLinkage()) {
857 case GlobalValue::CommonLinkage:
858 case GlobalValue::LinkOnceAnyLinkage:
859 case GlobalValue::LinkOnceODRLinkage:
860 case GlobalValue::WeakAnyLinkage:
861 case GlobalValue::WeakODRLinkage:
862 if (Subtarget->isTargetDarwin()) {
863 O << "\t.globl " << name << '\n'
864 << TAI->getWeakDefDirective() << name << '\n';
865 } else if (Subtarget->isTargetCygMing()) {
866 O << "\t.globl\t" << name << "\n"
867 "\t.linkonce same_size\n";
869 O << "\t.weak\t" << name << '\n';
872 case GlobalValue::DLLExportLinkage:
873 case GlobalValue::AppendingLinkage:
874 // FIXME: appending linkage variables should go into a section of
875 // their name or something. For now, just emit them as external.
876 case GlobalValue::ExternalLinkage:
877 // If external or appending, declare as a global symbol
878 O << "\t.globl " << name << '\n';
880 case GlobalValue::PrivateLinkage:
881 case GlobalValue::InternalLinkage:
884 assert(0 && "Unknown linkage type!");
887 EmitAlignment(Align, GVar);
888 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
889 PrintUnmangledNameSafely(GVar, O);
891 if (TAI->hasDotTypeDotSizeDirective())
892 O << "\t.size\t" << name << ", " << Size << '\n';
894 EmitGlobalConstant(C);
897 /// printGVStub - Print stub for a global value.
899 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
900 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
901 O << ":\n\t.indirect_symbol ";
902 if (Prefix) O << Prefix;
903 O << GV << "\n\t.long\t0\n";
906 /// printHiddenGVStub - Print stub for a hidden global value.
908 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
910 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
911 if (Prefix) O << Prefix;
912 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
916 bool X86ATTAsmPrinter::doFinalization(Module &M) {
917 // Print out module-level global variables here.
918 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
920 printModuleLevelGV(I);
922 if (I->hasDLLExportLinkage())
923 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
925 // If the global is a extern weak symbol, remember to emit the weak
927 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
928 // not used. But currently it's the only way to deal with extern weak
929 // initializers hidden deep inside constant expressions.
930 if (I->hasExternalWeakLinkage())
931 ExtWeakSymbols.insert(I);
934 for (Module::const_iterator I = M.begin(), E = M.end();
936 // If the global is a extern weak symbol, remember to emit the weak
938 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
939 // not used. But currently it's the only way to deal with extern weak
940 // initializers hidden deep inside constant expressions.
941 if (I->hasExternalWeakLinkage())
942 ExtWeakSymbols.insert(I);
945 // Output linker support code for dllexported globals
946 if (!DLLExportedGVs.empty())
947 SwitchToDataSection(".section .drectve");
949 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
950 e = DLLExportedGVs.end();
952 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
954 if (!DLLExportedFns.empty()) {
955 SwitchToDataSection(".section .drectve");
958 for (StringSet<>::iterator i = DLLExportedFns.begin(),
959 e = DLLExportedFns.end();
961 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
963 if (Subtarget->isTargetDarwin()) {
964 SwitchToDataSection("");
966 // Output stubs for dynamically-linked functions
967 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
969 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
970 "self_modifying_code+pure_instructions,5", 0);
971 const char *p = i->getKeyData();
972 printSuffixedName(p, "$stub");
974 "\t.indirect_symbol " << p << "\n"
975 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
980 // Print global value stubs.
981 bool InStubSection = false;
982 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
983 // Add the (possibly multiple) personalities to the set of global values.
984 // Only referenced functions get into the Personalities list.
985 const std::vector<Function *>& Personalities = MMI->getPersonalities();
986 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
987 E = Personalities.end(); I != E; ++I) {
990 if (!InStubSection) {
992 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
993 InStubSection = true;
995 printGVStub((*I)->getNameStart(), "_");
999 // Output stubs for external and common global variables.
1000 if (!InStubSection && !GVStubs.empty())
1001 SwitchToDataSection(
1002 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1003 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1005 printGVStub(i->getKeyData());
1007 if (!HiddenGVStubs.empty()) {
1008 SwitchToSection(TAI->getDataSection());
1009 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1011 printHiddenGVStub(i->getKeyData());
1014 // Emit final debug information.
1015 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1018 // Funny Darwin hack: This flag tells the linker that no global symbols
1019 // contain code that falls through to other global symbols (e.g. the obvious
1020 // implementation of multiple entry points). If this doesn't occur, the
1021 // linker can safely perform dead code stripping. Since LLVM never
1022 // generates code that does this, it is always safe to set.
1023 O << "\t.subsections_via_symbols\n";
1024 } else if (Subtarget->isTargetCygMing()) {
1025 // Emit type information for external functions
1026 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1028 O << "\t.def\t " << i->getKeyData()
1029 << ";\t.scl\t" << COFF::C_EXT
1030 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1034 // Emit final debug information.
1035 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1037 } else if (Subtarget->isTargetELF()) {
1038 // Emit final debug information.
1039 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1043 return AsmPrinter::doFinalization(M);
1046 // Include the auto-generated portion of the assembly writer.
1047 #include "X86GenAsmWriter.inc"