1 //===-- X86AsmPrinter.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 Intel and AT&T format assembly
12 // language. This printer is the output mechanism used by `llc' and `lli
13 // -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
18 #include "X86TargetMachine.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Support/CommandLine.h"
32 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
33 enum AsmWriterFlavor { att, intel };
35 cl::opt<AsmWriterFlavor>
36 AsmWriterFlavor("x86-asm-syntax",
37 cl::desc("Choose style of code to emit from X86 backend:"),
39 clEnumVal(att, " Emit AT&T-style assembly"),
40 clEnumVal(intel, " Emit Intel-style assembly"),
44 struct X86SharedAsmPrinter : public AsmPrinter {
45 X86SharedAsmPrinter(std::ostream &O, TargetMachine &TM)
46 : AsmPrinter(O, TM), forCygwin(false) { }
48 bool doInitialization(Module &M);
49 void printConstantPool(MachineConstantPool *MCP);
50 bool doFinalization(Module &M);
55 static bool isScale(const MachineOperand &MO) {
56 return MO.isImmediate() &&
57 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
58 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
61 static bool isMem(const MachineInstr *MI, unsigned Op) {
62 if (MI->getOperand(Op).isFrameIndex()) return true;
63 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
64 return Op+4 <= MI->getNumOperands() &&
65 MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) &&
66 MI->getOperand(Op+2).isRegister() && (MI->getOperand(Op+3).isImmediate() ||
67 MI->getOperand(Op+3).isGlobalAddress());
70 // SwitchSection - Switch to the specified section of the executable if we are
73 static void SwitchSection(std::ostream &OS, std::string &CurSection,
74 const char *NewSection) {
75 if (CurSection != NewSection) {
76 CurSection = NewSection;
77 if (!CurSection.empty())
78 OS << "\t" << NewSection << "\n";
82 /// doInitialization - determine
83 bool X86SharedAsmPrinter::doInitialization(Module& M) {
85 const std::string& TT = M.getTargetTriple();
87 forCygwin = TT.find("cygwin") != std::string::npos;
88 else if (TT.empty()) {
97 return AsmPrinter::doInitialization(M);
100 /// printConstantPool - Print to the current output stream assembly
101 /// representations of the constants in the constant pool MCP. This is
102 /// used to print out constants which have been "spilled to memory" by
103 /// the code generator.
105 void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
106 const std::vector<Constant*> &CP = MCP->getConstants();
107 const TargetData &TD = TM.getTargetData();
109 if (CP.empty()) return;
111 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
112 O << "\t.section .rodata\n";
113 emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
114 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
116 emitGlobalConstant(CP[i]);
120 bool X86SharedAsmPrinter::doFinalization(Module &M) {
121 const TargetData &TD = TM.getTargetData();
122 std::string CurSection;
124 // Print out module-level global variables here.
125 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
126 if (I->hasInitializer()) { // External global require no code
128 std::string name = Mang->getValueName(I);
129 Constant *C = I->getInitializer();
130 unsigned Size = TD.getTypeSize(C->getType());
131 unsigned Align = TD.getTypeAlignmentShift(C->getType());
133 if (C->isNullValue() &&
134 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
135 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
136 SwitchSection(O, CurSection, ".data");
137 if (!forCygwin && I->hasInternalLinkage())
138 O << "\t.local " << name << "\n";
140 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
142 O << "," << (1 << Align);
144 WriteAsOperand(O, I, true, true, &M);
147 switch (I->getLinkage()) {
148 case GlobalValue::LinkOnceLinkage:
149 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
150 // Nonnull linkonce -> weak
151 O << "\t.weak " << name << "\n";
152 SwitchSection(O, CurSection, "");
153 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
155 case GlobalValue::AppendingLinkage:
156 // FIXME: appending linkage variables should go into a section of
157 // their name or something. For now, just emit them as external.
158 case GlobalValue::ExternalLinkage:
159 // If external or appending, declare as a global symbol
160 O << "\t.globl " << name << "\n";
162 case GlobalValue::InternalLinkage:
163 if (C->isNullValue())
164 SwitchSection(O, CurSection, ".bss");
166 SwitchSection(O, CurSection, ".data");
168 case GlobalValue::GhostLinkage:
169 std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n";
173 emitAlignment(Align);
175 O << "\t.type " << name << ",@object\n";
176 O << "\t.size " << name << "," << Size << "\n";
178 O << name << ":\t\t\t\t# ";
179 WriteAsOperand(O, I, true, true, &M);
181 WriteAsOperand(O, C, false, false, &M);
183 emitGlobalConstant(C);
187 AsmPrinter::doFinalization(M);
188 return false; // success
192 struct X86IntelAsmPrinter : public X86SharedAsmPrinter {
193 X86IntelAsmPrinter(std::ostream &O, TargetMachine &TM)
194 : X86SharedAsmPrinter(O, TM) { }
196 virtual const char *getPassName() const {
197 return "X86 Intel-Style Assembly Printer";
200 /// printInstruction - This method is automatically generated by tablegen
201 /// from the instruction set description. This method returns true if the
202 /// machine instruction was sufficiently described to print it, otherwise it
204 bool printInstruction(const MachineInstr *MI);
206 // This method is used by the tablegen'erated instruction printer.
207 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
208 const MachineOperand &MO = MI->getOperand(OpNo);
209 if (MO.getType() == MachineOperand::MO_MachineRegister) {
210 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
211 // Bug Workaround: See note in Printer::doInitialization about %.
212 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
218 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
220 printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
223 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
226 default: assert(0 && "Unknown arg size!");
227 case MVT::i8: O << "BYTE PTR "; break;
228 case MVT::i16: O << "WORD PTR "; break;
230 case MVT::f32: O << "DWORD PTR "; break;
232 case MVT::f64: O << "QWORD PTR "; break;
233 case MVT::f80: O << "XWORD PTR "; break;
235 printMemReference(MI, OpNo);
238 void printMachineInstruction(const MachineInstr *MI);
239 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
240 void printMemReference(const MachineInstr *MI, unsigned Op);
241 bool runOnMachineFunction(MachineFunction &F);
242 bool doInitialization(Module &M);
244 } // end of anonymous namespace
247 // Include the auto-generated portion of the assembly writer.
248 #include "X86GenAsmWriter1.inc"
251 /// runOnMachineFunction - This uses the printMachineInstruction()
252 /// method to print assembly for each instruction.
254 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
255 setupMachineFunction(MF);
258 // Print out constants referenced by the function
259 printConstantPool(MF.getConstantPool());
261 // Print out labels for the function.
264 O << "\t.globl\t" << CurrentFnName << "\n";
266 O << "\t.type\t" << CurrentFnName << ", @function\n";
267 O << CurrentFnName << ":\n";
269 // Print out code for the function.
270 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
272 // Print a label for the basic block if there are any predecessors.
273 if (I->pred_begin() != I->pred_end())
274 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
275 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
276 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
278 // Print the assembly for the instruction.
280 printMachineInstruction(II);
284 // We didn't modify anything.
288 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
289 bool elideOffsetKeyword /* = false */) {
290 const MRegisterInfo &RI = *TM.getRegisterInfo();
291 switch (MO.getType()) {
292 case MachineOperand::MO_VirtualRegister:
293 if (Value *V = MO.getVRegValueOrNull()) {
294 O << "<" << V->getName() << ">";
298 case MachineOperand::MO_MachineRegister:
299 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
300 // Bug Workaround: See note in Printer::doInitialization about %.
301 O << "%" << RI.get(MO.getReg()).Name;
303 O << "%reg" << MO.getReg();
306 case MachineOperand::MO_SignExtendedImmed:
307 case MachineOperand::MO_UnextendedImmed:
308 O << (int)MO.getImmedValue();
310 case MachineOperand::MO_MachineBasicBlock: {
311 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
312 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
313 << "_" << MBBOp->getNumber () << "\t# "
314 << MBBOp->getBasicBlock ()->getName ();
317 case MachineOperand::MO_PCRelativeDisp:
318 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
321 case MachineOperand::MO_GlobalAddress: {
322 if (!elideOffsetKeyword)
324 O << Mang->getValueName(MO.getGlobal());
325 int Offset = MO.getOffset();
327 O << " + " << Offset;
329 O << " - " << -Offset;
332 case MachineOperand::MO_ExternalSymbol:
333 O << GlobalPrefix << MO.getSymbolName();
336 O << "<unknown operand type>"; return;
340 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
341 assert(isMem(MI, Op) && "Invalid memory reference!");
343 const MachineOperand &BaseReg = MI->getOperand(Op);
344 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
345 const MachineOperand &IndexReg = MI->getOperand(Op+2);
346 const MachineOperand &DispSpec = MI->getOperand(Op+3);
348 if (BaseReg.isFrameIndex()) {
349 O << "[frame slot #" << BaseReg.getFrameIndex();
350 if (DispSpec.getImmedValue())
351 O << " + " << DispSpec.getImmedValue();
354 } else if (BaseReg.isConstantPoolIndex()) {
355 O << "[.CPI" << CurrentFnName << "_"
356 << BaseReg.getConstantPoolIndex();
358 if (IndexReg.getReg()) {
361 O << ScaleVal << "*";
365 if (DispSpec.getImmedValue())
366 O << " + " << DispSpec.getImmedValue();
372 bool NeedPlus = false;
373 if (BaseReg.getReg()) {
374 printOp(BaseReg, true);
378 if (IndexReg.getReg()) {
379 if (NeedPlus) O << " + ";
381 O << ScaleVal << "*";
386 if (DispSpec.isGlobalAddress()) {
389 printOp(DispSpec, true);
391 int DispVal = DispSpec.getImmedValue();
392 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
407 /// printMachineInstruction -- Print out a single X86 LLVM instruction
408 /// MI in Intel syntax to the current output stream.
410 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
413 // Call the autogenerated instruction printer routines.
414 printInstruction(MI);
417 bool X86IntelAsmPrinter::doInitialization(Module &M) {
418 AsmPrinter::doInitialization(M);
419 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
421 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
422 // instruction as a reference to the register named sp, and if you try to
423 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
424 // before being looked up in the symbol table. This creates spurious
425 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
426 // mode, and decorate all register names with percent signs.
427 O << "\t.intel_syntax\n";
434 struct X86ATTAsmPrinter : public X86SharedAsmPrinter {
435 X86ATTAsmPrinter(std::ostream &O, TargetMachine &TM)
436 : X86SharedAsmPrinter(O, TM) { }
438 virtual const char *getPassName() const {
439 return "X86 AT&T-Style Assembly Printer";
442 /// printInstruction - This method is automatically generated by tablegen
443 /// from the instruction set description. This method returns true if the
444 /// machine instruction was sufficiently described to print it, otherwise it
446 bool printInstruction(const MachineInstr *MI);
448 // This method is used by the tablegen'erated instruction printer.
449 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
450 printOp(MI->getOperand(OpNo));
453 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
455 printOp(MI->getOperand(OpNo), true); // Don't print '$' prefix.
458 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
460 printMemReference(MI, OpNo);
463 void printMachineInstruction(const MachineInstr *MI);
464 void printOp(const MachineOperand &MO, bool isCallOperand = false);
465 void printMemReference(const MachineInstr *MI, unsigned Op);
466 bool runOnMachineFunction(MachineFunction &F);
468 } // end of anonymous namespace
471 // Include the auto-generated portion of the assembly writer.
472 #include "X86GenAsmWriter.inc"
475 /// runOnMachineFunction - This uses the printMachineInstruction()
476 /// method to print assembly for each instruction.
478 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
479 setupMachineFunction(MF);
482 // Print out constants referenced by the function
483 printConstantPool(MF.getConstantPool());
485 // Print out labels for the function.
488 O << "\t.globl\t" << CurrentFnName << "\n";
490 O << "\t.type\t" << CurrentFnName << ", @function\n";
491 O << CurrentFnName << ":\n";
493 // Print out code for the function.
494 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
496 // Print a label for the basic block.
497 if (I->pred_begin() != I->pred_end())
498 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
499 << CommentString << " " << I->getBasicBlock()->getName() << "\n";
500 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
502 // Print the assembly for the instruction.
504 printMachineInstruction(II);
508 // We didn't modify anything.
512 void X86ATTAsmPrinter::printOp(const MachineOperand &MO, bool isCallOp) {
513 const MRegisterInfo &RI = *TM.getRegisterInfo();
514 switch (MO.getType()) {
515 case MachineOperand::MO_VirtualRegister:
516 case MachineOperand::MO_MachineRegister:
517 assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
518 "Virtual registers should not make it this far!");
520 for (const char *Name = RI.get(MO.getReg()).Name; *Name; ++Name)
521 O << (char)tolower(*Name);
524 case MachineOperand::MO_SignExtendedImmed:
525 case MachineOperand::MO_UnextendedImmed:
526 O << '$' << (int)MO.getImmedValue();
528 case MachineOperand::MO_MachineBasicBlock: {
529 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
530 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
531 << "_" << MBBOp->getNumber () << "\t# "
532 << MBBOp->getBasicBlock ()->getName ();
535 case MachineOperand::MO_PCRelativeDisp:
536 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
539 case MachineOperand::MO_GlobalAddress: {
540 if (!isCallOp) O << '$';
541 O << Mang->getValueName(MO.getGlobal());
542 int Offset = MO.getOffset();
549 case MachineOperand::MO_ExternalSymbol:
550 if (!isCallOp) O << '$';
551 O << GlobalPrefix << MO.getSymbolName();
554 O << "<unknown operand type>"; return;
558 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
559 assert(isMem(MI, Op) && "Invalid memory reference!");
561 const MachineOperand &BaseReg = MI->getOperand(Op);
562 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
563 const MachineOperand &IndexReg = MI->getOperand(Op+2);
564 const MachineOperand &DispSpec = MI->getOperand(Op+3);
566 if (BaseReg.isFrameIndex()) {
567 O << "[frame slot #" << BaseReg.getFrameIndex();
568 if (DispSpec.getImmedValue())
569 O << " + " << DispSpec.getImmedValue();
572 } else if (BaseReg.isConstantPoolIndex()) {
573 O << ".CPI" << CurrentFnName << "_"
574 << BaseReg.getConstantPoolIndex();
575 if (DispSpec.getImmedValue())
576 O << "+" << DispSpec.getImmedValue();
577 if (IndexReg.getReg()) {
581 O << "," << ScaleVal;
587 if (DispSpec.isGlobalAddress()) {
588 printOp(DispSpec, true);
590 int DispVal = DispSpec.getImmedValue();
591 if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
595 if (IndexReg.getReg() || BaseReg.getReg()) {
597 if (BaseReg.getReg())
600 if (IndexReg.getReg()) {
604 O << "," << ScaleVal;
612 /// printMachineInstruction -- Print out a single X86 LLVM instruction
613 /// MI in Intel syntax to the current output stream.
615 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
617 // Call the autogenerated instruction printer routines.
618 printInstruction(MI);
622 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
623 /// for a MachineFunction to the given output stream, using the given target
624 /// machine description.
626 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
627 switch (AsmWriterFlavor) {
629 assert(0 && "Unknown asm flavor!");
631 return new X86IntelAsmPrinter(o, tm);
633 return new X86ATTAsmPrinter(o, tm);