1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86ATTInstPrinter.h"
19 #include "X86MCInstLower.h"
22 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/Statistic.h"
44 STATISTIC(EmittedInsts
, "Number of machine instrs printed");
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
50 void X86ATTAsmPrinter::printMCInst(const MCInst
*MI
) {
51 X86ATTInstPrinter(O
, MAI
).printInstruction(MI
);
54 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
55 // FIXME: Gross const cast hack.
56 X86ATTAsmPrinter
*AP
= const_cast<X86ATTAsmPrinter
*>(this);
57 X86MCInstLower(OutContext
, 0, *AP
).GetPICBaseSymbol()->print(O
, MAI
);
60 static X86MachineFunctionInfo
calculateFunctionInfo(const Function
*F
,
61 const TargetData
*TD
) {
62 X86MachineFunctionInfo Info
;
65 switch (F
->getCallingConv()) {
66 case CallingConv::X86_StdCall
:
67 Info
.setDecorationStyle(StdCall
);
69 case CallingConv::X86_FastCall
:
70 Info
.setDecorationStyle(FastCall
);
77 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
78 AI
!= AE
; ++AI
, ++argNum
) {
79 const Type
* Ty
= AI
->getType();
81 // 'Dereference' type in case of byval parameter attribute
82 if (F
->paramHasAttr(argNum
, Attribute::ByVal
))
83 Ty
= cast
<PointerType
>(Ty
)->getElementType();
85 // Size should be aligned to DWORD boundary
86 Size
+= ((TD
->getTypeAllocSize(Ty
) + 3)/4)*4;
89 // We're not supporting tooooo huge arguments :)
90 Info
.setBytesToPopOnReturn((unsigned int)Size
);
94 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
95 /// various name decorations for Cygwin and MingW.
96 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl
<char> &Name
,
97 const GlobalValue
*GV
) {
98 assert(Subtarget
->isTargetCygMing() && "This is only for cygwin and mingw");
100 const Function
*F
= dyn_cast
<Function
>(GV
);
103 // Save function name for later type emission.
104 if (F
->isDeclaration())
105 CygMingStubs
.insert(StringRef(Name
.data(), Name
.size()));
107 // We don't want to decorate non-stdcall or non-fastcall functions right now
108 CallingConv::ID CC
= F
->getCallingConv();
109 if (CC
!= CallingConv::X86_StdCall
&& CC
!= CallingConv::X86_FastCall
)
113 const X86MachineFunctionInfo
*Info
;
115 FMFInfoMap::const_iterator info_item
= FunctionInfoMap
.find(F
);
116 if (info_item
== FunctionInfoMap
.end()) {
117 // Calculate apropriate function info and populate map
118 FunctionInfoMap
[F
] = calculateFunctionInfo(F
, TM
.getTargetData());
119 Info
= &FunctionInfoMap
[F
];
121 Info
= &info_item
->second
;
124 if (Info
->getDecorationStyle() == None
) return;
125 const FunctionType
*FT
= F
->getFunctionType();
127 // "Pure" variadic functions do not receive @0 suffix.
128 if (!FT
->isVarArg() || FT
->getNumParams() == 0 ||
129 (FT
->getNumParams() == 1 && F
->hasStructRetAttr()))
130 raw_svector_ostream(Name
) << '@' << Info
->getBytesToPopOnReturn();
132 if (Info
->getDecorationStyle() == FastCall
) {
136 Name
.insert(Name
.begin(), '@');
140 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
141 /// various name decorations for Cygwin and MingW.
142 void X86ATTAsmPrinter::DecorateCygMingName(std::string
&Name
,
143 const GlobalValue
*GV
) {
144 SmallString
<128> NameStr(Name
.begin(), Name
.end());
145 DecorateCygMingName(NameStr
, GV
);
146 Name
.assign(NameStr
.begin(), NameStr
.end());
149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction
&MF
) {
150 unsigned FnAlign
= MF
.getAlignment();
151 const Function
*F
= MF
.getFunction();
153 if (Subtarget
->isTargetCygMing())
154 DecorateCygMingName(CurrentFnName
, F
);
156 OutStreamer
.SwitchSection(getObjFileLowering().SectionForGlobal(F
, Mang
, TM
));
157 EmitAlignment(FnAlign
, F
);
159 switch (F
->getLinkage()) {
160 default: llvm_unreachable("Unknown linkage type!");
161 case Function::InternalLinkage
: // Symbols default to internal.
162 case Function::PrivateLinkage
:
164 case Function::DLLExportLinkage
:
165 case Function::ExternalLinkage
:
166 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
168 case Function::LinkerPrivateLinkage
:
169 case Function::LinkOnceAnyLinkage
:
170 case Function::LinkOnceODRLinkage
:
171 case Function::WeakAnyLinkage
:
172 case Function::WeakODRLinkage
:
173 if (Subtarget
->isTargetDarwin()) {
174 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
175 O
<< MAI
->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
<< ':';
199 O
.PadToColumn(MAI
->getCommentColumn());
200 O
<< MAI
->getCommentString() << ' ';
201 WriteAsOperand(O
, F
, /*PrintType=*/false, F
->getParent());
205 // Add some workaround for linkonce linkage on Cygwin\MinGW
206 if (Subtarget
->isTargetCygMing() &&
207 (F
->hasLinkOnceLinkage() || F
->hasWeakLinkage()))
208 O
<< "Lllvm$workaround$fake$stub$" << CurrentFnName
<< ":\n";
211 /// runOnMachineFunction - This uses the printMachineInstruction()
212 /// method to print assembly for each instruction.
214 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction
&MF
) {
215 const Function
*F
= MF
.getFunction();
217 CallingConv::ID CC
= F
->getCallingConv();
219 SetupMachineFunction(MF
);
222 // Populate function information map. Actually, We don't want to populate
223 // non-stdcall or non-fastcall functions' information right now.
224 if (CC
== CallingConv::X86_StdCall
|| CC
== CallingConv::X86_FastCall
)
225 FunctionInfoMap
[F
] = *MF
.getInfo
<X86MachineFunctionInfo
>();
227 // Print out constants referenced by the function
228 EmitConstantPool(MF
.getConstantPool());
230 if (F
->hasDLLExportLinkage())
231 DLLExportedFns
.insert(Mang
->getMangledName(F
));
233 // Print the 'header' of function
234 emitFunctionHeader(MF
);
236 // Emit pre-function debug and/or EH information.
237 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
238 DW
->BeginFunction(&MF
);
240 // Print out code for the function.
241 bool hasAnyRealCode
= false;
242 for (MachineFunction::const_iterator I
= MF
.begin(), E
= MF
.end();
244 // Print a label for the basic block.
245 if (!VerboseAsm
&& (I
->pred_empty() || I
->isOnlyReachableByFallthrough())) {
246 // This is an entry block or a block that's only reachable via a
247 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
249 EmitBasicBlockStart(I
);
252 for (MachineBasicBlock::const_iterator II
= I
->begin(), IE
= I
->end();
254 // Print the assembly for the instruction.
256 hasAnyRealCode
= true;
257 printMachineInstruction(II
);
261 if (Subtarget
->isTargetDarwin() && !hasAnyRealCode
) {
262 // If the function is empty, then we need to emit *something*. Otherwise,
263 // the function's label might be associated with something that it wasn't
264 // meant to be associated with. We emit a noop in this situation.
265 // We are assuming inline asms are code.
269 if (MAI
->hasDotTypeDotSizeDirective())
270 O
<< "\t.size\t" << CurrentFnName
<< ", .-" << CurrentFnName
<< '\n';
272 // Emit post-function debug information.
273 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
274 DW
->EndFunction(&MF
);
276 // Print out jump tables referenced by the function.
277 EmitJumpTableInfo(MF
.getJumpTableInfo(), MF
);
279 // We didn't modify anything.
283 /// printSymbolOperand - Print a raw symbol reference operand. This handles
284 /// jump tables, constant pools, global address and external symbols, all of
285 /// which print to a label with various suffixes for relocation types etc.
286 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand
&MO
) {
287 switch (MO
.getType()) {
288 default: llvm_unreachable("unknown symbol type!");
289 case MachineOperand::MO_JumpTableIndex
:
290 O
<< MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
293 case MachineOperand::MO_ConstantPoolIndex
:
294 O
<< MAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
296 printOffset(MO
.getOffset());
298 case MachineOperand::MO_GlobalAddress
: {
299 const GlobalValue
*GV
= MO
.getGlobal();
301 const char *Suffix
= "";
302 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
)
304 else if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
305 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
||
306 MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
)
307 Suffix
= "$non_lazy_ptr";
309 std::string Name
= Mang
->getMangledName(GV
, Suffix
, Suffix
[0] != '\0');
310 if (Subtarget
->isTargetCygMing())
311 DecorateCygMingName(Name
, GV
);
313 // Handle dllimport linkage.
314 if (MO
.getTargetFlags() == X86II::MO_DLLIMPORT
)
315 Name
= "__imp_" + Name
;
317 if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
318 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
) {
319 SmallString
<128> NameStr
;
320 Mang
->getNameWithPrefix(NameStr
, GV
, true);
321 NameStr
+= "$non_lazy_ptr";
322 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
323 MCSymbol
*&StubSym
= GVStubs
[Sym
];
326 Mang
->getNameWithPrefix(NameStr
, GV
, false);
327 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
329 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
){
330 SmallString
<128> NameStr
;
331 Mang
->getNameWithPrefix(NameStr
, GV
, true);
332 NameStr
+= "$non_lazy_ptr";
333 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
334 MCSymbol
*&StubSym
= HiddenGVStubs
[Sym
];
337 Mang
->getNameWithPrefix(NameStr
, GV
, false);
338 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
340 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
341 SmallString
<128> NameStr
;
342 Mang
->getNameWithPrefix(NameStr
, GV
, true);
344 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
345 MCSymbol
*&StubSym
= FnStubs
[Sym
];
348 Mang
->getNameWithPrefix(NameStr
, GV
, false);
349 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
353 // If the name begins with a dollar-sign, enclose it in parens. We do this
354 // to avoid having it look like an integer immediate to the assembler.
356 O
<< '(' << Name
<< ')';
360 printOffset(MO
.getOffset());
363 case MachineOperand::MO_ExternalSymbol
: {
364 std::string Name
= Mang
->makeNameProper(MO
.getSymbolName());
365 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
367 MCSymbol
*&StubSym
= FnStubs
[OutContext
.GetOrCreateSymbol(Name
)];
369 Name
.erase(Name
.end()-5, Name
.end());
370 StubSym
= OutContext
.GetOrCreateSymbol(Name
);
374 // If the name begins with a dollar-sign, enclose it in parens. We do this
375 // to avoid having it look like an integer immediate to the assembler.
377 O
<< '(' << Name
<< ')';
384 switch (MO
.getTargetFlags()) {
386 llvm_unreachable("Unknown target flag on GV operand");
387 case X86II::MO_NO_FLAG
: // No flag.
389 case X86II::MO_DARWIN_NONLAZY
:
390 case X86II::MO_DLLIMPORT
:
391 case X86II::MO_DARWIN_STUB
:
392 // These affect the name of the symbol, not any suffix.
394 case X86II::MO_GOT_ABSOLUTE_ADDRESS
:
396 PrintPICBaseSymbol();
399 case X86II::MO_PIC_BASE_OFFSET
:
400 case X86II::MO_DARWIN_NONLAZY_PIC_BASE
:
401 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
:
403 PrintPICBaseSymbol();
405 case X86II::MO_TLSGD
: O
<< "@TLSGD"; break;
406 case X86II::MO_GOTTPOFF
: O
<< "@GOTTPOFF"; break;
407 case X86II::MO_INDNTPOFF
: O
<< "@INDNTPOFF"; break;
408 case X86II::MO_TPOFF
: O
<< "@TPOFF"; break;
409 case X86II::MO_NTPOFF
: O
<< "@NTPOFF"; break;
410 case X86II::MO_GOTPCREL
: O
<< "@GOTPCREL"; break;
411 case X86II::MO_GOT
: O
<< "@GOT"; break;
412 case X86II::MO_GOTOFF
: O
<< "@GOTOFF"; break;
413 case X86II::MO_PLT
: O
<< "@PLT"; break;
417 /// print_pcrel_imm - This is used to print an immediate value that ends up
418 /// being encoded as a pc-relative value. These print slightly differently, for
419 /// example, a $ is not emitted.
420 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr
*MI
, unsigned OpNo
) {
421 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
422 switch (MO
.getType()) {
423 default: llvm_unreachable("Unknown pcrel immediate operand");
424 case MachineOperand::MO_Immediate
:
427 case MachineOperand::MO_MachineBasicBlock
:
428 GetMBBSymbol(MO
.getMBB()->getNumber())->print(O
, MAI
);
430 case MachineOperand::MO_GlobalAddress
:
431 case MachineOperand::MO_ExternalSymbol
:
432 printSymbolOperand(MO
);
438 void X86ATTAsmPrinter::printOperand(const MachineInstr
*MI
, unsigned OpNo
,
439 const char *Modifier
) {
440 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
441 switch (MO
.getType()) {
442 default: llvm_unreachable("unknown operand type!");
443 case MachineOperand::MO_Register
: {
444 assert(TargetRegisterInfo::isPhysicalRegister(MO
.getReg()) &&
445 "Virtual registers should not make it this far!");
447 unsigned Reg
= MO
.getReg();
448 if (Modifier
&& strncmp(Modifier
, "subreg", strlen("subreg")) == 0) {
449 EVT VT
= (strcmp(Modifier
+6,"64") == 0) ?
450 MVT::i64
: ((strcmp(Modifier
+6, "32") == 0) ? MVT::i32
:
451 ((strcmp(Modifier
+6,"16") == 0) ? MVT::i16
: MVT::i8
));
452 Reg
= getX86SubSuperRegister(Reg
, VT
);
454 O
<< TRI
->getAsmName(Reg
);
458 case MachineOperand::MO_Immediate
:
459 O
<< '$' << MO
.getImm();
462 case MachineOperand::MO_JumpTableIndex
:
463 case MachineOperand::MO_ConstantPoolIndex
:
464 case MachineOperand::MO_GlobalAddress
:
465 case MachineOperand::MO_ExternalSymbol
: {
467 printSymbolOperand(MO
);
473 void X86ATTAsmPrinter::printSSECC(const MachineInstr
*MI
, unsigned Op
) {
474 unsigned char value
= MI
->getOperand(Op
).getImm();
475 assert(value
<= 7 && "Invalid ssecc argument!");
477 case 0: O
<< "eq"; break;
478 case 1: O
<< "lt"; break;
479 case 2: O
<< "le"; break;
480 case 3: O
<< "unord"; break;
481 case 4: O
<< "neq"; break;
482 case 5: O
<< "nlt"; break;
483 case 6: O
<< "nle"; break;
484 case 7: O
<< "ord"; break;
488 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr
*MI
, unsigned Op
,
489 const char *Modifier
) {
490 const MachineOperand
&BaseReg
= MI
->getOperand(Op
);
491 const MachineOperand
&IndexReg
= MI
->getOperand(Op
+2);
492 const MachineOperand
&DispSpec
= MI
->getOperand(Op
+3);
494 // If we really don't want to print out (rip), don't.
495 bool HasBaseReg
= BaseReg
.getReg() != 0;
496 if (HasBaseReg
&& Modifier
&& !strcmp(Modifier
, "no-rip") &&
497 BaseReg
.getReg() == X86::RIP
)
500 // HasParenPart - True if we will print out the () part of the mem ref.
501 bool HasParenPart
= IndexReg
.getReg() || HasBaseReg
;
503 if (DispSpec
.isImm()) {
504 int DispVal
= DispSpec
.getImm();
505 if (DispVal
|| !HasParenPart
)
508 assert(DispSpec
.isGlobal() || DispSpec
.isCPI() ||
509 DispSpec
.isJTI() || DispSpec
.isSymbol());
510 printSymbolOperand(MI
->getOperand(Op
+3));
514 assert(IndexReg
.getReg() != X86::ESP
&&
515 "X86 doesn't allow scaling by ESP");
519 printOperand(MI
, Op
, Modifier
);
521 if (IndexReg
.getReg()) {
523 printOperand(MI
, Op
+2, Modifier
);
524 unsigned ScaleVal
= MI
->getOperand(Op
+1).getImm();
526 O
<< ',' << ScaleVal
;
532 void X86ATTAsmPrinter::printMemReference(const MachineInstr
*MI
, unsigned Op
,
533 const char *Modifier
) {
534 assert(isMem(MI
, Op
) && "Invalid memory reference!");
535 const MachineOperand
&Segment
= MI
->getOperand(Op
+4);
536 if (Segment
.getReg()) {
537 printOperand(MI
, Op
+4, Modifier
);
540 printLeaMemReference(MI
, Op
, Modifier
);
543 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
544 const MachineBasicBlock
*MBB
) const {
545 if (!MAI
->getSetDirective())
548 // We don't need .set machinery if we have GOT-style relocations
549 if (Subtarget
->isPICStyleGOT())
552 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
553 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
555 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
557 if (Subtarget
->isPICStyleRIPRel())
558 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
559 << '_' << uid
<< '\n';
562 PrintPICBaseSymbol();
568 void X86ATTAsmPrinter::printPICLabel(const MachineInstr
*MI
, unsigned Op
) {
569 PrintPICBaseSymbol();
571 PrintPICBaseSymbol();
575 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
576 const MachineBasicBlock
*MBB
,
577 unsigned uid
) const {
578 const char *JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
579 MAI
->getData32bitsDirective() : MAI
->getData64bitsDirective();
581 O
<< JTEntryDirective
<< ' ';
583 if (Subtarget
->isPICStyleRIPRel() || Subtarget
->isPICStyleStubPIC()) {
584 O
<< MAI
->getPrivateGlobalPrefix() << getFunctionNumber()
585 << '_' << uid
<< "_set_" << MBB
->getNumber();
586 } else if (Subtarget
->isPICStyleGOT()) {
587 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
590 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
593 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand
&MO
, char Mode
) {
594 unsigned Reg
= MO
.getReg();
596 default: return true; // Unknown mode.
597 case 'b': // Print QImode register
598 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
);
600 case 'h': // Print QImode high register
601 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
, true);
603 case 'w': // Print HImode register
604 Reg
= getX86SubSuperRegister(Reg
, MVT::i16
);
606 case 'k': // Print SImode register
607 Reg
= getX86SubSuperRegister(Reg
, MVT::i32
);
609 case 'q': // Print DImode register
610 Reg
= getX86SubSuperRegister(Reg
, MVT::i64
);
614 O
<< '%'<< TRI
->getAsmName(Reg
);
618 /// PrintAsmOperand - Print out an operand for an inline asm expression.
620 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
622 const char *ExtraCode
) {
623 // Does this asm operand have a single letter operand modifier?
624 if (ExtraCode
&& ExtraCode
[0]) {
625 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
627 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
629 switch (ExtraCode
[0]) {
630 default: return true; // Unknown modifier.
631 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
636 if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol()) {
637 printSymbolOperand(MO
);
642 printOperand(MI
, OpNo
);
648 case 'c': // Don't print "$" before a global var name or constant.
651 else if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol())
652 printSymbolOperand(MO
);
654 printOperand(MI
, OpNo
);
657 case 'A': // Print '*' before a register (it must be a register)
660 printOperand(MI
, OpNo
);
665 case 'b': // Print QImode register
666 case 'h': // Print QImode high register
667 case 'w': // Print HImode register
668 case 'k': // Print SImode register
669 case 'q': // Print DImode register
671 return printAsmMRegister(MO
, ExtraCode
[0]);
672 printOperand(MI
, OpNo
);
675 case 'P': // This is the operand of a call, treat specially.
676 print_pcrel_imm(MI
, OpNo
);
679 case 'n': // Negate the immediate or print a '-' before the operand.
680 // Note: this is a temporary solution. It should be handled target
681 // independently as part of the 'MC' work.
690 printOperand(MI
, OpNo
);
694 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
,
697 const char *ExtraCode
) {
698 if (ExtraCode
&& ExtraCode
[0]) {
699 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
701 switch (ExtraCode
[0]) {
702 default: return true; // Unknown modifier.
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 SImode register
708 // These only apply to registers, ignore on mem.
710 case 'P': // Don't print @PLT, but do print as memory.
711 printMemReference(MI
, OpNo
, "no-rip");
715 printMemReference(MI
, OpNo
);
721 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
722 /// AT&T syntax to the current output stream.
724 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr
*MI
) {
727 processDebugLoc(MI
->getDebugLoc());
729 printInstructionThroughMCStreamer(MI
);
731 if (VerboseAsm
&& !MI
->getDebugLoc().isUnknown())
736 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable
* GVar
) {
737 const TargetData
*TD
= TM
.getTargetData();
739 if (!GVar
->hasInitializer())
740 return; // External global require no code
742 // Check to see if this is a special global used by LLVM, if so, emit it.
743 if (EmitSpecialLLVMGlobal(GVar
)) {
744 if (Subtarget
->isTargetDarwin() &&
745 TM
.getRelocationModel() == Reloc::Static
) {
746 if (GVar
->getName() == "llvm.global_ctors")
747 O
<< ".reference .constructors_used\n";
748 else if (GVar
->getName() == "llvm.global_dtors")
749 O
<< ".reference .destructors_used\n";
754 std::string name
= Mang
->getMangledName(GVar
);
755 Constant
*C
= GVar
->getInitializer();
756 const Type
*Type
= C
->getType();
757 unsigned Size
= TD
->getTypeAllocSize(Type
);
758 unsigned Align
= TD
->getPreferredAlignmentLog(GVar
);
760 printVisibility(name
, GVar
->getVisibility());
762 if (Subtarget
->isTargetELF())
763 O
<< "\t.type\t" << name
<< ",@object\n";
766 SectionKind GVKind
= TargetLoweringObjectFile::getKindForGlobal(GVar
, TM
);
767 const MCSection
*TheSection
=
768 getObjFileLowering().SectionForGlobal(GVar
, GVKind
, Mang
, TM
);
769 OutStreamer
.SwitchSection(TheSection
);
771 // FIXME: get this stuff from section kind flags.
772 if (C
->isNullValue() && !GVar
->hasSection() &&
773 // Don't put things that should go in the cstring section into "comm".
774 !TheSection
->getKind().isMergeableCString()) {
775 if (GVar
->hasExternalLinkage()) {
776 if (const char *Directive
= MAI
->getZeroFillDirective()) {
777 O
<< "\t.globl " << name
<< '\n';
778 O
<< Directive
<< "__DATA, __common, " << name
<< ", "
779 << Size
<< ", " << Align
<< '\n';
784 if (!GVar
->isThreadLocal() &&
785 (GVar
->hasLocalLinkage() || GVar
->isWeakForLinker())) {
786 if (Size
== 0) Size
= 1; // .comm Foo, 0 is undefined, avoid it.
788 if (MAI
->getLCOMMDirective() != NULL
) {
789 if (GVar
->hasLocalLinkage()) {
790 O
<< MAI
->getLCOMMDirective() << name
<< ',' << Size
;
791 if (Subtarget
->isTargetDarwin())
793 } else if (Subtarget
->isTargetDarwin() && !GVar
->hasCommonLinkage()) {
794 O
<< "\t.globl " << name
<< '\n'
795 << MAI
->getWeakDefDirective() << name
<< '\n';
796 EmitAlignment(Align
, GVar
);
799 O
.PadToColumn(MAI
->getCommentColumn());
800 O
<< MAI
->getCommentString() << ' ';
801 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
804 EmitGlobalConstant(C
);
807 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
808 if (MAI
->getCOMMDirectiveTakesAlignment())
809 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
812 if (!Subtarget
->isTargetCygMing()) {
813 if (GVar
->hasLocalLinkage())
814 O
<< "\t.local\t" << name
<< '\n';
816 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
817 if (MAI
->getCOMMDirectiveTakesAlignment())
818 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
821 O
.PadToColumn(MAI
->getCommentColumn());
822 O
<< MAI
->getCommentString() << ' ';
823 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
830 switch (GVar
->getLinkage()) {
831 case GlobalValue::CommonLinkage
:
832 case GlobalValue::LinkOnceAnyLinkage
:
833 case GlobalValue::LinkOnceODRLinkage
:
834 case GlobalValue::WeakAnyLinkage
:
835 case GlobalValue::WeakODRLinkage
:
836 case GlobalValue::LinkerPrivateLinkage
:
837 if (Subtarget
->isTargetDarwin()) {
838 O
<< "\t.globl " << name
<< '\n'
839 << MAI
->getWeakDefDirective() << name
<< '\n';
840 } else if (Subtarget
->isTargetCygMing()) {
841 O
<< "\t.globl\t" << name
<< "\n"
842 "\t.linkonce same_size\n";
844 O
<< "\t.weak\t" << name
<< '\n';
847 case GlobalValue::DLLExportLinkage
:
848 case GlobalValue::AppendingLinkage
:
849 // FIXME: appending linkage variables should go into a section of
850 // their name or something. For now, just emit them as external.
851 case GlobalValue::ExternalLinkage
:
852 // If external or appending, declare as a global symbol
853 O
<< "\t.globl " << name
<< '\n';
855 case GlobalValue::PrivateLinkage
:
856 case GlobalValue::InternalLinkage
:
859 llvm_unreachable("Unknown linkage type!");
862 EmitAlignment(Align
, GVar
);
865 O
.PadToColumn(MAI
->getCommentColumn());
866 O
<< MAI
->getCommentString() << ' ';
867 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
871 EmitGlobalConstant(C
);
873 if (MAI
->hasDotTypeDotSizeDirective())
874 O
<< "\t.size\t" << name
<< ", " << Size
<< '\n';
877 static int SortSymbolPair(const void *LHS
, const void *RHS
) {
878 MCSymbol
*LHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)LHS
)->first
;
879 MCSymbol
*RHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)RHS
)->first
;
880 return LHSS
->getName().compare(RHSS
->getName());
883 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
885 static std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> >
886 GetSortedStubs(const DenseMap
<MCSymbol
*, MCSymbol
*> &Map
) {
887 assert(!Map
.empty());
888 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > List(Map
.begin(), Map
.end());
889 qsort(&List
[0], List
.size(), sizeof(List
[0]), SortSymbolPair
);
893 bool X86ATTAsmPrinter::doFinalization(Module
&M
) {
894 // Print out module-level global variables here.
895 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
897 if (I
->hasDLLExportLinkage())
898 DLLExportedGVs
.insert(Mang
->getMangledName(I
));
901 if (Subtarget
->isTargetDarwin()) {
902 // All darwin targets use mach-o.
903 TargetLoweringObjectFileMachO
&TLOFMacho
=
904 static_cast<TargetLoweringObjectFileMachO
&>(getObjFileLowering());
906 // Add the (possibly multiple) personalities to the set of global value
907 // stubs. Only referenced functions get into the Personalities list.
908 if (MAI
->doesSupportExceptionHandling() && MMI
&& !Subtarget
->is64Bit()) {
909 const std::vector
<Function
*> &Personalities
= MMI
->getPersonalities();
910 for (unsigned i
= 0, e
= Personalities
.size(); i
!= e
; ++i
) {
911 if (Personalities
[i
] == 0)
914 SmallString
<128> Name
;
915 Mang
->getNameWithPrefix(Name
, Personalities
[i
], true /*private label*/);
916 Name
+= "$non_lazy_ptr";
917 MCSymbol
*NLPName
= OutContext
.GetOrCreateSymbol(Name
.str());
919 MCSymbol
*&StubName
= GVStubs
[NLPName
];
920 if (StubName
!= 0) continue;
924 Mang
->getNameWithPrefix(Name
, Personalities
[i
], false);
925 StubName
= OutContext
.GetOrCreateSymbol(Name
.str());
929 // Output stubs for dynamically-linked functions
930 if (!FnStubs
.empty()) {
931 const MCSection
*TheSection
=
932 TLOFMacho
.getMachOSection("__IMPORT", "__jump_table",
933 MCSectionMachO::S_SYMBOL_STUBS
|
934 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE
|
935 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS
,
936 5, SectionKind::getMetadata());
937 OutStreamer
.SwitchSection(TheSection
);
939 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
940 = GetSortedStubs(FnStubs
);
941 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
942 Stubs
[i
].first
->print(O
, MAI
);
943 O
<< ":\n" << "\t.indirect_symbol ";
944 // Get the MCSymbol without the $stub suffix.
945 Stubs
[i
].second
->print(O
, MAI
);
946 O
<< "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
951 // Output stubs for external and common global variables.
952 if (!GVStubs
.empty()) {
953 const MCSection
*TheSection
=
954 TLOFMacho
.getMachOSection("__IMPORT", "__pointers",
955 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS
,
956 SectionKind::getMetadata());
957 OutStreamer
.SwitchSection(TheSection
);
959 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
960 = GetSortedStubs(GVStubs
);
961 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
962 Stubs
[i
].first
->print(O
, MAI
);
963 O
<< ":\n\t.indirect_symbol ";
964 Stubs
[i
].second
->print(O
, MAI
);
965 O
<< "\n\t.long\t0\n";
969 if (!HiddenGVStubs
.empty()) {
970 OutStreamer
.SwitchSection(getObjFileLowering().getDataSection());
973 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
974 = GetSortedStubs(HiddenGVStubs
);
975 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
976 Stubs
[i
].first
->print(O
, MAI
);
977 O
<< ":\n" << MAI
->getData32bitsDirective();
978 Stubs
[i
].second
->print(O
, MAI
);
983 // Funny Darwin hack: This flag tells the linker that no global symbols
984 // contain code that falls through to other global symbols (e.g. the obvious
985 // implementation of multiple entry points). If this doesn't occur, the
986 // linker can safely perform dead code stripping. Since LLVM never
987 // generates code that does this, it is always safe to set.
988 O
<< "\t.subsections_via_symbols\n";
989 } else if (Subtarget
->isTargetCygMing()) {
990 // Emit type information for external functions
991 for (StringSet
<>::iterator i
= CygMingStubs
.begin(), e
= CygMingStubs
.end();
993 O
<< "\t.def\t " << i
->getKeyData()
994 << ";\t.scl\t" << COFF::C_EXT
995 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
1001 // Output linker support code for dllexported globals on windows.
1002 if (!DLLExportedGVs
.empty() || !DLLExportedFns
.empty()) {
1003 // dllexport symbols only exist on coff targets.
1004 TargetLoweringObjectFileCOFF
&TLOFMacho
=
1005 static_cast<TargetLoweringObjectFileCOFF
&>(getObjFileLowering());
1007 OutStreamer
.SwitchSection(TLOFMacho
.getCOFFSection(".section .drectve",true,
1008 SectionKind::getMetadata()));
1010 for (StringSet
<>::iterator i
= DLLExportedGVs
.begin(),
1011 e
= DLLExportedGVs
.end(); i
!= e
; ++i
)
1012 O
<< "\t.ascii \" -export:" << i
->getKeyData() << ",data\"\n";
1014 for (StringSet
<>::iterator i
= DLLExportedFns
.begin(),
1015 e
= DLLExportedFns
.end();
1017 O
<< "\t.ascii \" -export:" << i
->getKeyData() << "\"\n";
1020 // Do common shutdown.
1021 return AsmPrinter::doFinalization(M
);