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/MachineJumpTableInfo.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetOptions.h"
35 STATISTIC(EmittedInsts, "Number of machine instrs printed");
37 static std::string getPICLabelString(unsigned FnNum,
38 const TargetAsmInfo *TAI,
39 const X86Subtarget* Subtarget) {
41 if (Subtarget->isTargetDarwin())
42 label = "\"L" + utostr_32(FnNum) + "$pb\"";
43 else if (Subtarget->isTargetELF())
44 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
46 assert(0 && "Don't know how to print PIC label!\n");
51 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
52 const TargetData *TD) {
53 X86MachineFunctionInfo Info;
56 switch (F->getCallingConv()) {
57 case CallingConv::X86_StdCall:
58 Info.setDecorationStyle(StdCall);
60 case CallingConv::X86_FastCall:
61 Info.setDecorationStyle(FastCall);
68 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
69 AI != AE; ++AI, ++argNum) {
70 const Type* Ty = AI->getType();
72 // 'Dereference' type in case of byval parameter attribute
73 if (F->paramHasAttr(argNum, ParamAttr::ByVal))
74 Ty = cast<PointerType>(Ty)->getElementType();
76 // Size should be aligned to DWORD boundary
77 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
80 // We're not supporting tooooo huge arguments :)
81 Info.setBytesToPopOnReturn((unsigned int)Size);
85 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
86 /// Don't print things like \n or \0.
87 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
88 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
94 /// decorateName - Query FunctionInfoMap and use this information for various
96 void X86ATTAsmPrinter::decorateName(std::string &Name,
97 const GlobalValue *GV) {
98 const Function *F = dyn_cast<Function>(GV);
101 // We don't want to decorate non-stdcall or non-fastcall functions right now
102 unsigned CC = F->getCallingConv();
103 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
106 // Decorate names only when we're targeting Cygwin/Mingw32 targets
107 if (!Subtarget->isTargetCygMing())
110 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
112 const X86MachineFunctionInfo *Info;
113 if (info_item == FunctionInfoMap.end()) {
114 // Calculate apropriate function info and populate map
115 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
116 Info = &FunctionInfoMap[F];
118 Info = &info_item->second;
121 const FunctionType *FT = F->getFunctionType();
122 switch (Info->getDecorationStyle()) {
126 // "Pure" variadic functions do not receive @0 suffix.
127 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
128 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
129 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
132 // "Pure" variadic functions do not receive @0 suffix.
133 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
134 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
135 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
137 if (Name[0] == '_') {
144 assert(0 && "Unsupported DecorationStyle");
148 /// getSectionForFunction - Return the section that we should emit the
149 /// specified function body into.
150 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
151 switch (F.getLinkage()) {
152 default: assert(0 && "Unknown linkage type!");
153 case Function::InternalLinkage:
154 case Function::DLLExportLinkage:
155 case Function::ExternalLinkage:
156 return TAI->getTextSection();
157 case Function::WeakLinkage:
158 case Function::LinkOnceLinkage:
159 if (Subtarget->isTargetDarwin()) {
160 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
161 } else if (Subtarget->isTargetCygMing()) {
162 return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"";
164 return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
170 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
171 const Function *F = MF.getFunction();
173 decorateName(CurrentFnName, F);
175 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
177 unsigned FnAlign = OptimizeForSize ? 1 : 4;
178 switch (F->getLinkage()) {
179 default: assert(0 && "Unknown linkage type!");
180 case Function::InternalLinkage: // Symbols default to internal.
181 EmitAlignment(FnAlign, F);
183 case Function::DLLExportLinkage:
184 case Function::ExternalLinkage:
185 EmitAlignment(FnAlign, F);
186 O << "\t.globl\t" << CurrentFnName << '\n';
188 case Function::LinkOnceLinkage:
189 case Function::WeakLinkage:
190 EmitAlignment(FnAlign, F);
191 if (Subtarget->isTargetDarwin()) {
192 O << "\t.globl\t" << CurrentFnName << '\n';
193 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
194 } else if (Subtarget->isTargetCygMing()) {
195 O << "\t.globl\t" << CurrentFnName << "\n"
196 "\t.linkonce discard\n";
198 O << "\t.weak\t" << CurrentFnName << '\n';
202 if (F->hasHiddenVisibility()) {
203 if (const char *Directive = TAI->getHiddenDirective())
204 O << Directive << CurrentFnName << '\n';
205 } else if (F->hasProtectedVisibility()) {
206 if (const char *Directive = TAI->getProtectedDirective())
207 O << Directive << CurrentFnName << '\n';
210 if (Subtarget->isTargetELF())
211 O << "\t.type\t" << CurrentFnName << ",@function\n";
212 else if (Subtarget->isTargetCygMing()) {
213 O << "\t.def\t " << CurrentFnName
215 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
216 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
220 O << CurrentFnName << ":\n";
221 // Add some workaround for linkonce linkage on Cygwin\MinGW
222 if (Subtarget->isTargetCygMing() &&
223 (F->getLinkage() == Function::LinkOnceLinkage ||
224 F->getLinkage() == Function::WeakLinkage))
225 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
228 /// runOnMachineFunction - This uses the printMachineInstruction()
229 /// method to print assembly for each instruction.
231 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
232 const Function *F = MF.getFunction();
233 unsigned CC = F->getCallingConv();
235 if (TAI->doesSupportDebugInformation()) {
236 // Let PassManager know we need debug information and relay
237 // the MachineModuleInfo address on to DwarfWriter.
238 MMI = &getAnalysis<MachineModuleInfo>();
239 DW.SetModuleInfo(MMI);
242 SetupMachineFunction(MF);
245 // Populate function information map. Actually, We don't want to populate
246 // non-stdcall or non-fastcall functions' information right now.
247 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
248 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
250 // Print out constants referenced by the function
251 EmitConstantPool(MF.getConstantPool());
253 if (F->hasDLLExportLinkage())
254 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
256 // Print the 'header' of function
257 emitFunctionHeader(MF);
259 // Emit pre-function debug and/or EH information.
260 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
261 DW.BeginFunction(&MF);
263 // Print out code for the function.
264 bool hasAnyRealCode = false;
265 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
267 // Print a label for the basic block.
268 if (!I->pred_empty()) {
269 printBasicBlockLabel(I, true, true);
272 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
274 // Print the assembly for the instruction.
276 hasAnyRealCode = true;
277 printMachineInstruction(II);
281 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
282 // If the function is empty, then we need to emit *something*. Otherwise,
283 // the function's label might be associated with something that it wasn't
284 // meant to be associated with. We emit a noop in this situation.
285 // We are assuming inline asms are code.
289 if (TAI->hasDotTypeDotSizeDirective())
290 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
292 // Emit post-function debug information.
293 if (TAI->doesSupportDebugInformation())
296 // Print out jump tables referenced by the function.
297 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
299 // We didn't modify anything.
303 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
304 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
307 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
308 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
309 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
312 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
313 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
316 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
317 const char *Modifier, bool NotRIPRel) {
318 const MachineOperand &MO = MI->getOperand(OpNo);
319 switch (MO.getType()) {
320 case MachineOperand::MO_Register: {
321 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
322 "Virtual registers should not make it this far!");
324 unsigned Reg = MO.getReg();
325 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
326 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
327 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
328 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
329 Reg = getX86SubSuperRegister(Reg, VT);
331 for (const char *Name = TRI->getAsmName(Reg); *Name; ++Name)
332 O << (char)tolower(*Name);
336 case MachineOperand::MO_Immediate:
338 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
342 case MachineOperand::MO_MachineBasicBlock:
343 printBasicBlockLabel(MO.getMBB());
345 case MachineOperand::MO_JumpTableIndex: {
346 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
347 if (!isMemOp) O << '$';
348 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
351 if (TM.getRelocationModel() == Reloc::PIC_) {
352 if (Subtarget->isPICStyleStub())
353 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
355 else if (Subtarget->isPICStyleGOT())
359 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
363 case MachineOperand::MO_ConstantPoolIndex: {
364 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
365 if (!isMemOp) O << '$';
366 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
369 if (TM.getRelocationModel() == Reloc::PIC_) {
370 if (Subtarget->isPICStyleStub())
371 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
373 else if (Subtarget->isPICStyleGOT())
377 int Offset = MO.getOffset();
383 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
387 case MachineOperand::MO_GlobalAddress: {
388 bool isCallOp = Modifier && !strcmp(Modifier, "call");
389 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
390 bool needCloseParen = false;
392 const GlobalValue *GV = MO.getGlobal();
393 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
395 // If GV is an alias then use the aliasee for determining
397 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
398 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
401 bool isThreadLocal = GVar && GVar->isThreadLocal();
403 std::string Name = Mang->getValueName(GV);
404 decorateName(Name, GV);
406 if (!isMemOp && !isCallOp)
408 else if (Name[0] == '$') {
409 // The name begins with a dollar-sign. In order to avoid having it look
410 // like an integer immediate to the assembler, enclose it in parens.
412 needCloseParen = true;
415 if (shouldPrintStub(TM, Subtarget)) {
416 // Link-once, declaration, or Weakly-linked global variables need
417 // non-lazily-resolved stubs
418 if (GV->isDeclaration() ||
419 GV->hasWeakLinkage() ||
420 GV->hasLinkOnceLinkage() ||
421 GV->hasCommonLinkage()) {
422 // Dynamically-resolved functions need a stub for the function.
423 if (isCallOp && isa<Function>(GV)) {
424 FnStubs.insert(Name);
425 printSuffixedName(Name, "$stub");
427 GVStubs.insert(Name);
428 printSuffixedName(Name, "$non_lazy_ptr");
431 if (GV->hasDLLImportLinkage())
436 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
437 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
439 if (GV->hasDLLImportLinkage()) {
445 if (shouldPrintPLT(TM, Subtarget)) {
446 // Assemble call via PLT for externally visible symbols
447 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
448 !GV->hasInternalLinkage())
451 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
452 // Save function name for later type emission
453 FnStubs.insert(Name);
457 if (GV->hasExternalWeakLinkage())
458 ExtWeakSymbols.insert(GV);
460 int Offset = MO.getOffset();
467 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
468 O << "@TLSGD"; // general dynamic TLS model
470 if (GV->isDeclaration())
471 O << "@INDNTPOFF"; // initial exec TLS model
473 O << "@NTPOFF"; // local exec TLS model
474 } else if (isMemOp) {
475 if (shouldPrintGOT(TM, Subtarget)) {
476 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
480 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
481 TM.getRelocationModel() != Reloc::Static) {
482 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
485 if (needCloseParen) {
486 needCloseParen = false;
490 // Use rip when possible to reduce code size, except when
491 // index or base register are also part of the address. e.g.
492 // foo(%rip)(%rcx,%rax,4) is not legal
502 case MachineOperand::MO_ExternalSymbol: {
503 bool isCallOp = Modifier && !strcmp(Modifier, "call");
504 bool needCloseParen = false;
505 std::string Name(TAI->getGlobalPrefix());
506 Name += MO.getSymbolName();
507 if (isCallOp && shouldPrintStub(TM, Subtarget)) {
508 FnStubs.insert(Name);
509 printSuffixedName(Name, "$stub");
514 else if (Name[0] == '$') {
515 // The name begins with a dollar-sign. In order to avoid having it look
516 // like an integer immediate to the assembler, enclose it in parens.
518 needCloseParen = true;
523 if (shouldPrintPLT(TM, Subtarget)) {
524 std::string GOTName(TAI->getGlobalPrefix());
525 GOTName+="_GLOBAL_OFFSET_TABLE_";
527 // HACK! Emit extra offset to PC during printing GOT offset to
528 // compensate for the size of popl instruction. The resulting code
532 // popl %some_register
533 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
535 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
544 if (!isCallOp && Subtarget->isPICStyleRIPRel())
550 O << "<unknown operand type>"; return;
554 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
555 unsigned char value = MI->getOperand(Op).getImm();
556 assert(value <= 7 && "Invalid ssecc argument!");
558 case 0: O << "eq"; break;
559 case 1: O << "lt"; break;
560 case 2: O << "le"; break;
561 case 3: O << "unord"; break;
562 case 4: O << "neq"; break;
563 case 5: O << "nlt"; break;
564 case 6: O << "nle"; break;
565 case 7: O << "ord"; break;
569 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
570 const char *Modifier){
571 assert(isMem(MI, Op) && "Invalid memory reference!");
572 MachineOperand BaseReg = MI->getOperand(Op);
573 MachineOperand IndexReg = MI->getOperand(Op+2);
574 const MachineOperand &DispSpec = MI->getOperand(Op+3);
576 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
577 if (DispSpec.isGlobalAddress() ||
578 DispSpec.isConstantPoolIndex() ||
579 DispSpec.isJumpTableIndex()) {
580 printOperand(MI, Op+3, "mem", NotRIPRel);
582 int DispVal = DispSpec.getImm();
583 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
587 if (IndexReg.getReg() || BaseReg.getReg()) {
588 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
589 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
591 // There are cases where we can end up with ESP/RSP in the indexreg slot.
592 // If this happens, swap the base/index register to support assemblers that
593 // don't work when the index is *SP.
594 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
595 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
596 std::swap(BaseReg, IndexReg);
597 std::swap(BaseRegOperand, IndexRegOperand);
601 if (BaseReg.getReg())
602 printOperand(MI, Op+BaseRegOperand, Modifier);
604 if (IndexReg.getReg()) {
606 printOperand(MI, Op+IndexRegOperand, Modifier);
608 O << ',' << ScaleVal;
614 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
615 const MachineBasicBlock *MBB) const {
616 if (!TAI->getSetDirective())
619 // We don't need .set machinery if we have GOT-style relocations
620 if (Subtarget->isPICStyleGOT())
623 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
624 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
625 printBasicBlockLabel(MBB, false, false, false);
626 if (Subtarget->isPICStyleRIPRel())
627 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
628 << '_' << uid << '\n';
630 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
633 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
634 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
635 O << label << '\n' << label << ':';
639 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
640 const MachineBasicBlock *MBB,
643 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
644 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
646 O << JTEntryDirective << ' ';
648 if (TM.getRelocationModel() == Reloc::PIC_) {
649 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
650 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
651 << '_' << uid << "_set_" << MBB->getNumber();
652 } else if (Subtarget->isPICStyleGOT()) {
653 printBasicBlockLabel(MBB, false, false, false);
656 assert(0 && "Don't know how to print MBB label for this PIC mode");
658 printBasicBlockLabel(MBB, false, false, false);
661 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
663 unsigned Reg = MO.getReg();
665 default: return true; // Unknown mode.
666 case 'b': // Print QImode register
667 Reg = getX86SubSuperRegister(Reg, MVT::i8);
669 case 'h': // Print QImode high register
670 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
672 case 'w': // Print HImode register
673 Reg = getX86SubSuperRegister(Reg, MVT::i16);
675 case 'k': // Print SImode register
676 Reg = getX86SubSuperRegister(Reg, MVT::i32);
678 case 'q': // Print DImode register
679 Reg = getX86SubSuperRegister(Reg, MVT::i64);
684 for (const char *Name = TRI->getAsmName(Reg); *Name; ++Name)
685 O << (char)tolower(*Name);
689 /// PrintAsmOperand - Print out an operand for an inline asm expression.
691 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
693 const char *ExtraCode) {
694 // Does this asm operand have a single letter operand modifier?
695 if (ExtraCode && ExtraCode[0]) {
696 if (ExtraCode[1] != 0) return true; // Unknown modifier.
698 switch (ExtraCode[0]) {
699 default: return true; // Unknown modifier.
700 case 'c': // Don't print "$" before a global var name or constant.
701 printOperand(MI, OpNo, "mem");
703 case 'b': // Print QImode register
704 case 'h': // Print QImode high register
705 case 'w': // Print HImode register
706 case 'k': // Print SImode register
707 case 'q': // Print DImode register
708 if (MI->getOperand(OpNo).isRegister())
709 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
710 printOperand(MI, OpNo);
713 case 'P': // Don't print @PLT, but do print as memory.
714 printOperand(MI, OpNo, "mem");
719 printOperand(MI, OpNo);
723 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
726 const char *ExtraCode) {
727 if (ExtraCode && ExtraCode[0]) {
728 if (ExtraCode[1] != 0) return true; // Unknown modifier.
730 switch (ExtraCode[0]) {
731 default: return true; // Unknown modifier.
732 case 'b': // Print QImode register
733 case 'h': // Print QImode high register
734 case 'w': // Print HImode register
735 case 'k': // Print SImode register
736 case 'q': // Print SImode register
737 // These only apply to registers, ignore on mem.
741 printMemReference(MI, OpNo);
745 /// printMachineInstruction -- Print out a single X86 LLVM instruction
746 /// MI in AT&T syntax to the current output stream.
748 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
751 // Call the autogenerated instruction printer routines.
752 printInstruction(MI);
756 bool X86ATTAsmPrinter::doInitialization(Module &M) {
757 if (TAI->doesSupportDebugInformation()) {
758 // Emit initial debug information.
762 bool Result = AsmPrinter::doInitialization(M);
764 // Darwin wants symbols to be quoted if they have complex names.
765 if (Subtarget->isTargetDarwin())
766 Mang->setUseQuotes(true);
772 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
773 const TargetData *TD = TM.getTargetData();
775 if (!GVar->hasInitializer())
776 return; // External global require no code
778 // Check to see if this is a special global used by LLVM, if so, emit it.
779 if (EmitSpecialLLVMGlobal(GVar)) {
780 if (Subtarget->isTargetDarwin() &&
781 TM.getRelocationModel() == Reloc::Static) {
782 if (GVar->getName() == "llvm.global_ctors")
783 O << ".reference .constructors_used\n";
784 else if (GVar->getName() == "llvm.global_dtors")
785 O << ".reference .destructors_used\n";
790 std::string name = Mang->getValueName(GVar);
791 Constant *C = GVar->getInitializer();
792 const Type *Type = C->getType();
793 unsigned Size = TD->getABITypeSize(Type);
794 unsigned Align = TD->getPreferredAlignmentLog(GVar);
796 if (GVar->hasHiddenVisibility()) {
797 if (const char *Directive = TAI->getHiddenDirective())
798 O << Directive << name << '\n';
799 } else if (GVar->hasProtectedVisibility()) {
800 if (const char *Directive = TAI->getProtectedDirective())
801 O << Directive << name << '\n';
804 if (Subtarget->isTargetELF())
805 O << "\t.type\t" << name << ",@object\n";
807 if (C->isNullValue() && !GVar->hasSection()) {
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->hasInternalLinkage() || GVar->hasWeakLinkage() ||
819 GVar->hasLinkOnceLinkage() || GVar->hasCommonLinkage())) {
820 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
821 if (!NoZerosInBSS && TAI->getBSSSection())
822 SwitchToDataSection(TAI->getBSSSection(), GVar);
824 SwitchToDataSection(TAI->getDataSection(), GVar);
825 if (TAI->getLCOMMDirective() != NULL) {
826 if (GVar->hasInternalLinkage()) {
827 O << TAI->getLCOMMDirective() << name << ',' << Size;
828 if (Subtarget->isTargetDarwin())
830 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
831 O << "\t.globl " << name << '\n'
832 << TAI->getWeakDefDirective() << name << '\n';
833 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", GVar);
834 EmitAlignment(Align, GVar);
835 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
836 PrintUnmangledNameSafely(GVar, O);
838 EmitGlobalConstant(C);
841 O << TAI->getCOMMDirective() << name << ',' << Size;
843 // Leopard and above support aligned common symbols.
844 if (Subtarget->getDarwinVers() >= 9)
848 if (!Subtarget->isTargetCygMing()) {
849 if (GVar->hasInternalLinkage())
850 O << "\t.local\t" << name << '\n';
852 O << TAI->getCOMMDirective() << name << ',' << Size;
853 if (TAI->getCOMMDirectiveTakesAlignment())
854 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
856 O << "\t\t" << TAI->getCommentString() << ' ';
857 PrintUnmangledNameSafely(GVar, O);
863 switch (GVar->getLinkage()) {
864 case GlobalValue::CommonLinkage:
865 case GlobalValue::LinkOnceLinkage:
866 case GlobalValue::WeakLinkage:
867 if (Subtarget->isTargetDarwin()) {
868 O << "\t.globl " << name << '\n'
869 << TAI->getWeakDefDirective() << name << '\n';
870 if (!GVar->isConstant())
871 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", GVar);
873 const ArrayType *AT = dyn_cast<ArrayType>(Type);
874 if (AT && AT->getElementType()==Type::Int8Ty)
875 SwitchToDataSection("\t.section __TEXT,__const_coal,coalesced", GVar);
877 SwitchToDataSection("\t.section __DATA,__const_coal,coalesced", GVar);
879 } else if (Subtarget->isTargetCygMing()) {
880 std::string SectionName(".section\t.data$linkonce." +
883 SwitchToDataSection(SectionName.c_str(), GVar);
884 O << "\t.globl\t" << name << "\n"
885 "\t.linkonce same_size\n";
887 std::string SectionName("\t.section\t.llvm.linkonce.d." +
889 ",\"aw\",@progbits");
890 SwitchToDataSection(SectionName.c_str(), GVar);
891 O << "\t.weak\t" << name << '\n';
894 case GlobalValue::DLLExportLinkage:
895 case GlobalValue::AppendingLinkage:
896 // FIXME: appending linkage variables should go into a section of
897 // their name or something. For now, just emit them as external.
898 case GlobalValue::ExternalLinkage:
899 // If external or appending, declare as a global symbol
900 O << "\t.globl " << name << '\n';
902 case GlobalValue::InternalLinkage: {
903 if (GVar->isConstant()) {
904 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
905 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
906 SwitchToDataSection(TAI->getCStringSection(), GVar);
910 // FIXME: special handling for ".ctors" & ".dtors" sections
911 if (GVar->hasSection() &&
912 (GVar->getSection() == ".ctors" || GVar->getSection() == ".dtors")) {
913 std::string SectionName = ".section " + GVar->getSection();
915 if (Subtarget->isTargetCygMing()) {
916 SectionName += ",\"aw\"";
918 assert(!Subtarget->isTargetDarwin());
919 SectionName += ",\"aw\",@progbits";
921 SwitchToDataSection(SectionName.c_str());
922 } else if (GVar->hasSection() && Subtarget->isTargetDarwin()) {
923 // Honor all section names on Darwin; ObjC uses this
924 std::string SectionName = ".section " + GVar->getSection();
925 SwitchToDataSection(SectionName.c_str());
927 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
928 SwitchToDataSection(GVar->isThreadLocal() ? TAI->getTLSBSSSection() :
929 TAI->getBSSSection(), GVar);
930 else if (!GVar->isConstant())
931 SwitchToDataSection(GVar->isThreadLocal() ? TAI->getTLSDataSection() :
932 TAI->getDataSection(), GVar);
933 else if (GVar->isThreadLocal())
934 SwitchToDataSection(TAI->getTLSDataSection());
937 bool HasReloc = C->ContainsRelocations();
939 Subtarget->isTargetDarwin() &&
940 TM.getRelocationModel() != Reloc::Static)
941 SwitchToDataSection("\t.const_data\n");
942 else if (!HasReloc && Size == 4 &&
943 TAI->getFourByteConstantSection())
944 SwitchToDataSection(TAI->getFourByteConstantSection(), GVar);
945 else if (!HasReloc && Size == 8 &&
946 TAI->getEightByteConstantSection())
947 SwitchToDataSection(TAI->getEightByteConstantSection(), GVar);
948 else if (!HasReloc && Size == 16 &&
949 TAI->getSixteenByteConstantSection())
950 SwitchToDataSection(TAI->getSixteenByteConstantSection(), GVar);
951 else if (TAI->getReadOnlySection())
952 SwitchToDataSection(TAI->getReadOnlySection(), GVar);
954 SwitchToDataSection(TAI->getDataSection(), GVar);
961 assert(0 && "Unknown linkage type!");
964 EmitAlignment(Align, GVar);
965 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
966 PrintUnmangledNameSafely(GVar, O);
968 if (TAI->hasDotTypeDotSizeDirective())
969 O << "\t.size\t" << name << ", " << Size << '\n';
971 // If the initializer is a extern weak symbol, remember to emit the weak
973 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
974 if (GV->hasExternalWeakLinkage())
975 ExtWeakSymbols.insert(GV);
977 EmitGlobalConstant(C);
981 bool X86ATTAsmPrinter::doFinalization(Module &M) {
982 // Print out module-level global variables here.
983 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
985 printModuleLevelGV(I);
987 if (I->hasDLLExportLinkage())
988 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
991 // Output linker support code for dllexported globals
992 if (!DLLExportedGVs.empty())
993 SwitchToDataSection(".section .drectve");
995 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
996 e = DLLExportedGVs.end();
998 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1000 if (!DLLExportedFns.empty()) {
1001 SwitchToDataSection(".section .drectve");
1004 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1005 e = DLLExportedFns.end();
1007 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1009 if (Subtarget->isTargetDarwin()) {
1010 SwitchToDataSection("");
1012 // Output stubs for dynamically-linked functions
1014 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1016 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1017 "self_modifying_code+pure_instructions,5", 0);
1018 std::string p = i->getKeyData();
1019 printSuffixedName(p, "$stub");
1021 "\t.indirect_symbol " << p << "\n"
1022 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1027 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1028 // Add the (possibly multiple) personalities to the set of global values.
1029 // Only referenced functions get into the Personalities list.
1030 const std::vector<Function *>& Personalities = MMI->getPersonalities();
1032 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1033 E = Personalities.end(); I != E; ++I)
1034 if (*I) GVStubs.insert('_' + (*I)->getName());
1037 // Output stubs for external and common global variables.
1038 if (!GVStubs.empty())
1039 SwitchToDataSection(
1040 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1041 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1043 std::string p = i->getKeyData();
1044 printSuffixedName(p, "$non_lazy_ptr");
1046 "\t.indirect_symbol " << p << "\n"
1050 // Emit final debug information.
1053 // Funny Darwin hack: This flag tells the linker that no global symbols
1054 // contain code that falls through to other global symbols (e.g. the obvious
1055 // implementation of multiple entry points). If this doesn't occur, the
1056 // linker can safely perform dead code stripping. Since LLVM never
1057 // generates code that does this, it is always safe to set.
1058 O << "\t.subsections_via_symbols\n";
1059 } else if (Subtarget->isTargetCygMing()) {
1060 // Emit type information for external functions
1061 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1063 O << "\t.def\t " << i->getKeyData()
1064 << ";\t.scl\t" << COFF::C_EXT
1065 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1069 // Emit final debug information.
1071 } else if (Subtarget->isTargetELF()) {
1072 // Emit final debug information.
1076 return AsmPrinter::doFinalization(M);
1079 // Include the auto-generated portion of the assembly writer.
1080 #include "X86GenAsmWriter.inc"