1 //===-- X86/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===//
3 // This file contains a printer that converts from our internal
4 // representation of machine-dependent LLVM code to Intel-format
5 // assembly language. This printer is the output mechanism used
6 // by `llc' and `lli -printmachineinstrs' on X86.
8 //===----------------------------------------------------------------------===//
11 #include "X86InstrInfo.h"
12 #include "llvm/Module.h"
13 #include "llvm/Type.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/Mangler.h"
22 #include "Support/StringExtras.h"
25 struct Printer : public MachineFunctionPass {
26 /// Output stream on which we're printing assembly code.
30 /// Target machine description which we query for reg. names, data
35 /// Name-mangler for global names.
39 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
41 /// We name each basic block in a Function with a unique number, so
42 /// that we can consistently refer to them later. This is cleared
43 /// at the beginning of each call to runOnMachineFunction().
45 typedef std::map<const Value *, unsigned> ValueMapTy;
46 ValueMapTy NumberForBB;
48 /// Cache of mangled name for current function. This is
49 /// recalculated at the beginning of each call to
50 /// runOnMachineFunction().
52 std::string CurrentFnName;
54 virtual const char *getPassName() const {
55 return "X86 Assembly Printer";
58 void printMachineInstruction(const MachineInstr *MI);
59 void printOp(const MachineOperand &MO,
60 bool elideOffsetKeyword = false);
61 void printMemReference(const MachineInstr *MI, unsigned Op);
62 void printConstantPool(MachineConstantPool *MCP);
63 bool runOnMachineFunction(MachineFunction &F);
64 std::string ConstantExprToString(const ConstantExpr* CE);
65 std::string valToExprString(const Value* V);
66 bool doInitialization(Module &M);
67 bool doFinalization(Module &M);
68 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
69 void printSingleConstantValue(const Constant* CV);
71 } // end of anonymous namespace
73 /// createX86CodePrinterPass - Returns a pass that prints the X86
74 /// assembly code for a MachineFunction to the given output stream,
75 /// using the given target machine description. This should work
76 /// regardless of whether the function is in SSA form.
78 Pass *createX86CodePrinterPass(std::ostream &o, TargetMachine &tm) {
79 return new Printer(o, tm);
82 /// valToExprString - Helper function for ConstantExprToString().
83 /// Appends result to argument string S.
85 std::string Printer::valToExprString(const Value* V) {
88 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
89 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
90 S += std::string(CB == ConstantBool::True ? "1" : "0");
91 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
92 S += itostr(CI->getValue());
93 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
94 S += utostr(CI->getValue());
95 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
96 S += ftostr(CFP->getValue());
97 else if (isa<ConstantPointerNull>(CV))
99 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
100 S += valToExprString(CPR->getValue());
101 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
102 S += ConstantExprToString(CE);
105 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
106 S += Mang->getValueName(GV);
112 assert(0 && "Cannot convert value to string");
113 S += "<illegal-value>";
118 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
119 /// and return this as a string.
121 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
123 const TargetData &TD = TM.getTargetData();
124 switch(CE->getOpcode()) {
125 case Instruction::GetElementPtr:
126 { // generate a symbolic expression for the byte address
127 const Value* ptrVal = CE->getOperand(0);
128 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
129 S += "(" + valToExprString(ptrVal) + ") + ("
130 + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
134 case Instruction::Cast:
135 // Support only non-converting or widening casts for now, that is,
136 // ones that do not involve a change in value. This assertion is
137 // not a complete check.
139 Constant *Op = CE->getOperand(0);
140 const Type *OpTy = Op->getType(), *Ty = CE->getType();
141 assert(((isa<PointerType>(OpTy)
142 && (Ty == Type::LongTy || Ty == Type::ULongTy))
143 || (isa<PointerType>(Ty)
144 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
145 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
146 && (OpTy-> isLosslesslyConvertibleTo(Ty))))
147 && "FIXME: Don't yet support this kind of constant cast expr");
148 S += "(" + valToExprString(Op) + ")";
152 case Instruction::Add:
153 S += "(" + valToExprString(CE->getOperand(0)) + ") + ("
154 + valToExprString(CE->getOperand(1)) + ")";
158 assert(0 && "Unsupported operator in ConstantExprToString()");
165 /// printSingleConstantValue - Print a single constant value.
168 Printer::printSingleConstantValue(const Constant* CV)
170 assert(CV->getType() != Type::VoidTy &&
171 CV->getType() != Type::TypeTy &&
172 CV->getType() != Type::LabelTy &&
173 "Unexpected type for Constant");
175 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
176 && "Aggregate types should be handled outside this function");
178 const Type *type = CV->getType();
180 switch(type->getPrimitiveID())
182 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
185 case Type::UShortTyID: case Type::ShortTyID:
188 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
191 case Type::ULongTyID: case Type::LongTyID:
194 case Type::FloatTyID:
197 case Type::DoubleTyID:
200 case Type::ArrayTyID:
201 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
202 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
205 assert (0 && "Can't handle printing this type of array");
208 assert (0 && "Can't handle printing this type of thing");
213 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
215 // Constant expression built from operators, constants, and
217 O << ConstantExprToString(CE) << "\n";
219 else if (type->isPrimitiveType())
221 if (type->isFloatingPoint()) {
222 // FP Constants are printed as integer constants to avoid losing
224 double Val = cast<ConstantFP>(CV)->getValue();
225 if (type == Type::FloatTy) {
226 float FVal = (float)Val;
227 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
228 O << *(unsigned int*)ProxyPtr;
229 } else if (type == Type::DoubleTy) {
230 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
231 O << *(uint64_t*)ProxyPtr;
233 assert(0 && "Unknown floating point type!");
236 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
238 WriteAsOperand(O, CV, false, false) << "\n";
241 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
243 // This is a constant address for a global variable or method.
244 // Use the name of the variable or method as the address value.
245 O << Mang->getValueName(CPR->getValue()) << "\n";
247 else if (isa<ConstantPointerNull>(CV))
249 // Null pointer value
254 assert(0 && "Unknown elementary type for constant");
258 /// isStringCompatible - Can we treat the specified array as a string?
259 /// Only if it is an array of ubytes or non-negative sbytes.
261 static bool isStringCompatible(const ConstantArray *CVA) {
262 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
263 if (ETy == Type::UByteTy) return true;
264 if (ETy != Type::SByteTy) return false;
266 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
267 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
273 /// toOctal - Convert the low order bits of X into an octal digit.
275 static inline char toOctal(int X) {
279 /// getAsCString - Return the specified array as a C compatible
280 /// string, only if the predicate isStringCompatible is true.
282 static std::string getAsCString(const ConstantArray *CVA) {
283 assert(isStringCompatible(CVA) && "Array is not string compatible!");
286 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
288 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
289 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
293 } else if (C == '\\') {
295 } else if (isprint(C)) {
299 case '\a': Result += "\\a"; break;
300 case '\b': Result += "\\b"; break;
301 case '\f': Result += "\\f"; break;
302 case '\n': Result += "\\n"; break;
303 case '\r': Result += "\\r"; break;
304 case '\t': Result += "\\t"; break;
305 case '\v': Result += "\\v"; break;
308 Result += toOctal(C >> 6);
309 Result += toOctal(C >> 3);
310 Result += toOctal(C >> 0);
319 // Print a constant value or values (it may be an aggregate).
320 // Uses printSingleConstantValue() to print each individual value.
322 Printer::printConstantValueOnly(const Constant* CV,
323 int numPadBytesAfter /* = 0 */)
325 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
326 const TargetData &TD = TM.getTargetData();
328 if (CVA && isStringCompatible(CVA))
329 { // print the string alone and return
330 O << "\t.string\t" << getAsCString(CVA) << "\n";
333 { // Not a string. Print the values in successive locations
334 const std::vector<Use> &constValues = CVA->getValues();
335 for (unsigned i=0; i < constValues.size(); i++)
336 printConstantValueOnly(cast<Constant>(constValues[i].get()));
338 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
339 { // Print the fields in successive locations. Pad to align if needed!
340 const StructLayout *cvsLayout =
341 TD.getStructLayout(CVS->getType());
342 const std::vector<Use>& constValues = CVS->getValues();
343 unsigned sizeSoFar = 0;
344 for (unsigned i=0, N = constValues.size(); i < N; i++)
346 const Constant* field = cast<Constant>(constValues[i].get());
348 // Check if padding is needed and insert one or more 0s.
349 unsigned fieldSize = TD.getTypeSize(field->getType());
350 int padSize = ((i == N-1? cvsLayout->StructSize
351 : cvsLayout->MemberOffsets[i+1])
352 - cvsLayout->MemberOffsets[i]) - fieldSize;
353 sizeSoFar += (fieldSize + padSize);
355 // Now print the actual field value
356 printConstantValueOnly(field, padSize);
358 assert(sizeSoFar == cvsLayout->StructSize &&
359 "Layout of constant struct may be incorrect!");
362 printSingleConstantValue(CV);
364 if (numPadBytesAfter) O << "\t.zero\t " << numPadBytesAfter << "\n";
367 /// printConstantPool - Print to the current output stream assembly
368 /// representations of the constants in the constant pool MCP. This is
369 /// used to print out constants which have been "spilled to memory" by
370 /// the code generator.
372 void Printer::printConstantPool(MachineConstantPool *MCP) {
373 const std::vector<Constant*> &CP = MCP->getConstants();
374 const TargetData &TD = TM.getTargetData();
376 if (CP.empty()) return;
378 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
379 O << "\t.section .rodata\n";
380 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
382 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
384 printConstantValueOnly (CP[i]);
388 /// runOnMachineFunction - This uses the printMachineInstruction()
389 /// method to print assembly for each instruction.
391 bool Printer::runOnMachineFunction(MachineFunction &MF) {
392 // BBNumber is used here so that a given Printer will never give two
393 // BBs the same name. (If you have a better way, please let me know!)
394 static unsigned BBNumber = 0;
397 // What's my mangled name?
398 CurrentFnName = Mang->getValueName(MF.getFunction());
400 // Print out constants referenced by the function
401 printConstantPool(MF.getConstantPool());
403 // Print out labels for the function.
405 O << "\t.align 16\n";
406 O << "\t.globl\t" << CurrentFnName << "\n";
407 O << "\t.type\t" << CurrentFnName << ", @function\n";
408 O << CurrentFnName << ":\n";
410 // Number each basic block so that we can consistently refer to them
411 // in PC-relative references.
413 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
415 NumberForBB[I->getBasicBlock()] = BBNumber++;
418 // Print out code for the function.
419 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
421 // Print a label for the basic block.
422 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
423 << I->getBasicBlock()->getName() << "\n";
424 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
426 // Print the assembly for the instruction.
428 printMachineInstruction(*II);
432 // We didn't modify anything.
436 static bool isScale(const MachineOperand &MO) {
437 return MO.isImmediate() &&
438 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
439 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
442 static bool isMem(const MachineInstr *MI, unsigned Op) {
443 if (MI->getOperand(Op).isFrameIndex()) return true;
444 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
445 return Op+4 <= MI->getNumOperands() &&
446 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
447 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
450 void Printer::printOp(const MachineOperand &MO,
451 bool elideOffsetKeyword /* = false */) {
452 const MRegisterInfo &RI = *TM.getRegisterInfo();
453 switch (MO.getType()) {
454 case MachineOperand::MO_VirtualRegister:
455 if (Value *V = MO.getVRegValueOrNull()) {
456 O << "<" << V->getName() << ">";
460 case MachineOperand::MO_MachineRegister:
461 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
462 O << RI.get(MO.getReg()).Name;
464 O << "%reg" << MO.getReg();
467 case MachineOperand::MO_SignExtendedImmed:
468 case MachineOperand::MO_UnextendedImmed:
469 O << (int)MO.getImmedValue();
471 case MachineOperand::MO_PCRelativeDisp:
473 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
474 assert (i != NumberForBB.end()
475 && "Could not find a BB I previously put in the NumberForBB map!");
476 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
479 case MachineOperand::MO_GlobalAddress:
480 if (!elideOffsetKeyword)
482 O << Mang->getValueName(MO.getGlobal());
484 case MachineOperand::MO_ExternalSymbol:
485 O << MO.getSymbolName();
488 O << "<unknown operand type>"; return;
492 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
493 switch (Desc.TSFlags & X86II::ArgMask) {
494 default: assert(0 && "Unknown arg size!");
495 case X86II::Arg8: return "BYTE PTR";
496 case X86II::Arg16: return "WORD PTR";
497 case X86II::Arg32: return "DWORD PTR";
498 case X86II::Arg64: return "QWORD PTR";
499 case X86II::ArgF32: return "DWORD PTR";
500 case X86II::ArgF64: return "QWORD PTR";
501 case X86II::ArgF80: return "XWORD PTR";
505 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
506 const MRegisterInfo &RI = *TM.getRegisterInfo();
507 assert(isMem(MI, Op) && "Invalid memory reference!");
509 if (MI->getOperand(Op).isFrameIndex()) {
510 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
511 if (MI->getOperand(Op+3).getImmedValue())
512 O << " + " << MI->getOperand(Op+3).getImmedValue();
515 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
516 O << "[.CPI" << CurrentFnName << "_"
517 << MI->getOperand(Op).getConstantPoolIndex();
518 if (MI->getOperand(Op+3).getImmedValue())
519 O << " + " << MI->getOperand(Op+3).getImmedValue();
524 const MachineOperand &BaseReg = MI->getOperand(Op);
525 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
526 const MachineOperand &IndexReg = MI->getOperand(Op+2);
527 int DispVal = MI->getOperand(Op+3).getImmedValue();
530 bool NeedPlus = false;
531 if (BaseReg.getReg()) {
536 if (IndexReg.getReg()) {
537 if (NeedPlus) O << " + ";
539 O << ScaleVal << "*";
557 /// printMachineInstruction -- Print out a single X86 LLVM instruction
558 /// MI in Intel syntax to the current output stream.
560 void Printer::printMachineInstruction(const MachineInstr *MI) {
561 unsigned Opcode = MI->getOpcode();
562 const TargetInstrInfo &TII = TM.getInstrInfo();
563 const TargetInstrDescriptor &Desc = TII.get(Opcode);
564 const MRegisterInfo &RI = *TM.getRegisterInfo();
566 switch (Desc.TSFlags & X86II::FormMask) {
568 // Print pseudo-instructions as comments; either they should have been
569 // turned into real instructions by now, or they don't need to be
570 // seen by the assembler (e.g., IMPLICIT_USEs.)
572 if (Opcode == X86::PHI) {
573 printOp(MI->getOperand(0));
575 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
576 if (i != 1) O << ", ";
578 printOp(MI->getOperand(i));
580 printOp(MI->getOperand(i+1));
585 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
586 MI->getOperand(0).opIsDefAndUse())) {
587 printOp(MI->getOperand(0));
591 O << TII.getName(MI->getOpcode());
593 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
595 if (MI->getOperand(i).opIsDefOnly() ||
596 MI->getOperand(i).opIsDefAndUse()) O << "*";
597 printOp(MI->getOperand(i));
598 if (MI->getOperand(i).opIsDefOnly() ||
599 MI->getOperand(i).opIsDefAndUse()) O << "*";
606 // The accepted forms of Raw instructions are:
607 // 1. nop - No operand required
608 // 2. jmp foo - PC relative displacement operand
609 // 3. call bar - GlobalAddress Operand or External Symbol Operand
611 assert(MI->getNumOperands() == 0 ||
612 (MI->getNumOperands() == 1 &&
613 (MI->getOperand(0).isPCRelativeDisp() ||
614 MI->getOperand(0).isGlobalAddress() ||
615 MI->getOperand(0).isExternalSymbol())) &&
616 "Illegal raw instruction!");
617 O << TII.getName(MI->getOpcode()) << " ";
619 if (MI->getNumOperands() == 1) {
620 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
625 case X86II::AddRegFrm: {
626 // There are currently two forms of acceptable AddRegFrm instructions.
627 // Either the instruction JUST takes a single register (like inc, dec, etc),
628 // or it takes a register and an immediate of the same size as the register
629 // (move immediate f.e.). Note that this immediate value might be stored as
630 // an LLVM value, to represent, for example, loading the address of a global
631 // into a register. The initial register might be duplicated if this is a
632 // M_2_ADDR_REG instruction
634 assert(MI->getOperand(0).isRegister() &&
635 (MI->getNumOperands() == 1 ||
636 (MI->getNumOperands() == 2 &&
637 (MI->getOperand(1).getVRegValueOrNull() ||
638 MI->getOperand(1).isImmediate() ||
639 MI->getOperand(1).isRegister() ||
640 MI->getOperand(1).isGlobalAddress() ||
641 MI->getOperand(1).isExternalSymbol()))) &&
642 "Illegal form for AddRegFrm instruction!");
644 unsigned Reg = MI->getOperand(0).getReg();
646 O << TII.getName(MI->getOpCode()) << " ";
647 printOp(MI->getOperand(0));
648 if (MI->getNumOperands() == 2 &&
649 (!MI->getOperand(1).isRegister() ||
650 MI->getOperand(1).getVRegValueOrNull() ||
651 MI->getOperand(1).isGlobalAddress() ||
652 MI->getOperand(1).isExternalSymbol())) {
654 printOp(MI->getOperand(1));
656 if (Desc.TSFlags & X86II::PrintImplUses) {
657 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
658 O << ", " << RI.get(*p).Name;
664 case X86II::MRMDestReg: {
665 // There are two acceptable forms of MRMDestReg instructions, those with 2,
668 // 2 Operands: this is for things like mov that do not read a second input
670 // 3 Operands: in this form, the first two registers (the destination, and
671 // the first operand) should be the same, post register allocation. The 3rd
672 // operand is an additional input. This should be for things like add
675 // 4 Operands: This form is for instructions which are 3 operands forms, but
676 // have a constant argument as well.
678 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
679 assert(MI->getOperand(0).isRegister() &&
680 (MI->getNumOperands() == 2 ||
681 (isTwoAddr && MI->getOperand(1).isRegister() &&
682 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
683 (MI->getNumOperands() == 3 ||
684 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
685 && "Bad format for MRMDestReg!");
687 O << TII.getName(MI->getOpCode()) << " ";
688 printOp(MI->getOperand(0));
690 printOp(MI->getOperand(1+isTwoAddr));
691 if (MI->getNumOperands() == 4) {
693 printOp(MI->getOperand(3));
699 case X86II::MRMDestMem: {
700 // These instructions are the same as MRMDestReg, but instead of having a
701 // register reference for the mod/rm field, it's a memory reference.
703 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
704 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
706 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
707 printMemReference(MI, 0);
709 printOp(MI->getOperand(4));
714 case X86II::MRMSrcReg: {
715 // There is a two forms that are acceptable for MRMSrcReg instructions,
716 // those with 3 and 2 operands:
718 // 3 Operands: in this form, the last register (the second input) is the
719 // ModR/M input. The first two operands should be the same, post register
720 // allocation. This is for things like: add r32, r/m32
722 // 2 Operands: this is for things like mov that do not read a second input
724 assert(MI->getOperand(0).isRegister() &&
725 MI->getOperand(1).isRegister() &&
726 (MI->getNumOperands() == 2 ||
727 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
728 && "Bad format for MRMSrcReg!");
729 if (MI->getNumOperands() == 3 &&
730 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
733 O << TII.getName(MI->getOpCode()) << " ";
734 printOp(MI->getOperand(0));
736 printOp(MI->getOperand(MI->getNumOperands()-1));
741 case X86II::MRMSrcMem: {
742 // These instructions are the same as MRMSrcReg, but instead of having a
743 // register reference for the mod/rm field, it's a memory reference.
745 assert(MI->getOperand(0).isRegister() &&
746 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
747 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
749 && "Bad format for MRMDestReg!");
750 if (MI->getNumOperands() == 2+4 &&
751 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
754 O << TII.getName(MI->getOpCode()) << " ";
755 printOp(MI->getOperand(0));
756 O << ", " << sizePtr(Desc) << " ";
757 printMemReference(MI, MI->getNumOperands()-4);
762 case X86II::MRMS0r: case X86II::MRMS1r:
763 case X86II::MRMS2r: case X86II::MRMS3r:
764 case X86II::MRMS4r: case X86II::MRMS5r:
765 case X86II::MRMS6r: case X86II::MRMS7r: {
766 // In this form, the following are valid formats:
768 // 2. cmp reg, immediate
769 // 2. shl rdest, rinput <implicit CL or 1>
770 // 3. sbb rdest, rinput, immediate [rdest = rinput]
772 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
773 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
774 assert((MI->getNumOperands() != 2 ||
775 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
776 "Bad MRMSxR format!");
777 assert((MI->getNumOperands() < 3 ||
778 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
779 "Bad MRMSxR format!");
781 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
782 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
785 O << TII.getName(MI->getOpCode()) << " ";
786 printOp(MI->getOperand(0));
787 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
789 printOp(MI->getOperand(MI->getNumOperands()-1));
791 if (Desc.TSFlags & X86II::PrintImplUses) {
792 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
793 O << ", " << RI.get(*p).Name;
801 case X86II::MRMS0m: case X86II::MRMS1m:
802 case X86II::MRMS2m: case X86II::MRMS3m:
803 case X86II::MRMS4m: case X86II::MRMS5m:
804 case X86II::MRMS6m: case X86II::MRMS7m: {
805 // In this form, the following are valid formats:
807 // 2. cmp [m], immediate
808 // 2. shl [m], rinput <implicit CL or 1>
809 // 3. sbb [m], immediate
811 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
812 isMem(MI, 0) && "Bad MRMSxM format!");
813 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
814 "Bad MRMSxM format!");
815 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
816 // is misassembled by gas in intel_syntax mode as its 32-bit
817 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
818 // opcode bytes instead of the instruction.
819 if (MI->getOpCode() == X86::FSTPr80) {
820 if ((MI->getOperand(0).getReg() == X86::ESP)
821 && (MI->getOperand(1).getImmedValue() == 1)) {
822 int DispVal = MI->getOperand(3).getImmedValue();
823 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
824 unsigned int val = (unsigned int) DispVal;
825 O << ".byte 0xdb, 0xbc, 0x24\n\t";
826 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
827 } else { // 1 byte disp.
828 unsigned char val = (unsigned char) DispVal;
829 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
830 << std::dec << "\t# ";
834 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
835 // misassembled by gas in intel_syntax mode as its 32-bit
836 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
837 // opcode bytes instead of the instruction.
838 if (MI->getOpCode() == X86::FLDr80) {
839 if ((MI->getOperand(0).getReg() == X86::ESP)
840 && (MI->getOperand(1).getImmedValue() == 1)) {
841 int DispVal = MI->getOperand(3).getImmedValue();
842 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
843 unsigned int val = (unsigned int) DispVal;
844 O << ".byte 0xdb, 0xac, 0x24\n\t";
845 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
846 } else { // 1 byte disp.
847 unsigned char val = (unsigned char) DispVal;
848 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
849 << std::dec << "\t# ";
853 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
854 // invalid opcode, saying "64 bit operations are only supported in
855 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
856 // [...]", which is wrong. Workaround: Output the raw opcode bytes
857 // instead of the instruction.
858 if (MI->getOpCode() == X86::FILDr64) {
859 if ((MI->getOperand(0).getReg() == X86::ESP)
860 && (MI->getOperand(1).getImmedValue() == 1)) {
861 int DispVal = MI->getOperand(3).getImmedValue();
862 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
863 unsigned int val = (unsigned int) DispVal;
864 O << ".byte 0xdf, 0xac, 0x24\n\t";
865 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
866 } else { // 1 byte disp.
867 unsigned char val = (unsigned char) DispVal;
868 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
869 << std::dec << "\t# ";
873 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
874 // an invalid opcode, saying "64 bit operations are only
875 // supported in 64 bit modes." libopcodes disassembles it as
876 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
877 // "fistpll DWORD PTR " instead, which is what libopcodes is
879 if (MI->getOpCode() == X86::FISTPr64) {
880 O << "fistpll DWORD PTR ";
881 printMemReference(MI, 0);
882 if (MI->getNumOperands() == 5) {
884 printOp(MI->getOperand(4));
889 O << TII.getName(MI->getOpCode()) << " ";
890 O << sizePtr(Desc) << " ";
891 printMemReference(MI, 0);
892 if (MI->getNumOperands() == 5) {
894 printOp(MI->getOperand(4));
901 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
905 bool Printer::doInitialization(Module &M)
907 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
908 // with no % decorations on register names.
909 O << "\t.intel_syntax noprefix\n";
910 Mang = new Mangler(M);
911 return false; // success
914 static const Function *isConstantFunctionPointerRef(const Constant *C) {
915 if (const ConstantPointerRef *R = dyn_cast<ConstantPointerRef>(C))
916 if (const Function *F = dyn_cast<Function>(R->getValue()))
921 bool Printer::doFinalization(Module &M)
923 const TargetData &TD = TM.getTargetData();
924 // Print out module-level global variables here.
925 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
926 std::string name(Mang->getValueName(I));
927 if (I->hasInitializer()) {
928 Constant *C = I->getInitializer();
929 if (C->isNullValue()) {
930 O << "\n\n\t.comm " << name << "," << TD.getTypeSize(C->getType())
931 << "," << (unsigned)TD.getTypeAlignment(C->getType());
933 WriteAsOperand(O, I, true, true, &M);
936 O << "\n\n\t.data\n";
937 O << "\t.globl " << name << "\n";
938 O << "\t.type " << name << ",@object\n";
939 O << "\t.size " << name << "," << TD.getTypeSize(C->getType()) << "\n";
940 O << "\t.align " << (unsigned)TD.getTypeAlignment(C->getType()) << "\n";
941 O << name << ":\t\t\t\t# ";
942 WriteAsOperand(O, I, true, true, &M);
944 WriteAsOperand(O, C, false, false, &M);
946 printConstantValueOnly(C);
949 O << "\t.globl " << name << "\n";
950 O << "\t.comm " << name << ", "
951 << (unsigned)TD.getTypeSize(I->getType()) << ", "
952 << (unsigned)TD.getTypeAlignment(I->getType()) << "\n";
956 return false; // success