1 //===-- X86/Printer.cpp - Convert X86 code to human readable rep. ---------===//
3 // This file contains a printer that converts from our internal representation
4 // of LLVM code to a nice human readable form that is suitable for debugging.
6 //===----------------------------------------------------------------------===//
9 #include "X86InstrInfo.h"
10 #include "llvm/Function.h"
11 #include "llvm/Constant.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineConstantPool.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "Support/Statistic.h"
17 #include "Support/hash_map"
18 #include "llvm/Type.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/SlotCalculator.h"
23 #include "Support/StringExtras.h"
24 #include "llvm/Module.h"
27 std::set<const Value *> MangledGlobals;
28 struct Printer : public MachineFunctionPass {
30 typedef std::map<const Value *, unsigned> ValueMapTy;
31 ValueMapTy NumberForBB;
32 Printer(std::ostream &o) : O(o) {}
34 std::string CurrentFnName;
35 virtual const char *getPassName() const {
36 return "X86 Assembly Printer";
39 void printMachineInstruction(const MachineInstr *MI, std::ostream &O,
40 const TargetMachine &TM) const;
41 void printOp(std::ostream &O, const MachineOperand &MO,
42 const MRegisterInfo &RI, bool elideOffsetKeyword = false) const;
43 void printMemReference(std::ostream &O, const MachineInstr *MI,
45 const MRegisterInfo &RI) const;
46 void printConstantPool(MachineConstantPool *MCP);
47 bool runOnMachineFunction(MachineFunction &F);
48 std::string ConstantExprToString(const ConstantExpr* CE);
49 std::string valToExprString(const Value* V);
50 bool doInitialization(Module &M);
51 bool doFinalization(Module &M);
52 void PrintZeroBytesToPad(int numBytes);
53 void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
54 void printSingleConstantValue(const Constant* CV);
56 } // end of anonymous namespace
58 /// createX86CodePrinterPass - Print out the specified machine code function to
59 /// the specified stream. This function should work regardless of whether or
60 /// not the function is in SSA form or not.
62 Pass *createX86CodePrinterPass(std::ostream &O) {
63 return new Printer(O);
66 // We don't want identifier names with ., space, or - in them,
67 // so we replace them with underscores.
68 static std::string makeNameProper(std::string x) {
70 for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
72 case '.': tmp += "d_"; break;
73 case ' ': tmp += "s_"; break;
74 case '-': tmp += "D_"; break;
80 static std::string getValueName(const Value *V) {
81 if (V->hasName()) { // Print out the label if it exists...
82 // Name mangling occurs as follows:
83 // - If V is not a global, mangling always occurs.
84 // - Otherwise, mangling occurs when any of the following are true:
85 // 1) V has internal linkage
86 // 2) V's name would collide if it is not mangled.
88 if(const GlobalValue* gv = dyn_cast<GlobalValue>(V)) {
89 if(!gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
90 // No internal linkage, name will not collide -> no mangling.
91 return makeNameProper(gv->getName());
94 // Non-global, or global with internal linkage / colliding name -> mangle.
95 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
96 makeNameProper(V->getName());
100 return "ltmp_" + itostr(Count) + "_" + utostr(V->getType()->getUniqueID());
103 // valToExprString - Helper function for ConstantExprToString().
104 // Appends result to argument string S.
106 std::string Printer::valToExprString(const Value* V) {
109 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
110 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
111 S += std::string(CB == ConstantBool::True ? "1" : "0");
112 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
113 S += itostr(CI->getValue());
114 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
115 S += utostr(CI->getValue());
116 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
117 S += ftostr(CFP->getValue());
118 else if (isa<ConstantPointerNull>(CV))
120 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
121 S += valToExprString(CPR->getValue());
122 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
123 S += ConstantExprToString(CE);
126 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
127 S += getValueName(GV);
133 assert(0 && "Cannot convert value to string");
134 S += "<illegal-value>";
139 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
140 // and return this as a string.
141 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
143 switch(CE->getOpcode()) {
144 case Instruction::GetElementPtr:
145 { // generate a symbolic expression for the byte address
146 const Value* ptrVal = CE->getOperand(0);
147 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
148 S += "(" + valToExprString(ptrVal) + ") + ("
149 + utostr(TD->getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
153 case Instruction::Cast:
154 // Support only non-converting casts for now, i.e., a no-op.
155 // This assertion is not a complete check.
156 assert(TD->getTypeSize(CE->getType()) ==
157 TD->getTypeSize(CE->getOperand(0)->getType()));
158 S += "(" + valToExprString(CE->getOperand(0)) + ")";
161 case Instruction::Add:
162 S += "(" + valToExprString(CE->getOperand(0)) + ") + ("
163 + valToExprString(CE->getOperand(1)) + ")";
167 assert(0 && "Unsupported operator in ConstantExprToString()");
174 // Print a single constant value.
176 Printer::printSingleConstantValue(const Constant* CV)
178 assert(CV->getType() != Type::VoidTy &&
179 CV->getType() != Type::TypeTy &&
180 CV->getType() != Type::LabelTy &&
181 "Unexpected type for Constant");
183 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
184 && "Aggregate types should be handled outside this function");
186 const Type *type = CV->getType();
188 switch(type->getPrimitiveID())
190 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
193 case Type::UShortTyID: case Type::ShortTyID:
196 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
199 case Type::ULongTyID: case Type::LongTyID:
202 case Type::FloatTyID:
205 case Type::DoubleTyID:
208 case Type::ArrayTyID:
209 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
210 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
213 assert (0 && "Can't handle printing this type of array");
216 assert (0 && "Can't handle printing this type of thing");
221 if (type->isPrimitiveType())
223 if (type->isFloatingPoint()) {
224 // FP Constants are printed as integer constants to avoid losing
226 double Val = cast<ConstantFP>(CV)->getValue();
227 if (type == Type::FloatTy) {
228 float FVal = (float)Val;
229 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
230 O << *(unsigned int*)ProxyPtr;
231 } else if (type == Type::DoubleTy) {
232 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
233 O << *(uint64_t*)ProxyPtr;
235 assert(0 && "Unknown floating point type!");
238 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
240 WriteAsOperand(O, CV, false, false) << "\n";
243 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
245 // This is a constant address for a global variable or method.
246 // Use the name of the variable or method as the address value.
247 O << getValueName(CPR->getValue()) << "\n";
249 else if (isa<ConstantPointerNull>(CV))
251 // Null pointer value
254 else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
256 // Constant expression built from operators, constants, and
258 O << ConstantExprToString(CE) << "\n";
262 assert(0 && "Unknown elementary type for constant");
266 // Can we treat the specified array as a string? Only if it is an array of
267 // ubytes or non-negative sbytes.
269 static bool isStringCompatible(const ConstantArray *CVA) {
270 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
271 if (ETy == Type::UByteTy) return true;
272 if (ETy != Type::SByteTy) return false;
274 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
275 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
281 // toOctal - Convert the low order bits of X into an octal letter
282 static inline char toOctal(int X) {
286 // getAsCString - Return the specified array as a C compatible string, only if
287 // the predicate isStringCompatible is true.
289 static std::string getAsCString(const ConstantArray *CVA) {
290 assert(isStringCompatible(CVA) && "Array is not string compatible!");
293 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
295 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
296 unsigned char C = (ETy == Type::SByteTy) ?
297 (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
298 (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
302 } else if (C == '\\') {
304 } else if (isprint(C)) {
308 case '\a': Result += "\\a"; break;
309 case '\b': Result += "\\b"; break;
310 case '\f': Result += "\\f"; break;
311 case '\n': Result += "\\n"; break;
312 case '\r': Result += "\\r"; break;
313 case '\t': Result += "\\t"; break;
314 case '\v': Result += "\\v"; break;
317 Result += toOctal(C >> 6);
318 Result += toOctal(C >> 3);
319 Result += toOctal(C >> 0);
328 // Print a constant value or values (it may be an aggregate).
329 // Uses printSingleConstantValue() to print each individual value.
331 Printer::printConstantValueOnly(const Constant* CV,
332 int numPadBytesAfter /* = 0 */)
334 const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
336 if (CVA && isStringCompatible(CVA))
337 { // print the string alone and return
338 O << "\t" << ".string" << "\t" << getAsCString(CVA) << "\n";
341 { // Not a string. Print the values in successive locations
342 const std::vector<Use> &constValues = CVA->getValues();
343 for (unsigned i=0; i < constValues.size(); i++)
344 printConstantValueOnly(cast<Constant>(constValues[i].get()));
346 else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
347 { // Print the fields in successive locations. Pad to align if needed!
348 const StructLayout *cvsLayout =
349 TD->getStructLayout(CVS->getType());
350 const std::vector<Use>& constValues = CVS->getValues();
351 unsigned sizeSoFar = 0;
352 for (unsigned i=0, N = constValues.size(); i < N; i++)
354 const Constant* field = cast<Constant>(constValues[i].get());
356 // Check if padding is needed and insert one or more 0s.
357 unsigned fieldSize = TD->getTypeSize(field->getType());
358 int padSize = ((i == N-1? cvsLayout->StructSize
359 : cvsLayout->MemberOffsets[i+1])
360 - cvsLayout->MemberOffsets[i]) - fieldSize;
361 sizeSoFar += (fieldSize + padSize);
363 // Now print the actual field value
364 printConstantValueOnly(field, padSize);
366 assert(sizeSoFar == cvsLayout->StructSize &&
367 "Layout of constant struct may be incorrect!");
370 printSingleConstantValue(CV);
372 if (numPadBytesAfter) {
373 unsigned numBytes = numPadBytesAfter;
374 for ( ; numBytes >= 8; numBytes -= 8)
375 printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
378 printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
382 printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
386 // printConstantPool - Print out any constants which have been spilled to
388 void Printer::printConstantPool(MachineConstantPool *MCP){
389 const std::vector<Constant*> &CP = MCP->getConstants();
390 if (CP.empty()) return;
392 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
393 O << "\t.section .rodata\n";
394 O << "\t.align " << (unsigned)TD->getTypeAlignment(CP[i]->getType())
396 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
398 printConstantValueOnly (CP[i]);
402 /// runOnMachineFunction - This uses the X86InstructionInfo::print method
403 /// to print assembly for each instruction.
404 bool Printer::runOnMachineFunction(MachineFunction &MF) {
405 static unsigned BBNumber = 0;
406 const TargetMachine &TM = MF.getTarget();
407 const TargetInstrInfo &TII = TM.getInstrInfo();
408 TD = &TM.getTargetData();
410 // What's my mangled name?
411 CurrentFnName = getValueName(MF.getFunction());
413 // Print out constants referenced by the function
414 printConstantPool(MF.getConstantPool());
416 // Print out labels for the function.
418 O << "\t.align 16\n";
419 O << "\t.globl\t" << CurrentFnName << "\n";
420 O << "\t.type\t" << CurrentFnName << ", @function\n";
421 O << CurrentFnName << ":\n";
423 // Number each basic block so that we can consistently refer to them
424 // in PC-relative references.
426 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
428 NumberForBB[I->getBasicBlock()] = BBNumber++;
431 // Print out code for the function.
432 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
434 // Print a label for the basic block.
435 O << ".BB" << NumberForBB[I->getBasicBlock()] << ":\t# "
436 << I->getBasicBlock()->getName() << "\n";
437 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
439 // Print the assembly for the instruction.
441 printMachineInstruction(*II, O, TM);
445 // We didn't modify anything.
449 static bool isScale(const MachineOperand &MO) {
450 return MO.isImmediate() &&
451 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
452 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
455 static bool isMem(const MachineInstr *MI, unsigned Op) {
456 if (MI->getOperand(Op).isFrameIndex()) return true;
457 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
458 return Op+4 <= MI->getNumOperands() &&
459 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
460 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
463 void Printer::printOp(std::ostream &O, const MachineOperand &MO,
464 const MRegisterInfo &RI,
465 bool elideOffsetKeyword /* = false */) const {
466 switch (MO.getType()) {
467 case MachineOperand::MO_VirtualRegister:
468 if (Value *V = MO.getVRegValueOrNull()) {
469 O << "<" << V->getName() << ">";
473 case MachineOperand::MO_MachineRegister:
474 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
475 O << RI.get(MO.getReg()).Name;
477 O << "%reg" << MO.getReg();
480 case MachineOperand::MO_SignExtendedImmed:
481 case MachineOperand::MO_UnextendedImmed:
482 O << (int)MO.getImmedValue();
484 case MachineOperand::MO_PCRelativeDisp:
486 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
487 assert (i != NumberForBB.end()
488 && "Could not find a BB I previously put in the NumberForBB map!");
489 O << ".BB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
492 case MachineOperand::MO_GlobalAddress:
493 if (!elideOffsetKeyword) O << "OFFSET "; O << getValueName(MO.getGlobal());
495 case MachineOperand::MO_ExternalSymbol:
496 O << MO.getSymbolName();
499 O << "<unknown operand type>"; return;
503 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
504 switch (Desc.TSFlags & X86II::ArgMask) {
505 default: assert(0 && "Unknown arg size!");
506 case X86II::Arg8: return "BYTE PTR";
507 case X86II::Arg16: return "WORD PTR";
508 case X86II::Arg32: return "DWORD PTR";
509 case X86II::Arg64: return "QWORD PTR";
510 case X86II::ArgF32: return "DWORD PTR";
511 case X86II::ArgF64: return "QWORD PTR";
512 case X86II::ArgF80: return "XWORD PTR";
516 void Printer::printMemReference(std::ostream &O, const MachineInstr *MI,
518 const MRegisterInfo &RI) const {
519 assert(isMem(MI, Op) && "Invalid memory reference!");
521 if (MI->getOperand(Op).isFrameIndex()) {
522 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
523 if (MI->getOperand(Op+3).getImmedValue())
524 O << " + " << MI->getOperand(Op+3).getImmedValue();
527 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
528 O << "[.CPI" << CurrentFnName << "_"
529 << MI->getOperand(Op).getConstantPoolIndex();
530 if (MI->getOperand(Op+3).getImmedValue())
531 O << " + " << MI->getOperand(Op+3).getImmedValue();
536 const MachineOperand &BaseReg = MI->getOperand(Op);
537 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
538 const MachineOperand &IndexReg = MI->getOperand(Op+2);
539 int DispVal = MI->getOperand(Op+3).getImmedValue();
542 bool NeedPlus = false;
543 if (BaseReg.getReg()) {
544 printOp(O, BaseReg, RI);
548 if (IndexReg.getReg()) {
549 if (NeedPlus) O << " + ";
551 O << ScaleVal << "*";
552 printOp(O, IndexReg, RI);
569 /// printMachineInstruction -- Print out an x86 instruction in intel syntax
571 void Printer::printMachineInstruction(const MachineInstr *MI, std::ostream &O,
572 const TargetMachine &TM) const {
573 unsigned Opcode = MI->getOpcode();
574 const TargetInstrInfo &TII = TM.getInstrInfo();
575 const TargetInstrDescriptor &Desc = TII.get(Opcode);
576 const MRegisterInfo &RI = *TM.getRegisterInfo();
578 switch (Desc.TSFlags & X86II::FormMask) {
580 // Print pseudo-instructions as comments; either they should have been
581 // turned into real instructions by now, or they don't need to be
582 // seen by the assembler (e.g., IMPLICIT_USEs.)
584 if (Opcode == X86::PHI) {
585 printOp(O, MI->getOperand(0), RI);
587 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
588 if (i != 1) O << ", ";
590 printOp(O, MI->getOperand(i), RI);
592 printOp(O, MI->getOperand(i+1), RI);
597 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
598 MI->getOperand(0).opIsDefAndUse())) {
599 printOp(O, MI->getOperand(0), RI);
603 O << TII.getName(MI->getOpcode());
605 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
607 if (MI->getOperand(i).opIsDefOnly() ||
608 MI->getOperand(i).opIsDefAndUse()) O << "*";
609 printOp(O, MI->getOperand(i), RI);
610 if (MI->getOperand(i).opIsDefOnly() ||
611 MI->getOperand(i).opIsDefAndUse()) O << "*";
618 // The accepted forms of Raw instructions are:
619 // 1. nop - No operand required
620 // 2. jmp foo - PC relative displacement operand
621 // 3. call bar - GlobalAddress Operand or External Symbol Operand
623 assert(MI->getNumOperands() == 0 ||
624 (MI->getNumOperands() == 1 &&
625 (MI->getOperand(0).isPCRelativeDisp() ||
626 MI->getOperand(0).isGlobalAddress() ||
627 MI->getOperand(0).isExternalSymbol())) &&
628 "Illegal raw instruction!");
629 O << TII.getName(MI->getOpcode()) << " ";
631 if (MI->getNumOperands() == 1) {
632 printOp(O, MI->getOperand(0), RI, true); // Don't print "OFFSET"...
637 case X86II::AddRegFrm: {
638 // There are currently two forms of acceptable AddRegFrm instructions.
639 // Either the instruction JUST takes a single register (like inc, dec, etc),
640 // or it takes a register and an immediate of the same size as the register
641 // (move immediate f.e.). Note that this immediate value might be stored as
642 // an LLVM value, to represent, for example, loading the address of a global
643 // into a register. The initial register might be duplicated if this is a
644 // M_2_ADDR_REG instruction
646 assert(MI->getOperand(0).isRegister() &&
647 (MI->getNumOperands() == 1 ||
648 (MI->getNumOperands() == 2 &&
649 (MI->getOperand(1).getVRegValueOrNull() ||
650 MI->getOperand(1).isImmediate() ||
651 MI->getOperand(1).isRegister() ||
652 MI->getOperand(1).isGlobalAddress() ||
653 MI->getOperand(1).isExternalSymbol()))) &&
654 "Illegal form for AddRegFrm instruction!");
656 unsigned Reg = MI->getOperand(0).getReg();
658 O << TII.getName(MI->getOpCode()) << " ";
659 printOp(O, MI->getOperand(0), RI);
660 if (MI->getNumOperands() == 2 &&
661 (!MI->getOperand(1).isRegister() ||
662 MI->getOperand(1).getVRegValueOrNull() ||
663 MI->getOperand(1).isGlobalAddress() ||
664 MI->getOperand(1).isExternalSymbol())) {
666 printOp(O, MI->getOperand(1), RI);
668 if (Desc.TSFlags & X86II::PrintImplUses) {
669 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
670 O << ", " << RI.get(*p).Name;
676 case X86II::MRMDestReg: {
677 // There are two acceptable forms of MRMDestReg instructions, those with 2,
680 // 2 Operands: this is for things like mov that do not read a second input
682 // 3 Operands: in this form, the first two registers (the destination, and
683 // the first operand) should be the same, post register allocation. The 3rd
684 // operand is an additional input. This should be for things like add
687 // 4 Operands: This form is for instructions which are 3 operands forms, but
688 // have a constant argument as well.
690 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
691 assert(MI->getOperand(0).isRegister() &&
692 (MI->getNumOperands() == 2 ||
693 (isTwoAddr && MI->getOperand(1).isRegister() &&
694 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
695 (MI->getNumOperands() == 3 ||
696 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
697 && "Bad format for MRMDestReg!");
699 O << TII.getName(MI->getOpCode()) << " ";
700 printOp(O, MI->getOperand(0), RI);
702 printOp(O, MI->getOperand(1+isTwoAddr), RI);
703 if (MI->getNumOperands() == 4) {
705 printOp(O, MI->getOperand(3), RI);
711 case X86II::MRMDestMem: {
712 // These instructions are the same as MRMDestReg, but instead of having a
713 // register reference for the mod/rm field, it's a memory reference.
715 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
716 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
718 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
719 printMemReference(O, MI, 0, RI);
721 printOp(O, MI->getOperand(4), RI);
726 case X86II::MRMSrcReg: {
727 // There is a two forms that are acceptable for MRMSrcReg instructions,
728 // those with 3 and 2 operands:
730 // 3 Operands: in this form, the last register (the second input) is the
731 // ModR/M input. The first two operands should be the same, post register
732 // allocation. This is for things like: add r32, r/m32
734 // 2 Operands: this is for things like mov that do not read a second input
736 assert(MI->getOperand(0).isRegister() &&
737 MI->getOperand(1).isRegister() &&
738 (MI->getNumOperands() == 2 ||
739 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
740 && "Bad format for MRMSrcReg!");
741 if (MI->getNumOperands() == 3 &&
742 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
745 O << TII.getName(MI->getOpCode()) << " ";
746 printOp(O, MI->getOperand(0), RI);
748 printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
753 case X86II::MRMSrcMem: {
754 // These instructions are the same as MRMSrcReg, but instead of having a
755 // register reference for the mod/rm field, it's a memory reference.
757 assert(MI->getOperand(0).isRegister() &&
758 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
759 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
761 && "Bad format for MRMDestReg!");
762 if (MI->getNumOperands() == 2+4 &&
763 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
766 O << TII.getName(MI->getOpCode()) << " ";
767 printOp(O, MI->getOperand(0), RI);
768 O << ", " << sizePtr(Desc) << " ";
769 printMemReference(O, MI, MI->getNumOperands()-4, RI);
774 case X86II::MRMS0r: case X86II::MRMS1r:
775 case X86II::MRMS2r: case X86II::MRMS3r:
776 case X86II::MRMS4r: case X86II::MRMS5r:
777 case X86II::MRMS6r: case X86II::MRMS7r: {
778 // In this form, the following are valid formats:
780 // 2. cmp reg, immediate
781 // 2. shl rdest, rinput <implicit CL or 1>
782 // 3. sbb rdest, rinput, immediate [rdest = rinput]
784 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
785 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
786 assert((MI->getNumOperands() != 2 ||
787 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
788 "Bad MRMSxR format!");
789 assert((MI->getNumOperands() < 3 ||
790 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
791 "Bad MRMSxR format!");
793 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
794 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
797 O << TII.getName(MI->getOpCode()) << " ";
798 printOp(O, MI->getOperand(0), RI);
799 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
801 printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
803 if (Desc.TSFlags & X86II::PrintImplUses) {
804 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
805 O << ", " << RI.get(*p).Name;
813 case X86II::MRMS0m: case X86II::MRMS1m:
814 case X86II::MRMS2m: case X86II::MRMS3m:
815 case X86II::MRMS4m: case X86II::MRMS5m:
816 case X86II::MRMS6m: case X86II::MRMS7m: {
817 // In this form, the following are valid formats:
819 // 2. cmp [m], immediate
820 // 2. shl [m], rinput <implicit CL or 1>
821 // 3. sbb [m], immediate
823 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
824 isMem(MI, 0) && "Bad MRMSxM format!");
825 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
826 "Bad MRMSxM format!");
827 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
828 // is misassembled by gas in intel_syntax mode as its 32-bit
829 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
830 // opcode bytes instead of the instruction.
831 if (MI->getOpCode() == X86::FSTPr80) {
832 if ((MI->getOperand(0).getReg() == X86::ESP)
833 && (MI->getOperand(1).getImmedValue() == 1)) {
834 int DispVal = MI->getOperand(3).getImmedValue();
835 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
836 unsigned int val = (unsigned int) DispVal;
837 O << ".byte 0xdb, 0xbc, 0x24\n\t";
838 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
839 } else { // 1 byte disp.
840 unsigned char val = (unsigned char) DispVal;
841 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
842 << std::dec << "\t# ";
846 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
847 // misassembled by gas in intel_syntax mode as its 32-bit
848 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
849 // opcode bytes instead of the instruction.
850 if (MI->getOpCode() == X86::FLDr80) {
851 if ((MI->getOperand(0).getReg() == X86::ESP)
852 && (MI->getOperand(1).getImmedValue() == 1)) {
853 int DispVal = MI->getOperand(3).getImmedValue();
854 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
855 unsigned int val = (unsigned int) DispVal;
856 O << ".byte 0xdb, 0xac, 0x24\n\t";
857 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
858 } else { // 1 byte disp.
859 unsigned char val = (unsigned char) DispVal;
860 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
861 << std::dec << "\t# ";
865 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
866 // invalid opcode, saying "64 bit operations are only supported in
867 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
868 // [...]", which is wrong. Workaround: Output the raw opcode bytes
869 // instead of the instruction.
870 if (MI->getOpCode() == X86::FILDr64) {
871 if ((MI->getOperand(0).getReg() == X86::ESP)
872 && (MI->getOperand(1).getImmedValue() == 1)) {
873 int DispVal = MI->getOperand(3).getImmedValue();
874 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
875 unsigned int val = (unsigned int) DispVal;
876 O << ".byte 0xdf, 0xac, 0x24\n\t";
877 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
878 } else { // 1 byte disp.
879 unsigned char val = (unsigned char) DispVal;
880 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
881 << std::dec << "\t# ";
885 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
886 // an invalid opcode, saying "64 bit operations are only
887 // supported in 64 bit modes." libopcodes disassembles it as
888 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
889 // "fistpll DWORD PTR " instead, which is what libopcodes is
891 if (MI->getOpCode() == X86::FISTPr64) {
892 O << "fistpll DWORD PTR ";
893 printMemReference(O, MI, 0, RI);
894 if (MI->getNumOperands() == 5) {
896 printOp(O, MI->getOperand(4), RI);
901 O << TII.getName(MI->getOpCode()) << " ";
902 O << sizePtr(Desc) << " ";
903 printMemReference(O, MI, 0, RI);
904 if (MI->getNumOperands() == 5) {
906 printOp(O, MI->getOperand(4), RI);
913 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
917 bool Printer::doInitialization(Module &M)
919 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
920 // with no % decorations on register names.
921 O << "\t.intel_syntax noprefix\n";
923 // Ripped from CWriter:
924 // Calculate which global values have names that will collide when we throw
925 // away type information.
926 { // Scope to delete the FoundNames set when we are done with it...
927 std::set<std::string> FoundNames;
928 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
929 if (I->hasName()) // If the global has a name...
930 if (FoundNames.count(I->getName())) // And the name is already used
931 MangledGlobals.insert(I); // Mangle the name
933 FoundNames.insert(I->getName()); // Otherwise, keep track of name
935 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
936 if (I->hasName()) // If the global has a name...
937 if (FoundNames.count(I->getName())) // And the name is already used
938 MangledGlobals.insert(I); // Mangle the name
940 FoundNames.insert(I->getName()); // Otherwise, keep track of name
943 return false; // success
946 bool Printer::doFinalization(Module &M)
948 // Print out module-level global variables here.
949 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
950 std::string name(getValueName(I));
951 if (I->hasInitializer()) {
952 Constant *C = I->getInitializer();
954 O << "\t.globl " << name << "\n";
955 O << "\t.type " << name << ",@object\n";
956 O << "\t.size " << name << ","
957 << (unsigned)TD->getTypeSize(I->getType()) << "\n";
958 O << "\t.align " << (unsigned)TD->getTypeAlignment(C->getType()) << "\n";
959 O << name << ":\t\t\t\t\t#" << *C << "\n";
960 printConstantValueOnly (C);
962 O << "\t.globl " << name << "\n";
963 O << "\t.comm " << name << ", "
964 << (unsigned)TD->getTypeSize(I->getType()) << ", "
965 << (unsigned)TD->getTypeAlignment(I->getType()) << "\n";
968 MangledGlobals.clear();
969 return false; // success