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-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
33 #include "Support/CommandLine.h"
37 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39 // FIXME: This should be automatically picked up by autoconf from the C
41 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
42 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
44 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
45 GasBugWorkaroundEmitter(std::ostream& o)
46 : O(o), OldFlags(O.flags()), firstByte(true) {
50 ~GasBugWorkaroundEmitter() {
54 virtual void emitByte(unsigned char B) {
55 if (!firstByte) O << "\n\t";
57 O << ".byte 0x" << (unsigned) B;
60 // These should never be called
61 virtual void emitWord(unsigned W) { assert(0); }
62 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
63 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
64 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
65 virtual uint64_t getCurrentPCValue() { abort(); }
66 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
70 std::ios::fmtflags OldFlags;
74 struct X86AsmPrinter : public MachineFunctionPass {
75 /// Output stream on which we're printing assembly code.
79 /// Target machine description which we query for reg. names, data
84 /// Name-mangler for global names.
88 X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
90 /// Cache of mangled name for current function. This is
91 /// recalculated at the beginning of each call to
92 /// runOnMachineFunction().
94 std::string CurrentFnName;
96 virtual const char *getPassName() const {
97 return "X86 Assembly Printer";
100 /// printInstruction - This method is automatically generated by tablegen
101 /// from the instruction set description. This method returns true if the
102 /// machine instruction was sufficiently described to print it, otherwise it
104 bool printInstruction(const MachineInstr *MI);
106 // This method is used by the tablegen'erated instruction printer.
107 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
108 const MachineOperand &MO = MI->getOperand(OpNo);
109 if (MO.getType() == MachineOperand::MO_MachineRegister) {
110 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
111 // Bug Workaround: See note in Printer::doInitialization about %.
112 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
118 void printCallOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
119 printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
122 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
125 default: assert(0 && "Unknown arg size!");
126 case MVT::i8: O << "BYTE PTR "; break;
127 case MVT::i16: O << "WORD PTR "; break;
129 case MVT::f32: O << "DWORD PTR "; break;
131 case MVT::f64: O << "QWORD PTR "; break;
132 case MVT::f80: O << "XWORD PTR "; break;
134 printMemReference(MI, OpNo);
137 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
138 void printMachineInstruction(const MachineInstr *MI);
139 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
140 void printMemReference(const MachineInstr *MI, unsigned Op);
141 void printConstantPool(MachineConstantPool *MCP);
142 bool runOnMachineFunction(MachineFunction &F);
143 bool doInitialization(Module &M);
144 bool doFinalization(Module &M);
145 void emitGlobalConstant(const Constant* CV);
146 void emitConstantValueOnly(const Constant *CV);
148 } // end of anonymous namespace
150 /// createX86CodePrinterPass - Returns a pass that prints the X86
151 /// assembly code for a MachineFunction to the given output stream,
152 /// using the given target machine description. This should work
153 /// regardless of whether the function is in SSA form.
155 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
156 return new X86AsmPrinter(o, tm);
160 // Include the auto-generated portion of the assembly writer.
161 #include "X86GenAsmWriter.inc"
164 /// toOctal - Convert the low order bits of X into an octal digit.
166 static inline char toOctal(int X) {
170 /// getAsCString - Return the specified array as a C compatible
171 /// string, only if the predicate isStringCompatible is true.
173 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
174 assert(CVA->isString() && "Array is not string compatible!");
177 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
178 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
182 } else if (C == '\\') {
184 } else if (isprint(C)) {
188 case '\b': O << "\\b"; break;
189 case '\f': O << "\\f"; break;
190 case '\n': O << "\\n"; break;
191 case '\r': O << "\\r"; break;
192 case '\t': O << "\\t"; break;
195 O << toOctal(C >> 6);
196 O << toOctal(C >> 3);
197 O << toOctal(C >> 0);
205 // Print out the specified constant, without a storage class. Only the
206 // constants valid in constant expressions can occur here.
207 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
208 if (CV->isNullValue())
210 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
211 assert(CB == ConstantBool::True);
213 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
214 if (((CI->getValue() << 32) >> 32) == CI->getValue())
217 O << (unsigned long long)CI->getValue();
218 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
220 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
221 // This is a constant address for a global variable or function. Use the
222 // name of the variable or function as the address value.
223 O << Mang->getValueName(GV);
224 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
225 const TargetData &TD = TM.getTargetData();
226 switch(CE->getOpcode()) {
227 case Instruction::GetElementPtr: {
228 // generate a symbolic expression for the byte address
229 const Constant *ptrVal = CE->getOperand(0);
230 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
231 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
233 emitConstantValueOnly(ptrVal);
234 O << ") + " << Offset;
236 emitConstantValueOnly(ptrVal);
240 case Instruction::Cast: {
241 // Support only non-converting or widening casts for now, that is, ones
242 // that do not involve a change in value. This assertion is really gross,
243 // and may not even be a complete check.
244 Constant *Op = CE->getOperand(0);
245 const Type *OpTy = Op->getType(), *Ty = CE->getType();
247 // Remember, kids, pointers on x86 can be losslessly converted back and
248 // forth into 32-bit or wider integers, regardless of signedness. :-P
249 assert(((isa<PointerType>(OpTy)
250 && (Ty == Type::LongTy || Ty == Type::ULongTy
251 || Ty == Type::IntTy || Ty == Type::UIntTy))
252 || (isa<PointerType>(Ty)
253 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
254 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
255 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
256 && OpTy->isLosslesslyConvertibleTo(Ty))))
257 && "FIXME: Don't yet support this kind of constant cast expr");
259 emitConstantValueOnly(Op);
263 case Instruction::Add:
265 emitConstantValueOnly(CE->getOperand(0));
267 emitConstantValueOnly(CE->getOperand(1));
271 assert(0 && "Unsupported operator!");
274 assert(0 && "Unknown constant value!");
278 // Print a constant value or values, with the appropriate storage class as a
280 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
281 const TargetData &TD = TM.getTargetData();
283 if (CV->isNullValue()) {
284 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
286 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
287 if (CVA->isString()) {
289 printAsCString(O, CVA);
291 } else { // Not a string. Print the values in successive locations
292 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
293 emitGlobalConstant(CVA->getOperand(i));
296 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
297 // Print the fields in successive locations. Pad to align if needed!
298 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
299 unsigned sizeSoFar = 0;
300 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
301 const Constant* field = CVS->getOperand(i);
303 // Check if padding is needed and insert one or more 0s.
304 unsigned fieldSize = TD.getTypeSize(field->getType());
305 unsigned padSize = ((i == e-1? cvsLayout->StructSize
306 : cvsLayout->MemberOffsets[i+1])
307 - cvsLayout->MemberOffsets[i]) - fieldSize;
308 sizeSoFar += fieldSize + padSize;
310 // Now print the actual field value
311 emitGlobalConstant(field);
313 // Insert the field padding unless it's zero bytes...
315 O << "\t.zero\t " << padSize << "\n";
317 assert(sizeSoFar == cvsLayout->StructSize &&
318 "Layout of constant struct may be incorrect!");
320 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
321 // FP Constants are printed as integer constants to avoid losing
323 double Val = CFP->getValue();
324 switch (CFP->getType()->getTypeID()) {
325 default: assert(0 && "Unknown floating point type!");
326 case Type::FloatTyID: {
327 union FU { // Abide by C TBAA rules
332 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
335 case Type::DoubleTyID: {
336 union DU { // Abide by C TBAA rules
341 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
347 const Type *type = CV->getType();
349 switch (type->getTypeID()) {
350 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
353 case Type::UShortTyID: case Type::ShortTyID:
356 case Type::FloatTyID: case Type::PointerTyID:
357 case Type::UIntTyID: case Type::IntTyID:
360 case Type::DoubleTyID:
361 case Type::ULongTyID: case Type::LongTyID:
365 assert (0 && "Can't handle printing this type of thing");
369 emitConstantValueOnly(CV);
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
378 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
379 const std::vector<Constant*> &CP = MCP->getConstants();
380 const TargetData &TD = TM.getTargetData();
382 if (CP.empty()) return;
384 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385 O << "\t.section .rodata\n";
386 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
388 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
390 emitGlobalConstant(CP[i]);
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
397 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
399 // What's my mangled name?
400 CurrentFnName = Mang->getValueName(MF.getFunction());
402 // Print out constants referenced by the function
403 printConstantPool(MF.getConstantPool());
405 // Print out labels for the function.
407 O << "\t.align 16\n";
408 O << "\t.globl\t" << CurrentFnName << "\n";
410 O << "\t.type\t" << CurrentFnName << ", @function\n";
411 O << CurrentFnName << ":\n";
413 // Print out code for the function.
414 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
416 // Print a label for the basic block.
417 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
418 << I->getBasicBlock()->getName() << "\n";
419 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
421 // Print the assembly for the instruction.
423 printMachineInstruction(II);
427 // We didn't modify anything.
431 static bool isScale(const MachineOperand &MO) {
432 return MO.isImmediate() &&
433 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
434 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
437 static bool isMem(const MachineInstr *MI, unsigned Op) {
438 if (MI->getOperand(Op).isFrameIndex()) return true;
439 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
440 return Op+4 <= MI->getNumOperands() &&
441 MI->getOperand(Op ).isRegister() && isScale(MI->getOperand(Op+1)) &&
442 MI->getOperand(Op+2).isRegister() && MI->getOperand(Op+3).isImmediate();
447 void X86AsmPrinter::printOp(const MachineOperand &MO,
448 bool elideOffsetKeyword /* = false */) {
449 const MRegisterInfo &RI = *TM.getRegisterInfo();
450 switch (MO.getType()) {
451 case MachineOperand::MO_VirtualRegister:
452 if (Value *V = MO.getVRegValueOrNull()) {
453 O << "<" << V->getName() << ">";
457 case MachineOperand::MO_MachineRegister:
458 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
459 // Bug Workaround: See note in Printer::doInitialization about %.
460 O << "%" << RI.get(MO.getReg()).Name;
462 O << "%reg" << MO.getReg();
465 case MachineOperand::MO_SignExtendedImmed:
466 case MachineOperand::MO_UnextendedImmed:
467 O << (int)MO.getImmedValue();
469 case MachineOperand::MO_MachineBasicBlock: {
470 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
471 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
472 << "_" << MBBOp->getNumber () << "\t# "
473 << MBBOp->getBasicBlock ()->getName ();
476 case MachineOperand::MO_PCRelativeDisp:
477 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
480 case MachineOperand::MO_GlobalAddress:
481 if (!elideOffsetKeyword)
483 O << Mang->getValueName(MO.getGlobal());
485 case MachineOperand::MO_ExternalSymbol:
486 O << MO.getSymbolName();
489 O << "<unknown operand type>"; return;
493 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
494 assert(isMem(MI, Op) && "Invalid memory reference!");
496 if (MI->getOperand(Op).isFrameIndex()) {
497 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
498 if (MI->getOperand(Op+3).getImmedValue())
499 O << " + " << MI->getOperand(Op+3).getImmedValue();
502 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
503 O << "[.CPI" << CurrentFnName << "_"
504 << MI->getOperand(Op).getConstantPoolIndex();
505 if (MI->getOperand(Op+3).getImmedValue())
506 O << " + " << MI->getOperand(Op+3).getImmedValue();
511 const MachineOperand &BaseReg = MI->getOperand(Op);
512 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
513 const MachineOperand &IndexReg = MI->getOperand(Op+2);
514 int DispVal = MI->getOperand(Op+3).getImmedValue();
517 bool NeedPlus = false;
518 if (BaseReg.getReg()) {
523 if (IndexReg.getReg()) {
524 if (NeedPlus) O << " + ";
526 O << ScaleVal << "*";
544 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
545 /// described by DESC, if its PrintImplUsesAfter flag is set.
548 /// Comma - List of registers will need a leading comma.
549 /// Desc - Description of the Instruction.
552 /// true - Emitted one or more registers.
553 /// false - Emitted no registers.
555 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
556 const bool Comma = true) {
557 const MRegisterInfo &RI = *TM.getRegisterInfo();
558 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
559 bool emitted = false;
560 const unsigned *p = Desc.ImplicitUses;
562 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
567 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
568 O << ", %" << RI.get(*p).Name;
576 /// printMachineInstruction -- Print out a single X86 LLVM instruction
577 /// MI in Intel syntax to the current output stream.
579 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
584 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]" is misassembled
585 // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR
586 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
588 // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas
589 // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR
590 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
592 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode,
593 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
594 // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround:
595 // Output the raw opcode bytes instead of the instruction.
597 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode,
598 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
599 // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround:
600 // Output the raw opcode bytes instead of the instruction.
601 switch (MI->getOpcode()) {
606 GasBugWorkaroundEmitter gwe(O);
607 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
611 // Call the autogenerated instruction printer routines.
612 bool Handled = printInstruction(MI);
615 assert(0 && "Do not know how to print this instruction!");
620 bool X86AsmPrinter::doInitialization(Module &M) {
621 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
623 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
624 // instruction as a reference to the register named sp, and if you try to
625 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
626 // before being looked up in the symbol table. This creates spurious
627 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
628 // mode, and decorate all register names with percent signs.
629 O << "\t.intel_syntax\n";
630 Mang = new Mangler(M, EmitCygwin);
631 return false; // success
634 // SwitchSection - Switch to the specified section of the executable if we are
635 // not already in it!
637 static void SwitchSection(std::ostream &OS, std::string &CurSection,
638 const char *NewSection) {
639 if (CurSection != NewSection) {
640 CurSection = NewSection;
641 if (!CurSection.empty())
642 OS << "\t" << NewSection << "\n";
646 bool X86AsmPrinter::doFinalization(Module &M) {
647 const TargetData &TD = TM.getTargetData();
648 std::string CurSection;
650 // Print out module-level global variables here.
651 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
652 if (I->hasInitializer()) { // External global require no code
654 std::string name = Mang->getValueName(I);
655 Constant *C = I->getInitializer();
656 unsigned Size = TD.getTypeSize(C->getType());
657 unsigned Align = TD.getTypeAlignment(C->getType());
659 if (C->isNullValue() &&
660 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
661 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
662 SwitchSection(O, CurSection, ".data");
663 if (I->hasInternalLinkage())
664 O << "\t.local " << name << "\n";
666 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
667 << "," << (unsigned)TD.getTypeAlignment(C->getType());
669 WriteAsOperand(O, I, true, true, &M);
672 switch (I->getLinkage()) {
673 case GlobalValue::LinkOnceLinkage:
674 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
675 // Nonnull linkonce -> weak
676 O << "\t.weak " << name << "\n";
677 SwitchSection(O, CurSection, "");
678 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
681 case GlobalValue::AppendingLinkage:
682 // FIXME: appending linkage variables should go into a section of
683 // their name or something. For now, just emit them as external.
684 case GlobalValue::ExternalLinkage:
685 // If external or appending, declare as a global symbol
686 O << "\t.globl " << name << "\n";
688 case GlobalValue::InternalLinkage:
689 if (C->isNullValue())
690 SwitchSection(O, CurSection, ".bss");
692 SwitchSection(O, CurSection, ".data");
696 O << "\t.align " << Align << "\n";
697 O << "\t.type " << name << ",@object\n";
698 O << "\t.size " << name << "," << Size << "\n";
699 O << name << ":\t\t\t\t# ";
700 WriteAsOperand(O, I, true, true, &M);
702 WriteAsOperand(O, C, false, false, &M);
704 emitGlobalConstant(C);
709 return false; // success