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 /// Cache of mangled name for current function. This is
91 /// recalculated at the beginning of each call to
92 /// runOnMachineFunction().
94 std::string CurrentFnName;
96 virtual const char *getPassName() const {
97 return "X86 Assembly Printer";
100 void printImplUsesBefore(const TargetInstrDescriptor &Desc);
101 bool printImplDefsBefore(const TargetInstrDescriptor &Desc);
102 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
103 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
104 void printMachineInstruction(const MachineInstr *MI);
105 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
106 void printMemReference(const MachineInstr *MI, unsigned Op);
107 void printConstantPool(MachineConstantPool *MCP);
108 bool runOnMachineFunction(MachineFunction &F);
109 bool doInitialization(Module &M);
110 bool doFinalization(Module &M);
111 void emitGlobalConstant(const Constant* CV);
112 void emitConstantValueOnly(const Constant *CV);
114 } // end of anonymous namespace
116 /// createX86CodePrinterPass - Returns a pass that prints the X86
117 /// assembly code for a MachineFunction to the given output stream,
118 /// using the given target machine description. This should work
119 /// regardless of whether the function is in SSA form.
121 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
122 return new Printer(o, tm);
125 /// toOctal - Convert the low order bits of X into an octal digit.
127 static inline char toOctal(int X) {
131 /// getAsCString - Return the specified array as a C compatible
132 /// string, only if the predicate isStringCompatible is true.
134 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
135 assert(CVA->isString() && "Array is not string compatible!");
138 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
139 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
143 } else if (C == '\\') {
145 } else if (isprint(C)) {
149 case '\b': O << "\\b"; break;
150 case '\f': O << "\\f"; break;
151 case '\n': O << "\\n"; break;
152 case '\r': O << "\\r"; break;
153 case '\t': O << "\\t"; break;
156 O << toOctal(C >> 6);
157 O << toOctal(C >> 3);
158 O << toOctal(C >> 0);
166 // Print out the specified constant, without a storage class. Only the
167 // constants valid in constant expressions can occur here.
168 void Printer::emitConstantValueOnly(const Constant *CV) {
169 if (CV->isNullValue())
171 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
172 assert(CB == ConstantBool::True);
174 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
175 if (((CI->getValue() << 32) >> 32) == CI->getValue())
178 O << (unsigned long long)CI->getValue();
179 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
181 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
182 // This is a constant address for a global variable or function. Use the
183 // name of the variable or function as the address value.
184 O << Mang->getValueName(CPR->getValue());
185 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
186 const TargetData &TD = TM.getTargetData();
187 switch(CE->getOpcode()) {
188 case Instruction::GetElementPtr: {
189 // generate a symbolic expression for the byte address
190 const Constant *ptrVal = CE->getOperand(0);
191 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
192 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
194 emitConstantValueOnly(ptrVal);
195 O << ") + " << Offset;
197 emitConstantValueOnly(ptrVal);
201 case Instruction::Cast: {
202 // Support only non-converting or widening casts for now, that is, ones
203 // that do not involve a change in value. This assertion is really gross,
204 // and may not even be a complete check.
205 Constant *Op = CE->getOperand(0);
206 const Type *OpTy = Op->getType(), *Ty = CE->getType();
208 // Remember, kids, pointers on x86 can be losslessly converted back and
209 // forth into 32-bit or wider integers, regardless of signedness. :-P
210 assert(((isa<PointerType>(OpTy)
211 && (Ty == Type::LongTy || Ty == Type::ULongTy
212 || Ty == Type::IntTy || Ty == Type::UIntTy))
213 || (isa<PointerType>(Ty)
214 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
215 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
216 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
217 && OpTy->isLosslesslyConvertibleTo(Ty))))
218 && "FIXME: Don't yet support this kind of constant cast expr");
220 emitConstantValueOnly(Op);
224 case Instruction::Add:
226 emitConstantValueOnly(CE->getOperand(0));
228 emitConstantValueOnly(CE->getOperand(1));
232 assert(0 && "Unsupported operator!");
235 assert(0 && "Unknown constant value!");
239 // Print a constant value or values, with the appropriate storage class as a
241 void Printer::emitGlobalConstant(const Constant *CV) {
242 const TargetData &TD = TM.getTargetData();
244 if (CV->isNullValue()) {
245 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
247 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
248 if (CVA->isString()) {
250 printAsCString(O, CVA);
252 } else { // Not a string. Print the values in successive locations
253 const std::vector<Use> &constValues = CVA->getValues();
254 for (unsigned i=0; i < constValues.size(); i++)
255 emitGlobalConstant(cast<Constant>(constValues[i].get()));
258 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
259 // Print the fields in successive locations. Pad to align if needed!
260 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
261 const std::vector<Use>& constValues = CVS->getValues();
262 unsigned sizeSoFar = 0;
263 for (unsigned i=0, N = constValues.size(); i < N; i++) {
264 const Constant* field = cast<Constant>(constValues[i].get());
266 // Check if padding is needed and insert one or more 0s.
267 unsigned fieldSize = TD.getTypeSize(field->getType());
268 unsigned padSize = ((i == N-1? cvsLayout->StructSize
269 : cvsLayout->MemberOffsets[i+1])
270 - cvsLayout->MemberOffsets[i]) - fieldSize;
271 sizeSoFar += fieldSize + padSize;
273 // Now print the actual field value
274 emitGlobalConstant(field);
276 // Insert the field padding unless it's zero bytes...
278 O << "\t.zero\t " << padSize << "\n";
280 assert(sizeSoFar == cvsLayout->StructSize &&
281 "Layout of constant struct may be incorrect!");
283 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
284 // FP Constants are printed as integer constants to avoid losing
286 double Val = CFP->getValue();
287 switch (CFP->getType()->getTypeID()) {
288 default: assert(0 && "Unknown floating point type!");
289 case Type::FloatTyID: {
290 union FU { // Abide by C TBAA rules
295 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
298 case Type::DoubleTyID: {
299 union DU { // Abide by C TBAA rules
304 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
310 const Type *type = CV->getType();
312 switch (type->getTypeID()) {
313 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
316 case Type::UShortTyID: case Type::ShortTyID:
319 case Type::FloatTyID: case Type::PointerTyID:
320 case Type::UIntTyID: case Type::IntTyID:
323 case Type::DoubleTyID:
324 case Type::ULongTyID: case Type::LongTyID:
328 assert (0 && "Can't handle printing this type of thing");
332 emitConstantValueOnly(CV);
336 /// printConstantPool - Print to the current output stream assembly
337 /// representations of the constants in the constant pool MCP. This is
338 /// used to print out constants which have been "spilled to memory" by
339 /// the code generator.
341 void Printer::printConstantPool(MachineConstantPool *MCP) {
342 const std::vector<Constant*> &CP = MCP->getConstants();
343 const TargetData &TD = TM.getTargetData();
345 if (CP.empty()) return;
347 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
348 O << "\t.section .rodata\n";
349 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
351 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
353 emitGlobalConstant(CP[i]);
357 /// runOnMachineFunction - This uses the printMachineInstruction()
358 /// method to print assembly for each instruction.
360 bool Printer::runOnMachineFunction(MachineFunction &MF) {
362 // What's my mangled name?
363 CurrentFnName = Mang->getValueName(MF.getFunction());
365 // Print out constants referenced by the function
366 printConstantPool(MF.getConstantPool());
368 // Print out labels for the function.
370 O << "\t.align 16\n";
371 O << "\t.globl\t" << CurrentFnName << "\n";
373 O << "\t.type\t" << CurrentFnName << ", @function\n";
374 O << CurrentFnName << ":\n";
376 // Print out code for the function.
377 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
379 // Print a label for the basic block.
380 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
381 << I->getBasicBlock()->getName() << "\n";
382 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
384 // Print the assembly for the instruction.
386 printMachineInstruction(II);
390 // We didn't modify anything.
394 static bool isScale(const MachineOperand &MO) {
395 return MO.isImmediate() &&
396 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
397 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
400 static bool isMem(const MachineInstr *MI, unsigned Op) {
401 if (MI->getOperand(Op).isFrameIndex()) return true;
402 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
403 return Op+4 <= MI->getNumOperands() &&
404 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
405 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
410 void Printer::printOp(const MachineOperand &MO,
411 bool elideOffsetKeyword /* = false */) {
412 const MRegisterInfo &RI = *TM.getRegisterInfo();
413 switch (MO.getType()) {
414 case MachineOperand::MO_VirtualRegister:
415 if (Value *V = MO.getVRegValueOrNull()) {
416 O << "<" << V->getName() << ">";
420 case MachineOperand::MO_MachineRegister:
421 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
422 // Bug Workaround: See note in Printer::doInitialization about %.
423 O << "%" << RI.get(MO.getReg()).Name;
425 O << "%reg" << MO.getReg();
428 case MachineOperand::MO_SignExtendedImmed:
429 case MachineOperand::MO_UnextendedImmed:
430 O << (int)MO.getImmedValue();
432 case MachineOperand::MO_MachineBasicBlock: {
433 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
434 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
435 << "_" << MBBOp->getNumber () << "\t# "
436 << MBBOp->getBasicBlock ()->getName ();
439 case MachineOperand::MO_PCRelativeDisp:
440 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
443 case MachineOperand::MO_GlobalAddress:
444 if (!elideOffsetKeyword)
446 O << Mang->getValueName(MO.getGlobal());
448 case MachineOperand::MO_ExternalSymbol:
449 O << MO.getSymbolName();
452 O << "<unknown operand type>"; return;
456 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
457 switch (Desc.TSFlags & X86II::MemMask) {
458 default: assert(0 && "Unknown arg size!");
459 case X86II::Mem8: return "BYTE PTR";
460 case X86II::Mem16: return "WORD PTR";
461 case X86II::Mem32: return "DWORD PTR";
462 case X86II::Mem64: return "QWORD PTR";
463 case X86II::Mem80: return "XWORD PTR";
467 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
468 assert(isMem(MI, Op) && "Invalid memory reference!");
470 if (MI->getOperand(Op).isFrameIndex()) {
471 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
472 if (MI->getOperand(Op+3).getImmedValue())
473 O << " + " << MI->getOperand(Op+3).getImmedValue();
476 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
477 O << "[.CPI" << CurrentFnName << "_"
478 << MI->getOperand(Op).getConstantPoolIndex();
479 if (MI->getOperand(Op+3).getImmedValue())
480 O << " + " << MI->getOperand(Op+3).getImmedValue();
485 const MachineOperand &BaseReg = MI->getOperand(Op);
486 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
487 const MachineOperand &IndexReg = MI->getOperand(Op+2);
488 int DispVal = MI->getOperand(Op+3).getImmedValue();
491 bool NeedPlus = false;
492 if (BaseReg.getReg()) {
497 if (IndexReg.getReg()) {
498 if (NeedPlus) O << " + ";
500 O << ScaleVal << "*";
519 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
520 /// described by DESC, if its PrintImplUsesBefore flag is set.
522 void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
523 const MRegisterInfo &RI = *TM.getRegisterInfo();
524 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
525 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
526 // Bug Workaround: See note in Printer::doInitialization about %.
527 O << "%" << RI.get(*p).Name << ", ";
532 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
533 /// described by DESC, if its PrintImplUsesBefore flag is set. Return true if
534 /// we printed any registers.
536 bool Printer::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
537 bool Printed = false;
538 const MRegisterInfo &RI = *TM.getRegisterInfo();
539 if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
540 const unsigned *p = Desc.ImplicitDefs;
542 O << (Printed ? ", %" : "%") << RI.get (*p).Name;
547 // Bug Workaround: See note in Printer::doInitialization about %.
548 O << ", %" << RI.get(*p).Name;
556 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
557 /// described by DESC, if its PrintImplUsesAfter flag is set.
560 /// Comma - List of registers will need a leading comma.
561 /// Desc - Description of the Instruction.
564 /// true - Emitted one or more registers.
565 /// false - Emitted no registers.
567 bool Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc,
568 const bool Comma = true) {
569 const MRegisterInfo &RI = *TM.getRegisterInfo();
570 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
571 bool emitted = false;
572 const unsigned *p = Desc.ImplicitUses;
574 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
579 // Bug Workaround: See note in Printer::doInitialization about %.
580 O << ", %" << RI.get(*p).Name;
588 /// printImplDefsAfter - Emit the implicit-definition registers for the
589 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
592 /// Comma - List of registers will need a leading comma.
593 /// Desc - Description of the Instruction
596 /// true - Emitted one or more registers.
597 /// false - Emitted no registers.
599 bool Printer::printImplDefsAfter(const TargetInstrDescriptor &Desc,
600 const bool Comma = true) {
601 const MRegisterInfo &RI = *TM.getRegisterInfo();
602 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
603 bool emitted = false;
604 const unsigned *p = Desc.ImplicitDefs;
606 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
611 // Bug Workaround: See note in Printer::doInitialization about %.
612 O << ", %" << RI.get(*p).Name;
620 /// printMachineInstruction -- Print out a single X86 LLVM instruction
621 /// MI in Intel syntax to the current output stream.
623 void Printer::printMachineInstruction(const MachineInstr *MI) {
624 unsigned Opcode = MI->getOpcode();
625 const TargetInstrInfo &TII = *TM.getInstrInfo();
626 const TargetInstrDescriptor &Desc = TII.get(Opcode);
629 switch (Desc.TSFlags & X86II::FormMask) {
631 // Print pseudo-instructions as comments; either they should have been
632 // turned into real instructions by now, or they don't need to be
633 // seen by the assembler (e.g., IMPLICIT_USEs.)
635 if (Opcode == X86::PHI) {
636 printOp(MI->getOperand(0));
638 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
639 if (i != 1) O << ", ";
641 printOp(MI->getOperand(i));
643 printOp(MI->getOperand(i+1));
648 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
649 printOp(MI->getOperand(0));
653 O << TII.getName(MI->getOpcode());
655 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
657 if (MI->getOperand(i).isDef()) O << "*";
658 printOp(MI->getOperand(i));
659 if (MI->getOperand(i).isDef()) O << "*";
667 // The accepted forms of Raw instructions are:
668 // 1. nop - No operand required
669 // 2. jmp foo - MachineBasicBlock operand
670 // 3. call bar - GlobalAddress Operand or External Symbol Operand
671 // 4. in AL, imm - Immediate operand
673 assert(MI->getNumOperands() == 0 ||
674 (MI->getNumOperands() == 1 &&
675 (MI->getOperand(0).isMachineBasicBlock() ||
676 MI->getOperand(0).isGlobalAddress() ||
677 MI->getOperand(0).isExternalSymbol() ||
678 MI->getOperand(0).isImmediate())) &&
679 "Illegal raw instruction!");
680 O << TII.getName(MI->getOpcode()) << " ";
682 bool LeadingComma = printImplDefsBefore(Desc);
684 if (MI->getNumOperands() == 1) {
685 if (LeadingComma) O << ", ";
686 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
689 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
690 printImplUsesAfter(Desc, LeadingComma);
695 case X86II::AddRegFrm: {
696 // There are currently two forms of acceptable AddRegFrm instructions.
697 // Either the instruction JUST takes a single register (like inc, dec, etc),
698 // or it takes a register and an immediate of the same size as the register
699 // (move immediate f.e.). Note that this immediate value might be stored as
700 // an LLVM value, to represent, for example, loading the address of a global
701 // into a register. The initial register might be duplicated if this is a
702 // M_2_ADDR_REG instruction
704 assert(MI->getOperand(0).isRegister() &&
705 (MI->getNumOperands() == 1 ||
706 (MI->getNumOperands() == 2 &&
707 (MI->getOperand(1).getVRegValueOrNull() ||
708 MI->getOperand(1).isImmediate() ||
709 MI->getOperand(1).isRegister() ||
710 MI->getOperand(1).isGlobalAddress() ||
711 MI->getOperand(1).isExternalSymbol()))) &&
712 "Illegal form for AddRegFrm instruction!");
714 unsigned Reg = MI->getOperand(0).getReg();
716 O << TII.getName(MI->getOpcode()) << " ";
718 printImplUsesBefore(Desc); // fcmov*
720 printOp(MI->getOperand(0));
721 if (MI->getNumOperands() == 2 &&
722 (!MI->getOperand(1).isRegister() ||
723 MI->getOperand(1).getVRegValueOrNull() ||
724 MI->getOperand(1).isGlobalAddress() ||
725 MI->getOperand(1).isExternalSymbol())) {
727 printOp(MI->getOperand(1));
729 printImplUsesAfter(Desc);
733 case X86II::MRMDestReg: {
734 // There are three forms of MRMDestReg instructions, those with 2
737 // 2 Operands: this is for things like mov that do not read a
740 // 2 Operands: two address instructions which def&use the first
741 // argument and use the second as input.
743 // 3 Operands: in this form, two address instructions are the same
744 // as in 2 but have a constant argument as well.
746 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
747 assert(MI->getOperand(0).isRegister() &&
748 (MI->getNumOperands() == 2 ||
749 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
750 && "Bad format for MRMDestReg!");
752 O << TII.getName(MI->getOpcode()) << " ";
753 printOp(MI->getOperand(0));
755 printOp(MI->getOperand(1));
756 if (MI->getNumOperands() == 3) {
758 printOp(MI->getOperand(2));
760 printImplUsesAfter(Desc);
765 case X86II::MRMDestMem: {
766 // These instructions are the same as MRMDestReg, but instead of having a
767 // register reference for the mod/rm field, it's a memory reference.
769 assert(isMem(MI, 0) &&
770 (MI->getNumOperands() == 4+1 ||
771 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
772 && "Bad format for MRMDestMem!");
774 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
775 printMemReference(MI, 0);
777 printOp(MI->getOperand(4));
778 if (MI->getNumOperands() == 4+2) {
780 printOp(MI->getOperand(5));
782 printImplUsesAfter(Desc);
787 case X86II::MRMSrcReg: {
788 // There are three forms that are acceptable for MRMSrcReg
789 // instructions, those with 2 or 3 operands:
791 // 2 Operands: this is for things like mov that do not read a
794 // 2 Operands: in this form, the last register is the ModR/M
795 // input. The first operand is a def&use. This is for things
796 // like: add r32, r/m32
798 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
799 // for instructions like the IMULrri instructions.
802 assert(MI->getOperand(0).isRegister() &&
803 MI->getOperand(1).isRegister() &&
804 (MI->getNumOperands() == 2 ||
805 (MI->getNumOperands() == 3 &&
806 (MI->getOperand(2).isImmediate())))
807 && "Bad format for MRMSrcReg!");
809 O << TII.getName(MI->getOpcode()) << " ";
810 printOp(MI->getOperand(0));
812 printOp(MI->getOperand(1));
813 if (MI->getNumOperands() == 3) {
815 printOp(MI->getOperand(2));
821 case X86II::MRMSrcMem: {
822 // These instructions are the same as MRMSrcReg, but instead of having a
823 // register reference for the mod/rm field, it's a memory reference.
825 assert(MI->getOperand(0).isRegister() &&
826 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
827 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
829 && "Bad format for MRMSrcMem!");
830 O << TII.getName(MI->getOpcode()) << " ";
831 printOp(MI->getOperand(0));
832 O << ", " << sizePtr(Desc) << " ";
833 printMemReference(MI, 1);
834 if (MI->getNumOperands() == 2+4) {
836 printOp(MI->getOperand(5));
842 case X86II::MRM0r: case X86II::MRM1r:
843 case X86II::MRM2r: case X86II::MRM3r:
844 case X86II::MRM4r: case X86II::MRM5r:
845 case X86II::MRM6r: case X86II::MRM7r: {
846 // In this form, the following are valid formats:
848 // 2. cmp reg, immediate
849 // 2. shl rdest, rinput <implicit CL or 1>
850 // 3. sbb rdest, rinput, immediate [rdest = rinput]
852 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
853 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
854 assert((MI->getNumOperands() != 2 ||
855 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
856 "Bad MRMSxR format!");
857 assert((MI->getNumOperands() < 3 ||
858 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
859 "Bad MRMSxR format!");
861 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
862 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
865 O << TII.getName(MI->getOpcode()) << " ";
866 printOp(MI->getOperand(0));
867 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
869 printOp(MI->getOperand(MI->getNumOperands()-1));
871 printImplUsesAfter(Desc);
877 case X86II::MRM0m: case X86II::MRM1m:
878 case X86II::MRM2m: case X86II::MRM3m:
879 case X86II::MRM4m: case X86II::MRM5m:
880 case X86II::MRM6m: case X86II::MRM7m: {
881 // In this form, the following are valid formats:
883 // 2. cmp [m], immediate
884 // 2. shl [m], rinput <implicit CL or 1>
885 // 3. sbb [m], immediate
887 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
888 isMem(MI, 0) && "Bad MRMSxM format!");
889 assert((MI->getNumOperands() != 5 ||
890 (MI->getOperand(4).isImmediate() ||
891 MI->getOperand(4).isGlobalAddress())) &&
892 "Bad MRMSxM format!");
894 const MachineOperand &Op3 = MI->getOperand(3);
898 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
899 // is misassembled by gas in intel_syntax mode as its 32-bit
900 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
901 // opcode bytes instead of the instruction.
903 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
904 // misassembled by gas in intel_syntax mode as its 32-bit
905 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
906 // opcode bytes instead of the instruction.
908 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
909 // invalid opcode, saying "64 bit operations are only supported in
910 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
911 // [...]", which is wrong. Workaround: Output the raw opcode bytes
912 // instead of the instruction.
914 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
915 // invalid opcode, saying "64 bit operations are only supported in
916 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
917 // [...]", which is wrong. Workaround: Output the raw opcode bytes
918 // instead of the instruction.
919 if (MI->getOpcode() == X86::FSTP80m ||
920 MI->getOpcode() == X86::FLD80m ||
921 MI->getOpcode() == X86::FILD64m ||
922 MI->getOpcode() == X86::FISTP64m) {
923 GasBugWorkaroundEmitter gwe(O);
924 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
927 O << TII.getName(MI->getOpcode()) << " ";
928 O << sizePtr(Desc) << " ";
929 printMemReference(MI, 0);
930 if (MI->getNumOperands() == 5) {
932 printOp(MI->getOperand(4));
934 printImplUsesAfter(Desc);
939 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
943 bool Printer::doInitialization(Module &M) {
944 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
946 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
947 // instruction as a reference to the register named sp, and if you try to
948 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
949 // before being looked up in the symbol table. This creates spurious
950 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
951 // mode, and decorate all register names with percent signs.
952 O << "\t.intel_syntax\n";
953 Mang = new Mangler(M, EmitCygwin);
954 return false; // success
957 // SwitchSection - Switch to the specified section of the executable if we are
958 // not already in it!
960 static void SwitchSection(std::ostream &OS, std::string &CurSection,
961 const char *NewSection) {
962 if (CurSection != NewSection) {
963 CurSection = NewSection;
964 if (!CurSection.empty())
965 OS << "\t" << NewSection << "\n";
969 bool Printer::doFinalization(Module &M) {
970 const TargetData &TD = TM.getTargetData();
971 std::string CurSection;
973 // Print out module-level global variables here.
974 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
975 if (I->hasInitializer()) { // External global require no code
977 std::string name = Mang->getValueName(I);
978 Constant *C = I->getInitializer();
979 unsigned Size = TD.getTypeSize(C->getType());
980 unsigned Align = TD.getTypeAlignment(C->getType());
982 if (C->isNullValue() &&
983 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
984 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
985 SwitchSection(O, CurSection, ".data");
986 if (I->hasInternalLinkage())
987 O << "\t.local " << name << "\n";
989 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
990 << "," << (unsigned)TD.getTypeAlignment(C->getType());
992 WriteAsOperand(O, I, true, true, &M);
995 switch (I->getLinkage()) {
996 case GlobalValue::LinkOnceLinkage:
997 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
998 // Nonnull linkonce -> weak
999 O << "\t.weak " << name << "\n";
1000 SwitchSection(O, CurSection, "");
1001 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
1004 case GlobalValue::AppendingLinkage:
1005 // FIXME: appending linkage variables should go into a section of
1006 // their name or something. For now, just emit them as external.
1007 case GlobalValue::ExternalLinkage:
1008 // If external or appending, declare as a global symbol
1009 O << "\t.globl " << name << "\n";
1011 case GlobalValue::InternalLinkage:
1012 if (C->isNullValue())
1013 SwitchSection(O, CurSection, ".bss");
1015 SwitchSection(O, CurSection, ".data");
1019 O << "\t.align " << Align << "\n";
1020 O << "\t.type " << name << ",@object\n";
1021 O << "\t.size " << name << "," << Size << "\n";
1022 O << name << ":\t\t\t\t# ";
1023 WriteAsOperand(O, I, true, true, &M);
1025 WriteAsOperand(O, C, false, false, &M);
1027 emitGlobalConstant(C);
1032 return false; // success