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 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
109 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
110 void printMachineInstruction(const MachineInstr *MI);
111 void printOp(const MachineOperand &MO,
112 bool elideOffsetKeyword = false);
113 void printMemReference(const MachineInstr *MI, unsigned Op);
114 void printConstantPool(MachineConstantPool *MCP);
115 bool runOnMachineFunction(MachineFunction &F);
116 bool doInitialization(Module &M);
117 bool doFinalization(Module &M);
118 void emitGlobalConstant(const Constant* CV);
119 void emitConstantValueOnly(const Constant *CV);
121 } // end of anonymous namespace
123 /// createX86CodePrinterPass - Returns a pass that prints the X86
124 /// assembly code for a MachineFunction to the given output stream,
125 /// using the given target machine description. This should work
126 /// regardless of whether the function is in SSA form.
128 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
129 return new Printer(o, tm);
132 /// toOctal - Convert the low order bits of X into an octal digit.
134 static inline char toOctal(int X) {
138 /// getAsCString - Return the specified array as a C compatible
139 /// string, only if the predicate isStringCompatible is true.
141 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
142 assert(CVA->isString() && "Array is not string compatible!");
145 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
146 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
150 } else if (C == '\\') {
152 } else if (isprint(C)) {
156 case '\b': O << "\\b"; break;
157 case '\f': O << "\\f"; break;
158 case '\n': O << "\\n"; break;
159 case '\r': O << "\\r"; break;
160 case '\t': O << "\\t"; break;
163 O << toOctal(C >> 6);
164 O << toOctal(C >> 3);
165 O << toOctal(C >> 0);
173 // Print out the specified constant, without a storage class. Only the
174 // constants valid in constant expressions can occur here.
175 void Printer::emitConstantValueOnly(const Constant *CV) {
176 if (CV->isNullValue())
178 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
179 assert(CB == ConstantBool::True);
181 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
182 if (((CI->getValue() << 32) >> 32) == CI->getValue())
185 O << (unsigned long long)CI->getValue();
186 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
188 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
189 // This is a constant address for a global variable or function. Use the
190 // name of the variable or function as the address value.
191 O << Mang->getValueName(CPR->getValue());
192 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
193 const TargetData &TD = TM.getTargetData();
194 switch(CE->getOpcode()) {
195 case Instruction::GetElementPtr: {
196 // generate a symbolic expression for the byte address
197 const Constant *ptrVal = CE->getOperand(0);
198 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
199 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
201 emitConstantValueOnly(ptrVal);
202 O << ") + " << Offset;
204 emitConstantValueOnly(ptrVal);
208 case Instruction::Cast: {
209 // Support only non-converting or widening casts for now, that is, ones
210 // that do not involve a change in value. This assertion is really gross,
211 // and may not even be a complete check.
212 Constant *Op = CE->getOperand(0);
213 const Type *OpTy = Op->getType(), *Ty = CE->getType();
215 // Remember, kids, pointers on x86 can be losslessly converted back and
216 // forth into 32-bit or wider integers, regardless of signedness. :-P
217 assert(((isa<PointerType>(OpTy)
218 && (Ty == Type::LongTy || Ty == Type::ULongTy
219 || Ty == Type::IntTy || Ty == Type::UIntTy))
220 || (isa<PointerType>(Ty)
221 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
222 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
223 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
224 && OpTy->isLosslesslyConvertibleTo(Ty))))
225 && "FIXME: Don't yet support this kind of constant cast expr");
227 emitConstantValueOnly(Op);
231 case Instruction::Add:
233 emitConstantValueOnly(CE->getOperand(0));
235 emitConstantValueOnly(CE->getOperand(1));
239 assert(0 && "Unsupported operator!");
242 assert(0 && "Unknown constant value!");
246 // Print a constant value or values, with the appropriate storage class as a
248 void Printer::emitGlobalConstant(const Constant *CV) {
249 const TargetData &TD = TM.getTargetData();
251 if (CV->isNullValue()) {
252 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
254 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
255 if (CVA->isString()) {
257 printAsCString(O, CVA);
259 } else { // Not a string. Print the values in successive locations
260 const std::vector<Use> &constValues = CVA->getValues();
261 for (unsigned i=0; i < constValues.size(); i++)
262 emitGlobalConstant(cast<Constant>(constValues[i].get()));
265 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
266 // Print the fields in successive locations. Pad to align if needed!
267 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
268 const std::vector<Use>& constValues = CVS->getValues();
269 unsigned sizeSoFar = 0;
270 for (unsigned i=0, N = constValues.size(); i < N; i++) {
271 const Constant* field = cast<Constant>(constValues[i].get());
273 // Check if padding is needed and insert one or more 0s.
274 unsigned fieldSize = TD.getTypeSize(field->getType());
275 unsigned padSize = ((i == N-1? cvsLayout->StructSize
276 : cvsLayout->MemberOffsets[i+1])
277 - cvsLayout->MemberOffsets[i]) - fieldSize;
278 sizeSoFar += fieldSize + padSize;
280 // Now print the actual field value
281 emitGlobalConstant(field);
283 // Insert the field padding unless it's zero bytes...
285 O << "\t.zero\t " << padSize << "\n";
287 assert(sizeSoFar == cvsLayout->StructSize &&
288 "Layout of constant struct may be incorrect!");
290 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
291 // FP Constants are printed as integer constants to avoid losing
293 double Val = CFP->getValue();
294 switch (CFP->getType()->getPrimitiveID()) {
295 default: assert(0 && "Unknown floating point type!");
296 case Type::FloatTyID: {
297 union FU { // Abide by C TBAA rules
302 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
305 case Type::DoubleTyID: {
306 union DU { // Abide by C TBAA rules
311 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
317 const Type *type = CV->getType();
319 switch (type->getPrimitiveID()) {
320 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
323 case Type::UShortTyID: case Type::ShortTyID:
326 case Type::FloatTyID: case Type::PointerTyID:
327 case Type::UIntTyID: case Type::IntTyID:
330 case Type::DoubleTyID:
331 case Type::ULongTyID: case Type::LongTyID:
335 assert (0 && "Can't handle printing this type of thing");
339 emitConstantValueOnly(CV);
343 /// printConstantPool - Print to the current output stream assembly
344 /// representations of the constants in the constant pool MCP. This is
345 /// used to print out constants which have been "spilled to memory" by
346 /// the code generator.
348 void Printer::printConstantPool(MachineConstantPool *MCP) {
349 const std::vector<Constant*> &CP = MCP->getConstants();
350 const TargetData &TD = TM.getTargetData();
352 if (CP.empty()) return;
354 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
355 O << "\t.section .rodata\n";
356 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
358 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
360 emitGlobalConstant(CP[i]);
364 /// runOnMachineFunction - This uses the printMachineInstruction()
365 /// method to print assembly for each instruction.
367 bool Printer::runOnMachineFunction(MachineFunction &MF) {
368 // BBNumber is used here so that a given Printer will never give two
369 // BBs the same name. (If you have a better way, please let me know!)
370 static unsigned BBNumber = 0;
373 // What's my mangled name?
374 CurrentFnName = Mang->getValueName(MF.getFunction());
376 // Print out constants referenced by the function
377 printConstantPool(MF.getConstantPool());
379 // Print out labels for the function.
381 O << "\t.align 16\n";
382 O << "\t.globl\t" << CurrentFnName << "\n";
384 O << "\t.type\t" << CurrentFnName << ", @function\n";
385 O << CurrentFnName << ":\n";
387 // Number each basic block so that we can consistently refer to them
388 // in PC-relative references.
390 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
392 NumberForBB[I->getBasicBlock()] = BBNumber++;
395 // Print out code for the function.
396 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
398 // Print a label for the basic block.
399 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
400 << I->getBasicBlock()->getName() << "\n";
401 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
403 // Print the assembly for the instruction.
405 printMachineInstruction(II);
409 // We didn't modify anything.
413 static bool isScale(const MachineOperand &MO) {
414 return MO.isImmediate() &&
415 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
416 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
419 static bool isMem(const MachineInstr *MI, unsigned Op) {
420 if (MI->getOperand(Op).isFrameIndex()) return true;
421 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
422 return Op+4 <= MI->getNumOperands() &&
423 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
424 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
429 void Printer::printOp(const MachineOperand &MO,
430 bool elideOffsetKeyword /* = false */) {
431 const MRegisterInfo &RI = *TM.getRegisterInfo();
432 switch (MO.getType()) {
433 case MachineOperand::MO_VirtualRegister:
434 if (Value *V = MO.getVRegValueOrNull()) {
435 O << "<" << V->getName() << ">";
439 case MachineOperand::MO_MachineRegister:
440 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
441 // Bug Workaround: See note in Printer::doInitialization about %.
442 O << "%" << RI.get(MO.getReg()).Name;
444 O << "%reg" << MO.getReg();
447 case MachineOperand::MO_SignExtendedImmed:
448 case MachineOperand::MO_UnextendedImmed:
449 O << (int)MO.getImmedValue();
451 case MachineOperand::MO_PCRelativeDisp: {
452 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
453 assert (i != NumberForBB.end()
454 && "Could not find a BB in the NumberForBB map!");
455 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
458 case MachineOperand::MO_GlobalAddress:
459 if (!elideOffsetKeyword)
461 O << Mang->getValueName(MO.getGlobal());
463 case MachineOperand::MO_ExternalSymbol:
464 O << MO.getSymbolName();
467 O << "<unknown operand type>"; return;
471 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
472 switch (Desc.TSFlags & X86II::MemMask) {
473 default: assert(0 && "Unknown arg size!");
474 case X86II::Mem8: return "BYTE PTR";
475 case X86II::Mem16: return "WORD PTR";
476 case X86II::Mem32: return "DWORD PTR";
477 case X86II::Mem64: return "QWORD PTR";
478 case X86II::Mem80: return "XWORD PTR";
482 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
483 assert(isMem(MI, Op) && "Invalid memory reference!");
485 if (MI->getOperand(Op).isFrameIndex()) {
486 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
487 if (MI->getOperand(Op+3).getImmedValue())
488 O << " + " << MI->getOperand(Op+3).getImmedValue();
491 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
492 O << "[.CPI" << CurrentFnName << "_"
493 << MI->getOperand(Op).getConstantPoolIndex();
494 if (MI->getOperand(Op+3).getImmedValue())
495 O << " + " << MI->getOperand(Op+3).getImmedValue();
500 const MachineOperand &BaseReg = MI->getOperand(Op);
501 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
502 const MachineOperand &IndexReg = MI->getOperand(Op+2);
503 int DispVal = MI->getOperand(Op+3).getImmedValue();
506 bool NeedPlus = false;
507 if (BaseReg.getReg()) {
512 if (IndexReg.getReg()) {
513 if (NeedPlus) O << " + ";
515 O << ScaleVal << "*";
534 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
535 /// described by DESC, if its PrintImplUsesBefore flag is set.
537 void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
538 const MRegisterInfo &RI = *TM.getRegisterInfo();
539 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
540 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
541 // Bug Workaround: See note in Printer::doInitialization about %.
542 O << "%" << RI.get(*p).Name << ", ";
547 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
548 /// described by DESC, if its PrintImplUsesAfter flag is set.
551 /// Comma - List of registers will need a leading comma.
552 /// Desc - Description of the Instruction.
555 /// true - Emitted one or more registers.
556 /// false - Emitted no registers.
558 bool Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc,
559 const bool Comma = true) {
560 const MRegisterInfo &RI = *TM.getRegisterInfo();
561 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
562 bool emitted = false;
563 const unsigned *p = Desc.ImplicitUses;
565 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
570 // Bug Workaround: See note in Printer::doInitialization about %.
571 O << ", %" << RI.get(*p).Name;
579 /// printImplDefsAfter - Emit the implicit-definition registers for the
580 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
583 /// Comma - List of registers will need a leading comma.
584 /// Desc - Description of the Instruction
587 /// true - Emitted one or more registers.
588 /// false - Emitted no registers.
590 bool Printer::printImplDefsAfter(const TargetInstrDescriptor &Desc,
591 const bool Comma = true) {
592 const MRegisterInfo &RI = *TM.getRegisterInfo();
593 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
594 bool emitted = false;
595 const unsigned *p = Desc.ImplicitDefs;
597 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
602 // Bug Workaround: See note in Printer::doInitialization about %.
603 O << ", %" << RI.get(*p).Name;
611 /// printMachineInstruction -- Print out a single X86 LLVM instruction
612 /// MI in Intel syntax to the current output stream.
614 void Printer::printMachineInstruction(const MachineInstr *MI) {
615 unsigned Opcode = MI->getOpcode();
616 const TargetInstrInfo &TII = TM.getInstrInfo();
617 const TargetInstrDescriptor &Desc = TII.get(Opcode);
620 switch (Desc.TSFlags & X86II::FormMask) {
622 // Print pseudo-instructions as comments; either they should have been
623 // turned into real instructions by now, or they don't need to be
624 // seen by the assembler (e.g., IMPLICIT_USEs.)
626 if (Opcode == X86::PHI) {
627 printOp(MI->getOperand(0));
629 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
630 if (i != 1) O << ", ";
632 printOp(MI->getOperand(i));
634 printOp(MI->getOperand(i+1));
639 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
640 printOp(MI->getOperand(0));
644 O << TII.getName(MI->getOpcode());
646 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
648 if (MI->getOperand(i).isDef()) O << "*";
649 printOp(MI->getOperand(i));
650 if (MI->getOperand(i).isDef()) O << "*";
658 bool LeadingComma = false;
660 // The accepted forms of Raw instructions are:
661 // 1. nop - No operand required
662 // 2. jmp foo - PC relative displacement operand
663 // 3. call bar - GlobalAddress Operand or External Symbol Operand
665 assert(MI->getNumOperands() == 0 ||
666 (MI->getNumOperands() == 1 &&
667 (MI->getOperand(0).isPCRelativeDisp() ||
668 MI->getOperand(0).isGlobalAddress() ||
669 MI->getOperand(0).isExternalSymbol())) &&
670 "Illegal raw instruction!");
671 O << TII.getName(MI->getOpcode()) << " ";
673 if (MI->getNumOperands() == 1) {
674 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
677 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
678 printImplUsesAfter(Desc, LeadingComma);
683 case X86II::AddRegFrm: {
684 // There are currently two forms of acceptable AddRegFrm instructions.
685 // Either the instruction JUST takes a single register (like inc, dec, etc),
686 // or it takes a register and an immediate of the same size as the register
687 // (move immediate f.e.). Note that this immediate value might be stored as
688 // an LLVM value, to represent, for example, loading the address of a global
689 // into a register. The initial register might be duplicated if this is a
690 // M_2_ADDR_REG instruction
692 assert(MI->getOperand(0).isRegister() &&
693 (MI->getNumOperands() == 1 ||
694 (MI->getNumOperands() == 2 &&
695 (MI->getOperand(1).getVRegValueOrNull() ||
696 MI->getOperand(1).isImmediate() ||
697 MI->getOperand(1).isRegister() ||
698 MI->getOperand(1).isGlobalAddress() ||
699 MI->getOperand(1).isExternalSymbol()))) &&
700 "Illegal form for AddRegFrm instruction!");
702 unsigned Reg = MI->getOperand(0).getReg();
704 O << TII.getName(MI->getOpcode()) << " ";
706 printImplUsesBefore(Desc); // fcmov*
708 printOp(MI->getOperand(0));
709 if (MI->getNumOperands() == 2 &&
710 (!MI->getOperand(1).isRegister() ||
711 MI->getOperand(1).getVRegValueOrNull() ||
712 MI->getOperand(1).isGlobalAddress() ||
713 MI->getOperand(1).isExternalSymbol())) {
715 printOp(MI->getOperand(1));
717 printImplUsesAfter(Desc);
721 case X86II::MRMDestReg: {
722 // There are three forms of MRMDestReg instructions, those with 2
725 // 2 Operands: this is for things like mov that do not read a
728 // 2 Operands: two address instructions which def&use the first
729 // argument and use the second as input.
731 // 3 Operands: in this form, two address instructions are the same
732 // as in 2 but have a constant argument as well.
734 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
735 assert(MI->getOperand(0).isRegister() &&
736 (MI->getNumOperands() == 2 ||
737 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
738 && "Bad format for MRMDestReg!");
740 O << TII.getName(MI->getOpcode()) << " ";
741 printOp(MI->getOperand(0));
743 printOp(MI->getOperand(1));
744 if (MI->getNumOperands() == 3) {
746 printOp(MI->getOperand(2));
748 printImplUsesAfter(Desc);
753 case X86II::MRMDestMem: {
754 // These instructions are the same as MRMDestReg, but instead of having a
755 // register reference for the mod/rm field, it's a memory reference.
757 assert(isMem(MI, 0) &&
758 (MI->getNumOperands() == 4+1 ||
759 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
760 && "Bad format for MRMDestMem!");
762 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
763 printMemReference(MI, 0);
765 printOp(MI->getOperand(4));
766 if (MI->getNumOperands() == 4+2) {
768 printOp(MI->getOperand(5));
770 printImplUsesAfter(Desc);
775 case X86II::MRMSrcReg: {
776 // There are three forms that are acceptable for MRMSrcReg
777 // instructions, those with 2 or 3 operands:
779 // 2 Operands: this is for things like mov that do not read a
782 // 2 Operands: in this form, the last register is the ModR/M
783 // input. The first operand is a def&use. This is for things
784 // like: add r32, r/m32
786 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
787 // for instructions like the IMULrri instructions.
790 assert(MI->getOperand(0).isRegister() &&
791 MI->getOperand(1).isRegister() &&
792 (MI->getNumOperands() == 2 ||
793 (MI->getNumOperands() == 3 &&
794 (MI->getOperand(2).isImmediate())))
795 && "Bad format for MRMSrcReg!");
797 O << TII.getName(MI->getOpcode()) << " ";
798 printOp(MI->getOperand(0));
800 printOp(MI->getOperand(1));
801 if (MI->getNumOperands() == 3) {
803 printOp(MI->getOperand(2));
809 case X86II::MRMSrcMem: {
810 // These instructions are the same as MRMSrcReg, but instead of having a
811 // register reference for the mod/rm field, it's a memory reference.
813 assert(MI->getOperand(0).isRegister() &&
814 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
815 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
816 && "Bad format for MRMSrcMem!");
817 O << TII.getName(MI->getOpcode()) << " ";
818 printOp(MI->getOperand(0));
819 O << ", " << sizePtr(Desc) << " ";
820 printMemReference(MI, 1);
821 if (MI->getNumOperands() == 2+4) {
823 printOp(MI->getOperand(5));
829 case X86II::MRM0r: case X86II::MRM1r:
830 case X86II::MRM2r: case X86II::MRM3r:
831 case X86II::MRM4r: case X86II::MRM5r:
832 case X86II::MRM6r: case X86II::MRM7r: {
833 // In this form, the following are valid formats:
835 // 2. cmp reg, immediate
836 // 2. shl rdest, rinput <implicit CL or 1>
837 // 3. sbb rdest, rinput, immediate [rdest = rinput]
839 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
840 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
841 assert((MI->getNumOperands() != 2 ||
842 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
843 "Bad MRMSxR format!");
844 assert((MI->getNumOperands() < 3 ||
845 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
846 "Bad MRMSxR format!");
848 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
849 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
852 O << TII.getName(MI->getOpcode()) << " ";
853 printOp(MI->getOperand(0));
854 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
856 printOp(MI->getOperand(MI->getNumOperands()-1));
858 printImplUsesAfter(Desc);
864 case X86II::MRM0m: case X86II::MRM1m:
865 case X86II::MRM2m: case X86II::MRM3m:
866 case X86II::MRM4m: case X86II::MRM5m:
867 case X86II::MRM6m: case X86II::MRM7m: {
868 // In this form, the following are valid formats:
870 // 2. cmp [m], immediate
871 // 2. shl [m], rinput <implicit CL or 1>
872 // 3. sbb [m], immediate
874 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
875 isMem(MI, 0) && "Bad MRMSxM format!");
876 assert((MI->getNumOperands() != 5 ||
877 (MI->getOperand(4).isImmediate() ||
878 MI->getOperand(4).isGlobalAddress())) &&
879 "Bad MRMSxM format!");
881 const MachineOperand &Op3 = MI->getOperand(3);
885 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
886 // is misassembled by gas in intel_syntax mode as its 32-bit
887 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
888 // opcode bytes instead of the instruction.
890 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
891 // misassembled by gas in intel_syntax mode as its 32-bit
892 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
893 // opcode bytes instead of the instruction.
895 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
896 // invalid opcode, saying "64 bit operations are only supported in
897 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
898 // [...]", which is wrong. Workaround: Output the raw opcode bytes
899 // instead of the instruction.
901 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
902 // invalid opcode, saying "64 bit operations are only supported in
903 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
904 // [...]", which is wrong. Workaround: Output the raw opcode bytes
905 // instead of the instruction.
906 if (MI->getOpcode() == X86::FSTP80m ||
907 MI->getOpcode() == X86::FLD80m ||
908 MI->getOpcode() == X86::FILD64m ||
909 MI->getOpcode() == X86::FISTP64m) {
910 GasBugWorkaroundEmitter gwe(O);
911 X86::emitInstruction(gwe, (X86InstrInfo&)TM.getInstrInfo(), *MI);
914 O << TII.getName(MI->getOpcode()) << " ";
915 O << sizePtr(Desc) << " ";
916 printMemReference(MI, 0);
917 if (MI->getNumOperands() == 5) {
919 printOp(MI->getOperand(4));
921 printImplUsesAfter(Desc);
926 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
930 bool Printer::doInitialization(Module &M) {
931 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
933 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
934 // instruction as a reference to the register named sp, and if you try to
935 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
936 // before being looked up in the symbol table. This creates spurious
937 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
938 // mode, and decorate all register names with percent signs.
939 O << "\t.intel_syntax\n";
940 Mang = new Mangler(M, EmitCygwin);
941 return false; // success
944 // SwitchSection - Switch to the specified section of the executable if we are
945 // not already in it!
947 static void SwitchSection(std::ostream &OS, std::string &CurSection,
948 const char *NewSection) {
949 if (CurSection != NewSection) {
950 CurSection = NewSection;
951 if (!CurSection.empty())
952 OS << "\t" << NewSection << "\n";
956 bool Printer::doFinalization(Module &M) {
957 const TargetData &TD = TM.getTargetData();
958 std::string CurSection;
960 // Print out module-level global variables here.
961 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
962 if (I->hasInitializer()) { // External global require no code
964 std::string name = Mang->getValueName(I);
965 Constant *C = I->getInitializer();
966 unsigned Size = TD.getTypeSize(C->getType());
967 unsigned Align = TD.getTypeAlignment(C->getType());
969 if (C->isNullValue() &&
970 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
971 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
972 SwitchSection(O, CurSection, ".data");
973 if (I->hasInternalLinkage())
974 O << "\t.local " << name << "\n";
976 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
977 << "," << (unsigned)TD.getTypeAlignment(C->getType());
979 WriteAsOperand(O, I, true, true, &M);
982 switch (I->getLinkage()) {
983 case GlobalValue::LinkOnceLinkage:
984 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
985 // Nonnull linkonce -> weak
986 O << "\t.weak " << name << "\n";
987 SwitchSection(O, CurSection, "");
988 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
991 case GlobalValue::AppendingLinkage:
992 // FIXME: appending linkage variables should go into a section of
993 // their name or something. For now, just emit them as external.
994 case GlobalValue::ExternalLinkage:
995 // If external or appending, declare as a global symbol
996 O << "\t.globl " << name << "\n";
998 case GlobalValue::InternalLinkage:
999 if (C->isNullValue())
1000 SwitchSection(O, CurSection, ".bss");
1002 SwitchSection(O, CurSection, ".data");
1006 O << "\t.align " << Align << "\n";
1007 O << "\t.type " << name << ",@object\n";
1008 O << "\t.size " << name << "," << Size << "\n";
1009 O << name << ":\t\t\t\t# ";
1010 WriteAsOperand(O, I, true, true, &M);
1012 WriteAsOperand(O, C, false, false, &M);
1014 emitGlobalConstant(C);
1019 return false; // success