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/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetOptions.h"
36 STATISTIC(EmittedInsts, "Number of machine instrs printed");
38 static std::string getPICLabelString(unsigned FnNum,
39 const TargetAsmInfo *TAI,
40 const X86Subtarget* Subtarget) {
42 if (Subtarget->isTargetDarwin())
43 label = "\"L" + utostr_32(FnNum) + "$pb\"";
44 else if (Subtarget->isTargetELF())
45 label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
47 assert(0 && "Don't know how to print PIC label!\n");
52 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
53 const TargetData *TD) {
54 X86MachineFunctionInfo Info;
57 switch (F->getCallingConv()) {
58 case CallingConv::X86_StdCall:
59 Info.setDecorationStyle(StdCall);
61 case CallingConv::X86_FastCall:
62 Info.setDecorationStyle(FastCall);
69 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
70 AI != AE; ++AI, ++argNum) {
71 const Type* Ty = AI->getType();
73 // 'Dereference' type in case of byval parameter attribute
74 if (F->paramHasAttr(argNum, Attribute::ByVal))
75 Ty = cast<PointerType>(Ty)->getElementType();
77 // Size should be aligned to DWORD boundary
78 Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
81 // We're not supporting tooooo huge arguments :)
82 Info.setBytesToPopOnReturn((unsigned int)Size);
86 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
87 /// Don't print things like \n or \0.
88 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
89 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
95 /// decorateName - Query FunctionInfoMap and use this information for various
97 void X86ATTAsmPrinter::decorateName(std::string &Name,
98 const GlobalValue *GV) {
99 const Function *F = dyn_cast<Function>(GV);
102 // We don't want to decorate non-stdcall or non-fastcall functions right now
103 unsigned CC = F->getCallingConv();
104 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
107 // Decorate names only when we're targeting Cygwin/Mingw32 targets
108 if (!Subtarget->isTargetCygMing())
111 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
113 const X86MachineFunctionInfo *Info;
114 if (info_item == FunctionInfoMap.end()) {
115 // Calculate apropriate function info and populate map
116 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
117 Info = &FunctionInfoMap[F];
119 Info = &info_item->second;
122 const FunctionType *FT = F->getFunctionType();
123 switch (Info->getDecorationStyle()) {
127 // "Pure" variadic functions do not receive @0 suffix.
128 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
129 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
130 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
133 // "Pure" variadic functions do not receive @0 suffix.
134 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
135 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
136 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
138 if (Name[0] == '_') {
145 assert(0 && "Unsupported DecorationStyle");
149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
150 const Function *F = MF.getFunction();
152 decorateName(CurrentFnName, F);
154 SwitchToSection(TAI->SectionForGlobal(F));
156 unsigned FnAlign = 4;
157 if (F->hasFnAttr(Attribute::OptimizeForSize))
159 switch (F->getLinkage()) {
160 default: assert(0 && "Unknown linkage type!");
161 case Function::InternalLinkage: // Symbols default to internal.
162 case Function::PrivateLinkage:
163 EmitAlignment(FnAlign, F);
165 case Function::DLLExportLinkage:
166 case Function::ExternalLinkage:
167 EmitAlignment(FnAlign, F);
168 O << "\t.globl\t" << CurrentFnName << '\n';
170 case Function::LinkOnceLinkage:
171 case Function::WeakLinkage:
172 EmitAlignment(FnAlign, F);
173 if (Subtarget->isTargetDarwin()) {
174 O << "\t.globl\t" << CurrentFnName << '\n';
175 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
176 } else if (Subtarget->isTargetCygMing()) {
177 O << "\t.globl\t" << CurrentFnName << "\n"
178 "\t.linkonce discard\n";
180 O << "\t.weak\t" << CurrentFnName << '\n';
185 printVisibility(CurrentFnName, F->getVisibility());
187 if (Subtarget->isTargetELF())
188 O << "\t.type\t" << CurrentFnName << ",@function\n";
189 else if (Subtarget->isTargetCygMing()) {
190 O << "\t.def\t " << CurrentFnName
192 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
193 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
197 O << CurrentFnName << ":\n";
198 // Add some workaround for linkonce linkage on Cygwin\MinGW
199 if (Subtarget->isTargetCygMing() &&
200 (F->getLinkage() == Function::LinkOnceLinkage ||
201 F->getLinkage() == Function::WeakLinkage))
202 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
205 /// runOnMachineFunction - This uses the printMachineInstruction()
206 /// method to print assembly for each instruction.
208 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
209 const Function *F = MF.getFunction();
211 unsigned CC = F->getCallingConv();
213 SetupMachineFunction(MF);
216 // Populate function information map. Actually, We don't want to populate
217 // non-stdcall or non-fastcall functions' information right now.
218 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
219 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
221 // Print out constants referenced by the function
222 EmitConstantPool(MF.getConstantPool());
224 if (F->hasDLLExportLinkage())
225 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
227 // Print the 'header' of function
228 emitFunctionHeader(MF);
230 // Emit pre-function debug and/or EH information.
231 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
232 DW->BeginFunction(&MF);
234 // Print out code for the function.
235 bool hasAnyRealCode = false;
236 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
238 // Print a label for the basic block.
239 if (!I->pred_empty()) {
240 printBasicBlockLabel(I, true, true);
243 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
245 // Print the assembly for the instruction.
247 hasAnyRealCode = true;
248 printMachineInstruction(II);
252 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
253 // If the function is empty, then we need to emit *something*. Otherwise,
254 // the function's label might be associated with something that it wasn't
255 // meant to be associated with. We emit a noop in this situation.
256 // We are assuming inline asms are code.
260 if (TAI->hasDotTypeDotSizeDirective())
261 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
263 // Emit post-function debug information.
264 if (TAI->doesSupportDebugInformation())
265 DW->EndFunction(&MF);
267 // Print out jump tables referenced by the function.
268 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
272 // We didn't modify anything.
276 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
277 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
280 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
281 return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
282 (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
285 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
286 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
289 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
290 const char *Modifier, bool NotRIPRel) {
291 const MachineOperand &MO = MI->getOperand(OpNo);
292 switch (MO.getType()) {
293 case MachineOperand::MO_Register: {
294 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
295 "Virtual registers should not make it this far!");
297 unsigned Reg = MO.getReg();
298 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
299 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
300 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
301 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
302 Reg = getX86SubSuperRegister(Reg, VT);
304 O << TRI->getAsmName(Reg);
308 case MachineOperand::MO_Immediate:
310 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
314 case MachineOperand::MO_MachineBasicBlock:
315 printBasicBlockLabel(MO.getMBB());
317 case MachineOperand::MO_JumpTableIndex: {
318 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
319 if (!isMemOp) O << '$';
320 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
323 if (TM.getRelocationModel() == Reloc::PIC_) {
324 if (Subtarget->isPICStyleStub())
325 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
327 else if (Subtarget->isPICStyleGOT())
331 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
335 case MachineOperand::MO_ConstantPoolIndex: {
336 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
337 if (!isMemOp) O << '$';
338 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
341 if (TM.getRelocationModel() == Reloc::PIC_) {
342 if (Subtarget->isPICStyleStub())
343 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
345 else if (Subtarget->isPICStyleGOT())
349 printOffset(MO.getOffset());
351 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
355 case MachineOperand::MO_GlobalAddress: {
356 bool isCallOp = Modifier && !strcmp(Modifier, "call");
357 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
358 bool needCloseParen = false;
360 const GlobalValue *GV = MO.getGlobal();
361 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
363 // If GV is an alias then use the aliasee for determining
365 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
366 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
369 bool isThreadLocal = GVar && GVar->isThreadLocal();
371 std::string Name = Mang->getValueName(GV);
372 decorateName(Name, GV);
374 if (!isMemOp && !isCallOp)
376 else if (Name[0] == '$') {
377 // The name begins with a dollar-sign. In order to avoid having it look
378 // like an integer immediate to the assembler, enclose it in parens.
380 needCloseParen = true;
383 if (shouldPrintStub(TM, Subtarget)) {
384 // Link-once, declaration, or Weakly-linked global variables need
385 // non-lazily-resolved stubs
386 if (GV->isDeclaration() || GV->mayBeOverridden()) {
387 // Dynamically-resolved functions need a stub for the function.
388 if (isCallOp && isa<Function>(GV)) {
389 // Function stubs are no longer needed for Mac OS X 10.5 and up.
390 if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
393 FnStubs.insert(Name);
394 printSuffixedName(Name, "$stub");
396 } else if (GV->hasHiddenVisibility()) {
397 if (!GV->isDeclaration() && !GV->hasCommonLinkage())
398 // Definition is not definitely in the current translation unit.
401 HiddenGVStubs.insert(Name);
402 printSuffixedName(Name, "$non_lazy_ptr");
405 GVStubs.insert(Name);
406 printSuffixedName(Name, "$non_lazy_ptr");
409 if (GV->hasDLLImportLinkage())
414 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
415 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
417 if (GV->hasDLLImportLinkage()) {
423 if (shouldPrintPLT(TM, Subtarget)) {
424 // Assemble call via PLT for externally visible symbols
425 if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
426 !GV->hasLocalLinkage())
429 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
430 // Save function name for later type emission
431 FnStubs.insert(Name);
435 if (GV->hasExternalWeakLinkage())
436 ExtWeakSymbols.insert(GV);
438 printOffset(MO.getOffset());
441 if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
442 O << "@TLSGD"; // general dynamic TLS model
444 if (GV->isDeclaration())
445 O << "@INDNTPOFF"; // initial exec TLS model
447 O << "@NTPOFF"; // local exec TLS model
448 } else if (isMemOp) {
449 if (shouldPrintGOT(TM, Subtarget)) {
450 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
454 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
455 TM.getRelocationModel() != Reloc::Static) {
456 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
459 if (needCloseParen) {
460 needCloseParen = false;
464 // Use rip when possible to reduce code size, except when
465 // index or base register are also part of the address. e.g.
466 // foo(%rip)(%rcx,%rax,4) is not legal
476 case MachineOperand::MO_ExternalSymbol: {
477 bool isCallOp = Modifier && !strcmp(Modifier, "call");
478 bool needCloseParen = false;
479 std::string Name(TAI->getGlobalPrefix());
480 Name += MO.getSymbolName();
481 // Print function stub suffix unless it's Mac OS X 10.5 and up.
482 if (isCallOp && shouldPrintStub(TM, Subtarget) &&
483 !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
484 FnStubs.insert(Name);
485 printSuffixedName(Name, "$stub");
490 else if (Name[0] == '$') {
491 // The name begins with a dollar-sign. In order to avoid having it look
492 // like an integer immediate to the assembler, enclose it in parens.
494 needCloseParen = true;
499 if (shouldPrintPLT(TM, Subtarget)) {
500 std::string GOTName(TAI->getGlobalPrefix());
501 GOTName+="_GLOBAL_OFFSET_TABLE_";
503 // HACK! Emit extra offset to PC during printing GOT offset to
504 // compensate for the size of popl instruction. The resulting code
508 // popl %some_register
509 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
511 << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
520 if (!isCallOp && Subtarget->isPICStyleRIPRel())
526 O << "<unknown operand type>"; return;
530 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
531 unsigned char value = MI->getOperand(Op).getImm();
532 assert(value <= 7 && "Invalid ssecc argument!");
534 case 0: O << "eq"; break;
535 case 1: O << "lt"; break;
536 case 2: O << "le"; break;
537 case 3: O << "unord"; break;
538 case 4: O << "neq"; break;
539 case 5: O << "nlt"; break;
540 case 6: O << "nle"; break;
541 case 7: O << "ord"; break;
545 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
546 const char *Modifier){
547 assert(isMem(MI, Op) && "Invalid memory reference!");
548 MachineOperand BaseReg = MI->getOperand(Op);
549 MachineOperand IndexReg = MI->getOperand(Op+2);
550 const MachineOperand &DispSpec = MI->getOperand(Op+3);
552 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
553 if (DispSpec.isGlobal() ||
556 printOperand(MI, Op+3, "mem", NotRIPRel);
558 int DispVal = DispSpec.getImm();
559 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
563 if (IndexReg.getReg() || BaseReg.getReg()) {
564 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
565 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
567 // There are cases where we can end up with ESP/RSP in the indexreg slot.
568 // If this happens, swap the base/index register to support assemblers that
569 // don't work when the index is *SP.
570 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
571 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
572 std::swap(BaseReg, IndexReg);
573 std::swap(BaseRegOperand, IndexRegOperand);
577 if (BaseReg.getReg())
578 printOperand(MI, Op+BaseRegOperand, Modifier);
580 if (IndexReg.getReg()) {
582 printOperand(MI, Op+IndexRegOperand, Modifier);
584 O << ',' << ScaleVal;
590 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
591 const MachineBasicBlock *MBB) const {
592 if (!TAI->getSetDirective())
595 // We don't need .set machinery if we have GOT-style relocations
596 if (Subtarget->isPICStyleGOT())
599 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
600 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
601 printBasicBlockLabel(MBB, false, false, false);
602 if (Subtarget->isPICStyleRIPRel())
603 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
604 << '_' << uid << '\n';
606 O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
609 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
610 std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
611 O << label << '\n' << label << ':';
615 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
616 const MachineBasicBlock *MBB,
619 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
620 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
622 O << JTEntryDirective << ' ';
624 if (TM.getRelocationModel() == Reloc::PIC_) {
625 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
626 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
627 << '_' << uid << "_set_" << MBB->getNumber();
628 } else if (Subtarget->isPICStyleGOT()) {
629 printBasicBlockLabel(MBB, false, false, false);
632 assert(0 && "Don't know how to print MBB label for this PIC mode");
634 printBasicBlockLabel(MBB, false, false, false);
637 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
639 unsigned Reg = MO.getReg();
641 default: return true; // Unknown mode.
642 case 'b': // Print QImode register
643 Reg = getX86SubSuperRegister(Reg, MVT::i8);
645 case 'h': // Print QImode high register
646 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
648 case 'w': // Print HImode register
649 Reg = getX86SubSuperRegister(Reg, MVT::i16);
651 case 'k': // Print SImode register
652 Reg = getX86SubSuperRegister(Reg, MVT::i32);
654 case 'q': // Print DImode register
655 Reg = getX86SubSuperRegister(Reg, MVT::i64);
659 O << '%'<< TRI->getAsmName(Reg);
663 /// PrintAsmOperand - Print out an operand for an inline asm expression.
665 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
667 const char *ExtraCode) {
668 // Does this asm operand have a single letter operand modifier?
669 if (ExtraCode && ExtraCode[0]) {
670 if (ExtraCode[1] != 0) return true; // Unknown modifier.
672 switch (ExtraCode[0]) {
673 default: return true; // Unknown modifier.
674 case 'c': // Don't print "$" before a global var name or constant.
675 printOperand(MI, OpNo, "mem");
677 case 'b': // Print QImode register
678 case 'h': // Print QImode high register
679 case 'w': // Print HImode register
680 case 'k': // Print SImode register
681 case 'q': // Print DImode register
682 if (MI->getOperand(OpNo).isReg())
683 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
684 printOperand(MI, OpNo);
687 case 'P': // Don't print @PLT, but do print as memory.
688 printOperand(MI, OpNo, "mem");
693 printOperand(MI, OpNo);
697 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
700 const char *ExtraCode) {
701 if (ExtraCode && ExtraCode[0]) {
702 if (ExtraCode[1] != 0) return true; // Unknown modifier.
704 switch (ExtraCode[0]) {
705 default: return true; // Unknown modifier.
706 case 'b': // Print QImode register
707 case 'h': // Print QImode high register
708 case 'w': // Print HImode register
709 case 'k': // Print SImode register
710 case 'q': // Print SImode register
711 // These only apply to registers, ignore on mem.
713 case 'P': // Don't print @PLT, but do print as memory.
714 printOperand(MI, OpNo, "mem");
718 printMemReference(MI, OpNo);
722 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
723 /// AT&T syntax to the current output stream.
725 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
728 if (TAI->doesSupportDebugInformation()) {
729 const Function *F = MF->getFunction();
731 // FIXME: Support more than '-Os'.
732 if (F->hasFnAttr(Attribute::OptimizeForSize)) {
733 static DebugLoc PrevDL = DebugLoc::getUnknownLoc();
734 DebugLoc CurDL = MI->getDebugLoc();
736 if (!CurDL.isUnknown() && PrevDL != CurDL) {
737 DebugLocTuple DLT = MF->getDebugLocTuple(CurDL);
738 printLabel(DW->RecordSourceLine(DLT.Line, DLT.Col, DLT.Src));
745 // Call the autogenerated instruction printer routines.
746 printInstruction(MI);
750 bool X86ATTAsmPrinter::doInitialization(Module &M) {
752 bool Result = AsmPrinter::doInitialization(M);
754 if (TAI->doesSupportDebugInformation()) {
755 // Let PassManager know we need debug information and relay
756 // the MachineModuleInfo address on to DwarfWriter.
757 // AsmPrinter::doInitialization did this analysis.
758 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
759 DW = getAnalysisIfAvailable<DwarfWriter>();
760 DW->BeginModule(&M, MMI, O, this, TAI);
763 // Darwin wants symbols to be quoted if they have complex names.
764 if (Subtarget->isTargetDarwin())
765 Mang->setUseQuotes(true);
771 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
772 const TargetData *TD = TM.getTargetData();
774 if (!GVar->hasInitializer())
775 return; // External global require no code
777 // Check to see if this is a special global used by LLVM, if so, emit it.
778 if (EmitSpecialLLVMGlobal(GVar)) {
779 if (Subtarget->isTargetDarwin() &&
780 TM.getRelocationModel() == Reloc::Static) {
781 if (GVar->getName() == "llvm.global_ctors")
782 O << ".reference .constructors_used\n";
783 else if (GVar->getName() == "llvm.global_dtors")
784 O << ".reference .destructors_used\n";
789 std::string name = Mang->getValueName(GVar);
790 Constant *C = GVar->getInitializer();
791 const Type *Type = C->getType();
792 unsigned Size = TD->getTypePaddedSize(Type);
793 unsigned Align = TD->getPreferredAlignmentLog(GVar);
795 printVisibility(name, GVar->getVisibility());
797 if (Subtarget->isTargetELF())
798 O << "\t.type\t" << name << ",@object\n";
800 SwitchToSection(TAI->SectionForGlobal(GVar));
802 if (C->isNullValue() && !GVar->hasSection() &&
803 !(Subtarget->isTargetDarwin() &&
804 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
805 // FIXME: This seems to be pretty darwin-specific
806 if (GVar->hasExternalLinkage()) {
807 if (const char *Directive = TAI->getZeroFillDirective()) {
808 O << "\t.globl " << name << '\n';
809 O << Directive << "__DATA, __common, " << name << ", "
810 << Size << ", " << Align << '\n';
815 if (!GVar->isThreadLocal() &&
816 (GVar->hasLocalLinkage() || GVar->mayBeOverridden())) {
817 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
819 if (TAI->getLCOMMDirective() != NULL) {
820 if (GVar->hasLocalLinkage()) {
821 O << TAI->getLCOMMDirective() << name << ',' << Size;
822 if (Subtarget->isTargetDarwin())
824 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
825 O << "\t.globl " << name << '\n'
826 << TAI->getWeakDefDirective() << name << '\n';
827 EmitAlignment(Align, GVar);
828 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
829 PrintUnmangledNameSafely(GVar, O);
831 EmitGlobalConstant(C);
834 O << TAI->getCOMMDirective() << name << ',' << Size;
835 if (TAI->getCOMMDirectiveTakesAlignment())
836 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
839 if (!Subtarget->isTargetCygMing()) {
840 if (GVar->hasLocalLinkage())
841 O << "\t.local\t" << name << '\n';
843 O << TAI->getCOMMDirective() << name << ',' << Size;
844 if (TAI->getCOMMDirectiveTakesAlignment())
845 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
847 O << "\t\t" << TAI->getCommentString() << ' ';
848 PrintUnmangledNameSafely(GVar, O);
854 switch (GVar->getLinkage()) {
855 case GlobalValue::CommonLinkage:
856 case GlobalValue::LinkOnceLinkage:
857 case GlobalValue::WeakLinkage:
858 if (Subtarget->isTargetDarwin()) {
859 O << "\t.globl " << name << '\n'
860 << TAI->getWeakDefDirective() << name << '\n';
861 } else if (Subtarget->isTargetCygMing()) {
862 O << "\t.globl\t" << name << "\n"
863 "\t.linkonce same_size\n";
865 O << "\t.weak\t" << name << '\n';
868 case GlobalValue::DLLExportLinkage:
869 case GlobalValue::AppendingLinkage:
870 // FIXME: appending linkage variables should go into a section of
871 // their name or something. For now, just emit them as external.
872 case GlobalValue::ExternalLinkage:
873 // If external or appending, declare as a global symbol
874 O << "\t.globl " << name << '\n';
876 case GlobalValue::PrivateLinkage:
877 case GlobalValue::InternalLinkage:
880 assert(0 && "Unknown linkage type!");
883 EmitAlignment(Align, GVar);
884 O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
885 PrintUnmangledNameSafely(GVar, O);
887 if (TAI->hasDotTypeDotSizeDirective())
888 O << "\t.size\t" << name << ", " << Size << '\n';
890 // If the initializer is a extern weak symbol, remember to emit the weak
892 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
893 if (GV->hasExternalWeakLinkage())
894 ExtWeakSymbols.insert(GV);
896 EmitGlobalConstant(C);
899 /// printGVStub - Print stub for a global value.
901 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
902 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
903 O << ":\n\t.indirect_symbol ";
904 if (Prefix) O << Prefix;
905 O << GV << "\n\t.long\t0\n";
908 /// printHiddenGVStub - Print stub for a hidden global value.
910 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
912 printSuffixedName(GV, "$non_lazy_ptr", Prefix);
913 if (Prefix) O << Prefix;
914 O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
918 bool X86ATTAsmPrinter::doFinalization(Module &M) {
919 // Print out module-level global variables here.
920 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
922 printModuleLevelGV(I);
924 if (I->hasDLLExportLinkage())
925 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
928 // Output linker support code for dllexported globals
929 if (!DLLExportedGVs.empty())
930 SwitchToDataSection(".section .drectve");
932 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
933 e = DLLExportedGVs.end();
935 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
937 if (!DLLExportedFns.empty()) {
938 SwitchToDataSection(".section .drectve");
941 for (StringSet<>::iterator i = DLLExportedFns.begin(),
942 e = DLLExportedFns.end();
944 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
946 if (Subtarget->isTargetDarwin()) {
947 SwitchToDataSection("");
949 // Output stubs for dynamically-linked functions
950 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
952 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
953 "self_modifying_code+pure_instructions,5", 0);
954 const char *p = i->getKeyData();
955 printSuffixedName(p, "$stub");
957 "\t.indirect_symbol " << p << "\n"
958 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
963 // Print global value stubs.
964 bool InStubSection = false;
965 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
966 // Add the (possibly multiple) personalities to the set of global values.
967 // Only referenced functions get into the Personalities list.
968 const std::vector<Function *>& Personalities = MMI->getPersonalities();
969 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
970 E = Personalities.end(); I != E; ++I) {
973 if (!InStubSection) {
975 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
976 InStubSection = true;
978 printGVStub((*I)->getNameStart(), "_");
982 // Output stubs for external and common global variables.
983 if (!InStubSection && !GVStubs.empty())
985 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
986 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
988 printGVStub(i->getKeyData());
990 if (!HiddenGVStubs.empty()) {
991 SwitchToSection(TAI->getDataSection());
992 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
994 printHiddenGVStub(i->getKeyData());
997 // Emit final debug information.
998 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1001 // Funny Darwin hack: This flag tells the linker that no global symbols
1002 // contain code that falls through to other global symbols (e.g. the obvious
1003 // implementation of multiple entry points). If this doesn't occur, the
1004 // linker can safely perform dead code stripping. Since LLVM never
1005 // generates code that does this, it is always safe to set.
1006 O << "\t.subsections_via_symbols\n";
1007 } else if (Subtarget->isTargetCygMing()) {
1008 // Emit type information for external functions
1009 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1011 O << "\t.def\t " << i->getKeyData()
1012 << ";\t.scl\t" << COFF::C_EXT
1013 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1017 // Emit final debug information.
1018 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1020 } else if (Subtarget->isTargetELF()) {
1021 // Emit final debug information.
1022 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1026 return AsmPrinter::doFinalization(M);
1029 // Include the auto-generated portion of the assembly writer.
1030 #include "X86GenAsmWriter.inc"