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\"";
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 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
104 case Function::DLLExportLinkage:
105 DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
107 case Function::ExternalLinkage:
108 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
109 O << "\t.globl\t" << CurrentFnName << "\n";
111 case Function::LinkOnceLinkage:
112 case Function::WeakLinkage:
113 if (Subtarget->isTargetDarwin()) {
114 O << "\t.globl\t" << CurrentFnName << "\n";
115 O << "\t.weak_definition\t" << CurrentFnName << "\n";
116 } else if (Subtarget->isTargetCygMing()) {
117 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
118 O << "\t.globl " << CurrentFnName << "\n";
119 O << "\t.linkonce discard\n";
121 EmitAlignment(4, F); // FIXME: This should be parameterized somewhere.
122 O << "\t.weak " << CurrentFnName << "\n";
126 if (F->hasHiddenVisibility()) {
127 if (const char *Directive = TAI->getHiddenDirective())
128 O << Directive << CurrentFnName << "\n";
129 } else if (F->hasProtectedVisibility()) {
130 if (const char *Directive = TAI->getProtectedDirective())
131 O << Directive << CurrentFnName << "\n";
134 if (Subtarget->isTargetELF())
135 O << "\t.type " << CurrentFnName << ",@function\n";
136 else if (Subtarget->isTargetCygMing()) {
137 O << "\t.def\t " << CurrentFnName
139 (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
140 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
144 O << CurrentFnName << ":\n";
145 // Add some workaround for linkonce linkage on Cygwin\MinGW
146 if (Subtarget->isTargetCygMing() &&
147 (F->getLinkage() == Function::LinkOnceLinkage ||
148 F->getLinkage() == Function::WeakLinkage))
149 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
151 if (TAI->doesSupportDebugInformation()) {
152 // Emit pre-function debug information.
153 DW.BeginFunction(&MF);
156 // Print out code for the function.
157 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
159 // Print a label for the basic block.
160 if (I->pred_begin() != I->pred_end()) {
161 printBasicBlockLabel(I, true);
164 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
166 // Print the assembly for the instruction.
168 printMachineInstruction(II);
172 if (TAI->hasDotTypeDotSizeDirective())
173 O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
175 if (TAI->doesSupportDebugInformation()) {
176 // Emit post-function debug information.
180 // Print out jump tables referenced by the function.
181 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
183 // We didn't modify anything.
187 static inline bool printGOT(TargetMachine &TM, const X86Subtarget* ST) {
188 return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
191 static inline bool printStub(TargetMachine &TM, const X86Subtarget* ST) {
192 return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
195 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
196 const char *Modifier, bool NotRIPRel) {
197 const MachineOperand &MO = MI->getOperand(OpNo);
198 const MRegisterInfo &RI = *TM.getRegisterInfo();
199 switch (MO.getType()) {
200 case MachineOperand::MO_Register: {
201 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
202 "Virtual registers should not make it this far!");
204 unsigned Reg = MO.getReg();
205 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
206 MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
207 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
208 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
209 Reg = getX86SubSuperRegister(Reg, VT);
211 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
212 O << (char)tolower(*Name);
216 case MachineOperand::MO_Immediate:
218 (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
220 O << MO.getImmedValue();
222 case MachineOperand::MO_MachineBasicBlock:
223 printBasicBlockLabel(MO.getMachineBasicBlock());
225 case MachineOperand::MO_JumpTableIndex: {
226 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
227 if (!isMemOp) O << '$';
228 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
229 << MO.getJumpTableIndex();
231 if (TM.getRelocationModel() == Reloc::PIC_) {
232 if (Subtarget->isPICStyleStub())
233 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
235 else if (Subtarget->isPICStyleGOT())
239 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
243 case MachineOperand::MO_ConstantPoolIndex: {
244 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
245 if (!isMemOp) O << '$';
246 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
247 << MO.getConstantPoolIndex();
249 if (TM.getRelocationModel() == Reloc::PIC_) {
250 if (Subtarget->isPICStyleStub())
251 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
253 else if (Subtarget->isPICStyleGOT())
257 int Offset = MO.getOffset();
263 if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
267 case MachineOperand::MO_GlobalAddress: {
268 bool isCallOp = Modifier && !strcmp(Modifier, "call");
269 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
270 bool needCloseParen = false;
272 GlobalValue *GV = MO.getGlobal();
273 GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
274 bool isThreadLocal = GVar && GVar->isThreadLocal();
276 std::string Name = Mang->getValueName(GV);
277 X86SharedAsmPrinter::decorateName(Name, GV);
279 if (!isMemOp && !isCallOp)
281 else if (Name[0] == '$') {
282 // The name begins with a dollar-sign. In order to avoid having it look
283 // like an integer immediate to the assembler, enclose it in parens.
285 needCloseParen = true;
288 if (printStub(TM, Subtarget)) {
289 // Link-once, declaration, or Weakly-linked global variables need
290 // non-lazily-resolved stubs
291 if (GV->isDeclaration() ||
292 GV->hasWeakLinkage() ||
293 GV->hasLinkOnceLinkage()) {
294 // Dynamically-resolved functions need a stub for the function.
295 if (isCallOp && isa<Function>(GV)) {
296 FnStubs.insert(Name);
297 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
299 GVStubs.insert(Name);
300 O << TAI->getPrivateGlobalPrefix() << Name << "$non_lazy_ptr";
303 if (GV->hasDLLImportLinkage())
308 if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
309 O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
312 if (GV->hasDLLImportLinkage()) {
317 if (isCallOp && isa<Function>(GV)) {
318 if (printGOT(TM, Subtarget)) {
319 // Assemble call via PLT for non-local symbols
320 if (!(GV->hasHiddenVisibility() || GV->hasProtectedVisibility()) ||
324 if (Subtarget->isTargetCygMing() && GV->isDeclaration())
325 // Save function name for later type emission
326 FnStubs.insert(Name);
330 if (GV->hasExternalWeakLinkage())
331 ExtWeakSymbols.insert(GV);
333 int Offset = MO.getOffset();
340 if (TM.getRelocationModel() == Reloc::PIC_)
341 O << "@TLSGD"; // general dynamic TLS model
343 if (GV->isDeclaration())
344 O << "@INDNTPOFF"; // initial exec TLS model
346 O << "@NTPOFF"; // local exec TLS model
347 } else if (isMemOp) {
348 if (printGOT(TM, Subtarget)) {
349 if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
353 } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
354 if ((GV->isDeclaration() ||
355 GV->hasWeakLinkage() ||
356 GV->hasLinkOnceLinkage()) &&
357 TM.getRelocationModel() != Reloc::Static)
360 if (needCloseParen) {
361 needCloseParen = false;
365 // Use rip when possible to reduce code size, except when
366 // index or base register are also part of the address. e.g.
367 // foo(%rip)(%rcx,%rax,4) is not legal
377 case MachineOperand::MO_ExternalSymbol: {
378 bool isCallOp = Modifier && !strcmp(Modifier, "call");
379 bool needCloseParen = false;
380 std::string Name(TAI->getGlobalPrefix());
381 Name += MO.getSymbolName();
382 if (isCallOp && printStub(TM, Subtarget)) {
383 FnStubs.insert(Name);
384 O << TAI->getPrivateGlobalPrefix() << Name << "$stub";
389 else if (Name[0] == '$') {
390 // The name begins with a dollar-sign. In order to avoid having it look
391 // like an integer immediate to the assembler, enclose it in parens.
393 needCloseParen = true;
398 if (printGOT(TM, Subtarget)) {
399 std::string GOTName(TAI->getGlobalPrefix());
400 GOTName+="_GLOBAL_OFFSET_TABLE_";
402 // HACK! Emit extra offset to PC during printing GOT offset to
403 // compensate for the size of popl instruction. The resulting code
407 // popl %some_register
408 // addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
410 << computePICLabel(getFunctionNumber(), TAI, Subtarget) << "]";
419 if (!isCallOp && Subtarget->isPICStyleRIPRel())
425 O << "<unknown operand type>"; return;
429 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
430 unsigned char value = MI->getOperand(Op).getImmedValue();
431 assert(value <= 7 && "Invalid ssecc argument!");
433 case 0: O << "eq"; break;
434 case 1: O << "lt"; break;
435 case 2: O << "le"; break;
436 case 3: O << "unord"; break;
437 case 4: O << "neq"; break;
438 case 5: O << "nlt"; break;
439 case 6: O << "nle"; break;
440 case 7: O << "ord"; break;
444 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
445 const char *Modifier){
446 assert(isMem(MI, Op) && "Invalid memory reference!");
447 MachineOperand BaseReg = MI->getOperand(Op);
448 MachineOperand IndexReg = MI->getOperand(Op+2);
449 const MachineOperand &DispSpec = MI->getOperand(Op+3);
451 bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
452 if (DispSpec.isGlobalAddress() ||
453 DispSpec.isConstantPoolIndex() ||
454 DispSpec.isJumpTableIndex()) {
455 printOperand(MI, Op+3, "mem", NotRIPRel);
457 int DispVal = DispSpec.getImmedValue();
458 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
462 if (IndexReg.getReg() || BaseReg.getReg()) {
463 unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
464 unsigned BaseRegOperand = 0, IndexRegOperand = 2;
466 // There are cases where we can end up with ESP/RSP in the indexreg slot.
467 // If this happens, swap the base/index register to support assemblers that
468 // don't work when the index is *SP.
469 if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
470 assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
471 std::swap(BaseReg, IndexReg);
472 std::swap(BaseRegOperand, IndexRegOperand);
476 if (BaseReg.getReg())
477 printOperand(MI, Op+BaseRegOperand, Modifier);
479 if (IndexReg.getReg()) {
481 printOperand(MI, Op+IndexRegOperand, Modifier);
483 O << "," << ScaleVal;
489 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
490 std::string label = computePICLabel(getFunctionNumber(), TAI, Subtarget);
491 O << label << "\n" << label << ":";
495 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
497 const MRegisterInfo &RI = *TM.getRegisterInfo();
498 unsigned Reg = MO.getReg();
500 default: return true; // Unknown mode.
501 case 'b': // Print QImode register
502 Reg = getX86SubSuperRegister(Reg, MVT::i8);
504 case 'h': // Print QImode high register
505 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
507 case 'w': // Print HImode register
508 Reg = getX86SubSuperRegister(Reg, MVT::i16);
510 case 'k': // Print SImode register
511 Reg = getX86SubSuperRegister(Reg, MVT::i32);
516 for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
517 O << (char)tolower(*Name);
521 /// PrintAsmOperand - Print out an operand for an inline asm expression.
523 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
525 const char *ExtraCode) {
526 // Does this asm operand have a single letter operand modifier?
527 if (ExtraCode && ExtraCode[0]) {
528 if (ExtraCode[1] != 0) return true; // Unknown modifier.
530 switch (ExtraCode[0]) {
531 default: return true; // Unknown modifier.
532 case 'c': // Don't print "$" before a global var name or constant.
533 printOperand(MI, OpNo, "mem");
535 case 'b': // Print QImode register
536 case 'h': // Print QImode high register
537 case 'w': // Print HImode register
538 case 'k': // Print SImode register
539 if (MI->getOperand(OpNo).isReg())
540 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
541 printOperand(MI, OpNo);
544 case 'P': // Don't print @PLT, but do print as memory.
545 printOperand(MI, OpNo, "mem");
550 printOperand(MI, OpNo);
554 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
557 const char *ExtraCode) {
558 if (ExtraCode && ExtraCode[0])
559 return true; // Unknown modifier.
560 printMemReference(MI, OpNo);
564 /// printMachineInstruction -- Print out a single X86 LLVM instruction
565 /// MI in Intel syntax to the current output stream.
567 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
570 // See if a truncate instruction can be turned into a nop.
571 switch (MI->getOpcode()) {
573 case X86::TRUNC_64to32:
574 case X86::TRUNC_64to16:
575 case X86::TRUNC_32to16:
576 case X86::TRUNC_32to8:
577 case X86::TRUNC_16to8:
578 case X86::TRUNC_32_to8:
579 case X86::TRUNC_16_to8: {
580 const MachineOperand &MO0 = MI->getOperand(0);
581 const MachineOperand &MO1 = MI->getOperand(1);
582 unsigned Reg0 = MO0.getReg();
583 unsigned Reg1 = MO1.getReg();
584 unsigned Opc = MI->getOpcode();
585 if (Opc == X86::TRUNC_64to32)
586 Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
587 else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
588 Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
590 Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
591 O << TAI->getCommentString() << " TRUNCATE ";
596 case X86::PsMOVZX64rr32:
597 O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
601 // Call the autogenerated instruction printer routines.
602 printInstruction(MI);
605 // Include the auto-generated portion of the assembly writer.
606 #include "X86GenAsmWriter.inc"