1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to Intel 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\"\n";
64 return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
65 ",\"ax\",@progbits\n";
70 /// runOnMachineFunction - This uses the printMachineInstruction()
71 /// method to print assembly for each instruction.
73 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
74 if (Subtarget->isTargetDarwin() ||
75 Subtarget->isTargetELF() ||
76 Subtarget->isTargetCygMing()) {
77 // Let PassManager know we need debug information and relay
78 // the MachineModuleInfo address on to DwarfWriter.
79 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
82 SetupMachineFunction(MF);
85 // Print out constants referenced by the function
86 EmitConstantPool(MF.getConstantPool());
88 // Print out labels for the function.
89 const Function *F = MF.getFunction();
90 unsigned CC = F->getCallingConv();
92 // Populate function information map. Actually, We don't want to populate
93 // non-stdcall or non-fastcall functions' information right now.
94 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
95 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
97 X86SharedAsmPrinter::decorateName(CurrentFnName, F);
99 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
101 switch (F->getLinkage()) {
102 default: assert(0 && "Unknown linkage type!");
103 case Function::InternalLinkage: // Symbols default to internal.
104 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
106 case Function::DLLExportLinkage:
107 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
109 case Function::ExternalLinkage:
110 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
111 O << "\t.globl\t" << CurrentFnName << "\n";
113 case Function::LinkOnceLinkage:
114 case Function::WeakLinkage:
115 if (Subtarget->isTargetDarwin()) {
116 O << "\t.globl\t" << CurrentFnName << "\n";
117 O << "\t.weak_definition\t" << CurrentFnName << "\n";
118 } else if (Subtarget->isTargetCygMing()) {
119 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
120 O << "\t.globl " << CurrentFnName << "\n";
121 O << "\t.linkonce discard\n";
123 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
124 O << "\t.weak " << CurrentFnName << "\n";
128 if (F->hasHiddenVisibility()) {
129 if (const char *Directive = TAI->getHiddenDirective())
130 O << Directive << CurrentFnName << "\n";
131 } else if (F->hasProtectedVisibility()) {
132 if (const char *Directive = TAI->getProtectedDirective())
133 O << Directive << CurrentFnName << "\n";
136 if (Subtarget->isTargetELF())
137 O << "\t.type " << CurrentFnName << ",@function\n";
138 else if (Subtarget->isTargetCygMing()) {
139 O << "\t.def\t " << CurrentFnName
141 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
142 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
146 O << CurrentFnName << ":\n";
147 // Add some workaround for linkonce linkage on Cygwin\MinGW
148 if (Subtarget->isTargetCygMing() &&
149 (F->getLinkage() == Function::LinkOnceLinkage ||
150 F->getLinkage() == Function::WeakLinkage))
151 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
153 if (Subtarget->isTargetDarwin() ||
154 Subtarget->isTargetELF() ||
155 Subtarget->isTargetCygMing()) {
156 // Emit pre-function debug information.
157 DW.BeginFunction(&MF);
160 // Print out code for the function.
161 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
163 // Print a label for the basic block.
164 if (I->pred_begin() != I->pred_end()) {
165 printBasicBlockLabel(I, true);
168 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
170 // Print the assembly for the instruction.
172 printMachineInstruction(II);
176 // Print out jump tables referenced by the function.
178 // Mac OS X requires that the jump table follow the function, so that the jump
179 // table is part of the same atom that the function is in.
180 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
182 if (TAI->hasDotTypeDotSizeDirective())
183 O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
185 if (Subtarget->isTargetDarwin() ||
186 Subtarget->isTargetELF() ||
187 Subtarget->isTargetCygMing()) {
188 // Emit post-function debug information.
192 // We didn't modify anything.
196 static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
197 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
200 static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
201 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
204 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
205 const char *Modifier, bool NotRIPRel) {
206 const MachineOperand &MO = MI->getOperand(OpNo);
207 const MRegisterInfo &RI = *TM.getRegisterInfo();
208 switch (MO.getType()) {
209 case MachineOperand::MO_Register: {
210 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
211 "Virtual registers should not make it this far!");
213 unsigned Reg = MO.getReg();
214 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
215 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
216 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
217 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
218 Reg = getX86SubSuperRegister(Reg, VT);
220 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
221 O << (char)tolower(*Name);
225 case MachineOperand::MO_Immediate:
227 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
229 O << MO.getImmedValue();
231 case MachineOperand::MO_MachineBasicBlock:
232 printBasicBlockLabel(MO.getMachineBasicBlock());
234 case MachineOperand::MO_JumpTableIndex: {
235 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
236 if (!isMemOp) O << '$';
237 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
238 << MO.getJumpTableIndex();
240 if (TM.getRelocationModel() == Reloc::PIC_) {
241 if (Subtarget->isPICStyleStub())
242 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
244 else if (Subtarget->isPICStyleGOT())
248 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
252 case MachineOperand::MO_ConstantPoolIndex: {
253 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
254 if (!isMemOp) O << '$';
255 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
256 << MO.getConstantPoolIndex();
258 if (TM.getRelocationModel() == Reloc::PIC_) {
259 if (Subtarget->isPICStyleStub())
260 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
262 else if (Subtarget->isPICStyleGOT())
266 int Offset = MO.getOffset();
272 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
276 case MachineOperand::MO_GlobalAddress: {
277 bool isCallOp = Modifier && !strcmp(Modifier, "call");
278 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
279 bool needCloseParen = false;
281 GlobalValue *GV = MO.getGlobal();
282 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
283 bool isThreadLocal = GVar && GVar->isThreadLocal();
285 std::string Name = Mang->getValueName(GV);
286 X86SharedAsmPrinter::decorateName(Name, GV);
288 if (!isMemOp && !isCallOp)
290 else if (Name[0] == '$') {
291 // The name begins with a dollar-sign. In order to avoid having it look
292 // like an integer immediate to the assembler, enclose it in parens.
294 needCloseParen = true;
297 if (printStub(TM, Subtarget)) {
298 // Link-once, External, or Weakly-linked global variables need
299 // non-lazily-resolved stubs
300 if (GV->isDeclaration() ||
301 GV->hasWeakLinkage() ||
302 GV->hasLinkOnceLinkage()) {
303 // Dynamically-resolved functions need a stub for the function.
304 if (isCallOp && isa<Function>(GV)) {
305 FnStubs.insert(Name);
306 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
308 GVStubs.insert(Name);
309 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
312 if (GV->hasDLLImportLinkage())
317 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
318 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
321 if (GV->hasDLLImportLinkage()) {
326 if (isCallOp && isa<Function>(GV)) {
327 if (printGOT(TM, Subtarget)) {
328 // Assemble call via PLT for non-local symbols
329 if (!(GV->hasHiddenVisibility() || GV->hasProtectedVisibility()) ||
333 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
334 // Save function name for later type emission
335 FnStubs.insert(Name);
339 if (GV->hasExternalWeakLinkage())
340 ExtWeakSymbols.insert(GV);
342 int Offset = MO.getOffset();
349 if (TM.getRelocationModel() == Reloc::PIC_)
350 O << "@TLSGD"; // general dynamic TLS model
352 if (GV->isDeclaration())
353 O << "@INDNTPOFF"; // initial exec TLS model
355 O << "@NTPOFF"; // local exec TLS model
356 } else if (isMemOp) {
357 if (printGOT(TM, Subtarget)) {
358 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
362 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
363 if ((GV->hasExternalLinkage() ||
364 GV->hasWeakLinkage() ||
365 GV->hasLinkOnceLinkage()) &&
366 TM.getRelocationModel() != Reloc::Static)
369 if (needCloseParen) {
370 needCloseParen = false;
374 // Use rip when possible to reduce code size, except when
375 // index or base register are also part of the address. e.g.
376 // foo(%rip)(%rcx,%rax,4) is not legal
386 case MachineOperand::MO_ExternalSymbol: {
387 bool isCallOp = Modifier && !strcmp(Modifier, "call");
388 bool needCloseParen = false;
389 std::string Name(TAI->getGlobalPrefix());
390 Name += MO.getSymbolName();
391 if (isCallOp && printStub(TM, Subtarget)) {
392 FnStubs.insert(Name);
393 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
398 else if (Name[0] == '$') {
399 // The name begins with a dollar-sign. In order to avoid having it look
400 // like an integer immediate to the assembler, enclose it in parens.
402 needCloseParen = true;
407 if (printGOT(TM, Subtarget)) {
408 std::string GOTName(TAI->getGlobalPrefix());
409 GOTName+="_GLOBAL_OFFSET_TABLE_";
411 // HACK! Emit extra offset to PC during printing GOT offset to
412 // compensate for the size of popl instruction. The resulting code
416 // popl %some_register
417 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
419 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
428 if (!isCallOp && Subtarget->isPICStyleRIPRel())
434 O << "<unknown operand type>"; return;
438 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
439 unsigned char value = MI->getOperand(Op).getImmedValue();
440 assert(value <= 7 && "Invalid ssecc argument!");
442 case 0: O << "eq"; break;
443 case 1: O << "lt"; break;
444 case 2: O << "le"; break;
445 case 3: O << "unord"; break;
446 case 4: O << "neq"; break;
447 case 5: O << "nlt"; break;
448 case 6: O << "nle"; break;
449 case 7: O << "ord"; break;
453 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
454 const char *Modifier){
455 assert(isMem(MI, Op) && "Invalid memory reference!");
456 MachineOperand BaseReg = MI->getOperand(Op);
457 MachineOperand IndexReg = MI->getOperand(Op+2);
458 const MachineOperand &DispSpec = MI->getOperand(Op+3);
460 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
461 if (DispSpec.isGlobalAddress() ||
462 DispSpec.isConstantPoolIndex() ||
463 DispSpec.isJumpTableIndex()) {
464 printOperand(MI, Op+3, "mem", NotRIPRel);
466 int DispVal = DispSpec.getImmedValue();
467 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
471 if (IndexReg.getReg() || BaseReg.getReg()) {
472 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
473 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
475 // There are cases where we can end up with ESP/RSP in the indexreg slot.
476 // If this happens, swap the base/index register to support assemblers that
477 // don't work when the index is *SP.
478 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
479 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
480 std::swap(BaseReg, IndexReg);
481 std::swap(BaseRegOperand, IndexRegOperand);
485 if (BaseReg.getReg())
486 printOperand(MI, Op+BaseRegOperand, Modifier);
488 if (IndexReg.getReg()) {
490 printOperand(MI, Op+IndexRegOperand, Modifier);
492 O << "," << ScaleVal;
498 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
499 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
500 O << label << "\n" << label << ":";
504 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
506 const MRegisterInfo &RI = *TM.getRegisterInfo();
507 unsigned Reg = MO.getReg();
509 default: return true; // Unknown mode.
510 case 'b': // Print QImode register
511 Reg = getX86SubSuperRegister(Reg, MVT::i8);
513 case 'h': // Print QImode high register
514 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
516 case 'w': // Print HImode register
517 Reg = getX86SubSuperRegister(Reg, MVT::i16);
519 case 'k': // Print SImode register
520 Reg = getX86SubSuperRegister(Reg, MVT::i32);
525 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
526 O << (char)tolower(*Name);
530 /// PrintAsmOperand - Print out an operand for an inline asm expression.
532 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
534 const char *ExtraCode) {
535 // Does this asm operand have a single letter operand modifier?
536 if (ExtraCode && ExtraCode[0]) {
537 if (ExtraCode[1] != 0) return true; // Unknown modifier.
539 switch (ExtraCode[0]) {
540 default: return true; // Unknown modifier.
541 case 'c': // Don't print "$" before a global var name or constant.
542 printOperand(MI, OpNo, "mem");
544 case 'b': // Print QImode register
545 case 'h': // Print QImode high register
546 case 'w': // Print HImode register
547 case 'k': // Print SImode register
548 if (MI->getOperand(OpNo).isReg())
549 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
550 printOperand(MI, OpNo);
553 case 'P': // Don't print @PLT, but do print as memory.
554 printOperand(MI, OpNo, "mem");
559 printOperand(MI, OpNo);
563 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
566 const char *ExtraCode) {
567 if (ExtraCode && ExtraCode[0])
568 return true; // Unknown modifier.
569 printMemReference(MI, OpNo);
573 /// printMachineInstruction -- Print out a single X86 LLVM instruction
574 /// MI in Intel syntax to the current output stream.
576 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
579 // See if a truncate instruction can be turned into a nop.
580 switch (MI->getOpcode()) {
582 case X86::TRUNC_64to32:
583 case X86::TRUNC_64to16:
584 case X86::TRUNC_32to16:
585 case X86::TRUNC_32to8:
586 case X86::TRUNC_16to8:
587 case X86::TRUNC_32_to8:
588 case X86::TRUNC_16_to8: {
589 const MachineOperand &MO0 = MI->getOperand(0);
590 const MachineOperand &MO1 = MI->getOperand(1);
591 unsigned Reg0 = MO0.getReg();
592 unsigned Reg1 = MO1.getReg();
593 unsigned Opc = MI->getOpcode();
594 if (Opc == X86::TRUNC_64to32)
595 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
596 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
597 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
599 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
600 O << TAI->getCommentString() << " TRUNCATE ";
605 case X86::PsMOVZX64rr32:
606 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
610 // Call the autogenerated instruction printer routines.
611 printInstruction(MI);
614 // Include the auto-generated portion of the assembly writer.
615 #include "X86GenAsmWriter.inc"