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 (!VerboseAsm
&& (I
->pred_empty() || I
->isOnlyReachableByFallthrough())) {
242 // This is an entry block or a block that's only reachable via a
243 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
245 printBasicBlockLabel(I
, true, true, VerboseAsm
);
248 for (MachineBasicBlock::const_iterator II
= I
->begin(), IE
= I
->end();
250 // Print the assembly for the instruction.
252 hasAnyRealCode
= true;
253 printMachineInstruction(II
);
257 if (Subtarget
->isTargetDarwin() && !hasAnyRealCode
) {
258 // If the function is empty, then we need to emit *something*. Otherwise,
259 // the function's label might be associated with something that it wasn't
260 // meant to be associated with. We emit a noop in this situation.
261 // We are assuming inline asms are code.
265 if (TAI
->hasDotTypeDotSizeDirective())
266 O
<< "\t.size\t" << CurrentFnName
<< ", .-" << CurrentFnName
<< '\n';
268 // Emit post-function debug information.
269 if (TAI
->doesSupportDebugInformation())
270 DW
->EndFunction(&MF
);
272 // Print out jump tables referenced by the function.
273 EmitJumpTableInfo(MF
.getJumpTableInfo(), MF
);
277 // We didn't modify anything.
281 static inline bool shouldPrintGOT(TargetMachine
&TM
, const X86Subtarget
* ST
) {
282 return ST
->isPICStyleGOT() && TM
.getRelocationModel() == Reloc::PIC_
;
285 static inline bool shouldPrintPLT(TargetMachine
&TM
, const X86Subtarget
* ST
) {
286 return ST
->isTargetELF() && TM
.getRelocationModel() == Reloc::PIC_
&&
287 (ST
->isPICStyleRIPRel() || ST
->isPICStyleGOT());
290 static inline bool shouldPrintStub(TargetMachine
&TM
, const X86Subtarget
* ST
) {
291 return ST
->isPICStyleStub() && TM
.getRelocationModel() != Reloc::Static
;
294 void X86ATTAsmPrinter::printOperand(const MachineInstr
*MI
, unsigned OpNo
,
295 const char *Modifier
, bool NotRIPRel
) {
296 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
297 switch (MO
.getType()) {
298 case MachineOperand::MO_Register
: {
299 assert(TargetRegisterInfo::isPhysicalRegister(MO
.getReg()) &&
300 "Virtual registers should not make it this far!");
302 unsigned Reg
= MO
.getReg();
303 if (Modifier
&& strncmp(Modifier
, "subreg", strlen("subreg")) == 0) {
304 MVT VT
= (strcmp(Modifier
+6,"64") == 0) ?
305 MVT::i64
: ((strcmp(Modifier
+6, "32") == 0) ? MVT::i32
:
306 ((strcmp(Modifier
+6,"16") == 0) ? MVT::i16
: MVT::i8
));
307 Reg
= getX86SubSuperRegister(Reg
, VT
);
309 O
<< TRI
->getAsmName(Reg
);
313 case MachineOperand::MO_Immediate
:
314 if (!Modifier
|| (strcmp(Modifier
, "debug") &&
315 strcmp(Modifier
, "mem") &&
316 strcmp(Modifier
, "call")))
320 case MachineOperand::MO_MachineBasicBlock
:
321 printBasicBlockLabel(MO
.getMBB(), false, false, VerboseAsm
);
323 case MachineOperand::MO_JumpTableIndex
: {
324 bool isMemOp
= Modifier
&& !strcmp(Modifier
, "mem");
325 if (!isMemOp
) O
<< '$';
326 O
<< TAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
329 if (TM
.getRelocationModel() == Reloc::PIC_
) {
330 if (Subtarget
->isPICStyleStub())
331 O
<< "-\"" << TAI
->getPrivateGlobalPrefix() << getFunctionNumber()
333 else if (Subtarget
->isPICStyleGOT())
337 if (isMemOp
&& Subtarget
->isPICStyleRIPRel() && !NotRIPRel
)
341 case MachineOperand::MO_ConstantPoolIndex
: {
342 bool isMemOp
= Modifier
&& !strcmp(Modifier
, "mem");
343 if (!isMemOp
) O
<< '$';
344 O
<< TAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
347 if (TM
.getRelocationModel() == Reloc::PIC_
) {
348 if (Subtarget
->isPICStyleStub())
349 O
<< "-\"" << TAI
->getPrivateGlobalPrefix() << getFunctionNumber()
351 else if (Subtarget
->isPICStyleGOT())
355 printOffset(MO
.getOffset());
357 if (isMemOp
&& Subtarget
->isPICStyleRIPRel() && !NotRIPRel
)
361 case MachineOperand::MO_GlobalAddress
: {
362 bool isCallOp
= Modifier
&& !strcmp(Modifier
, "call");
363 bool isMemOp
= Modifier
&& !strcmp(Modifier
, "mem");
364 bool needCloseParen
= false;
366 const GlobalValue
*GV
= MO
.getGlobal();
367 const GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(GV
);
369 // If GV is an alias then use the aliasee for determining
371 if (const GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(GV
))
372 GVar
= dyn_cast_or_null
<GlobalVariable
>(GA
->resolveAliasedGlobal(false));
375 bool isThreadLocal
= GVar
&& GVar
->isThreadLocal();
377 std::string Name
= Mang
->getValueName(GV
);
378 decorateName(Name
, GV
);
380 if (!isMemOp
&& !isCallOp
)
382 else if (Name
[0] == '$') {
383 // The name begins with a dollar-sign. In order to avoid having it look
384 // like an integer immediate to the assembler, enclose it in parens.
386 needCloseParen
= true;
389 if (shouldPrintStub(TM
, Subtarget
)) {
390 // Link-once, declaration, or Weakly-linked global variables need
391 // non-lazily-resolved stubs
392 if (GV
->isDeclaration() || GV
->isWeakForLinker()) {
393 // Dynamically-resolved functions need a stub for the function.
394 if (isCallOp
&& isa
<Function
>(GV
)) {
395 // Function stubs are no longer needed for Mac OS X 10.5 and up.
396 if (Subtarget
->isTargetDarwin() && Subtarget
->getDarwinVers() >= 9) {
399 FnStubs
.insert(Name
);
400 printSuffixedName(Name
, "$stub");
402 } else if (GV
->hasHiddenVisibility()) {
403 if (!GV
->isDeclaration() && !GV
->hasCommonLinkage())
404 // Definition is not definitely in the current translation unit.
407 HiddenGVStubs
.insert(Name
);
408 printSuffixedName(Name
, "$non_lazy_ptr");
411 GVStubs
.insert(Name
);
412 printSuffixedName(Name
, "$non_lazy_ptr");
415 if (GV
->hasDLLImportLinkage())
420 if (!isCallOp
&& TM
.getRelocationModel() == Reloc::PIC_
)
421 O
<< '-' << getPICLabelString(getFunctionNumber(), TAI
, Subtarget
);
423 if (GV
->hasDLLImportLinkage()) {
429 if (shouldPrintPLT(TM
, Subtarget
)) {
430 // Assemble call via PLT for externally visible symbols
431 if (!GV
->hasHiddenVisibility() && !GV
->hasProtectedVisibility() &&
432 !GV
->hasLocalLinkage())
435 if (Subtarget
->isTargetCygMing() && GV
->isDeclaration())
436 // Save function name for later type emission
437 FnStubs
.insert(Name
);
441 if (GV
->hasExternalWeakLinkage())
442 ExtWeakSymbols
.insert(GV
);
444 printOffset(MO
.getOffset());
447 TLSModel::Model model
= getTLSModel(GVar
, TM
.getRelocationModel());
449 case TLSModel::GeneralDynamic
:
452 case TLSModel::LocalDynamic
:
453 // O << "@TLSLD"; // local dynamic not implemented
456 case TLSModel::InitialExec
:
457 if (Subtarget
->is64Bit())
458 O
<< "@TLSGD"; // 64 bit intial exec not implemented
462 case TLSModel::LocalExec
:
463 if (Subtarget
->is64Bit())
464 O
<< "@TLSGD"; // 64 bit local exec not implemented
469 assert (0 && "Unknown TLS model");
471 } else if (isMemOp
) {
472 if (shouldPrintGOT(TM
, Subtarget
)) {
473 if (Subtarget
->GVRequiresExtraLoad(GV
, TM
, false))
477 } else if (Subtarget
->isPICStyleRIPRel() && !NotRIPRel
) {
478 if (TM
.getRelocationModel() != Reloc::Static
) {
479 if (Subtarget
->GVRequiresExtraLoad(GV
, TM
, false))
482 if (needCloseParen
) {
483 needCloseParen
= false;
488 // Use rip when possible to reduce code size, except when
489 // index or base register are also part of the address. e.g.
490 // foo(%rip)(%rcx,%rax,4) is not legal
500 case MachineOperand::MO_ExternalSymbol
: {
501 bool isCallOp
= Modifier
&& !strcmp(Modifier
, "call");
502 bool needCloseParen
= false;
503 std::string
Name(TAI
->getGlobalPrefix());
504 Name
+= MO
.getSymbolName();
505 // Print function stub suffix unless it's Mac OS X 10.5 and up.
506 if (isCallOp
&& shouldPrintStub(TM
, Subtarget
) &&
507 !(Subtarget
->isTargetDarwin() && Subtarget
->getDarwinVers() >= 9)) {
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
.isGlobal() ||
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
);
683 O
<< '%'<< TRI
->getAsmName(Reg
);
687 /// PrintAsmOperand - Print out an operand for an inline asm expression.
689 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
691 const char *ExtraCode
) {
692 // Does this asm operand have a single letter operand modifier?
693 if (ExtraCode
&& ExtraCode
[0]) {
694 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
696 switch (ExtraCode
[0]) {
697 default: return true; // Unknown modifier.
698 case 'c': // Don't print "$" before a global var name or constant.
699 printOperand(MI
, OpNo
, "mem", /*NotRIPRel=*/true);
701 case 'b': // Print QImode register
702 case 'h': // Print QImode high register
703 case 'w': // Print HImode register
704 case 'k': // Print SImode register
705 case 'q': // Print DImode register
706 if (MI
->getOperand(OpNo
).isReg())
707 return printAsmMRegister(MI
->getOperand(OpNo
), ExtraCode
[0]);
708 printOperand(MI
, OpNo
);
711 case 'P': // Don't print @PLT, but do print as memory.
712 printOperand(MI
, OpNo
, "mem");
717 printOperand(MI
, OpNo
);
721 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
,
724 const char *ExtraCode
) {
725 if (ExtraCode
&& ExtraCode
[0]) {
726 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
728 switch (ExtraCode
[0]) {
729 default: return true; // Unknown modifier.
730 case 'b': // Print QImode register
731 case 'h': // Print QImode high register
732 case 'w': // Print HImode register
733 case 'k': // Print SImode register
734 case 'q': // Print SImode register
735 // These only apply to registers, ignore on mem.
737 case 'P': // Don't print @PLT, but do print as memory.
738 printOperand(MI
, OpNo
, "mem");
742 printMemReference(MI
, OpNo
);
746 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
747 /// AT&T syntax to the current output stream.
749 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr
*MI
) {
752 // Call the autogenerated instruction printer routines.
753 printInstruction(MI
);
757 bool X86ATTAsmPrinter::doInitialization(Module
&M
) {
759 bool Result
= AsmPrinter::doInitialization(M
);
761 if (TAI
->doesSupportDebugInformation()) {
762 // Let PassManager know we need debug information and relay
763 // the MachineModuleInfo address on to DwarfWriter.
764 // AsmPrinter::doInitialization did this analysis.
765 MMI
= getAnalysisIfAvailable
<MachineModuleInfo
>();
766 DW
= getAnalysisIfAvailable
<DwarfWriter
>();
767 DW
->BeginModule(&M
, MMI
, O
, this, TAI
);
770 // Darwin wants symbols to be quoted if they have complex names.
771 if (Subtarget
->isTargetDarwin())
772 Mang
->setUseQuotes(true);
778 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable
* GVar
) {
779 const TargetData
*TD
= TM
.getTargetData();
781 if (!GVar
->hasInitializer())
782 return; // External global require no code
784 // Check to see if this is a special global used by LLVM, if so, emit it.
785 if (EmitSpecialLLVMGlobal(GVar
)) {
786 if (Subtarget
->isTargetDarwin() &&
787 TM
.getRelocationModel() == Reloc::Static
) {
788 if (GVar
->getName() == "llvm.global_ctors")
789 O
<< ".reference .constructors_used\n";
790 else if (GVar
->getName() == "llvm.global_dtors")
791 O
<< ".reference .destructors_used\n";
796 std::string name
= Mang
->getValueName(GVar
);
797 Constant
*C
= GVar
->getInitializer();
798 const Type
*Type
= C
->getType();
799 unsigned Size
= TD
->getTypePaddedSize(Type
);
800 unsigned Align
= TD
->getPreferredAlignmentLog(GVar
);
802 printVisibility(name
, GVar
->getVisibility());
804 if (Subtarget
->isTargetELF())
805 O
<< "\t.type\t" << name
<< ",@object\n";
807 SwitchToSection(TAI
->SectionForGlobal(GVar
));
809 if (C
->isNullValue() && !GVar
->hasSection() &&
810 !(Subtarget
->isTargetDarwin() &&
811 TAI
->SectionKindForGlobal(GVar
) == SectionKind::RODataMergeStr
)) {
812 // FIXME: This seems to be pretty darwin-specific
813 if (GVar
->hasExternalLinkage()) {
814 if (const char *Directive
= TAI
->getZeroFillDirective()) {
815 O
<< "\t.globl " << name
<< '\n';
816 O
<< Directive
<< "__DATA, __common, " << name
<< ", "
817 << Size
<< ", " << Align
<< '\n';
822 if (!GVar
->isThreadLocal() &&
823 (GVar
->hasLocalLinkage() || GVar
->isWeakForLinker())) {
824 if (Size
== 0) Size
= 1; // .comm Foo, 0 is undefined, avoid it.
826 if (TAI
->getLCOMMDirective() != NULL
) {
827 if (GVar
->hasLocalLinkage()) {
828 O
<< TAI
->getLCOMMDirective() << name
<< ',' << Size
;
829 if (Subtarget
->isTargetDarwin())
831 } else if (Subtarget
->isTargetDarwin() && !GVar
->hasCommonLinkage()) {
832 O
<< "\t.globl " << name
<< '\n'
833 << TAI
->getWeakDefDirective() << name
<< '\n';
834 EmitAlignment(Align
, GVar
);
837 O
<< "\t\t\t\t" << TAI
->getCommentString() << ' ';
838 PrintUnmangledNameSafely(GVar
, O
);
841 EmitGlobalConstant(C
);
844 O
<< TAI
->getCOMMDirective() << name
<< ',' << Size
;
845 if (TAI
->getCOMMDirectiveTakesAlignment())
846 O
<< ',' << (TAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
849 if (!Subtarget
->isTargetCygMing()) {
850 if (GVar
->hasLocalLinkage())
851 O
<< "\t.local\t" << name
<< '\n';
853 O
<< TAI
->getCOMMDirective() << name
<< ',' << Size
;
854 if (TAI
->getCOMMDirectiveTakesAlignment())
855 O
<< ',' << (TAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
858 O
<< "\t\t" << TAI
->getCommentString() << ' ';
859 PrintUnmangledNameSafely(GVar
, O
);
866 switch (GVar
->getLinkage()) {
867 case GlobalValue::CommonLinkage
:
868 case GlobalValue::LinkOnceAnyLinkage
:
869 case GlobalValue::LinkOnceODRLinkage
:
870 case GlobalValue::WeakAnyLinkage
:
871 case GlobalValue::WeakODRLinkage
:
872 if (Subtarget
->isTargetDarwin()) {
873 O
<< "\t.globl " << name
<< '\n'
874 << TAI
->getWeakDefDirective() << name
<< '\n';
875 } else if (Subtarget
->isTargetCygMing()) {
876 O
<< "\t.globl\t" << name
<< "\n"
877 "\t.linkonce same_size\n";
879 O
<< "\t.weak\t" << name
<< '\n';
882 case GlobalValue::DLLExportLinkage
:
883 case GlobalValue::AppendingLinkage
:
884 // FIXME: appending linkage variables should go into a section of
885 // their name or something. For now, just emit them as external.
886 case GlobalValue::ExternalLinkage
:
887 // If external or appending, declare as a global symbol
888 O
<< "\t.globl " << name
<< '\n';
890 case GlobalValue::PrivateLinkage
:
891 case GlobalValue::InternalLinkage
:
894 assert(0 && "Unknown linkage type!");
897 EmitAlignment(Align
, GVar
);
900 O
<< "\t\t\t\t" << TAI
->getCommentString() << ' ';
901 PrintUnmangledNameSafely(GVar
, O
);
904 if (TAI
->hasDotTypeDotSizeDirective())
905 O
<< "\t.size\t" << name
<< ", " << Size
<< '\n';
907 EmitGlobalConstant(C
);
910 /// printGVStub - Print stub for a global value.
912 void X86ATTAsmPrinter::printGVStub(const char *GV
, const char *Prefix
) {
913 printSuffixedName(GV
, "$non_lazy_ptr", Prefix
);
914 O
<< ":\n\t.indirect_symbol ";
915 if (Prefix
) O
<< Prefix
;
916 O
<< GV
<< "\n\t.long\t0\n";
919 /// printHiddenGVStub - Print stub for a hidden global value.
921 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV
, const char *Prefix
) {
923 printSuffixedName(GV
, "$non_lazy_ptr", Prefix
);
924 if (Prefix
) O
<< Prefix
;
925 O
<< ":\n" << TAI
->getData32bitsDirective() << GV
<< '\n';
929 bool X86ATTAsmPrinter::doFinalization(Module
&M
) {
930 // Print out module-level global variables here.
931 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
933 printModuleLevelGV(I
);
935 if (I
->hasDLLExportLinkage())
936 DLLExportedGVs
.insert(Mang
->makeNameProper(I
->getName(),""));
938 // If the global is a extern weak symbol, remember to emit the weak
940 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
941 // not used. But currently it's the only way to deal with extern weak
942 // initializers hidden deep inside constant expressions.
943 if (I
->hasExternalWeakLinkage())
944 ExtWeakSymbols
.insert(I
);
947 for (Module::const_iterator I
= M
.begin(), E
= M
.end();
949 // If the global is a extern weak symbol, remember to emit the weak
951 // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
952 // not used. But currently it's the only way to deal with extern weak
953 // initializers hidden deep inside constant expressions.
954 if (I
->hasExternalWeakLinkage())
955 ExtWeakSymbols
.insert(I
);
958 // Output linker support code for dllexported globals
959 if (!DLLExportedGVs
.empty())
960 SwitchToDataSection(".section .drectve");
962 for (StringSet
<>::iterator i
= DLLExportedGVs
.begin(),
963 e
= DLLExportedGVs
.end();
965 O
<< "\t.ascii \" -export:" << i
->getKeyData() << ",data\"\n";
967 if (!DLLExportedFns
.empty()) {
968 SwitchToDataSection(".section .drectve");
971 for (StringSet
<>::iterator i
= DLLExportedFns
.begin(),
972 e
= DLLExportedFns
.end();
974 O
<< "\t.ascii \" -export:" << i
->getKeyData() << "\"\n";
976 if (Subtarget
->isTargetDarwin()) {
977 SwitchToDataSection("");
979 // Output stubs for dynamically-linked functions
980 for (StringSet
<>::iterator i
= FnStubs
.begin(), e
= FnStubs
.end();
982 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
983 "self_modifying_code+pure_instructions,5", 0);
984 const char *p
= i
->getKeyData();
985 printSuffixedName(p
, "$stub");
987 "\t.indirect_symbol " << p
<< "\n"
988 "\thlt ; hlt ; hlt ; hlt ; hlt\n";
993 // Print global value stubs.
994 bool InStubSection
= false;
995 if (TAI
->doesSupportExceptionHandling() && MMI
&& !Subtarget
->is64Bit()) {
996 // Add the (possibly multiple) personalities to the set of global values.
997 // Only referenced functions get into the Personalities list.
998 const std::vector
<Function
*>& Personalities
= MMI
->getPersonalities();
999 for (std::vector
<Function
*>::const_iterator I
= Personalities
.begin(),
1000 E
= Personalities
.end(); I
!= E
; ++I
) {
1003 if (!InStubSection
) {
1004 SwitchToDataSection(
1005 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1006 InStubSection
= true;
1008 printGVStub((*I
)->getNameStart(), "_");
1012 // Output stubs for external and common global variables.
1013 if (!InStubSection
&& !GVStubs
.empty())
1014 SwitchToDataSection(
1015 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1016 for (StringSet
<>::iterator i
= GVStubs
.begin(), e
= GVStubs
.end();
1018 printGVStub(i
->getKeyData());
1020 if (!HiddenGVStubs
.empty()) {
1021 SwitchToSection(TAI
->getDataSection());
1022 for (StringSet
<>::iterator i
= HiddenGVStubs
.begin(), e
= HiddenGVStubs
.end();
1024 printHiddenGVStub(i
->getKeyData());
1027 // Emit final debug information.
1028 DwarfWriter
*DW
= getAnalysisIfAvailable
<DwarfWriter
>();
1031 // Funny Darwin hack: This flag tells the linker that no global symbols
1032 // contain code that falls through to other global symbols (e.g. the obvious
1033 // implementation of multiple entry points). If this doesn't occur, the
1034 // linker can safely perform dead code stripping. Since LLVM never
1035 // generates code that does this, it is always safe to set.
1036 O
<< "\t.subsections_via_symbols\n";
1037 } else if (Subtarget
->isTargetCygMing()) {
1038 // Emit type information for external functions
1039 for (StringSet
<>::iterator i
= FnStubs
.begin(), e
= FnStubs
.end();
1041 O
<< "\t.def\t " << i
->getKeyData()
1042 << ";\t.scl\t" << COFF::C_EXT
1043 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
1047 // Emit final debug information.
1048 DwarfWriter
*DW
= getAnalysisIfAvailable
<DwarfWriter
>();
1050 } else if (Subtarget
->isTargetELF()) {
1051 // Emit final debug information.
1052 DwarfWriter
*DW
= getAnalysisIfAvailable
<DwarfWriter
>();
1056 return AsmPrinter::doFinalization(M
);
1059 // Include the auto-generated portion of the assembly writer.
1060 #include "X86GenAsmWriter.inc"