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 "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/Statistic.h"
42 STATISTIC(EmittedInsts
, "Number of machine instrs printed");
44 //===----------------------------------------------------------------------===//
45 // Primitive Helper Functions.
46 //===----------------------------------------------------------------------===//
48 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
49 // FIXME: the actual label generated doesn't matter here! Just mangle in
50 // something unique (the function number) with Private prefix.
51 if (Subtarget
->isTargetDarwin())
52 O
<< "\"L" << getFunctionNumber() << "$pb\"";
54 assert(Subtarget
->isTargetELF() && "Don't know how to print PIC label!");
55 O
<< ".Lllvm$" << getFunctionNumber() << ".$piclabel";
59 static X86MachineFunctionInfo
calculateFunctionInfo(const Function
*F
,
60 const TargetData
*TD
) {
61 X86MachineFunctionInfo Info
;
64 switch (F
->getCallingConv()) {
65 case CallingConv::X86_StdCall
:
66 Info
.setDecorationStyle(StdCall
);
68 case CallingConv::X86_FastCall
:
69 Info
.setDecorationStyle(FastCall
);
76 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
77 AI
!= AE
; ++AI
, ++argNum
) {
78 const Type
* Ty
= AI
->getType();
80 // 'Dereference' type in case of byval parameter attribute
81 if (F
->paramHasAttr(argNum
, Attribute::ByVal
))
82 Ty
= cast
<PointerType
>(Ty
)->getElementType();
84 // Size should be aligned to DWORD boundary
85 Size
+= ((TD
->getTypeAllocSize(Ty
) + 3)/4)*4;
88 // We're not supporting tooooo huge arguments :)
89 Info
.setBytesToPopOnReturn((unsigned int)Size
);
93 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
94 /// various name decorations for Cygwin and MingW.
95 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl
<char> &Name
,
96 const GlobalValue
*GV
) {
97 assert(Subtarget
->isTargetCygMing() && "This is only for cygwin and mingw");
99 const Function
*F
= dyn_cast
<Function
>(GV
);
102 // Save function name for later type emission.
103 if (F
->isDeclaration())
104 CygMingStubs
.insert(StringRef(Name
.data(), Name
.size()));
106 // We don't want to decorate non-stdcall or non-fastcall functions right now
107 CallingConv::ID CC
= F
->getCallingConv();
108 if (CC
!= CallingConv::X86_StdCall
&& CC
!= CallingConv::X86_FastCall
)
112 const X86MachineFunctionInfo
*Info
;
114 FMFInfoMap::const_iterator info_item
= FunctionInfoMap
.find(F
);
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 if (Info
->getDecorationStyle() == None
) return;
124 const FunctionType
*FT
= F
->getFunctionType();
126 // "Pure" variadic functions do not receive @0 suffix.
127 if (!FT
->isVarArg() || FT
->getNumParams() == 0 ||
128 (FT
->getNumParams() == 1 && F
->hasStructRetAttr()))
129 raw_svector_ostream(Name
) << '@' << Info
->getBytesToPopOnReturn();
131 if (Info
->getDecorationStyle() == FastCall
) {
135 Name
.insert(Name
.begin(), '@');
139 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
140 /// various name decorations for Cygwin and MingW.
141 void X86ATTAsmPrinter::DecorateCygMingName(std::string
&Name
,
142 const GlobalValue
*GV
) {
143 SmallString
<128> NameStr(Name
.begin(), Name
.end());
144 DecorateCygMingName(NameStr
, GV
);
145 Name
.assign(NameStr
.begin(), NameStr
.end());
148 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction
&MF
) {
149 unsigned FnAlign
= MF
.getAlignment();
150 const Function
*F
= MF
.getFunction();
152 if (Subtarget
->isTargetCygMing())
153 DecorateCygMingName(CurrentFnName
, F
);
155 OutStreamer
.SwitchSection(getObjFileLowering().SectionForGlobal(F
, Mang
, TM
));
156 EmitAlignment(FnAlign
, F
);
158 switch (F
->getLinkage()) {
159 default: llvm_unreachable("Unknown linkage type!");
160 case Function::InternalLinkage
: // Symbols default to internal.
161 case Function::PrivateLinkage
:
163 case Function::DLLExportLinkage
:
164 case Function::ExternalLinkage
:
165 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
167 case Function::LinkerPrivateLinkage
:
168 case Function::LinkOnceAnyLinkage
:
169 case Function::LinkOnceODRLinkage
:
170 case Function::WeakAnyLinkage
:
171 case Function::WeakODRLinkage
:
172 if (Subtarget
->isTargetDarwin()) {
173 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
174 O
<< MAI
->getWeakDefDirective() << CurrentFnName
<< '\n';
175 } else if (Subtarget
->isTargetCygMing()) {
176 O
<< "\t.globl\t" << CurrentFnName
<< "\n"
177 "\t.linkonce discard\n";
179 O
<< "\t.weak\t" << CurrentFnName
<< '\n';
184 printVisibility(CurrentFnName
, F
->getVisibility());
186 if (Subtarget
->isTargetELF())
187 O
<< "\t.type\t" << CurrentFnName
<< ",@function\n";
188 else if (Subtarget
->isTargetCygMing()) {
189 O
<< "\t.def\t " << CurrentFnName
191 (F
->hasInternalLinkage() ? COFF::C_STAT
: COFF::C_EXT
)
192 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
196 O
<< CurrentFnName
<< ':';
198 O
.PadToColumn(MAI
->getCommentColumn());
199 O
<< MAI
->getCommentString() << ' ';
200 WriteAsOperand(O
, F
, /*PrintType=*/false, F
->getParent());
204 // Add some workaround for linkonce linkage on Cygwin\MinGW
205 if (Subtarget
->isTargetCygMing() &&
206 (F
->hasLinkOnceLinkage() || F
->hasWeakLinkage()))
207 O
<< "Lllvm$workaround$fake$stub$" << CurrentFnName
<< ":\n";
210 /// runOnMachineFunction - This uses the printMachineInstruction()
211 /// method to print assembly for each instruction.
213 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction
&MF
) {
214 const Function
*F
= MF
.getFunction();
216 CallingConv::ID CC
= F
->getCallingConv();
218 SetupMachineFunction(MF
);
221 // Populate function information map. Actually, We don't want to populate
222 // non-stdcall or non-fastcall functions' information right now.
223 if (CC
== CallingConv::X86_StdCall
|| CC
== CallingConv::X86_FastCall
)
224 FunctionInfoMap
[F
] = *MF
.getInfo
<X86MachineFunctionInfo
>();
226 // Print out constants referenced by the function
227 EmitConstantPool(MF
.getConstantPool());
229 if (F
->hasDLLExportLinkage())
230 DLLExportedFns
.insert(Mang
->getMangledName(F
));
232 // Print the 'header' of function
233 emitFunctionHeader(MF
);
235 // Emit pre-function debug and/or EH information.
236 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
237 DW
->BeginFunction(&MF
);
239 // Print out code for the function.
240 bool hasAnyRealCode
= false;
241 for (MachineFunction::const_iterator I
= MF
.begin(), E
= MF
.end();
243 // Print a label for the basic block.
244 if (!VerboseAsm
&& (I
->pred_empty() || I
->isOnlyReachableByFallthrough())) {
245 // This is an entry block or a block that's only reachable via a
246 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
248 EmitBasicBlockStart(I
);
251 for (MachineBasicBlock::const_iterator II
= I
->begin(), IE
= I
->end();
253 // Print the assembly for the instruction.
255 hasAnyRealCode
= true;
256 printMachineInstruction(II
);
260 if (Subtarget
->isTargetDarwin() && !hasAnyRealCode
) {
261 // If the function is empty, then we need to emit *something*. Otherwise,
262 // the function's label might be associated with something that it wasn't
263 // meant to be associated with. We emit a noop in this situation.
264 // We are assuming inline asms are code.
268 if (MAI
->hasDotTypeDotSizeDirective())
269 O
<< "\t.size\t" << CurrentFnName
<< ", .-" << CurrentFnName
<< '\n';
271 // Emit post-function debug information.
272 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
273 DW
->EndFunction(&MF
);
275 // Print out jump tables referenced by the function.
276 EmitJumpTableInfo(MF
.getJumpTableInfo(), MF
);
278 // We didn't modify anything.
282 /// printSymbolOperand - Print a raw symbol reference operand. This handles
283 /// jump tables, constant pools, global address and external symbols, all of
284 /// which print to a label with various suffixes for relocation types etc.
285 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand
&MO
) {
286 switch (MO
.getType()) {
287 default: llvm_unreachable("unknown symbol type!");
288 case MachineOperand::MO_JumpTableIndex
:
289 O
<< MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
292 case MachineOperand::MO_ConstantPoolIndex
:
293 O
<< MAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
295 printOffset(MO
.getOffset());
297 case MachineOperand::MO_GlobalAddress
: {
298 const GlobalValue
*GV
= MO
.getGlobal();
300 const char *Suffix
= "";
301 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
)
303 else if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
304 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
||
305 MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
)
306 Suffix
= "$non_lazy_ptr";
308 std::string Name
= Mang
->getMangledName(GV
, Suffix
, Suffix
[0] != '\0');
309 if (Subtarget
->isTargetCygMing())
310 DecorateCygMingName(Name
, GV
);
312 // Handle dllimport linkage.
313 if (MO
.getTargetFlags() == X86II::MO_DLLIMPORT
)
314 Name
= "__imp_" + Name
;
316 if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
317 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
) {
318 SmallString
<128> NameStr
;
319 Mang
->getNameWithPrefix(NameStr
, GV
, true);
320 NameStr
+= "$non_lazy_ptr";
321 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
322 MCSymbol
*&StubSym
= GVStubs
[Sym
];
325 Mang
->getNameWithPrefix(NameStr
, GV
, false);
326 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
328 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
){
329 SmallString
<128> NameStr
;
330 Mang
->getNameWithPrefix(NameStr
, GV
, true);
331 NameStr
+= "$non_lazy_ptr";
332 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
333 MCSymbol
*&StubSym
= HiddenGVStubs
[Sym
];
336 Mang
->getNameWithPrefix(NameStr
, GV
, false);
337 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
339 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
340 SmallString
<128> NameStr
;
341 Mang
->getNameWithPrefix(NameStr
, GV
, true);
343 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
344 MCSymbol
*&StubSym
= FnStubs
[Sym
];
347 Mang
->getNameWithPrefix(NameStr
, GV
, false);
348 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
352 // If the name begins with a dollar-sign, enclose it in parens. We do this
353 // to avoid having it look like an integer immediate to the assembler.
355 O
<< '(' << Name
<< ')';
359 printOffset(MO
.getOffset());
362 case MachineOperand::MO_ExternalSymbol
: {
363 std::string Name
= Mang
->makeNameProper(MO
.getSymbolName());
364 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
366 MCSymbol
*&StubSym
= FnStubs
[OutContext
.GetOrCreateSymbol(Name
)];
368 Name
.erase(Name
.end()-5, Name
.end());
369 StubSym
= OutContext
.GetOrCreateSymbol(Name
);
373 // If the name begins with a dollar-sign, enclose it in parens. We do this
374 // to avoid having it look like an integer immediate to the assembler.
376 O
<< '(' << Name
<< ')';
383 switch (MO
.getTargetFlags()) {
385 llvm_unreachable("Unknown target flag on GV operand");
386 case X86II::MO_NO_FLAG
: // No flag.
388 case X86II::MO_DARWIN_NONLAZY
:
389 case X86II::MO_DLLIMPORT
:
390 case X86II::MO_DARWIN_STUB
:
391 // These affect the name of the symbol, not any suffix.
393 case X86II::MO_GOT_ABSOLUTE_ADDRESS
:
395 PrintPICBaseSymbol();
398 case X86II::MO_PIC_BASE_OFFSET
:
399 case X86II::MO_DARWIN_NONLAZY_PIC_BASE
:
400 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
:
402 PrintPICBaseSymbol();
404 case X86II::MO_TLSGD
: O
<< "@TLSGD"; break;
405 case X86II::MO_GOTTPOFF
: O
<< "@GOTTPOFF"; break;
406 case X86II::MO_INDNTPOFF
: O
<< "@INDNTPOFF"; break;
407 case X86II::MO_TPOFF
: O
<< "@TPOFF"; break;
408 case X86II::MO_NTPOFF
: O
<< "@NTPOFF"; break;
409 case X86II::MO_GOTPCREL
: O
<< "@GOTPCREL"; break;
410 case X86II::MO_GOT
: O
<< "@GOT"; break;
411 case X86II::MO_GOTOFF
: O
<< "@GOTOFF"; break;
412 case X86II::MO_PLT
: O
<< "@PLT"; break;
416 /// print_pcrel_imm - This is used to print an immediate value that ends up
417 /// being encoded as a pc-relative value. These print slightly differently, for
418 /// example, a $ is not emitted.
419 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr
*MI
, unsigned OpNo
) {
420 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
421 switch (MO
.getType()) {
422 default: llvm_unreachable("Unknown pcrel immediate operand");
423 case MachineOperand::MO_Immediate
:
426 case MachineOperand::MO_MachineBasicBlock
:
427 GetMBBSymbol(MO
.getMBB()->getNumber())->print(O
, MAI
);
429 case MachineOperand::MO_GlobalAddress
:
430 case MachineOperand::MO_ExternalSymbol
:
431 printSymbolOperand(MO
);
437 void X86ATTAsmPrinter::printOperand(const MachineInstr
*MI
, unsigned OpNo
,
438 const char *Modifier
) {
439 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
440 switch (MO
.getType()) {
441 default: llvm_unreachable("unknown operand type!");
442 case MachineOperand::MO_Register
: {
443 assert(TargetRegisterInfo::isPhysicalRegister(MO
.getReg()) &&
444 "Virtual registers should not make it this far!");
446 unsigned Reg
= MO
.getReg();
447 if (Modifier
&& strncmp(Modifier
, "subreg", strlen("subreg")) == 0) {
448 EVT VT
= (strcmp(Modifier
+6,"64") == 0) ?
449 MVT::i64
: ((strcmp(Modifier
+6, "32") == 0) ? MVT::i32
:
450 ((strcmp(Modifier
+6,"16") == 0) ? MVT::i16
: MVT::i8
));
451 Reg
= getX86SubSuperRegister(Reg
, VT
);
453 O
<< TRI
->getAsmName(Reg
);
457 case MachineOperand::MO_Immediate
:
458 O
<< '$' << MO
.getImm();
461 case MachineOperand::MO_JumpTableIndex
:
462 case MachineOperand::MO_ConstantPoolIndex
:
463 case MachineOperand::MO_GlobalAddress
:
464 case MachineOperand::MO_ExternalSymbol
: {
466 printSymbolOperand(MO
);
472 void X86ATTAsmPrinter::printSSECC(const MachineInstr
*MI
, unsigned Op
) {
473 unsigned char value
= MI
->getOperand(Op
).getImm();
474 assert(value
<= 7 && "Invalid ssecc argument!");
476 case 0: O
<< "eq"; break;
477 case 1: O
<< "lt"; break;
478 case 2: O
<< "le"; break;
479 case 3: O
<< "unord"; break;
480 case 4: O
<< "neq"; break;
481 case 5: O
<< "nlt"; break;
482 case 6: O
<< "nle"; break;
483 case 7: O
<< "ord"; break;
487 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr
*MI
, unsigned Op
,
488 const char *Modifier
) {
489 const MachineOperand
&BaseReg
= MI
->getOperand(Op
);
490 const MachineOperand
&IndexReg
= MI
->getOperand(Op
+2);
491 const MachineOperand
&DispSpec
= MI
->getOperand(Op
+3);
493 // If we really don't want to print out (rip), don't.
494 bool HasBaseReg
= BaseReg
.getReg() != 0;
495 if (HasBaseReg
&& Modifier
&& !strcmp(Modifier
, "no-rip") &&
496 BaseReg
.getReg() == X86::RIP
)
499 // HasParenPart - True if we will print out the () part of the mem ref.
500 bool HasParenPart
= IndexReg
.getReg() || HasBaseReg
;
502 if (DispSpec
.isImm()) {
503 int DispVal
= DispSpec
.getImm();
504 if (DispVal
|| !HasParenPart
)
507 assert(DispSpec
.isGlobal() || DispSpec
.isCPI() ||
508 DispSpec
.isJTI() || DispSpec
.isSymbol());
509 printSymbolOperand(MI
->getOperand(Op
+3));
513 assert(IndexReg
.getReg() != X86::ESP
&&
514 "X86 doesn't allow scaling by ESP");
518 printOperand(MI
, Op
, Modifier
);
520 if (IndexReg
.getReg()) {
522 printOperand(MI
, Op
+2, Modifier
);
523 unsigned ScaleVal
= MI
->getOperand(Op
+1).getImm();
525 O
<< ',' << ScaleVal
;
531 void X86ATTAsmPrinter::printMemReference(const MachineInstr
*MI
, unsigned Op
,
532 const char *Modifier
) {
533 assert(isMem(MI
, Op
) && "Invalid memory reference!");
534 const MachineOperand
&Segment
= MI
->getOperand(Op
+4);
535 if (Segment
.getReg()) {
536 printOperand(MI
, Op
+4, Modifier
);
539 printLeaMemReference(MI
, Op
, Modifier
);
542 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
543 const MachineBasicBlock
*MBB
) const {
544 if (!MAI
->getSetDirective())
547 // We don't need .set machinery if we have GOT-style relocations
548 if (Subtarget
->isPICStyleGOT())
551 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
552 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
554 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
556 if (Subtarget
->isPICStyleRIPRel())
557 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
558 << '_' << uid
<< '\n';
561 PrintPICBaseSymbol();
567 void X86ATTAsmPrinter::printPICLabel(const MachineInstr
*MI
, unsigned Op
) {
568 PrintPICBaseSymbol();
570 PrintPICBaseSymbol();
574 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
575 const MachineBasicBlock
*MBB
,
576 unsigned uid
) const {
577 const char *JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
578 MAI
->getData32bitsDirective() : MAI
->getData64bitsDirective();
580 O
<< JTEntryDirective
<< ' ';
582 if (Subtarget
->isPICStyleRIPRel() || Subtarget
->isPICStyleStubPIC()) {
583 O
<< MAI
->getPrivateGlobalPrefix() << getFunctionNumber()
584 << '_' << uid
<< "_set_" << MBB
->getNumber();
585 } else if (Subtarget
->isPICStyleGOT()) {
586 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
589 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
592 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand
&MO
, char Mode
) {
593 unsigned Reg
= MO
.getReg();
595 default: return true; // Unknown mode.
596 case 'b': // Print QImode register
597 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
);
599 case 'h': // Print QImode high register
600 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
, true);
602 case 'w': // Print HImode register
603 Reg
= getX86SubSuperRegister(Reg
, MVT::i16
);
605 case 'k': // Print SImode register
606 Reg
= getX86SubSuperRegister(Reg
, MVT::i32
);
608 case 'q': // Print DImode register
609 Reg
= getX86SubSuperRegister(Reg
, MVT::i64
);
613 O
<< '%'<< TRI
->getAsmName(Reg
);
617 /// PrintAsmOperand - Print out an operand for an inline asm expression.
619 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
621 const char *ExtraCode
) {
622 // Does this asm operand have a single letter operand modifier?
623 if (ExtraCode
&& ExtraCode
[0]) {
624 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
626 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
628 switch (ExtraCode
[0]) {
629 default: return true; // Unknown modifier.
630 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
635 if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol()) {
636 printSymbolOperand(MO
);
641 printOperand(MI
, OpNo
);
647 case 'c': // Don't print "$" before a global var name or constant.
650 else if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol())
651 printSymbolOperand(MO
);
653 printOperand(MI
, OpNo
);
656 case 'A': // Print '*' before a register (it must be a register)
659 printOperand(MI
, OpNo
);
664 case 'b': // Print QImode register
665 case 'h': // Print QImode high register
666 case 'w': // Print HImode register
667 case 'k': // Print SImode register
668 case 'q': // Print DImode register
670 return printAsmMRegister(MO
, ExtraCode
[0]);
671 printOperand(MI
, OpNo
);
674 case 'P': // This is the operand of a call, treat specially.
675 print_pcrel_imm(MI
, OpNo
);
678 case 'n': // Negate the immediate or print a '-' before the operand.
679 // Note: this is a temporary solution. It should be handled target
680 // independently as part of the 'MC' work.
689 printOperand(MI
, OpNo
);
693 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
,
696 const char *ExtraCode
) {
697 if (ExtraCode
&& ExtraCode
[0]) {
698 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
700 switch (ExtraCode
[0]) {
701 default: return true; // Unknown modifier.
702 case 'b': // Print QImode register
703 case 'h': // Print QImode high register
704 case 'w': // Print HImode register
705 case 'k': // Print SImode register
706 case 'q': // Print SImode register
707 // These only apply to registers, ignore on mem.
709 case 'P': // Don't print @PLT, but do print as memory.
710 printMemReference(MI
, OpNo
, "no-rip");
714 printMemReference(MI
, OpNo
);
720 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
721 /// AT&T syntax to the current output stream.
723 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr
*MI
) {
726 processDebugLoc(MI
->getDebugLoc());
728 printInstructionThroughMCStreamer(MI
);
730 if (VerboseAsm
&& !MI
->getDebugLoc().isUnknown())
735 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable
* GVar
) {
736 const TargetData
*TD
= TM
.getTargetData();
738 if (!GVar
->hasInitializer())
739 return; // External global require no code
741 // Check to see if this is a special global used by LLVM, if so, emit it.
742 if (EmitSpecialLLVMGlobal(GVar
)) {
743 if (Subtarget
->isTargetDarwin() &&
744 TM
.getRelocationModel() == Reloc::Static
) {
745 if (GVar
->getName() == "llvm.global_ctors")
746 O
<< ".reference .constructors_used\n";
747 else if (GVar
->getName() == "llvm.global_dtors")
748 O
<< ".reference .destructors_used\n";
753 std::string name
= Mang
->getMangledName(GVar
);
754 Constant
*C
= GVar
->getInitializer();
755 const Type
*Type
= C
->getType();
756 unsigned Size
= TD
->getTypeAllocSize(Type
);
757 unsigned Align
= TD
->getPreferredAlignmentLog(GVar
);
759 printVisibility(name
, GVar
->getVisibility());
761 if (Subtarget
->isTargetELF())
762 O
<< "\t.type\t" << name
<< ",@object\n";
765 SectionKind GVKind
= TargetLoweringObjectFile::getKindForGlobal(GVar
, TM
);
766 const MCSection
*TheSection
=
767 getObjFileLowering().SectionForGlobal(GVar
, GVKind
, Mang
, TM
);
768 OutStreamer
.SwitchSection(TheSection
);
770 // FIXME: get this stuff from section kind flags.
771 if (C
->isNullValue() && !GVar
->hasSection() &&
772 // Don't put things that should go in the cstring section into "comm".
773 !TheSection
->getKind().isMergeableCString()) {
774 if (GVar
->hasExternalLinkage()) {
775 if (const char *Directive
= MAI
->getZeroFillDirective()) {
776 O
<< "\t.globl " << name
<< '\n';
777 O
<< Directive
<< "__DATA, __common, " << name
<< ", "
778 << Size
<< ", " << Align
<< '\n';
783 if (!GVar
->isThreadLocal() &&
784 (GVar
->hasLocalLinkage() || GVar
->isWeakForLinker())) {
785 if (Size
== 0) Size
= 1; // .comm Foo, 0 is undefined, avoid it.
787 if (MAI
->getLCOMMDirective() != NULL
) {
788 if (GVar
->hasLocalLinkage()) {
789 O
<< MAI
->getLCOMMDirective() << name
<< ',' << Size
;
790 if (Subtarget
->isTargetDarwin())
792 } else if (Subtarget
->isTargetDarwin() && !GVar
->hasCommonLinkage()) {
793 O
<< "\t.globl " << name
<< '\n'
794 << MAI
->getWeakDefDirective() << name
<< '\n';
795 EmitAlignment(Align
, GVar
);
798 O
.PadToColumn(MAI
->getCommentColumn());
799 O
<< MAI
->getCommentString() << ' ';
800 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
803 EmitGlobalConstant(C
);
806 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
807 if (MAI
->getCOMMDirectiveTakesAlignment())
808 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
811 if (!Subtarget
->isTargetCygMing()) {
812 if (GVar
->hasLocalLinkage())
813 O
<< "\t.local\t" << name
<< '\n';
815 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
816 if (MAI
->getCOMMDirectiveTakesAlignment())
817 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
820 O
.PadToColumn(MAI
->getCommentColumn());
821 O
<< MAI
->getCommentString() << ' ';
822 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
829 switch (GVar
->getLinkage()) {
830 case GlobalValue::CommonLinkage
:
831 case GlobalValue::LinkOnceAnyLinkage
:
832 case GlobalValue::LinkOnceODRLinkage
:
833 case GlobalValue::WeakAnyLinkage
:
834 case GlobalValue::WeakODRLinkage
:
835 case GlobalValue::LinkerPrivateLinkage
:
836 if (Subtarget
->isTargetDarwin()) {
837 O
<< "\t.globl " << name
<< '\n'
838 << MAI
->getWeakDefDirective() << name
<< '\n';
839 } else if (Subtarget
->isTargetCygMing()) {
840 O
<< "\t.globl\t" << name
<< "\n"
841 "\t.linkonce same_size\n";
843 O
<< "\t.weak\t" << name
<< '\n';
846 case GlobalValue::DLLExportLinkage
:
847 case GlobalValue::AppendingLinkage
:
848 // FIXME: appending linkage variables should go into a section of
849 // their name or something. For now, just emit them as external.
850 case GlobalValue::ExternalLinkage
:
851 // If external or appending, declare as a global symbol
852 O
<< "\t.globl " << name
<< '\n';
854 case GlobalValue::PrivateLinkage
:
855 case GlobalValue::InternalLinkage
:
858 llvm_unreachable("Unknown linkage type!");
861 EmitAlignment(Align
, GVar
);
864 O
.PadToColumn(MAI
->getCommentColumn());
865 O
<< MAI
->getCommentString() << ' ';
866 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
870 EmitGlobalConstant(C
);
872 if (MAI
->hasDotTypeDotSizeDirective())
873 O
<< "\t.size\t" << name
<< ", " << Size
<< '\n';
876 static int SortSymbolPair(const void *LHS
, const void *RHS
) {
877 MCSymbol
*LHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)LHS
)->first
;
878 MCSymbol
*RHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)RHS
)->first
;
879 return LHSS
->getName().compare(RHSS
->getName());
882 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
884 static std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> >
885 GetSortedStubs(const DenseMap
<MCSymbol
*, MCSymbol
*> &Map
) {
886 assert(!Map
.empty());
887 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > List(Map
.begin(), Map
.end());
888 qsort(&List
[0], List
.size(), sizeof(List
[0]), SortSymbolPair
);
892 bool X86ATTAsmPrinter::doFinalization(Module
&M
) {
893 // Print out module-level global variables here.
894 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
896 if (I
->hasDLLExportLinkage())
897 DLLExportedGVs
.insert(Mang
->getMangledName(I
));
900 if (Subtarget
->isTargetDarwin()) {
901 // All darwin targets use mach-o.
902 TargetLoweringObjectFileMachO
&TLOFMacho
=
903 static_cast<TargetLoweringObjectFileMachO
&>(getObjFileLowering());
905 // Add the (possibly multiple) personalities to the set of global value
906 // stubs. Only referenced functions get into the Personalities list.
907 if (MAI
->doesSupportExceptionHandling() && MMI
&& !Subtarget
->is64Bit()) {
908 const std::vector
<Function
*> &Personalities
= MMI
->getPersonalities();
909 for (unsigned i
= 0, e
= Personalities
.size(); i
!= e
; ++i
) {
910 if (Personalities
[i
] == 0)
913 SmallString
<128> Name
;
914 Mang
->getNameWithPrefix(Name
, Personalities
[i
], true /*private label*/);
915 Name
+= "$non_lazy_ptr";
916 MCSymbol
*NLPName
= OutContext
.GetOrCreateSymbol(Name
.str());
918 MCSymbol
*&StubName
= GVStubs
[NLPName
];
919 if (StubName
!= 0) continue;
923 Mang
->getNameWithPrefix(Name
, Personalities
[i
], false);
924 StubName
= OutContext
.GetOrCreateSymbol(Name
.str());
928 // Output stubs for dynamically-linked functions
929 if (!FnStubs
.empty()) {
930 const MCSection
*TheSection
=
931 TLOFMacho
.getMachOSection("__IMPORT", "__jump_table",
932 MCSectionMachO::S_SYMBOL_STUBS
|
933 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE
|
934 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS
,
935 5, SectionKind::getMetadata());
936 OutStreamer
.SwitchSection(TheSection
);
938 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
939 = GetSortedStubs(FnStubs
);
940 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
941 Stubs
[i
].first
->print(O
, MAI
);
942 O
<< ":\n" << "\t.indirect_symbol ";
943 // Get the MCSymbol without the $stub suffix.
944 Stubs
[i
].second
->print(O
, MAI
);
945 O
<< "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
950 // Output stubs for external and common global variables.
951 if (!GVStubs
.empty()) {
952 const MCSection
*TheSection
=
953 TLOFMacho
.getMachOSection("__IMPORT", "__pointers",
954 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS
,
955 SectionKind::getMetadata());
956 OutStreamer
.SwitchSection(TheSection
);
958 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
959 = GetSortedStubs(GVStubs
);
960 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
961 Stubs
[i
].first
->print(O
, MAI
);
962 O
<< ":\n\t.indirect_symbol ";
963 Stubs
[i
].second
->print(O
, MAI
);
964 O
<< "\n\t.long\t0\n";
968 if (!HiddenGVStubs
.empty()) {
969 OutStreamer
.SwitchSection(getObjFileLowering().getDataSection());
972 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
973 = GetSortedStubs(HiddenGVStubs
);
974 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
975 Stubs
[i
].first
->print(O
, MAI
);
976 O
<< ":\n" << MAI
->getData32bitsDirective();
977 Stubs
[i
].second
->print(O
, MAI
);
982 // Funny Darwin hack: This flag tells the linker that no global symbols
983 // contain code that falls through to other global symbols (e.g. the obvious
984 // implementation of multiple entry points). If this doesn't occur, the
985 // linker can safely perform dead code stripping. Since LLVM never
986 // generates code that does this, it is always safe to set.
987 O
<< "\t.subsections_via_symbols\n";
988 } else if (Subtarget
->isTargetCygMing()) {
989 // Emit type information for external functions
990 for (StringSet
<>::iterator i
= CygMingStubs
.begin(), e
= CygMingStubs
.end();
992 O
<< "\t.def\t " << i
->getKeyData()
993 << ";\t.scl\t" << COFF::C_EXT
994 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
1000 // Output linker support code for dllexported globals on windows.
1001 if (!DLLExportedGVs
.empty() || !DLLExportedFns
.empty()) {
1002 // dllexport symbols only exist on coff targets.
1003 TargetLoweringObjectFileCOFF
&TLOFMacho
=
1004 static_cast<TargetLoweringObjectFileCOFF
&>(getObjFileLowering());
1006 OutStreamer
.SwitchSection(TLOFMacho
.getCOFFSection(".section .drectve",true,
1007 SectionKind::getMetadata()));
1009 for (StringSet
<>::iterator i
= DLLExportedGVs
.begin(),
1010 e
= DLLExportedGVs
.end(); i
!= e
; ++i
)
1011 O
<< "\t.ascii \" -export:" << i
->getKeyData() << ",data\"\n";
1013 for (StringSet
<>::iterator i
= DLLExportedFns
.begin(),
1014 e
= DLLExportedFns
.end();
1016 O
<< "\t.ascii \" -export:" << i
->getKeyData() << "\"\n";
1019 // Do common shutdown.
1020 return AsmPrinter::doFinalization(M
);