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 -print-machineinstrs' on X86.
8 //===----------------------------------------------------------------------===//
11 #include "X86InstrInfo.h"
12 #include "llvm/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Module.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Support/Mangler.h"
21 #include "Support/Statistic.h"
22 #include "Support/StringExtras.h"
23 #include "Support/CommandLine.h"
26 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
28 // FIXME: This should be automatically picked up by autoconf from the C
30 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
31 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
33 struct Printer : public MachineFunctionPass {
34 /// Output stream on which we're printing assembly code.
38 /// Target machine description which we query for reg. names, data
43 /// Name-mangler for global names.
47 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
49 /// We name each basic block in a Function with a unique number, so
50 /// that we can consistently refer to them later. This is cleared
51 /// at the beginning of each call to runOnMachineFunction().
53 typedef std::map<const Value *, unsigned> ValueMapTy;
54 ValueMapTy NumberForBB;
56 /// Cache of mangled name for current function. This is
57 /// recalculated at the beginning of each call to
58 /// runOnMachineFunction().
60 std::string CurrentFnName;
62 virtual const char *getPassName() const {
63 return "X86 Assembly Printer";
66 void checkImplUses (const TargetInstrDescriptor &Desc);
67 void printMachineInstruction(const MachineInstr *MI);
68 void printOp(const MachineOperand &MO,
69 bool elideOffsetKeyword = false);
70 void printMemReference(const MachineInstr *MI, unsigned Op);
71 void printConstantPool(MachineConstantPool *MCP);
72 bool runOnMachineFunction(MachineFunction &F);
73 std::string ConstantExprToString(const ConstantExpr* CE);
74 std::string valToExprString(const Value* V);
75 bool doInitialization(Module &M);
76 bool doFinalization(Module &M);
77 void printConstantValueOnly(const Constant* CV);
78 void printSingleConstantValue(const Constant* CV);
80 } // end of anonymous namespace
82 /// createX86CodePrinterPass - Returns a pass that prints the X86
83 /// assembly code for a MachineFunction to the given output stream,
84 /// using the given target machine description. This should work
85 /// regardless of whether the function is in SSA form.
87 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
88 return new Printer(o, tm);
91 /// valToExprString - Helper function for ConstantExprToString().
92 /// Appends result to argument string S.
94 std::string Printer::valToExprString(const Value* V) {
97 if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
98 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
99 S += std::string(CB == ConstantBool::True ? "1" : "0");
100 else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
101 S += itostr(CI->getValue());
102 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
103 S += utostr(CI->getValue());
104 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
105 S += ftostr(CFP->getValue());
106 else if (isa<ConstantPointerNull>(CV))
108 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
109 S += valToExprString(CPR->getValue());
110 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
111 S += ConstantExprToString(CE);
114 } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
115 S += Mang->getValueName(GV);
121 assert(0 && "Cannot convert value to string");
122 S += "<illegal-value>";
127 /// ConstantExprToString - Convert a ConstantExpr to an asm expression
128 /// and return this as a string.
130 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
131 const TargetData &TD = TM.getTargetData();
132 switch(CE->getOpcode()) {
133 case Instruction::GetElementPtr:
134 { // generate a symbolic expression for the byte address
135 const Value* ptrVal = CE->getOperand(0);
136 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
137 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec))
138 return "(" + valToExprString(ptrVal) + ") + " + utostr(Offset);
140 return valToExprString(ptrVal);
143 case Instruction::Cast:
144 // Support only non-converting or widening casts for now, that is,
145 // ones that do not involve a change in value. This assertion is
146 // not a complete check.
148 Constant *Op = CE->getOperand(0);
149 const Type *OpTy = Op->getType(), *Ty = CE->getType();
150 assert(((isa<PointerType>(OpTy)
151 && (Ty == Type::LongTy || Ty == Type::ULongTy))
152 || (isa<PointerType>(Ty)
153 && (OpTy == Type::LongTy || OpTy == Type::ULongTy)))
154 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
155 && (OpTy->isLosslesslyConvertibleTo(Ty))))
156 && "FIXME: Don't yet support this kind of constant cast expr");
157 return "(" + valToExprString(Op) + ")";
160 case Instruction::Add:
161 return "(" + valToExprString(CE->getOperand(0)) + ") + ("
162 + valToExprString(CE->getOperand(1)) + ")";
165 assert(0 && "Unsupported operator in ConstantExprToString()");
170 /// printSingleConstantValue - Print a single constant value.
173 Printer::printSingleConstantValue(const Constant* CV)
175 assert(CV->getType() != Type::VoidTy &&
176 CV->getType() != Type::TypeTy &&
177 CV->getType() != Type::LabelTy &&
178 "Unexpected type for Constant");
180 assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
181 && "Aggregate types should be handled outside this function");
183 const Type *type = CV->getType();
185 switch(type->getPrimitiveID())
187 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
190 case Type::UShortTyID: case Type::ShortTyID:
193 case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
196 case Type::ULongTyID: case Type::LongTyID:
199 case Type::FloatTyID:
202 case Type::DoubleTyID:
205 case Type::ArrayTyID:
206 if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
207 (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
210 assert (0 && "Can't handle printing this type of array");
213 assert (0 && "Can't handle printing this type of thing");
218 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
220 // Constant expression built from operators, constants, and
222 O << ConstantExprToString(CE) << "\n";
224 else if (type->isPrimitiveType())
226 if (type->isFloatingPoint()) {
227 // FP Constants are printed as integer constants to avoid losing
229 double Val = cast<ConstantFP>(CV)->getValue();
230 if (type == Type::FloatTy) {
231 float FVal = (float)Val;
232 char *ProxyPtr = (char*)&FVal; // Abide by C TBAA rules
233 O << *(unsigned int*)ProxyPtr;
234 } else if (type == Type::DoubleTy) {
235 char *ProxyPtr = (char*)&Val; // Abide by C TBAA rules
236 O << *(uint64_t*)ProxyPtr;
238 assert(0 && "Unknown floating point type!");
241 O << "\t# " << type->getDescription() << " value: " << Val << "\n";
243 WriteAsOperand(O, CV, false, false) << "\n";
246 else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
248 // This is a constant address for a global variable or method.
249 // Use the name of the variable or method as the address value.
250 O << Mang->getValueName(CPR->getValue()) << "\n";
252 else if (isa<ConstantPointerNull>(CV))
254 // Null pointer value
259 assert(0 && "Unknown elementary type for constant");
263 /// isStringCompatible - Can we treat the specified array as a string?
264 /// Only if it is an array of ubytes or non-negative sbytes.
266 static bool isStringCompatible(const ConstantArray *CVA) {
267 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
268 if (ETy == Type::UByteTy) return true;
269 if (ETy != Type::SByteTy) return false;
271 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
272 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
278 /// toOctal - Convert the low order bits of X into an octal digit.
280 static inline char toOctal(int X) {
284 /// getAsCString - Return the specified array as a C compatible
285 /// string, only if the predicate isStringCompatible is true.
287 static std::string getAsCString(const ConstantArray *CVA) {
288 assert(isStringCompatible(CVA) && "Array is not string compatible!");
291 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
293 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
294 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
298 } else if (C == '\\') {
300 } else if (isprint(C)) {
304 case '\b': Result += "\\b"; break;
305 case '\f': Result += "\\f"; break;
306 case '\n': Result += "\\n"; break;
307 case '\r': Result += "\\r"; break;
308 case '\t': Result += "\\t"; break;
311 Result += toOctal(C >> 6);
312 Result += toOctal(C >> 3);
313 Result += toOctal(C >> 0);
322 // Print a constant value or values (it may be an aggregate).
323 // Uses printSingleConstantValue() to print each individual value.
324 void Printer::printConstantValueOnly(const Constant *CV) {
325 const TargetData &TD = TM.getTargetData();
327 if (CV->isNullValue()) {
328 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
329 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
330 if (isStringCompatible(CVA)) {
331 // print the string alone and return
332 O << "\t.ascii\t" << getAsCString(CVA) << "\n";
333 } else { // 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 = TD.getStructLayout(CVS->getType());
341 const std::vector<Use>& constValues = CVS->getValues();
342 unsigned sizeSoFar = 0;
343 for (unsigned i=0, N = constValues.size(); i < N; i++) {
344 const Constant* field = cast<Constant>(constValues[i].get());
346 // Check if padding is needed and insert one or more 0s.
347 unsigned fieldSize = TD.getTypeSize(field->getType());
348 unsigned padSize = ((i == N-1? cvsLayout->StructSize
349 : cvsLayout->MemberOffsets[i+1])
350 - cvsLayout->MemberOffsets[i]) - fieldSize;
351 sizeSoFar += fieldSize + padSize;
353 // Now print the actual field value
354 printConstantValueOnly(field);
356 // Insert the field padding unless it's zero bytes...
358 O << "\t.zero\t " << padSize << "\n";
360 assert(sizeSoFar == cvsLayout->StructSize &&
361 "Layout of constant struct may be incorrect!");
363 printSingleConstantValue(CV);
366 /// printConstantPool - Print to the current output stream assembly
367 /// representations of the constants in the constant pool MCP. This is
368 /// used to print out constants which have been "spilled to memory" by
369 /// the code generator.
371 void Printer::printConstantPool(MachineConstantPool *MCP) {
372 const std::vector<Constant*> &CP = MCP->getConstants();
373 const TargetData &TD = TM.getTargetData();
375 if (CP.empty()) return;
377 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
378 O << "\t.section .rodata\n";
379 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
381 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
383 printConstantValueOnly (CP[i]);
387 /// runOnMachineFunction - This uses the printMachineInstruction()
388 /// method to print assembly for each instruction.
390 bool Printer::runOnMachineFunction(MachineFunction &MF) {
391 // BBNumber is used here so that a given Printer will never give two
392 // BBs the same name. (If you have a better way, please let me know!)
393 static unsigned BBNumber = 0;
396 // What's my mangled name?
397 CurrentFnName = Mang->getValueName(MF.getFunction());
399 // Print out constants referenced by the function
400 printConstantPool(MF.getConstantPool());
402 // Print out labels for the function.
404 O << "\t.align 16\n";
405 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();
452 void Printer::printOp(const MachineOperand &MO,
453 bool elideOffsetKeyword /* = false */) {
454 const MRegisterInfo &RI = *TM.getRegisterInfo();
455 switch (MO.getType()) {
456 case MachineOperand::MO_VirtualRegister:
457 if (Value *V = MO.getVRegValueOrNull()) {
458 O << "<" << V->getName() << ">";
462 case MachineOperand::MO_MachineRegister:
463 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
464 // Bug Workaround: See note in Printer::doInitialization about %.
465 O << "%" << RI.get(MO.getReg()).Name;
467 O << "%reg" << MO.getReg();
470 case MachineOperand::MO_SignExtendedImmed:
471 case MachineOperand::MO_UnextendedImmed:
472 O << (int)MO.getImmedValue();
474 case MachineOperand::MO_PCRelativeDisp: {
475 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
476 assert (i != NumberForBB.end()
477 && "Could not find a BB in the NumberForBB map!");
478 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
481 case MachineOperand::MO_GlobalAddress:
482 if (!elideOffsetKeyword)
484 O << Mang->getValueName(MO.getGlobal());
486 case MachineOperand::MO_ExternalSymbol:
487 O << MO.getSymbolName();
490 O << "<unknown operand type>"; return;
494 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
495 switch (Desc.TSFlags & X86II::ArgMask) {
496 default: assert(0 && "Unknown arg size!");
497 case X86II::Arg8: return "BYTE PTR";
498 case X86II::Arg16: return "WORD PTR";
499 case X86II::Arg32: return "DWORD PTR";
500 case X86II::Arg64: return "QWORD PTR";
501 case X86II::ArgF32: return "DWORD PTR";
502 case X86II::ArgF64: return "QWORD PTR";
503 case X86II::ArgF80: return "XWORD PTR";
507 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
508 assert(isMem(MI, Op) && "Invalid memory reference!");
510 if (MI->getOperand(Op).isFrameIndex()) {
511 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
512 if (MI->getOperand(Op+3).getImmedValue())
513 O << " + " << MI->getOperand(Op+3).getImmedValue();
516 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
517 O << "[.CPI" << CurrentFnName << "_"
518 << MI->getOperand(Op).getConstantPoolIndex();
519 if (MI->getOperand(Op+3).getImmedValue())
520 O << " + " << MI->getOperand(Op+3).getImmedValue();
525 const MachineOperand &BaseReg = MI->getOperand(Op);
526 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
527 const MachineOperand &IndexReg = MI->getOperand(Op+2);
528 int DispVal = MI->getOperand(Op+3).getImmedValue();
531 bool NeedPlus = false;
532 if (BaseReg.getReg()) {
537 if (IndexReg.getReg()) {
538 if (NeedPlus) O << " + ";
540 O << ScaleVal << "*";
558 /// checkImplUses - Emit the implicit-use registers for the
559 /// instruction described by DESC, if its PrintImplUses flag is set.
561 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
562 const MRegisterInfo &RI = *TM.getRegisterInfo();
563 if (Desc.TSFlags & X86II::PrintImplUses) {
564 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
565 // Bug Workaround: See note in Printer::doInitialization about %.
566 O << ", %" << RI.get(*p).Name;
571 /// printMachineInstruction -- Print out a single X86 LLVM instruction
572 /// MI in Intel syntax to the current output stream.
574 void Printer::printMachineInstruction(const MachineInstr *MI) {
575 unsigned Opcode = MI->getOpcode();
576 const TargetInstrInfo &TII = TM.getInstrInfo();
577 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).opIsDefOnly() ||
600 MI->getOperand(0).opIsDefAndUse())) {
601 printOp(MI->getOperand(0));
605 O << TII.getName(MI->getOpcode());
607 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
609 if (MI->getOperand(i).opIsDefOnly() ||
610 MI->getOperand(i).opIsDefAndUse()) O << "*";
611 printOp(MI->getOperand(i));
612 if (MI->getOperand(i).opIsDefOnly() ||
613 MI->getOperand(i).opIsDefAndUse()) O << "*";
620 // The accepted forms of Raw instructions are:
621 // 1. nop - No operand required
622 // 2. jmp foo - PC relative displacement operand
623 // 3. call bar - GlobalAddress Operand or External Symbol Operand
625 assert(MI->getNumOperands() == 0 ||
626 (MI->getNumOperands() == 1 &&
627 (MI->getOperand(0).isPCRelativeDisp() ||
628 MI->getOperand(0).isGlobalAddress() ||
629 MI->getOperand(0).isExternalSymbol())) &&
630 "Illegal raw instruction!");
631 O << TII.getName(MI->getOpcode()) << " ";
633 if (MI->getNumOperands() == 1) {
634 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
639 case X86II::AddRegFrm: {
640 // There are currently two forms of acceptable AddRegFrm instructions.
641 // Either the instruction JUST takes a single register (like inc, dec, etc),
642 // or it takes a register and an immediate of the same size as the register
643 // (move immediate f.e.). Note that this immediate value might be stored as
644 // an LLVM value, to represent, for example, loading the address of a global
645 // into a register. The initial register might be duplicated if this is a
646 // M_2_ADDR_REG instruction
648 assert(MI->getOperand(0).isRegister() &&
649 (MI->getNumOperands() == 1 ||
650 (MI->getNumOperands() == 2 &&
651 (MI->getOperand(1).getVRegValueOrNull() ||
652 MI->getOperand(1).isImmediate() ||
653 MI->getOperand(1).isRegister() ||
654 MI->getOperand(1).isGlobalAddress() ||
655 MI->getOperand(1).isExternalSymbol()))) &&
656 "Illegal form for AddRegFrm instruction!");
658 unsigned Reg = MI->getOperand(0).getReg();
660 O << TII.getName(MI->getOpCode()) << " ";
661 printOp(MI->getOperand(0));
662 if (MI->getNumOperands() == 2 &&
663 (!MI->getOperand(1).isRegister() ||
664 MI->getOperand(1).getVRegValueOrNull() ||
665 MI->getOperand(1).isGlobalAddress() ||
666 MI->getOperand(1).isExternalSymbol())) {
668 printOp(MI->getOperand(1));
674 case X86II::MRMDestReg: {
675 // There are two acceptable forms of MRMDestReg instructions, those with 2,
678 // 2 Operands: this is for things like mov that do not read a second input
680 // 3 Operands: in this form, the first two registers (the destination, and
681 // the first operand) should be the same, post register allocation. The 3rd
682 // operand is an additional input. This should be for things like add
685 // 4 Operands: This form is for instructions which are 3 operands forms, but
686 // have a constant argument as well.
688 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
689 assert(MI->getOperand(0).isRegister() &&
690 (MI->getNumOperands() == 2 ||
691 (isTwoAddr && MI->getOperand(1).isRegister() &&
692 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
693 (MI->getNumOperands() == 3 ||
694 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
695 && "Bad format for MRMDestReg!");
697 O << TII.getName(MI->getOpCode()) << " ";
698 printOp(MI->getOperand(0));
700 printOp(MI->getOperand(1+isTwoAddr));
701 if (MI->getNumOperands() == 4) {
703 printOp(MI->getOperand(3));
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) && MI->getNumOperands() == 4+1 &&
714 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
716 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
717 printMemReference(MI, 0);
719 printOp(MI->getOperand(4));
724 case X86II::MRMSrcReg: {
725 // There is a two forms that are acceptable for MRMSrcReg instructions,
726 // those with 3 and 2 operands:
728 // 3 Operands: in this form, the last register (the second input) is the
729 // ModR/M input. The first two operands should be the same, post register
730 // allocation. This is for things like: add r32, r/m32
732 // 2 Operands: this is for things like mov that do not read a second input
734 assert(MI->getOperand(0).isRegister() &&
735 MI->getOperand(1).isRegister() &&
736 (MI->getNumOperands() == 2 ||
737 (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
738 && "Bad format for MRMSrcReg!");
739 if (MI->getNumOperands() == 3 &&
740 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
743 O << TII.getName(MI->getOpCode()) << " ";
744 printOp(MI->getOperand(0));
746 printOp(MI->getOperand(MI->getNumOperands()-1));
751 case X86II::MRMSrcMem: {
752 // These instructions are the same as MRMSrcReg, but instead of having a
753 // register reference for the mod/rm field, it's a memory reference.
755 assert(MI->getOperand(0).isRegister() &&
756 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
757 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
759 && "Bad format for MRMDestReg!");
760 if (MI->getNumOperands() == 2+4 &&
761 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
764 O << TII.getName(MI->getOpCode()) << " ";
765 printOp(MI->getOperand(0));
766 O << ", " << sizePtr(Desc) << " ";
767 printMemReference(MI, MI->getNumOperands()-4);
772 case X86II::MRMS0r: case X86II::MRMS1r:
773 case X86II::MRMS2r: case X86II::MRMS3r:
774 case X86II::MRMS4r: case X86II::MRMS5r:
775 case X86II::MRMS6r: case X86II::MRMS7r: {
776 // In this form, the following are valid formats:
778 // 2. cmp reg, immediate
779 // 2. shl rdest, rinput <implicit CL or 1>
780 // 3. sbb rdest, rinput, immediate [rdest = rinput]
782 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
783 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
784 assert((MI->getNumOperands() != 2 ||
785 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
786 "Bad MRMSxR format!");
787 assert((MI->getNumOperands() < 3 ||
788 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
789 "Bad MRMSxR format!");
791 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
792 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
795 O << TII.getName(MI->getOpCode()) << " ";
796 printOp(MI->getOperand(0));
797 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
799 printOp(MI->getOperand(MI->getNumOperands()-1));
807 case X86II::MRMS0m: case X86II::MRMS1m:
808 case X86II::MRMS2m: case X86II::MRMS3m:
809 case X86II::MRMS4m: case X86II::MRMS5m:
810 case X86II::MRMS6m: case X86II::MRMS7m: {
811 // In this form, the following are valid formats:
813 // 2. cmp [m], immediate
814 // 2. shl [m], rinput <implicit CL or 1>
815 // 3. sbb [m], immediate
817 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
818 isMem(MI, 0) && "Bad MRMSxM format!");
819 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
820 "Bad MRMSxM format!");
821 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
822 // is misassembled by gas in intel_syntax mode as its 32-bit
823 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
824 // opcode bytes instead of the instruction.
825 if (MI->getOpCode() == X86::FSTPr80) {
826 if ((MI->getOperand(0).getReg() == X86::ESP)
827 && (MI->getOperand(1).getImmedValue() == 1)) {
828 int DispVal = MI->getOperand(3).getImmedValue();
829 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
830 unsigned int val = (unsigned int) DispVal;
831 O << ".byte 0xdb, 0xbc, 0x24\n\t";
832 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
833 } else { // 1 byte disp.
834 unsigned char val = (unsigned char) DispVal;
835 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
836 << std::dec << "\t# ";
840 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
841 // misassembled by gas in intel_syntax mode as its 32-bit
842 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
843 // opcode bytes instead of the instruction.
844 if (MI->getOpCode() == X86::FLDr80) {
845 if ((MI->getOperand(0).getReg() == X86::ESP)
846 && (MI->getOperand(1).getImmedValue() == 1)) {
847 int DispVal = MI->getOperand(3).getImmedValue();
848 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
849 unsigned int val = (unsigned int) DispVal;
850 O << ".byte 0xdb, 0xac, 0x24\n\t";
851 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
852 } else { // 1 byte disp.
853 unsigned char val = (unsigned char) DispVal;
854 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
855 << std::dec << "\t# ";
859 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
860 // invalid opcode, saying "64 bit operations are only supported in
861 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
862 // [...]", which is wrong. Workaround: Output the raw opcode bytes
863 // instead of the instruction.
864 if (MI->getOpCode() == X86::FILDr64) {
865 if ((MI->getOperand(0).getReg() == X86::ESP)
866 && (MI->getOperand(1).getImmedValue() == 1)) {
867 int DispVal = MI->getOperand(3).getImmedValue();
868 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
869 unsigned int val = (unsigned int) DispVal;
870 O << ".byte 0xdf, 0xac, 0x24\n\t";
871 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
872 } else { // 1 byte disp.
873 unsigned char val = (unsigned char) DispVal;
874 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
875 << std::dec << "\t# ";
879 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
880 // an invalid opcode, saying "64 bit operations are only
881 // supported in 64 bit modes." libopcodes disassembles it as
882 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
883 // "fistpll DWORD PTR " instead, which is what libopcodes is
885 if (MI->getOpCode() == X86::FISTPr64) {
886 O << "fistpll DWORD PTR ";
887 printMemReference(MI, 0);
888 if (MI->getNumOperands() == 5) {
890 printOp(MI->getOperand(4));
895 O << TII.getName(MI->getOpCode()) << " ";
896 O << sizePtr(Desc) << " ";
897 printMemReference(MI, 0);
898 if (MI->getNumOperands() == 5) {
900 printOp(MI->getOperand(4));
907 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
911 bool Printer::doInitialization(Module &M) {
912 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
914 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
915 // instruction as a reference to the register named sp, and if you try to
916 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
917 // before being looked up in the symbol table. This creates spurious
918 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
919 // mode, and decorate all register names with percent signs.
920 O << "\t.intel_syntax\n";
921 Mang = new Mangler(M, EmitCygwin);
922 return false; // success
925 // SwitchSection - Switch to the specified section of the executable if we are
926 // not already in it!
928 static void SwitchSection(std::ostream &OS, std::string &CurSection,
929 const char *NewSection) {
930 if (CurSection != NewSection) {
931 CurSection = NewSection;
932 if (!CurSection.empty())
933 OS << "\t" << NewSection << "\n";
937 bool Printer::doFinalization(Module &M) {
938 const TargetData &TD = TM.getTargetData();
939 std::string CurSection;
941 // Print out module-level global variables here.
942 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
943 if (I->hasInitializer()) { // External global require no code
945 std::string name = Mang->getValueName(I);
946 Constant *C = I->getInitializer();
947 unsigned Size = TD.getTypeSize(C->getType());
948 unsigned Align = TD.getTypeAlignment(C->getType());
950 if (C->isNullValue() &&
951 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
952 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
953 SwitchSection(O, CurSection, ".data");
954 if (I->hasInternalLinkage())
955 O << "\t.local " << name << "\n";
957 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
958 << "," << (unsigned)TD.getTypeAlignment(C->getType());
960 WriteAsOperand(O, I, true, true, &M);
963 switch (I->getLinkage()) {
964 case GlobalValue::LinkOnceLinkage:
965 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
966 // Nonnull linkonce -> weak
967 O << "\t.weak " << name << "\n";
968 SwitchSection(O, CurSection, "");
969 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
972 case GlobalValue::AppendingLinkage:
973 // FIXME: appending linkage variables should go into a section of
974 // their name or something. For now, just emit them as external.
975 case GlobalValue::ExternalLinkage:
976 // If external or appending, declare as a global symbol
977 O << "\t.globl " << name << "\n";
979 case GlobalValue::InternalLinkage:
980 if (C->isNullValue())
981 SwitchSection(O, CurSection, ".bss");
983 SwitchSection(O, CurSection, ".data");
987 O << "\t.align " << Align << "\n";
988 O << "\t.type " << name << ",@object\n";
989 O << "\t.size " << name << "," << Size << "\n";
990 O << name << ":\t\t\t\t# ";
991 WriteAsOperand(O, I, true, true, &M);
993 WriteAsOperand(O, C, false, false, &M);
995 printConstantValueOnly(C);
1000 return false; // success