1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/ADT/StringExtras.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/Target/TargetAsmInfo.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(EmittedInsts, "Number of machine instrs printed");
34 static std::string computePICLabel(unsigned FnNum,
35 const TargetAsmInfo *TAI,
36 const X86Subtarget* Subtarget) {
38 if (Subtarget->isTargetDarwin())
39 label = "\"L" + utostr_32(FnNum) + "$pb\"";
40 else if (Subtarget->isTargetELF())
41 label = ".Lllvm$" + utostr_32(FnNum) + "$piclabel";
43 assert(0 && "Don't know how to print PIC label!\n");
48 /// getSectionForFunction - Return the section that we should emit the
49 /// specified function body into.
50 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
51 switch (F.getLinkage()) {
52 default: assert(0 && "Unknown linkage type!");
53 case Function::InternalLinkage:
54 case Function::DLLExportLinkage:
55 case Function::ExternalLinkage:
56 return TAI->getTextSection();
57 case Function::WeakLinkage:
58 case Function::LinkOnceLinkage:
59 if (Subtarget->isTargetDarwin()) {
60 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
61 } else if (Subtarget->isTargetCygMing()) {
62 return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"";
64 return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
70 /// runOnMachineFunction - This uses the printMachineInstruction()
71 /// method to print assembly for each instruction.
73 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
74 if (TAI->doesSupportDebugInformation()) {
75 // Let PassManager know we need debug information and relay
76 // the MachineModuleInfo address on to DwarfWriter.
77 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
80 SetupMachineFunction(MF);
83 // Print out constants referenced by the function
84 EmitConstantPool(MF.getConstantPool());
86 // Print out labels for the function.
87 const Function *F = MF.getFunction();
88 unsigned CC = F->getCallingConv();
90 // Populate function information map. Actually, We don't want to populate
91 // non-stdcall or non-fastcall functions' information right now.
92 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
93 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
95 X86SharedAsmPrinter::decorateName(CurrentFnName, F);
97 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
99 switch (F->getLinkage()) {
100 default: assert(0 && "Unknown linkage type!");
101 case Function::InternalLinkage: // Symbols default to internal.
102 if (Subtarget->isTargetDarwin())
103 // FIXME: This should be parameterized somewhere.
104 EmitAlignment(4, F, 0, true, 0x90);
106 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
108 case Function::DLLExportLinkage:
109 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
111 case Function::ExternalLinkage:
112 if (Subtarget->isTargetDarwin())
113 // FIXME: This should be parameterized somewhere.
114 EmitAlignment(4, F, 0, true, 0x90);
116 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
117 O << "\t.globl\t" << CurrentFnName << "\n";
119 case Function::LinkOnceLinkage:
120 case Function::WeakLinkage:
121 if (Subtarget->isTargetDarwin()) {
122 // FIXME: This should be parameterized somewhere.
123 EmitAlignment(4, F, 0, true, 0x90);
124 O << "\t.globl\t" << CurrentFnName << "\n";
125 O << "\t.weak_definition\t" << CurrentFnName << "\n";
126 } else if (Subtarget->isTargetCygMing()) {
127 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
128 O << "\t.globl " << CurrentFnName << "\n";
129 O << "\t.linkonce discard\n";
131 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
132 O << "\t.weak\t" << CurrentFnName << "\n";
136 if (F->hasHiddenVisibility()) {
137 if (const char *Directive = TAI->getHiddenDirective())
138 O << Directive << CurrentFnName << "\n";
139 } else if (F->hasProtectedVisibility()) {
140 if (const char *Directive = TAI->getProtectedDirective())
141 O << Directive << CurrentFnName << "\n";
144 if (Subtarget->isTargetELF())
145 O << "\t.type\t" << CurrentFnName << ",@function\n";
146 else if (Subtarget->isTargetCygMing()) {
147 O << "\t.def\t " << CurrentFnName
149 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
150 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
154 O << CurrentFnName << ":\n";
155 // Add some workaround for linkonce linkage on Cygwin\MinGW
156 if (Subtarget->isTargetCygMing() &&
157 (F->getLinkage() == Function::LinkOnceLinkage ||
158 F->getLinkage() == Function::WeakLinkage))
159 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
161 if (TAI->doesSupportDebugInformation()) {
162 // Emit pre-function debug information.
163 DW.BeginFunction(&MF);
166 // Print out code for the function.
167 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
169 // Print a label for the basic block.
170 if (I->pred_begin() != I->pred_end()) {
171 printBasicBlockLabel(I, true);
174 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
176 // Print the assembly for the instruction.
178 printMachineInstruction(II);
182 if (TAI->hasDotTypeDotSizeDirective())
183 O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
185 if (TAI->doesSupportDebugInformation()) {
186 // Emit post-function debug information.
190 // Print out jump tables referenced by the function.
191 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
193 // We didn't modify anything.
197 static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
198 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
201 static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
202 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
205 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
206 const char *Modifier, bool NotRIPRel) {
207 const MachineOperand &MO = MI->getOperand(OpNo);
208 const MRegisterInfo &RI = *TM.getRegisterInfo();
209 switch (MO.getType()) {
210 case MachineOperand::MO_Register: {
211 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
212 "Virtual registers should not make it this far!");
214 unsigned Reg = MO.getReg();
215 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
216 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
217 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
218 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
219 Reg = getX86SubSuperRegister(Reg, VT);
221 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
222 O << (char)tolower(*Name);
226 case MachineOperand::MO_Immediate:
228 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
230 O << MO.getImmedValue();
232 case MachineOperand::MO_MachineBasicBlock:
233 printBasicBlockLabel(MO.getMachineBasicBlock());
235 case MachineOperand::MO_JumpTableIndex: {
236 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
237 if (!isMemOp) O << '$';
238 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
239 << MO.getJumpTableIndex();
241 if (TM.getRelocationModel() == Reloc::PIC_) {
242 if (Subtarget->isPICStyleStub())
243 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
245 else if (Subtarget->isPICStyleGOT())
249 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
253 case MachineOperand::MO_ConstantPoolIndex: {
254 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
255 if (!isMemOp) O << '$';
256 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
257 << MO.getConstantPoolIndex();
259 if (TM.getRelocationModel() == Reloc::PIC_) {
260 if (Subtarget->isPICStyleStub())
261 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
263 else if (Subtarget->isPICStyleGOT())
267 int Offset = MO.getOffset();
273 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
277 case MachineOperand::MO_GlobalAddress: {
278 bool isCallOp = Modifier && !strcmp(Modifier, "call");
279 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
280 bool needCloseParen = false;
282 GlobalValue *GV = MO.getGlobal();
283 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
284 bool isThreadLocal = GVar && GVar->isThreadLocal();
286 std::string Name = Mang->getValueName(GV);
287 X86SharedAsmPrinter::decorateName(Name, GV);
289 if (!isMemOp && !isCallOp)
291 else if (Name[0] == '$') {
292 // The name begins with a dollar-sign. In order to avoid having it look
293 // like an integer immediate to the assembler, enclose it in parens.
295 needCloseParen = true;
298 if (printStub(TM, Subtarget)) {
299 // Link-once, declaration, or Weakly-linked global variables need
300 // non-lazily-resolved stubs
301 if (GV->isDeclaration() ||
302 GV->hasWeakLinkage() ||
303 GV->hasLinkOnceLinkage()) {
304 // Dynamically-resolved functions need a stub for the function.
305 if (isCallOp && isa<Function>(GV)) {
306 FnStubs.insert(Name);
307 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
309 GVStubs.insert(Name);
310 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
313 if (GV->hasDLLImportLinkage())
318 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
319 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
322 if (GV->hasDLLImportLinkage()) {
327 if (isCallOp && isa<Function>(GV)) {
328 if (printGOT(TM, Subtarget)) {
329 // Assemble call via PLT for non-local symbols
330 if (!(GV->hasHiddenVisibility() || GV->hasProtectedVisibility()) ||
334 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
335 // Save function name for later type emission
336 FnStubs.insert(Name);
340 if (GV->hasExternalWeakLinkage())
341 ExtWeakSymbols.insert(GV);
343 int Offset = MO.getOffset();
350 if (TM.getRelocationModel() == Reloc::PIC_)
351 O << "@TLSGD"; // general dynamic TLS model
353 if (GV->isDeclaration())
354 O << "@INDNTPOFF"; // initial exec TLS model
356 O << "@NTPOFF"; // local exec TLS model
357 } else if (isMemOp) {
358 if (printGOT(TM, Subtarget)) {
359 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
363 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
364 if ((GV->isDeclaration() ||
365 GV->hasWeakLinkage() ||
366 GV->hasLinkOnceLinkage()) &&
367 TM.getRelocationModel() != Reloc::Static)
370 if (needCloseParen) {
371 needCloseParen = false;
375 // Use rip when possible to reduce code size, except when
376 // index or base register are also part of the address. e.g.
377 // foo(%rip)(%rcx,%rax,4) is not legal
387 case MachineOperand::MO_ExternalSymbol: {
388 bool isCallOp = Modifier && !strcmp(Modifier, "call");
389 bool needCloseParen = false;
390 std::string Name(TAI->getGlobalPrefix());
391 Name += MO.getSymbolName();
392 if (isCallOp && printStub(TM, Subtarget)) {
393 FnStubs.insert(Name);
394 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
399 else if (Name[0] == '$') {
400 // The name begins with a dollar-sign. In order to avoid having it look
401 // like an integer immediate to the assembler, enclose it in parens.
403 needCloseParen = true;
408 if (printGOT(TM, Subtarget)) {
409 std::string GOTName(TAI->getGlobalPrefix());
410 GOTName+="_GLOBAL_OFFSET_TABLE_";
412 // HACK! Emit extra offset to PC during printing GOT offset to
413 // compensate for the size of popl instruction. The resulting code
417 // popl %some_register
418 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
420 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
429 if (!isCallOp && Subtarget->isPICStyleRIPRel())
435 O << "<unknown operand type>"; return;
439 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
440 unsigned char value = MI->getOperand(Op).getImmedValue();
441 assert(value <= 7 && "Invalid ssecc argument!");
443 case 0: O << "eq"; break;
444 case 1: O << "lt"; break;
445 case 2: O << "le"; break;
446 case 3: O << "unord"; break;
447 case 4: O << "neq"; break;
448 case 5: O << "nlt"; break;
449 case 6: O << "nle"; break;
450 case 7: O << "ord"; break;
454 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
455 const char *Modifier){
456 assert(isMem(MI, Op) && "Invalid memory reference!");
457 MachineOperand BaseReg = MI->getOperand(Op);
458 MachineOperand IndexReg = MI->getOperand(Op+2);
459 const MachineOperand &DispSpec = MI->getOperand(Op+3);
461 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
462 if (DispSpec.isGlobalAddress() ||
463 DispSpec.isConstantPoolIndex() ||
464 DispSpec.isJumpTableIndex()) {
465 printOperand(MI, Op+3, "mem", NotRIPRel);
467 int DispVal = DispSpec.getImmedValue();
468 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
472 if (IndexReg.getReg() || BaseReg.getReg()) {
473 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
474 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
476 // There are cases where we can end up with ESP/RSP in the indexreg slot.
477 // If this happens, swap the base/index register to support assemblers that
478 // don't work when the index is *SP.
479 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
480 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
481 std::swap(BaseReg, IndexReg);
482 std::swap(BaseRegOperand, IndexRegOperand);
486 if (BaseReg.getReg())
487 printOperand(MI, Op+BaseRegOperand, Modifier);
489 if (IndexReg.getReg()) {
491 printOperand(MI, Op+IndexRegOperand, Modifier);
493 O << "," << ScaleVal;
499 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
500 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
501 O << label << "\n" << label << ":";
505 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
507 const MRegisterInfo &RI = *TM.getRegisterInfo();
508 unsigned Reg = MO.getReg();
510 default: return true; // Unknown mode.
511 case 'b': // Print QImode register
512 Reg = getX86SubSuperRegister(Reg, MVT::i8);
514 case 'h': // Print QImode high register
515 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
517 case 'w': // Print HImode register
518 Reg = getX86SubSuperRegister(Reg, MVT::i16);
520 case 'k': // Print SImode register
521 Reg = getX86SubSuperRegister(Reg, MVT::i32);
526 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
527 O << (char)tolower(*Name);
531 /// PrintAsmOperand - Print out an operand for an inline asm expression.
533 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
535 const char *ExtraCode) {
536 // Does this asm operand have a single letter operand modifier?
537 if (ExtraCode && ExtraCode[0]) {
538 if (ExtraCode[1] != 0) return true; // Unknown modifier.
540 switch (ExtraCode[0]) {
541 default: return true; // Unknown modifier.
542 case 'c': // Don't print "$" before a global var name or constant.
543 printOperand(MI, OpNo, "mem");
545 case 'b': // Print QImode register
546 case 'h': // Print QImode high register
547 case 'w': // Print HImode register
548 case 'k': // Print SImode register
549 if (MI->getOperand(OpNo).isReg())
550 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
551 printOperand(MI, OpNo);
554 case 'P': // Don't print @PLT, but do print as memory.
555 printOperand(MI, OpNo, "mem");
560 printOperand(MI, OpNo);
564 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
567 const char *ExtraCode) {
568 if (ExtraCode && ExtraCode[0])
569 return true; // Unknown modifier.
570 printMemReference(MI, OpNo);
574 /// printMachineInstruction -- Print out a single X86 LLVM instruction
575 /// MI in AT&T syntax to the current output stream.
577 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
580 // See if a truncate instruction can be turned into a nop.
581 switch (MI->getOpcode()) {
583 case X86::PsMOVZX64rr32:
584 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
588 // Call the autogenerated instruction printer routines.
589 printInstruction(MI);
592 // Include the auto-generated portion of the assembly writer.
593 #include "X86GenAsmWriter.inc"