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,
106 bool elideOffsetKeyword = false);
107 void printMemReference(const MachineInstr *MI, unsigned Op);
108 void printConstantPool(MachineConstantPool *MCP);
109 bool runOnMachineFunction(MachineFunction &F);
110 bool doInitialization(Module &M);
111 bool doFinalization(Module &M);
112 void emitGlobalConstant(const Constant* CV);
113 void emitConstantValueOnly(const Constant *CV);
115 } // end of anonymous namespace
117 /// createX86CodePrinterPass - Returns a pass that prints the X86
118 /// assembly code for a MachineFunction to the given output stream,
119 /// using the given target machine description. This should work
120 /// regardless of whether the function is in SSA form.
122 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
123 return new Printer(o, tm);
126 /// toOctal - Convert the low order bits of X into an octal digit.
128 static inline char toOctal(int X) {
132 /// getAsCString - Return the specified array as a C compatible
133 /// string, only if the predicate isStringCompatible is true.
135 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
136 assert(CVA->isString() && "Array is not string compatible!");
139 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
140 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
144 } else if (C == '\\') {
146 } else if (isprint(C)) {
150 case '\b': O << "\\b"; break;
151 case '\f': O << "\\f"; break;
152 case '\n': O << "\\n"; break;
153 case '\r': O << "\\r"; break;
154 case '\t': O << "\\t"; break;
157 O << toOctal(C >> 6);
158 O << toOctal(C >> 3);
159 O << toOctal(C >> 0);
167 // Print out the specified constant, without a storage class. Only the
168 // constants valid in constant expressions can occur here.
169 void Printer::emitConstantValueOnly(const Constant *CV) {
170 if (CV->isNullValue())
172 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
173 assert(CB == ConstantBool::True);
175 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
176 if (((CI->getValue() << 32) >> 32) == CI->getValue())
179 O << (unsigned long long)CI->getValue();
180 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
182 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
183 // This is a constant address for a global variable or function. Use the
184 // name of the variable or function as the address value.
185 O << Mang->getValueName(CPR->getValue());
186 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
187 const TargetData &TD = TM.getTargetData();
188 switch(CE->getOpcode()) {
189 case Instruction::GetElementPtr: {
190 // generate a symbolic expression for the byte address
191 const Constant *ptrVal = CE->getOperand(0);
192 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
193 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
195 emitConstantValueOnly(ptrVal);
196 O << ") + " << Offset;
198 emitConstantValueOnly(ptrVal);
202 case Instruction::Cast: {
203 // Support only non-converting or widening casts for now, that is, ones
204 // that do not involve a change in value. This assertion is really gross,
205 // and may not even be a complete check.
206 Constant *Op = CE->getOperand(0);
207 const Type *OpTy = Op->getType(), *Ty = CE->getType();
209 // Remember, kids, pointers on x86 can be losslessly converted back and
210 // forth into 32-bit or wider integers, regardless of signedness. :-P
211 assert(((isa<PointerType>(OpTy)
212 && (Ty == Type::LongTy || Ty == Type::ULongTy
213 || Ty == Type::IntTy || Ty == Type::UIntTy))
214 || (isa<PointerType>(Ty)
215 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
216 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
217 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
218 && OpTy->isLosslesslyConvertibleTo(Ty))))
219 && "FIXME: Don't yet support this kind of constant cast expr");
221 emitConstantValueOnly(Op);
225 case Instruction::Add:
227 emitConstantValueOnly(CE->getOperand(0));
229 emitConstantValueOnly(CE->getOperand(1));
233 assert(0 && "Unsupported operator!");
236 assert(0 && "Unknown constant value!");
240 // Print a constant value or values, with the appropriate storage class as a
242 void Printer::emitGlobalConstant(const Constant *CV) {
243 const TargetData &TD = TM.getTargetData();
245 if (CV->isNullValue()) {
246 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
248 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
249 if (CVA->isString()) {
251 printAsCString(O, CVA);
253 } else { // Not a string. Print the values in successive locations
254 const std::vector<Use> &constValues = CVA->getValues();
255 for (unsigned i=0; i < constValues.size(); i++)
256 emitGlobalConstant(cast<Constant>(constValues[i].get()));
259 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
260 // Print the fields in successive locations. Pad to align if needed!
261 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
262 const std::vector<Use>& constValues = CVS->getValues();
263 unsigned sizeSoFar = 0;
264 for (unsigned i=0, N = constValues.size(); i < N; i++) {
265 const Constant* field = cast<Constant>(constValues[i].get());
267 // Check if padding is needed and insert one or more 0s.
268 unsigned fieldSize = TD.getTypeSize(field->getType());
269 unsigned padSize = ((i == N-1? cvsLayout->StructSize
270 : cvsLayout->MemberOffsets[i+1])
271 - cvsLayout->MemberOffsets[i]) - fieldSize;
272 sizeSoFar += fieldSize + padSize;
274 // Now print the actual field value
275 emitGlobalConstant(field);
277 // Insert the field padding unless it's zero bytes...
279 O << "\t.zero\t " << padSize << "\n";
281 assert(sizeSoFar == cvsLayout->StructSize &&
282 "Layout of constant struct may be incorrect!");
284 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
285 // FP Constants are printed as integer constants to avoid losing
287 double Val = CFP->getValue();
288 switch (CFP->getType()->getPrimitiveID()) {
289 default: assert(0 && "Unknown floating point type!");
290 case Type::FloatTyID: {
291 union FU { // Abide by C TBAA rules
296 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
299 case Type::DoubleTyID: {
300 union DU { // Abide by C TBAA rules
305 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
311 const Type *type = CV->getType();
313 switch (type->getPrimitiveID()) {
314 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
317 case Type::UShortTyID: case Type::ShortTyID:
320 case Type::FloatTyID: case Type::PointerTyID:
321 case Type::UIntTyID: case Type::IntTyID:
324 case Type::DoubleTyID:
325 case Type::ULongTyID: case Type::LongTyID:
329 assert (0 && "Can't handle printing this type of thing");
333 emitConstantValueOnly(CV);
337 /// printConstantPool - Print to the current output stream assembly
338 /// representations of the constants in the constant pool MCP. This is
339 /// used to print out constants which have been "spilled to memory" by
340 /// the code generator.
342 void Printer::printConstantPool(MachineConstantPool *MCP) {
343 const std::vector<Constant*> &CP = MCP->getConstants();
344 const TargetData &TD = TM.getTargetData();
346 if (CP.empty()) return;
348 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
349 O << "\t.section .rodata\n";
350 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
352 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
354 emitGlobalConstant(CP[i]);
358 /// runOnMachineFunction - This uses the printMachineInstruction()
359 /// method to print assembly for each instruction.
361 bool Printer::runOnMachineFunction(MachineFunction &MF) {
363 // What's my mangled name?
364 CurrentFnName = Mang->getValueName(MF.getFunction());
366 // Print out constants referenced by the function
367 printConstantPool(MF.getConstantPool());
369 // Print out labels for the function.
371 O << "\t.align 16\n";
372 O << "\t.globl\t" << CurrentFnName << "\n";
374 O << "\t.type\t" << CurrentFnName << ", @function\n";
375 O << CurrentFnName << ":\n";
377 // Print out code for the function.
378 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
380 // Print a label for the basic block.
381 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
382 << I->getBasicBlock()->getName() << "\n";
383 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
385 // Print the assembly for the instruction.
387 printMachineInstruction(II);
391 // We didn't modify anything.
395 static bool isScale(const MachineOperand &MO) {
396 return MO.isImmediate() &&
397 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
398 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
401 static bool isMem(const MachineInstr *MI, unsigned Op) {
402 if (MI->getOperand(Op).isFrameIndex()) return true;
403 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
404 return Op+4 <= MI->getNumOperands() &&
405 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
406 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
411 void Printer::printOp(const MachineOperand &MO,
412 bool elideOffsetKeyword /* = false */) {
413 const MRegisterInfo &RI = *TM.getRegisterInfo();
414 switch (MO.getType()) {
415 case MachineOperand::MO_VirtualRegister:
416 if (Value *V = MO.getVRegValueOrNull()) {
417 O << "<" << V->getName() << ">";
421 case MachineOperand::MO_MachineRegister:
422 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
423 // Bug Workaround: See note in Printer::doInitialization about %.
424 O << "%" << RI.get(MO.getReg()).Name;
426 O << "%reg" << MO.getReg();
429 case MachineOperand::MO_SignExtendedImmed:
430 case MachineOperand::MO_UnextendedImmed:
431 O << (int)MO.getImmedValue();
433 case MachineOperand::MO_MachineBasicBlock: {
434 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
435 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
436 << "_" << MBBOp->getNumber () << "\t# "
437 << MBBOp->getBasicBlock ()->getName ();
440 case MachineOperand::MO_PCRelativeDisp:
441 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
444 case MachineOperand::MO_GlobalAddress:
445 if (!elideOffsetKeyword)
447 O << Mang->getValueName(MO.getGlobal());
449 case MachineOperand::MO_ExternalSymbol:
450 O << MO.getSymbolName();
453 O << "<unknown operand type>"; return;
457 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
458 switch (Desc.TSFlags & X86II::MemMask) {
459 default: assert(0 && "Unknown arg size!");
460 case X86II::Mem8: return "BYTE PTR";
461 case X86II::Mem16: return "WORD PTR";
462 case X86II::Mem32: return "DWORD PTR";
463 case X86II::Mem64: return "QWORD PTR";
464 case X86II::Mem80: return "XWORD PTR";
468 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
469 assert(isMem(MI, Op) && "Invalid memory reference!");
471 if (MI->getOperand(Op).isFrameIndex()) {
472 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
473 if (MI->getOperand(Op+3).getImmedValue())
474 O << " + " << MI->getOperand(Op+3).getImmedValue();
477 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
478 O << "[.CPI" << CurrentFnName << "_"
479 << MI->getOperand(Op).getConstantPoolIndex();
480 if (MI->getOperand(Op+3).getImmedValue())
481 O << " + " << MI->getOperand(Op+3).getImmedValue();
486 const MachineOperand &BaseReg = MI->getOperand(Op);
487 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
488 const MachineOperand &IndexReg = MI->getOperand(Op+2);
489 int DispVal = MI->getOperand(Op+3).getImmedValue();
492 bool NeedPlus = false;
493 if (BaseReg.getReg()) {
498 if (IndexReg.getReg()) {
499 if (NeedPlus) O << " + ";
501 O << ScaleVal << "*";
520 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
521 /// described by DESC, if its PrintImplUsesBefore flag is set.
523 void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
524 const MRegisterInfo &RI = *TM.getRegisterInfo();
525 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
526 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
527 // Bug Workaround: See note in Printer::doInitialization about %.
528 O << "%" << RI.get(*p).Name << ", ";
533 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
534 /// described by DESC, if its PrintImplUsesBefore flag is set. Return true if
535 /// we printed any registers.
537 bool Printer::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
538 bool Printed = false;
539 const MRegisterInfo &RI = *TM.getRegisterInfo();
540 if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
541 const unsigned *p = Desc.ImplicitDefs;
543 O << (Printed ? ", %" : "%") << RI.get (*p).Name;
548 // Bug Workaround: See note in Printer::doInitialization about %.
549 O << ", %" << RI.get(*p).Name;
557 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
558 /// described by DESC, if its PrintImplUsesAfter flag is set.
561 /// Comma - List of registers will need a leading comma.
562 /// Desc - Description of the Instruction.
565 /// true - Emitted one or more registers.
566 /// false - Emitted no registers.
568 bool Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc,
569 const bool Comma = true) {
570 const MRegisterInfo &RI = *TM.getRegisterInfo();
571 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
572 bool emitted = false;
573 const unsigned *p = Desc.ImplicitUses;
575 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
580 // Bug Workaround: See note in Printer::doInitialization about %.
581 O << ", %" << RI.get(*p).Name;
589 /// printImplDefsAfter - Emit the implicit-definition registers for the
590 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
593 /// Comma - List of registers will need a leading comma.
594 /// Desc - Description of the Instruction
597 /// true - Emitted one or more registers.
598 /// false - Emitted no registers.
600 bool Printer::printImplDefsAfter(const TargetInstrDescriptor &Desc,
601 const bool Comma = true) {
602 const MRegisterInfo &RI = *TM.getRegisterInfo();
603 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
604 bool emitted = false;
605 const unsigned *p = Desc.ImplicitDefs;
607 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
612 // Bug Workaround: See note in Printer::doInitialization about %.
613 O << ", %" << RI.get(*p).Name;
621 /// printMachineInstruction -- Print out a single X86 LLVM instruction
622 /// MI in Intel syntax to the current output stream.
624 void Printer::printMachineInstruction(const MachineInstr *MI) {
625 unsigned Opcode = MI->getOpcode();
626 const TargetInstrInfo &TII = TM.getInstrInfo();
627 const TargetInstrDescriptor &Desc = TII.get(Opcode);
630 switch (Desc.TSFlags & X86II::FormMask) {
632 // Print pseudo-instructions as comments; either they should have been
633 // turned into real instructions by now, or they don't need to be
634 // seen by the assembler (e.g., IMPLICIT_USEs.)
636 if (Opcode == X86::PHI) {
637 printOp(MI->getOperand(0));
639 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
640 if (i != 1) O << ", ";
642 printOp(MI->getOperand(i));
644 printOp(MI->getOperand(i+1));
649 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
650 printOp(MI->getOperand(0));
654 O << TII.getName(MI->getOpcode());
656 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
658 if (MI->getOperand(i).isDef()) O << "*";
659 printOp(MI->getOperand(i));
660 if (MI->getOperand(i).isDef()) O << "*";
668 // The accepted forms of Raw instructions are:
669 // 1. nop - No operand required
670 // 2. jmp foo - MachineBasicBlock operand
671 // 3. call bar - GlobalAddress Operand or External Symbol Operand
672 // 4. in AL, imm - Immediate operand
674 assert(MI->getNumOperands() == 0 ||
675 (MI->getNumOperands() == 1 &&
676 (MI->getOperand(0).isMachineBasicBlock() ||
677 MI->getOperand(0).isGlobalAddress() ||
678 MI->getOperand(0).isExternalSymbol() ||
679 MI->getOperand(0).isImmediate())) &&
680 "Illegal raw instruction!");
681 O << TII.getName(MI->getOpcode()) << " ";
683 bool LeadingComma = printImplDefsBefore(Desc);
685 if (MI->getNumOperands() == 1) {
686 if (LeadingComma) O << ", ";
687 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
690 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
691 printImplUsesAfter(Desc, LeadingComma);
696 case X86II::AddRegFrm: {
697 // There are currently two forms of acceptable AddRegFrm instructions.
698 // Either the instruction JUST takes a single register (like inc, dec, etc),
699 // or it takes a register and an immediate of the same size as the register
700 // (move immediate f.e.). Note that this immediate value might be stored as
701 // an LLVM value, to represent, for example, loading the address of a global
702 // into a register. The initial register might be duplicated if this is a
703 // M_2_ADDR_REG instruction
705 assert(MI->getOperand(0).isRegister() &&
706 (MI->getNumOperands() == 1 ||
707 (MI->getNumOperands() == 2 &&
708 (MI->getOperand(1).getVRegValueOrNull() ||
709 MI->getOperand(1).isImmediate() ||
710 MI->getOperand(1).isRegister() ||
711 MI->getOperand(1).isGlobalAddress() ||
712 MI->getOperand(1).isExternalSymbol()))) &&
713 "Illegal form for AddRegFrm instruction!");
715 unsigned Reg = MI->getOperand(0).getReg();
717 O << TII.getName(MI->getOpcode()) << " ";
719 printImplUsesBefore(Desc); // fcmov*
721 printOp(MI->getOperand(0));
722 if (MI->getNumOperands() == 2 &&
723 (!MI->getOperand(1).isRegister() ||
724 MI->getOperand(1).getVRegValueOrNull() ||
725 MI->getOperand(1).isGlobalAddress() ||
726 MI->getOperand(1).isExternalSymbol())) {
728 printOp(MI->getOperand(1));
730 printImplUsesAfter(Desc);
734 case X86II::MRMDestReg: {
735 // There are three forms of MRMDestReg instructions, those with 2
738 // 2 Operands: this is for things like mov that do not read a
741 // 2 Operands: two address instructions which def&use the first
742 // argument and use the second as input.
744 // 3 Operands: in this form, two address instructions are the same
745 // as in 2 but have a constant argument as well.
747 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
748 assert(MI->getOperand(0).isRegister() &&
749 (MI->getNumOperands() == 2 ||
750 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
751 && "Bad format for MRMDestReg!");
753 O << TII.getName(MI->getOpcode()) << " ";
754 printOp(MI->getOperand(0));
756 printOp(MI->getOperand(1));
757 if (MI->getNumOperands() == 3) {
759 printOp(MI->getOperand(2));
761 printImplUsesAfter(Desc);
766 case X86II::MRMDestMem: {
767 // These instructions are the same as MRMDestReg, but instead of having a
768 // register reference for the mod/rm field, it's a memory reference.
770 assert(isMem(MI, 0) &&
771 (MI->getNumOperands() == 4+1 ||
772 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
773 && "Bad format for MRMDestMem!");
775 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
776 printMemReference(MI, 0);
778 printOp(MI->getOperand(4));
779 if (MI->getNumOperands() == 4+2) {
781 printOp(MI->getOperand(5));
783 printImplUsesAfter(Desc);
788 case X86II::MRMSrcReg: {
789 // There are three forms that are acceptable for MRMSrcReg
790 // instructions, those with 2 or 3 operands:
792 // 2 Operands: this is for things like mov that do not read a
795 // 2 Operands: in this form, the last register is the ModR/M
796 // input. The first operand is a def&use. This is for things
797 // like: add r32, r/m32
799 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
800 // for instructions like the IMULrri instructions.
803 assert(MI->getOperand(0).isRegister() &&
804 MI->getOperand(1).isRegister() &&
805 (MI->getNumOperands() == 2 ||
806 (MI->getNumOperands() == 3 &&
807 (MI->getOperand(2).isImmediate())))
808 && "Bad format for MRMSrcReg!");
810 O << TII.getName(MI->getOpcode()) << " ";
811 printOp(MI->getOperand(0));
813 printOp(MI->getOperand(1));
814 if (MI->getNumOperands() == 3) {
816 printOp(MI->getOperand(2));
822 case X86II::MRMSrcMem: {
823 // These instructions are the same as MRMSrcReg, but instead of having a
824 // register reference for the mod/rm field, it's a memory reference.
826 assert(MI->getOperand(0).isRegister() &&
827 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
828 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
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