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() {
55 virtual void emitByte(unsigned char B) {
56 if (!firstByte) O << "\n\t";
58 O << ".byte 0x" << (unsigned) B;
61 // These should never be called
62 virtual void emitWord(unsigned W) { assert(0); }
63 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
64 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
65 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
66 virtual uint64_t getCurrentPCValue() { abort(); }
67 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
71 std::ios::fmtflags OldFlags;
75 struct X86AsmPrinter : public MachineFunctionPass {
76 /// Output stream on which we're printing assembly code.
80 /// Target machine description which we query for reg. names, data
85 /// Name-mangler for global names.
89 X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
91 /// Cache of mangled name for current function. This is
92 /// recalculated at the beginning of each call to
93 /// runOnMachineFunction().
95 std::string CurrentFnName;
97 virtual const char *getPassName() const {
98 return "X86 Assembly Printer";
101 /// printInstruction - This method is automatically generated by tablegen
102 /// from the instruction set description. This method returns true if the
103 /// machine instruction was sufficiently described to print it, otherwise it
105 bool printInstruction(const MachineInstr *MI);
107 // This method is used by the tablegen'erated instruction printer.
108 void printOperand(const MachineOperand &MO, MVT::ValueType VT) {
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 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
119 void printMachineInstruction(const MachineInstr *MI);
120 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
121 void printMemReference(const MachineInstr *MI, unsigned Op);
122 void printConstantPool(MachineConstantPool *MCP);
123 bool runOnMachineFunction(MachineFunction &F);
124 bool doInitialization(Module &M);
125 bool doFinalization(Module &M);
126 void emitGlobalConstant(const Constant* CV);
127 void emitConstantValueOnly(const Constant *CV);
129 } // end of anonymous namespace
131 /// createX86CodePrinterPass - Returns a pass that prints the X86
132 /// assembly code for a MachineFunction to the given output stream,
133 /// using the given target machine description. This should work
134 /// regardless of whether the function is in SSA form.
136 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
137 return new X86AsmPrinter(o, tm);
141 // Include the auto-generated portion of the assembly writer.
142 #include "X86GenAsmWriter.inc"
145 /// toOctal - Convert the low order bits of X into an octal digit.
147 static inline char toOctal(int X) {
151 /// getAsCString - Return the specified array as a C compatible
152 /// string, only if the predicate isStringCompatible is true.
154 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
155 assert(CVA->isString() && "Array is not string compatible!");
158 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
159 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
163 } else if (C == '\\') {
165 } else if (isprint(C)) {
169 case '\b': O << "\\b"; break;
170 case '\f': O << "\\f"; break;
171 case '\n': O << "\\n"; break;
172 case '\r': O << "\\r"; break;
173 case '\t': O << "\\t"; break;
176 O << toOctal(C >> 6);
177 O << toOctal(C >> 3);
178 O << toOctal(C >> 0);
186 // Print out the specified constant, without a storage class. Only the
187 // constants valid in constant expressions can occur here.
188 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
189 if (CV->isNullValue())
191 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
192 assert(CB == ConstantBool::True);
194 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
195 if (((CI->getValue() << 32) >> 32) == CI->getValue())
198 O << (unsigned long long)CI->getValue();
199 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
201 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
202 // This is a constant address for a global variable or function. Use the
203 // name of the variable or function as the address value.
204 O << Mang->getValueName(GV);
205 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
206 const TargetData &TD = TM.getTargetData();
207 switch(CE->getOpcode()) {
208 case Instruction::GetElementPtr: {
209 // generate a symbolic expression for the byte address
210 const Constant *ptrVal = CE->getOperand(0);
211 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
212 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
214 emitConstantValueOnly(ptrVal);
215 O << ") + " << Offset;
217 emitConstantValueOnly(ptrVal);
221 case Instruction::Cast: {
222 // Support only non-converting or widening casts for now, that is, ones
223 // that do not involve a change in value. This assertion is really gross,
224 // and may not even be a complete check.
225 Constant *Op = CE->getOperand(0);
226 const Type *OpTy = Op->getType(), *Ty = CE->getType();
228 // Remember, kids, pointers on x86 can be losslessly converted back and
229 // forth into 32-bit or wider integers, regardless of signedness. :-P
230 assert(((isa<PointerType>(OpTy)
231 && (Ty == Type::LongTy || Ty == Type::ULongTy
232 || Ty == Type::IntTy || Ty == Type::UIntTy))
233 || (isa<PointerType>(Ty)
234 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
235 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
236 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
237 && OpTy->isLosslesslyConvertibleTo(Ty))))
238 && "FIXME: Don't yet support this kind of constant cast expr");
240 emitConstantValueOnly(Op);
244 case Instruction::Add:
246 emitConstantValueOnly(CE->getOperand(0));
248 emitConstantValueOnly(CE->getOperand(1));
252 assert(0 && "Unsupported operator!");
255 assert(0 && "Unknown constant value!");
259 // Print a constant value or values, with the appropriate storage class as a
261 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
262 const TargetData &TD = TM.getTargetData();
264 if (CV->isNullValue()) {
265 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
267 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
268 if (CVA->isString()) {
270 printAsCString(O, CVA);
272 } else { // Not a string. Print the values in successive locations
273 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
274 emitGlobalConstant(CVA->getOperand(i));
277 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
278 // Print the fields in successive locations. Pad to align if needed!
279 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
280 unsigned sizeSoFar = 0;
281 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
282 const Constant* field = CVS->getOperand(i);
284 // Check if padding is needed and insert one or more 0s.
285 unsigned fieldSize = TD.getTypeSize(field->getType());
286 unsigned padSize = ((i == e-1? cvsLayout->StructSize
287 : cvsLayout->MemberOffsets[i+1])
288 - cvsLayout->MemberOffsets[i]) - fieldSize;
289 sizeSoFar += fieldSize + padSize;
291 // Now print the actual field value
292 emitGlobalConstant(field);
294 // Insert the field padding unless it's zero bytes...
296 O << "\t.zero\t " << padSize << "\n";
298 assert(sizeSoFar == cvsLayout->StructSize &&
299 "Layout of constant struct may be incorrect!");
301 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
302 // FP Constants are printed as integer constants to avoid losing
304 double Val = CFP->getValue();
305 switch (CFP->getType()->getTypeID()) {
306 default: assert(0 && "Unknown floating point type!");
307 case Type::FloatTyID: {
308 union FU { // Abide by C TBAA rules
313 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
316 case Type::DoubleTyID: {
317 union DU { // Abide by C TBAA rules
322 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
328 const Type *type = CV->getType();
330 switch (type->getTypeID()) {
331 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
334 case Type::UShortTyID: case Type::ShortTyID:
337 case Type::FloatTyID: case Type::PointerTyID:
338 case Type::UIntTyID: case Type::IntTyID:
341 case Type::DoubleTyID:
342 case Type::ULongTyID: case Type::LongTyID:
346 assert (0 && "Can't handle printing this type of thing");
350 emitConstantValueOnly(CV);
354 /// printConstantPool - Print to the current output stream assembly
355 /// representations of the constants in the constant pool MCP. This is
356 /// used to print out constants which have been "spilled to memory" by
357 /// the code generator.
359 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
360 const std::vector<Constant*> &CP = MCP->getConstants();
361 const TargetData &TD = TM.getTargetData();
363 if (CP.empty()) return;
365 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
366 O << "\t.section .rodata\n";
367 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
369 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
371 emitGlobalConstant(CP[i]);
375 /// runOnMachineFunction - This uses the printMachineInstruction()
376 /// method to print assembly for each instruction.
378 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
380 // What's my mangled name?
381 CurrentFnName = Mang->getValueName(MF.getFunction());
383 // Print out constants referenced by the function
384 printConstantPool(MF.getConstantPool());
386 // Print out labels for the function.
388 O << "\t.align 16\n";
389 O << "\t.globl\t" << CurrentFnName << "\n";
391 O << "\t.type\t" << CurrentFnName << ", @function\n";
392 O << CurrentFnName << ":\n";
394 // Print out code for the function.
395 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
397 // Print a label for the basic block.
398 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
399 << I->getBasicBlock()->getName() << "\n";
400 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
402 // Print the assembly for the instruction.
404 printMachineInstruction(II);
408 // We didn't modify anything.
412 static bool isScale(const MachineOperand &MO) {
413 return MO.isImmediate() &&
414 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
415 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
418 static bool isMem(const MachineInstr *MI, unsigned Op) {
419 if (MI->getOperand(Op).isFrameIndex()) return true;
420 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
421 return Op+4 <= MI->getNumOperands() &&
422 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
423 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
428 void X86AsmPrinter::printOp(const MachineOperand &MO,
429 bool elideOffsetKeyword /* = false */) {
430 const MRegisterInfo &RI = *TM.getRegisterInfo();
431 switch (MO.getType()) {
432 case MachineOperand::MO_VirtualRegister:
433 if (Value *V = MO.getVRegValueOrNull()) {
434 O << "<" << V->getName() << ">";
438 case MachineOperand::MO_MachineRegister:
439 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
440 // Bug Workaround: See note in Printer::doInitialization about %.
441 O << "%" << RI.get(MO.getReg()).Name;
443 O << "%reg" << MO.getReg();
446 case MachineOperand::MO_SignExtendedImmed:
447 case MachineOperand::MO_UnextendedImmed:
448 O << (int)MO.getImmedValue();
450 case MachineOperand::MO_MachineBasicBlock: {
451 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
452 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
453 << "_" << MBBOp->getNumber () << "\t# "
454 << MBBOp->getBasicBlock ()->getName ();
457 case MachineOperand::MO_PCRelativeDisp:
458 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
461 case MachineOperand::MO_GlobalAddress:
462 if (!elideOffsetKeyword)
464 O << Mang->getValueName(MO.getGlobal());
466 case MachineOperand::MO_ExternalSymbol:
467 O << MO.getSymbolName();
470 O << "<unknown operand type>"; return;
474 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
475 switch (Desc.TSFlags & X86II::MemMask) {
476 default: assert(0 && "Unknown arg size!");
477 case X86II::Mem8: return "BYTE PTR";
478 case X86II::Mem16: return "WORD PTR";
479 case X86II::Mem32: return "DWORD PTR";
480 case X86II::Mem64: return "QWORD PTR";
481 case X86II::Mem80: return "XWORD PTR";
485 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
486 assert(isMem(MI, Op) && "Invalid memory reference!");
488 if (MI->getOperand(Op).isFrameIndex()) {
489 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
490 if (MI->getOperand(Op+3).getImmedValue())
491 O << " + " << MI->getOperand(Op+3).getImmedValue();
494 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
495 O << "[.CPI" << CurrentFnName << "_"
496 << MI->getOperand(Op).getConstantPoolIndex();
497 if (MI->getOperand(Op+3).getImmedValue())
498 O << " + " << MI->getOperand(Op+3).getImmedValue();
503 const MachineOperand &BaseReg = MI->getOperand(Op);
504 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
505 const MachineOperand &IndexReg = MI->getOperand(Op+2);
506 int DispVal = MI->getOperand(Op+3).getImmedValue();
509 bool NeedPlus = false;
510 if (BaseReg.getReg()) {
515 if (IndexReg.getReg()) {
516 if (NeedPlus) O << " + ";
518 O << ScaleVal << "*";
536 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
537 /// described by DESC, if its PrintImplUsesAfter flag is set.
540 /// Comma - List of registers will need a leading comma.
541 /// Desc - Description of the Instruction.
544 /// true - Emitted one or more registers.
545 /// false - Emitted no registers.
547 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
548 const bool Comma = true) {
549 const MRegisterInfo &RI = *TM.getRegisterInfo();
550 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
551 bool emitted = false;
552 const unsigned *p = Desc.ImplicitUses;
554 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
559 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
560 O << ", %" << RI.get(*p).Name;
568 /// printMachineInstruction -- Print out a single X86 LLVM instruction
569 /// MI in Intel syntax to the current output stream.
571 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
573 if (printInstruction(MI))
574 return; // Printer was automatically generated
576 unsigned Opcode = MI->getOpcode();
577 const TargetInstrInfo &TII = *TM.getInstrInfo();
578 const TargetInstrDescriptor &Desc = TII.get(Opcode);
580 switch (Desc.TSFlags & X86II::FormMask) {
582 // Print pseudo-instructions as comments; either they should have been
583 // turned into real instructions by now, or they don't need to be
584 // seen by the assembler (e.g., IMPLICIT_USEs.)
586 if (Opcode == X86::PHI) {
587 printOp(MI->getOperand(0));
589 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
590 if (i != 1) O << ", ";
592 printOp(MI->getOperand(i));
594 printOp(MI->getOperand(i+1));
599 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
600 printOp(MI->getOperand(0));
604 O << TII.getName(MI->getOpcode());
606 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
608 if (MI->getOperand(i).isDef()) O << "*";
609 printOp(MI->getOperand(i));
610 if (MI->getOperand(i).isDef()) O << "*";
618 // The accepted forms of Raw instructions are:
619 // 1. jmp foo - MachineBasicBlock operand
620 // 2. call bar - GlobalAddress Operand or External Symbol Operand
621 // 3. in AL, imm - Immediate operand
623 assert(MI->getNumOperands() == 1 &&
624 (MI->getOperand(0).isMachineBasicBlock() ||
625 MI->getOperand(0).isGlobalAddress() ||
626 MI->getOperand(0).isExternalSymbol() ||
627 MI->getOperand(0).isImmediate()) &&
628 "Illegal raw instruction!");
629 O << TII.getName(MI->getOpcode()) << " ";
631 bool LeadingComma = false;
632 if (MI->getNumOperands() == 1) {
633 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
636 printImplUsesAfter(Desc, LeadingComma);
641 case X86II::AddRegFrm: {
642 // There are currently two forms of acceptable AddRegFrm instructions.
643 // Either the instruction JUST takes a single register (like inc, dec, etc),
644 // or it takes a register and an immediate of the same size as the register
645 // (move immediate f.e.). Note that this immediate value might be stored as
646 // an LLVM value, to represent, for example, loading the address of a global
647 // into a register. The initial register might be duplicated if this is a
648 // M_2_ADDR_REG instruction
650 assert(MI->getOperand(0).isRegister() &&
651 (MI->getNumOperands() == 1 ||
652 (MI->getNumOperands() == 2 &&
653 (MI->getOperand(1).getVRegValueOrNull() ||
654 MI->getOperand(1).isImmediate() ||
655 MI->getOperand(1).isRegister() ||
656 MI->getOperand(1).isGlobalAddress() ||
657 MI->getOperand(1).isExternalSymbol()))) &&
658 "Illegal form for AddRegFrm instruction!");
660 unsigned Reg = MI->getOperand(0).getReg();
662 O << TII.getName(MI->getOpcode()) << " ";
664 printOp(MI->getOperand(0));
665 if (MI->getNumOperands() == 2 &&
666 (!MI->getOperand(1).isRegister() ||
667 MI->getOperand(1).getVRegValueOrNull() ||
668 MI->getOperand(1).isGlobalAddress() ||
669 MI->getOperand(1).isExternalSymbol())) {
671 printOp(MI->getOperand(1));
673 printImplUsesAfter(Desc);
677 case X86II::MRMDestReg: {
678 // There are three forms of MRMDestReg instructions, those with 2
681 // 2 Operands: this is for things like mov that do not read a
684 // 2 Operands: two address instructions which def&use the first
685 // argument and use the second as input.
687 // 3 Operands: in this form, two address instructions are the same
688 // as in 2 but have a constant argument as well.
690 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
691 assert(MI->getOperand(0).isRegister() &&
692 (MI->getNumOperands() == 2 ||
693 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
694 && "Bad format for MRMDestReg!");
696 O << TII.getName(MI->getOpcode()) << " ";
697 printOp(MI->getOperand(0));
699 printOp(MI->getOperand(1));
700 if (MI->getNumOperands() == 3) {
702 printOp(MI->getOperand(2));
704 printImplUsesAfter(Desc);
709 case X86II::MRMDestMem: {
710 // These instructions are the same as MRMDestReg, but instead of having a
711 // register reference for the mod/rm field, it's a memory reference.
713 assert(isMem(MI, 0) &&
714 (MI->getNumOperands() == 4+1 ||
715 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
716 && "Bad format for MRMDestMem!");
718 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
719 printMemReference(MI, 0);
721 printOp(MI->getOperand(4));
722 if (MI->getNumOperands() == 4+2) {
724 printOp(MI->getOperand(5));
726 printImplUsesAfter(Desc);
731 case X86II::MRMSrcReg: {
732 // There are three forms that are acceptable for MRMSrcReg
733 // instructions, those with 2 or 3 operands:
735 // 2 Operands: this is for things like mov that do not read a
738 // 2 Operands: in this form, the last register is the ModR/M
739 // input. The first operand is a def&use. This is for things
740 // like: add r32, r/m32
742 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
743 // for instructions like the IMULrri instructions.
746 assert(MI->getOperand(0).isRegister() &&
747 MI->getOperand(1).isRegister() &&
748 (MI->getNumOperands() == 2 ||
749 (MI->getNumOperands() == 3 &&
750 (MI->getOperand(2).isImmediate())))
751 && "Bad format for MRMSrcReg!");
753 O << TII.getName(MI->getOpcode()) << " ";
754 printOp(MI->getOperand(0));
756 printOp(MI->getOperand(1));
757 if (MI->getNumOperands() == 3) {
759 printOp(MI->getOperand(2));
765 case X86II::MRMSrcMem: {
766 // These instructions are the same as MRMSrcReg, but instead of having a
767 // register reference for the mod/rm field, it's a memory reference.
769 assert(MI->getOperand(0).isRegister() &&
770 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
771 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
773 && "Bad format for MRMSrcMem!");
774 O << TII.getName(MI->getOpcode()) << " ";
775 printOp(MI->getOperand(0));
776 O << ", " << sizePtr(Desc) << " ";
777 printMemReference(MI, 1);
778 if (MI->getNumOperands() == 2+4) {
780 printOp(MI->getOperand(5));
786 case X86II::MRM0r: case X86II::MRM1r:
787 case X86II::MRM2r: case X86II::MRM3r:
788 case X86II::MRM4r: case X86II::MRM5r:
789 case X86II::MRM6r: case X86II::MRM7r: {
790 // In this form, the following are valid formats:
792 // 2. cmp reg, immediate
793 // 2. shl rdest, rinput <implicit CL or 1>
794 // 3. sbb rdest, rinput, immediate [rdest = rinput]
796 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
797 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
798 assert((MI->getNumOperands() != 2 ||
799 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
800 "Bad MRMSxR format!");
801 assert((MI->getNumOperands() < 3 ||
802 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
803 "Bad MRMSxR format!");
805 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
806 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
809 O << TII.getName(MI->getOpcode()) << " ";
810 printOp(MI->getOperand(0));
811 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
813 printOp(MI->getOperand(MI->getNumOperands()-1));
815 printImplUsesAfter(Desc);
821 case X86II::MRM0m: case X86II::MRM1m:
822 case X86II::MRM2m: case X86II::MRM3m:
823 case X86II::MRM4m: case X86II::MRM5m:
824 case X86II::MRM6m: case X86II::MRM7m: {
825 // In this form, the following are valid formats:
827 // 2. cmp [m], immediate
828 // 2. shl [m], rinput <implicit CL or 1>
829 // 3. sbb [m], immediate
831 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
832 isMem(MI, 0) && "Bad MRMSxM format!");
833 assert((MI->getNumOperands() != 5 ||
834 (MI->getOperand(4).isImmediate() ||
835 MI->getOperand(4).isGlobalAddress())) &&
836 "Bad MRMSxM format!");
838 const MachineOperand &Op3 = MI->getOperand(3);
842 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
843 // is misassembled by gas in intel_syntax mode as its 32-bit
844 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
845 // opcode bytes instead of the instruction.
847 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
848 // misassembled by gas in intel_syntax mode as its 32-bit
849 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
850 // opcode bytes instead of the instruction.
852 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
853 // invalid opcode, saying "64 bit operations are only supported in
854 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
855 // [...]", which is wrong. Workaround: Output the raw opcode bytes
856 // instead of the instruction.
858 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
859 // invalid opcode, saying "64 bit operations are only supported in
860 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
861 // [...]", which is wrong. Workaround: Output the raw opcode bytes
862 // instead of the instruction.
863 if (MI->getOpcode() == X86::FSTP80m ||
864 MI->getOpcode() == X86::FLD80m ||
865 MI->getOpcode() == X86::FILD64m ||
866 MI->getOpcode() == X86::FISTP64m) {
867 GasBugWorkaroundEmitter gwe(O);
868 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
871 O << TII.getName(MI->getOpcode()) << " ";
872 O << sizePtr(Desc) << " ";
873 printMemReference(MI, 0);
874 if (MI->getNumOperands() == 5) {
876 printOp(MI->getOperand(4));
878 printImplUsesAfter(Desc);
883 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
887 bool X86AsmPrinter::doInitialization(Module &M) {
888 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
890 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
891 // instruction as a reference to the register named sp, and if you try to
892 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
893 // before being looked up in the symbol table. This creates spurious
894 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
895 // mode, and decorate all register names with percent signs.
896 O << "\t.intel_syntax\n";
897 Mang = new Mangler(M, EmitCygwin);
898 return false; // success
901 // SwitchSection - Switch to the specified section of the executable if we are
902 // not already in it!
904 static void SwitchSection(std::ostream &OS, std::string &CurSection,
905 const char *NewSection) {
906 if (CurSection != NewSection) {
907 CurSection = NewSection;
908 if (!CurSection.empty())
909 OS << "\t" << NewSection << "\n";
913 bool X86AsmPrinter::doFinalization(Module &M) {
914 const TargetData &TD = TM.getTargetData();
915 std::string CurSection;
917 // Print out module-level global variables here.
918 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
919 if (I->hasInitializer()) { // External global require no code
921 std::string name = Mang->getValueName(I);
922 Constant *C = I->getInitializer();
923 unsigned Size = TD.getTypeSize(C->getType());
924 unsigned Align = TD.getTypeAlignment(C->getType());
926 if (C->isNullValue() &&
927 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
928 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
929 SwitchSection(O, CurSection, ".data");
930 if (I->hasInternalLinkage())
931 O << "\t.local " << name << "\n";
933 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
934 << "," << (unsigned)TD.getTypeAlignment(C->getType());
936 WriteAsOperand(O, I, true, true, &M);
939 switch (I->getLinkage()) {
940 case GlobalValue::LinkOnceLinkage:
941 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
942 // Nonnull linkonce -> weak
943 O << "\t.weak " << name << "\n";
944 SwitchSection(O, CurSection, "");
945 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
948 case GlobalValue::AppendingLinkage:
949 // FIXME: appending linkage variables should go into a section of
950 // their name or something. For now, just emit them as external.
951 case GlobalValue::ExternalLinkage:
952 // If external or appending, declare as a global symbol
953 O << "\t.globl " << name << "\n";
955 case GlobalValue::InternalLinkage:
956 if (C->isNullValue())
957 SwitchSection(O, CurSection, ".bss");
959 SwitchSection(O, CurSection, ".data");
963 O << "\t.align " << Align << "\n";
964 O << "\t.type " << name << ",@object\n";
965 O << "\t.size " << name << "," << Size << "\n";
966 O << name << ":\t\t\t\t# ";
967 WriteAsOperand(O, I, true, true, &M);
969 WriteAsOperand(O, C, false, false, &M);
971 emitGlobalConstant(C);
976 return false; // success