1 //===-- X86/Printer.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/Target/TargetMachine.h"
29 #include "llvm/Support/Mangler.h"
30 #include "Support/Statistic.h"
31 #include "Support/StringExtras.h"
32 #include "Support/CommandLine.h"
36 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
38 // FIXME: This should be automatically picked up by autoconf from the C
40 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
41 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
43 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
44 GasBugWorkaroundEmitter(std::ostream& o)
45 : O(o), OldFlags(O.flags()), firstByte(true) {
49 ~GasBugWorkaroundEmitter() {
54 virtual void emitByte(unsigned char B) {
55 if (!firstByte) O << "\n\t";
57 O << ".byte 0x" << (unsigned) B;
60 // These should never be called
61 virtual void emitWord(unsigned W) { assert(0); }
62 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
63 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
64 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
65 virtual uint64_t getCurrentPCValue() { abort(); }
66 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
70 std::ios::fmtflags OldFlags;
74 struct Printer : public MachineFunctionPass {
75 /// Output stream on which we're printing assembly code.
79 /// Target machine description which we query for reg. names, data
84 /// Name-mangler for global names.
88 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
90 /// We name each basic block in a Function with a unique number, so
91 /// that we can consistently refer to them later. This is cleared
92 /// at the beginning of each call to runOnMachineFunction().
94 typedef std::map<const Value *, unsigned> ValueMapTy;
95 ValueMapTy NumberForBB;
97 /// Cache of mangled name for current function. This is
98 /// recalculated at the beginning of each call to
99 /// runOnMachineFunction().
101 std::string CurrentFnName;
103 virtual const char *getPassName() const {
104 return "X86 Assembly Printer";
107 void printImplUsesBefore(const TargetInstrDescriptor &Desc);
108 void printImplUsesAfter(const TargetInstrDescriptor &Desc);
109 void printMachineInstruction(const MachineInstr *MI);
110 void printOp(const MachineOperand &MO,
111 bool elideOffsetKeyword = false);
112 void printMemReference(const MachineInstr *MI, unsigned Op);
113 void printConstantPool(MachineConstantPool *MCP);
114 bool runOnMachineFunction(MachineFunction &F);
115 bool doInitialization(Module &M);
116 bool doFinalization(Module &M);
117 void emitGlobalConstant(const Constant* CV);
118 void emitConstantValueOnly(const Constant *CV);
120 } // end of anonymous namespace
122 /// createX86CodePrinterPass - Returns a pass that prints the X86
123 /// assembly code for a MachineFunction to the given output stream,
124 /// using the given target machine description. This should work
125 /// regardless of whether the function is in SSA form.
127 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
128 return new Printer(o, tm);
131 /// toOctal - Convert the low order bits of X into an octal digit.
133 static inline char toOctal(int X) {
137 /// getAsCString - Return the specified array as a C compatible
138 /// string, only if the predicate isStringCompatible is true.
140 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
141 assert(CVA->isString() && "Array is not string compatible!");
144 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
145 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
149 } else if (C == '\\') {
151 } else if (isprint(C)) {
155 case '\b': O << "\\b"; break;
156 case '\f': O << "\\f"; break;
157 case '\n': O << "\\n"; break;
158 case '\r': O << "\\r"; break;
159 case '\t': O << "\\t"; break;
162 O << toOctal(C >> 6);
163 O << toOctal(C >> 3);
164 O << toOctal(C >> 0);
172 // Print out the specified constant, without a storage class. Only the
173 // constants valid in constant expressions can occur here.
174 void Printer::emitConstantValueOnly(const Constant *CV) {
175 if (CV->isNullValue())
177 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
178 assert(CB == ConstantBool::True);
180 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
181 if (((CI->getValue() << 32) >> 32) == CI->getValue())
184 O << (unsigned long long)CI->getValue();
185 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
187 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
188 // This is a constant address for a global variable or function. Use the
189 // name of the variable or function as the address value.
190 O << Mang->getValueName(CPR->getValue());
191 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
192 const TargetData &TD = TM.getTargetData();
193 switch(CE->getOpcode()) {
194 case Instruction::GetElementPtr: {
195 // generate a symbolic expression for the byte address
196 const Constant *ptrVal = CE->getOperand(0);
197 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
198 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
200 emitConstantValueOnly(ptrVal);
201 O << ") + " << Offset;
203 emitConstantValueOnly(ptrVal);
207 case Instruction::Cast: {
208 // Support only non-converting or widening casts for now, that is, ones
209 // that do not involve a change in value. This assertion is really gross,
210 // and may not even be a complete check.
211 Constant *Op = CE->getOperand(0);
212 const Type *OpTy = Op->getType(), *Ty = CE->getType();
214 // Remember, kids, pointers on x86 can be losslessly converted back and
215 // forth into 32-bit or wider integers, regardless of signedness. :-P
216 assert(((isa<PointerType>(OpTy)
217 && (Ty == Type::LongTy || Ty == Type::ULongTy
218 || Ty == Type::IntTy || Ty == Type::UIntTy))
219 || (isa<PointerType>(Ty)
220 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
221 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
222 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
223 && OpTy->isLosslesslyConvertibleTo(Ty))))
224 && "FIXME: Don't yet support this kind of constant cast expr");
226 emitConstantValueOnly(Op);
230 case Instruction::Add:
232 emitConstantValueOnly(CE->getOperand(0));
234 emitConstantValueOnly(CE->getOperand(1));
238 assert(0 && "Unsupported operator!");
241 assert(0 && "Unknown constant value!");
245 // Print a constant value or values, with the appropriate storage class as a
247 void Printer::emitGlobalConstant(const Constant *CV) {
248 const TargetData &TD = TM.getTargetData();
250 if (CV->isNullValue()) {
251 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
253 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
254 if (CVA->isString()) {
256 printAsCString(O, CVA);
258 } else { // Not a string. Print the values in successive locations
259 const std::vector<Use> &constValues = CVA->getValues();
260 for (unsigned i=0; i < constValues.size(); i++)
261 emitGlobalConstant(cast<Constant>(constValues[i].get()));
264 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
265 // Print the fields in successive locations. Pad to align if needed!
266 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
267 const std::vector<Use>& constValues = CVS->getValues();
268 unsigned sizeSoFar = 0;
269 for (unsigned i=0, N = constValues.size(); i < N; i++) {
270 const Constant* field = cast<Constant>(constValues[i].get());
272 // Check if padding is needed and insert one or more 0s.
273 unsigned fieldSize = TD.getTypeSize(field->getType());
274 unsigned padSize = ((i == N-1? cvsLayout->StructSize
275 : cvsLayout->MemberOffsets[i+1])
276 - cvsLayout->MemberOffsets[i]) - fieldSize;
277 sizeSoFar += fieldSize + padSize;
279 // Now print the actual field value
280 emitGlobalConstant(field);
282 // Insert the field padding unless it's zero bytes...
284 O << "\t.zero\t " << padSize << "\n";
286 assert(sizeSoFar == cvsLayout->StructSize &&
287 "Layout of constant struct may be incorrect!");
289 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
290 // FP Constants are printed as integer constants to avoid losing
292 double Val = CFP->getValue();
293 switch (CFP->getType()->getPrimitiveID()) {
294 default: assert(0 && "Unknown floating point type!");
295 case Type::FloatTyID: {
296 union FU { // Abide by C TBAA rules
301 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
304 case Type::DoubleTyID: {
305 union DU { // Abide by C TBAA rules
310 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
316 const Type *type = CV->getType();
318 switch (type->getPrimitiveID()) {
319 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
322 case Type::UShortTyID: case Type::ShortTyID:
325 case Type::FloatTyID: case Type::PointerTyID:
326 case Type::UIntTyID: case Type::IntTyID:
329 case Type::DoubleTyID:
330 case Type::ULongTyID: case Type::LongTyID:
334 assert (0 && "Can't handle printing this type of thing");
338 emitConstantValueOnly(CV);
342 /// printConstantPool - Print to the current output stream assembly
343 /// representations of the constants in the constant pool MCP. This is
344 /// used to print out constants which have been "spilled to memory" by
345 /// the code generator.
347 void Printer::printConstantPool(MachineConstantPool *MCP) {
348 const std::vector<Constant*> &CP = MCP->getConstants();
349 const TargetData &TD = TM.getTargetData();
351 if (CP.empty()) return;
353 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
354 O << "\t.section .rodata\n";
355 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
357 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
359 emitGlobalConstant(CP[i]);
363 /// runOnMachineFunction - This uses the printMachineInstruction()
364 /// method to print assembly for each instruction.
366 bool Printer::runOnMachineFunction(MachineFunction &MF) {
367 // BBNumber is used here so that a given Printer will never give two
368 // BBs the same name. (If you have a better way, please let me know!)
369 static unsigned BBNumber = 0;
372 // What's my mangled name?
373 CurrentFnName = Mang->getValueName(MF.getFunction());
375 // Print out constants referenced by the function
376 printConstantPool(MF.getConstantPool());
378 // Print out labels for the function.
380 O << "\t.align 16\n";
381 O << "\t.globl\t" << CurrentFnName << "\n";
383 O << "\t.type\t" << CurrentFnName << ", @function\n";
384 O << CurrentFnName << ":\n";
386 // Number each basic block so that we can consistently refer to them
387 // in PC-relative references.
389 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
391 NumberForBB[I->getBasicBlock()] = BBNumber++;
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" << NumberForBB[I->getBasicBlock()] << ":\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 Printer::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_PCRelativeDisp: {
451 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
452 assert (i != NumberForBB.end()
453 && "Could not find a BB in the NumberForBB map!");
454 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
457 case MachineOperand::MO_GlobalAddress:
458 if (!elideOffsetKeyword)
460 O << Mang->getValueName(MO.getGlobal());
462 case MachineOperand::MO_ExternalSymbol:
463 O << MO.getSymbolName();
466 O << "<unknown operand type>"; return;
470 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
471 switch (Desc.TSFlags & X86II::MemMask) {
472 default: assert(0 && "Unknown arg size!");
473 case X86II::Mem8: return "BYTE PTR";
474 case X86II::Mem16: return "WORD PTR";
475 case X86II::Mem32: return "DWORD PTR";
476 case X86II::Mem64: return "QWORD PTR";
477 case X86II::Mem80: return "XWORD PTR";
481 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
482 assert(isMem(MI, Op) && "Invalid memory reference!");
484 if (MI->getOperand(Op).isFrameIndex()) {
485 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
486 if (MI->getOperand(Op+3).getImmedValue())
487 O << " + " << MI->getOperand(Op+3).getImmedValue();
490 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
491 O << "[.CPI" << CurrentFnName << "_"
492 << MI->getOperand(Op).getConstantPoolIndex();
493 if (MI->getOperand(Op+3).getImmedValue())
494 O << " + " << MI->getOperand(Op+3).getImmedValue();
499 const MachineOperand &BaseReg = MI->getOperand(Op);
500 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
501 const MachineOperand &IndexReg = MI->getOperand(Op+2);
502 int DispVal = MI->getOperand(Op+3).getImmedValue();
505 bool NeedPlus = false;
506 if (BaseReg.getReg()) {
511 if (IndexReg.getReg()) {
512 if (NeedPlus) O << " + ";
514 O << ScaleVal << "*";
533 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
534 /// described by DESC, if its PrintImplUsesBefore flag is set.
536 void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
537 const MRegisterInfo &RI = *TM.getRegisterInfo();
538 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
539 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
540 // Bug Workaround: See note in Printer::doInitialization about %.
541 O << "%" << RI.get(*p).Name << ", ";
546 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
547 /// described by DESC, if its PrintImplUsesAfter flag is set.
549 void Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc) {
550 const MRegisterInfo &RI = *TM.getRegisterInfo();
551 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
552 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
553 // Bug Workaround: See note in Printer::doInitialization about %.
554 O << ", %" << RI.get(*p).Name;
559 /// printMachineInstruction -- Print out a single X86 LLVM instruction
560 /// MI in Intel syntax to the current output stream.
562 void Printer::printMachineInstruction(const MachineInstr *MI) {
563 unsigned Opcode = MI->getOpcode();
564 const TargetInstrInfo &TII = TM.getInstrInfo();
565 const TargetInstrDescriptor &Desc = TII.get(Opcode);
568 switch (Desc.TSFlags & X86II::FormMask) {
570 // Print pseudo-instructions as comments; either they should have been
571 // turned into real instructions by now, or they don't need to be
572 // seen by the assembler (e.g., IMPLICIT_USEs.)
574 if (Opcode == X86::PHI) {
575 printOp(MI->getOperand(0));
577 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
578 if (i != 1) O << ", ";
580 printOp(MI->getOperand(i));
582 printOp(MI->getOperand(i+1));
587 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
588 printOp(MI->getOperand(0));
592 O << TII.getName(MI->getOpcode());
594 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
596 if (MI->getOperand(i).isDef()) O << "*";
597 printOp(MI->getOperand(i));
598 if (MI->getOperand(i).isDef()) O << "*";
605 // The accepted forms of Raw instructions are:
606 // 1. nop - No operand required
607 // 2. jmp foo - PC relative displacement operand
608 // 3. call bar - GlobalAddress Operand or External Symbol Operand
610 assert(MI->getNumOperands() == 0 ||
611 (MI->getNumOperands() == 1 &&
612 (MI->getOperand(0).isPCRelativeDisp() ||
613 MI->getOperand(0).isGlobalAddress() ||
614 MI->getOperand(0).isExternalSymbol())) &&
615 "Illegal raw instruction!");
616 O << TII.getName(MI->getOpcode()) << " ";
618 if (MI->getNumOperands() == 1) {
619 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
624 case X86II::AddRegFrm: {
625 // There are currently two forms of acceptable AddRegFrm instructions.
626 // Either the instruction JUST takes a single register (like inc, dec, etc),
627 // or it takes a register and an immediate of the same size as the register
628 // (move immediate f.e.). Note that this immediate value might be stored as
629 // an LLVM value, to represent, for example, loading the address of a global
630 // into a register. The initial register might be duplicated if this is a
631 // M_2_ADDR_REG instruction
633 assert(MI->getOperand(0).isRegister() &&
634 (MI->getNumOperands() == 1 ||
635 (MI->getNumOperands() == 2 &&
636 (MI->getOperand(1).getVRegValueOrNull() ||
637 MI->getOperand(1).isImmediate() ||
638 MI->getOperand(1).isRegister() ||
639 MI->getOperand(1).isGlobalAddress() ||
640 MI->getOperand(1).isExternalSymbol()))) &&
641 "Illegal form for AddRegFrm instruction!");
643 unsigned Reg = MI->getOperand(0).getReg();
645 O << TII.getName(MI->getOpcode()) << " ";
647 printImplUsesBefore(Desc); // fcmov*
649 printOp(MI->getOperand(0));
650 if (MI->getNumOperands() == 2 &&
651 (!MI->getOperand(1).isRegister() ||
652 MI->getOperand(1).getVRegValueOrNull() ||
653 MI->getOperand(1).isGlobalAddress() ||
654 MI->getOperand(1).isExternalSymbol())) {
656 printOp(MI->getOperand(1));
658 printImplUsesAfter(Desc);
662 case X86II::MRMDestReg: {
663 // There are three forms of MRMDestReg instructions, those with 2
666 // 2 Operands: this is for things like mov that do not read a
669 // 2 Operands: two address instructions which def&use the first
670 // argument and use the second as input.
672 // 3 Operands: in this form, two address instructions are the same
673 // as in 2 but have a constant argument as well.
675 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
676 assert(MI->getOperand(0).isRegister() &&
677 (MI->getNumOperands() == 2 ||
678 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
679 && "Bad format for MRMDestReg!");
681 O << TII.getName(MI->getOpcode()) << " ";
682 printOp(MI->getOperand(0));
684 printOp(MI->getOperand(1));
685 if (MI->getNumOperands() == 3) {
687 printOp(MI->getOperand(2));
689 printImplUsesAfter(Desc);
694 case X86II::MRMDestMem: {
695 // These instructions are the same as MRMDestReg, but instead of having a
696 // register reference for the mod/rm field, it's a memory reference.
698 assert(isMem(MI, 0) &&
699 (MI->getNumOperands() == 4+1 ||
700 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
701 && "Bad format for MRMDestMem!");
703 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
704 printMemReference(MI, 0);
706 printOp(MI->getOperand(4));
707 if (MI->getNumOperands() == 4+2) {
709 printOp(MI->getOperand(5));
711 printImplUsesAfter(Desc);
716 case X86II::MRMSrcReg: {
717 // There are three forms that are acceptable for MRMSrcReg
718 // instructions, those with 2 or 3 operands:
720 // 2 Operands: this is for things like mov that do not read a
723 // 2 Operands: in this form, the last register is the ModR/M
724 // input. The first operand is a def&use. This is for things
725 // like: add r32, r/m32
727 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
728 // for instructions like the IMULrri instructions.
731 assert(MI->getOperand(0).isRegister() &&
732 MI->getOperand(1).isRegister() &&
733 (MI->getNumOperands() == 2 ||
734 (MI->getNumOperands() == 3 &&
735 (MI->getOperand(2).isImmediate())))
736 && "Bad format for MRMSrcReg!");
738 O << TII.getName(MI->getOpcode()) << " ";
739 printOp(MI->getOperand(0));
741 printOp(MI->getOperand(1));
742 if (MI->getNumOperands() == 3) {
744 printOp(MI->getOperand(2));
750 case X86II::MRMSrcMem: {
751 // These instructions are the same as MRMSrcReg, but instead of having a
752 // register reference for the mod/rm field, it's a memory reference.
754 assert(MI->getOperand(0).isRegister() &&
755 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
756 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
757 && "Bad format for MRMSrcMem!");
758 O << TII.getName(MI->getOpcode()) << " ";
759 printOp(MI->getOperand(0));
760 O << ", " << sizePtr(Desc) << " ";
761 printMemReference(MI, 1);
762 if (MI->getNumOperands() == 2+4) {
764 printOp(MI->getOperand(5));
770 case X86II::MRM0r: case X86II::MRM1r:
771 case X86II::MRM2r: case X86II::MRM3r:
772 case X86II::MRM4r: case X86II::MRM5r:
773 case X86II::MRM6r: case X86II::MRM7r: {
774 // In this form, the following are valid formats:
776 // 2. cmp reg, immediate
777 // 2. shl rdest, rinput <implicit CL or 1>
778 // 3. sbb rdest, rinput, immediate [rdest = rinput]
780 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
781 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
782 assert((MI->getNumOperands() != 2 ||
783 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
784 "Bad MRMSxR format!");
785 assert((MI->getNumOperands() < 3 ||
786 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
787 "Bad MRMSxR format!");
789 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
790 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
793 O << TII.getName(MI->getOpcode()) << " ";
794 printOp(MI->getOperand(0));
795 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
797 printOp(MI->getOperand(MI->getNumOperands()-1));
799 printImplUsesAfter(Desc);
805 case X86II::MRM0m: case X86II::MRM1m:
806 case X86II::MRM2m: case X86II::MRM3m:
807 case X86II::MRM4m: case X86II::MRM5m:
808 case X86II::MRM6m: case X86II::MRM7m: {
809 // In this form, the following are valid formats:
811 // 2. cmp [m], immediate
812 // 2. shl [m], rinput <implicit CL or 1>
813 // 3. sbb [m], immediate
815 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
816 isMem(MI, 0) && "Bad MRMSxM format!");
817 assert((MI->getNumOperands() != 5 ||
818 (MI->getOperand(4).isImmediate() ||
819 MI->getOperand(4).isGlobalAddress())) &&
820 "Bad MRMSxM format!");
822 const MachineOperand &Op3 = MI->getOperand(3);
826 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
827 // is misassembled by gas in intel_syntax mode as its 32-bit
828 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
829 // opcode bytes instead of the instruction.
831 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
832 // misassembled by gas in intel_syntax mode as its 32-bit
833 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
834 // opcode bytes instead of the instruction.
836 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
837 // invalid opcode, saying "64 bit operations are only supported in
838 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
839 // [...]", which is wrong. Workaround: Output the raw opcode bytes
840 // instead of the instruction.
842 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
843 // invalid opcode, saying "64 bit operations are only supported in
844 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
845 // [...]", which is wrong. Workaround: Output the raw opcode bytes
846 // instead of the instruction.
847 if (MI->getOpcode() == X86::FSTP80m ||
848 MI->getOpcode() == X86::FLD80m ||
849 MI->getOpcode() == X86::FILD64m ||
850 MI->getOpcode() == X86::FISTP64m) {
851 GasBugWorkaroundEmitter gwe(O);
852 X86::emitInstruction(gwe, (X86InstrInfo&)TM.getInstrInfo(), *MI);
855 O << TII.getName(MI->getOpcode()) << " ";
856 O << sizePtr(Desc) << " ";
857 printMemReference(MI, 0);
858 if (MI->getNumOperands() == 5) {
860 printOp(MI->getOperand(4));
862 printImplUsesAfter(Desc);
867 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
871 bool Printer::doInitialization(Module &M) {
872 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
874 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
875 // instruction as a reference to the register named sp, and if you try to
876 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
877 // before being looked up in the symbol table. This creates spurious
878 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
879 // mode, and decorate all register names with percent signs.
880 O << "\t.intel_syntax\n";
881 Mang = new Mangler(M, EmitCygwin);
882 return false; // success
885 // SwitchSection - Switch to the specified section of the executable if we are
886 // not already in it!
888 static void SwitchSection(std::ostream &OS, std::string &CurSection,
889 const char *NewSection) {
890 if (CurSection != NewSection) {
891 CurSection = NewSection;
892 if (!CurSection.empty())
893 OS << "\t" << NewSection << "\n";
897 bool Printer::doFinalization(Module &M) {
898 const TargetData &TD = TM.getTargetData();
899 std::string CurSection;
901 // Print out module-level global variables here.
902 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
903 if (I->hasInitializer()) { // External global require no code
905 std::string name = Mang->getValueName(I);
906 Constant *C = I->getInitializer();
907 unsigned Size = TD.getTypeSize(C->getType());
908 unsigned Align = TD.getTypeAlignment(C->getType());
910 if (C->isNullValue() &&
911 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
912 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
913 SwitchSection(O, CurSection, ".data");
914 if (I->hasInternalLinkage())
915 O << "\t.local " << name << "\n";
917 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
918 << "," << (unsigned)TD.getTypeAlignment(C->getType());
920 WriteAsOperand(O, I, true, true, &M);
923 switch (I->getLinkage()) {
924 case GlobalValue::LinkOnceLinkage:
925 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
926 // Nonnull linkonce -> weak
927 O << "\t.weak " << name << "\n";
928 SwitchSection(O, CurSection, "");
929 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
932 case GlobalValue::AppendingLinkage:
933 // FIXME: appending linkage variables should go into a section of
934 // their name or something. For now, just emit them as external.
935 case GlobalValue::ExternalLinkage:
936 // If external or appending, declare as a global symbol
937 O << "\t.globl " << name << "\n";
939 case GlobalValue::InternalLinkage:
940 if (C->isNullValue())
941 SwitchSection(O, CurSection, ".bss");
943 SwitchSection(O, CurSection, ".data");
947 O << "\t.align " << Align << "\n";
948 O << "\t.type " << name << ",@object\n";
949 O << "\t.size " << name << "," << Size << "\n";
950 O << name << ":\t\t\t\t# ";
951 WriteAsOperand(O, I, true, true, &M);
953 WriteAsOperand(O, C, false, false, &M);
955 emitGlobalConstant(C);
960 return false; // success