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 printImplDefsBefore(const TargetInstrDescriptor &Desc);
109 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
110 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
111 void printMachineInstruction(const MachineInstr *MI);
112 void printOp(const MachineOperand &MO,
113 bool elideOffsetKeyword = false);
114 void printMemReference(const MachineInstr *MI, unsigned Op);
115 void printConstantPool(MachineConstantPool *MCP);
116 bool runOnMachineFunction(MachineFunction &F);
117 bool doInitialization(Module &M);
118 bool doFinalization(Module &M);
119 void emitGlobalConstant(const Constant* CV);
120 void emitConstantValueOnly(const Constant *CV);
122 } // end of anonymous namespace
124 /// createX86CodePrinterPass - Returns a pass that prints the X86
125 /// assembly code for a MachineFunction to the given output stream,
126 /// using the given target machine description. This should work
127 /// regardless of whether the function is in SSA form.
129 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
130 return new Printer(o, tm);
133 /// toOctal - Convert the low order bits of X into an octal digit.
135 static inline char toOctal(int X) {
139 /// getAsCString - Return the specified array as a C compatible
140 /// string, only if the predicate isStringCompatible is true.
142 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
143 assert(CVA->isString() && "Array is not string compatible!");
146 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
147 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
151 } else if (C == '\\') {
153 } else if (isprint(C)) {
157 case '\b': O << "\\b"; break;
158 case '\f': O << "\\f"; break;
159 case '\n': O << "\\n"; break;
160 case '\r': O << "\\r"; break;
161 case '\t': O << "\\t"; break;
164 O << toOctal(C >> 6);
165 O << toOctal(C >> 3);
166 O << toOctal(C >> 0);
174 // Print out the specified constant, without a storage class. Only the
175 // constants valid in constant expressions can occur here.
176 void Printer::emitConstantValueOnly(const Constant *CV) {
177 if (CV->isNullValue())
179 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
180 assert(CB == ConstantBool::True);
182 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
183 if (((CI->getValue() << 32) >> 32) == CI->getValue())
186 O << (unsigned long long)CI->getValue();
187 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
189 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
190 // This is a constant address for a global variable or function. Use the
191 // name of the variable or function as the address value.
192 O << Mang->getValueName(CPR->getValue());
193 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
194 const TargetData &TD = TM.getTargetData();
195 switch(CE->getOpcode()) {
196 case Instruction::GetElementPtr: {
197 // generate a symbolic expression for the byte address
198 const Constant *ptrVal = CE->getOperand(0);
199 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
200 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
202 emitConstantValueOnly(ptrVal);
203 O << ") + " << Offset;
205 emitConstantValueOnly(ptrVal);
209 case Instruction::Cast: {
210 // Support only non-converting or widening casts for now, that is, ones
211 // that do not involve a change in value. This assertion is really gross,
212 // and may not even be a complete check.
213 Constant *Op = CE->getOperand(0);
214 const Type *OpTy = Op->getType(), *Ty = CE->getType();
216 // Remember, kids, pointers on x86 can be losslessly converted back and
217 // forth into 32-bit or wider integers, regardless of signedness. :-P
218 assert(((isa<PointerType>(OpTy)
219 && (Ty == Type::LongTy || Ty == Type::ULongTy
220 || Ty == Type::IntTy || Ty == Type::UIntTy))
221 || (isa<PointerType>(Ty)
222 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
223 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
224 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
225 && OpTy->isLosslesslyConvertibleTo(Ty))))
226 && "FIXME: Don't yet support this kind of constant cast expr");
228 emitConstantValueOnly(Op);
232 case Instruction::Add:
234 emitConstantValueOnly(CE->getOperand(0));
236 emitConstantValueOnly(CE->getOperand(1));
240 assert(0 && "Unsupported operator!");
243 assert(0 && "Unknown constant value!");
247 // Print a constant value or values, with the appropriate storage class as a
249 void Printer::emitGlobalConstant(const Constant *CV) {
250 const TargetData &TD = TM.getTargetData();
252 if (CV->isNullValue()) {
253 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
255 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
256 if (CVA->isString()) {
258 printAsCString(O, CVA);
260 } else { // Not a string. Print the values in successive locations
261 const std::vector<Use> &constValues = CVA->getValues();
262 for (unsigned i=0; i < constValues.size(); i++)
263 emitGlobalConstant(cast<Constant>(constValues[i].get()));
266 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
267 // Print the fields in successive locations. Pad to align if needed!
268 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
269 const std::vector<Use>& constValues = CVS->getValues();
270 unsigned sizeSoFar = 0;
271 for (unsigned i=0, N = constValues.size(); i < N; i++) {
272 const Constant* field = cast<Constant>(constValues[i].get());
274 // Check if padding is needed and insert one or more 0s.
275 unsigned fieldSize = TD.getTypeSize(field->getType());
276 unsigned padSize = ((i == N-1? cvsLayout->StructSize
277 : cvsLayout->MemberOffsets[i+1])
278 - cvsLayout->MemberOffsets[i]) - fieldSize;
279 sizeSoFar += fieldSize + padSize;
281 // Now print the actual field value
282 emitGlobalConstant(field);
284 // Insert the field padding unless it's zero bytes...
286 O << "\t.zero\t " << padSize << "\n";
288 assert(sizeSoFar == cvsLayout->StructSize &&
289 "Layout of constant struct may be incorrect!");
291 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
292 // FP Constants are printed as integer constants to avoid losing
294 double Val = CFP->getValue();
295 switch (CFP->getType()->getPrimitiveID()) {
296 default: assert(0 && "Unknown floating point type!");
297 case Type::FloatTyID: {
298 union FU { // Abide by C TBAA rules
303 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
306 case Type::DoubleTyID: {
307 union DU { // Abide by C TBAA rules
312 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
318 const Type *type = CV->getType();
320 switch (type->getPrimitiveID()) {
321 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
324 case Type::UShortTyID: case Type::ShortTyID:
327 case Type::FloatTyID: case Type::PointerTyID:
328 case Type::UIntTyID: case Type::IntTyID:
331 case Type::DoubleTyID:
332 case Type::ULongTyID: case Type::LongTyID:
336 assert (0 && "Can't handle printing this type of thing");
340 emitConstantValueOnly(CV);
344 /// printConstantPool - Print to the current output stream assembly
345 /// representations of the constants in the constant pool MCP. This is
346 /// used to print out constants which have been "spilled to memory" by
347 /// the code generator.
349 void Printer::printConstantPool(MachineConstantPool *MCP) {
350 const std::vector<Constant*> &CP = MCP->getConstants();
351 const TargetData &TD = TM.getTargetData();
353 if (CP.empty()) return;
355 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
356 O << "\t.section .rodata\n";
357 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
359 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
361 emitGlobalConstant(CP[i]);
365 /// runOnMachineFunction - This uses the printMachineInstruction()
366 /// method to print assembly for each instruction.
368 bool Printer::runOnMachineFunction(MachineFunction &MF) {
369 // BBNumber is used here so that a given Printer will never give two
370 // BBs the same name. (If you have a better way, please let me know!)
371 static unsigned BBNumber = 0;
374 // What's my mangled name?
375 CurrentFnName = Mang->getValueName(MF.getFunction());
377 // Print out constants referenced by the function
378 printConstantPool(MF.getConstantPool());
380 // Print out labels for the function.
382 O << "\t.align 16\n";
383 O << "\t.globl\t" << CurrentFnName << "\n";
385 O << "\t.type\t" << CurrentFnName << ", @function\n";
386 O << CurrentFnName << ":\n";
388 // Number each basic block so that we can consistently refer to them
389 // in PC-relative references.
391 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
393 NumberForBB[I->getBasicBlock()] = BBNumber++;
396 // Print out code for the function.
397 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
399 // Print a label for the basic block.
400 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
401 << I->getBasicBlock()->getName() << "\n";
402 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
404 // Print the assembly for the instruction.
406 printMachineInstruction(II);
410 // We didn't modify anything.
414 static bool isScale(const MachineOperand &MO) {
415 return MO.isImmediate() &&
416 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
417 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
420 static bool isMem(const MachineInstr *MI, unsigned Op) {
421 if (MI->getOperand(Op).isFrameIndex()) return true;
422 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
423 return Op+4 <= MI->getNumOperands() &&
424 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
425 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
430 void Printer::printOp(const MachineOperand &MO,
431 bool elideOffsetKeyword /* = false */) {
432 const MRegisterInfo &RI = *TM.getRegisterInfo();
433 switch (MO.getType()) {
434 case MachineOperand::MO_VirtualRegister:
435 if (Value *V = MO.getVRegValueOrNull()) {
436 O << "<" << V->getName() << ">";
440 case MachineOperand::MO_MachineRegister:
441 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
442 // Bug Workaround: See note in Printer::doInitialization about %.
443 O << "%" << RI.get(MO.getReg()).Name;
445 O << "%reg" << MO.getReg();
448 case MachineOperand::MO_SignExtendedImmed:
449 case MachineOperand::MO_UnextendedImmed:
450 O << (int)MO.getImmedValue();
452 case MachineOperand::MO_PCRelativeDisp: {
453 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
454 assert (i != NumberForBB.end()
455 && "Could not find a BB in the NumberForBB map!");
456 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
459 case MachineOperand::MO_GlobalAddress:
460 if (!elideOffsetKeyword)
462 O << Mang->getValueName(MO.getGlobal());
464 case MachineOperand::MO_ExternalSymbol:
465 O << MO.getSymbolName();
468 O << "<unknown operand type>"; return;
472 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
473 switch (Desc.TSFlags & X86II::MemMask) {
474 default: assert(0 && "Unknown arg size!");
475 case X86II::Mem8: return "BYTE PTR";
476 case X86II::Mem16: return "WORD PTR";
477 case X86II::Mem32: return "DWORD PTR";
478 case X86II::Mem64: return "QWORD PTR";
479 case X86II::Mem80: return "XWORD PTR";
483 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
484 assert(isMem(MI, Op) && "Invalid memory reference!");
486 if (MI->getOperand(Op).isFrameIndex()) {
487 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
488 if (MI->getOperand(Op+3).getImmedValue())
489 O << " + " << MI->getOperand(Op+3).getImmedValue();
492 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
493 O << "[.CPI" << CurrentFnName << "_"
494 << MI->getOperand(Op).getConstantPoolIndex();
495 if (MI->getOperand(Op+3).getImmedValue())
496 O << " + " << MI->getOperand(Op+3).getImmedValue();
501 const MachineOperand &BaseReg = MI->getOperand(Op);
502 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
503 const MachineOperand &IndexReg = MI->getOperand(Op+2);
504 int DispVal = MI->getOperand(Op+3).getImmedValue();
507 bool NeedPlus = false;
508 if (BaseReg.getReg()) {
513 if (IndexReg.getReg()) {
514 if (NeedPlus) O << " + ";
516 O << ScaleVal << "*";
535 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
536 /// described by DESC, if its PrintImplUsesBefore flag is set.
538 void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
539 const MRegisterInfo &RI = *TM.getRegisterInfo();
540 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
541 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
542 // Bug Workaround: See note in Printer::doInitialization about %.
543 O << "%" << RI.get(*p).Name << ", ";
548 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
549 /// described by DESC, if its PrintImplUsesBefore flag is set. Return true if
550 /// we printed any registers.
552 bool Printer::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
553 bool Printed = false;
554 const MRegisterInfo &RI = *TM.getRegisterInfo();
555 if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
556 const unsigned *p = Desc.ImplicitDefs;
558 O << (Printed ? ", %" : "%") << RI.get (*p).Name;
563 // Bug Workaround: See note in Printer::doInitialization about %.
564 O << ", %" << RI.get(*p).Name;
572 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
573 /// described by DESC, if its PrintImplUsesAfter flag is set.
576 /// Comma - List of registers will need a leading comma.
577 /// Desc - Description of the Instruction.
580 /// true - Emitted one or more registers.
581 /// false - Emitted no registers.
583 bool Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc,
584 const bool Comma = true) {
585 const MRegisterInfo &RI = *TM.getRegisterInfo();
586 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
587 bool emitted = false;
588 const unsigned *p = Desc.ImplicitUses;
590 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
595 // Bug Workaround: See note in Printer::doInitialization about %.
596 O << ", %" << RI.get(*p).Name;
604 /// printImplDefsAfter - Emit the implicit-definition registers for the
605 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
608 /// Comma - List of registers will need a leading comma.
609 /// Desc - Description of the Instruction
612 /// true - Emitted one or more registers.
613 /// false - Emitted no registers.
615 bool Printer::printImplDefsAfter(const TargetInstrDescriptor &Desc,
616 const bool Comma = true) {
617 const MRegisterInfo &RI = *TM.getRegisterInfo();
618 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
619 bool emitted = false;
620 const unsigned *p = Desc.ImplicitDefs;
622 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
627 // Bug Workaround: See note in Printer::doInitialization about %.
628 O << ", %" << RI.get(*p).Name;
636 /// printMachineInstruction -- Print out a single X86 LLVM instruction
637 /// MI in Intel syntax to the current output stream.
639 void Printer::printMachineInstruction(const MachineInstr *MI) {
640 unsigned Opcode = MI->getOpcode();
641 const TargetInstrInfo &TII = TM.getInstrInfo();
642 const TargetInstrDescriptor &Desc = TII.get(Opcode);
645 switch (Desc.TSFlags & X86II::FormMask) {
647 // Print pseudo-instructions as comments; either they should have been
648 // turned into real instructions by now, or they don't need to be
649 // seen by the assembler (e.g., IMPLICIT_USEs.)
651 if (Opcode == X86::PHI) {
652 printOp(MI->getOperand(0));
654 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
655 if (i != 1) O << ", ";
657 printOp(MI->getOperand(i));
659 printOp(MI->getOperand(i+1));
664 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
665 printOp(MI->getOperand(0));
669 O << TII.getName(MI->getOpcode());
671 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
673 if (MI->getOperand(i).isDef()) O << "*";
674 printOp(MI->getOperand(i));
675 if (MI->getOperand(i).isDef()) O << "*";
683 // The accepted forms of Raw instructions are:
684 // 1. nop - No operand required
685 // 2. jmp foo - PC relative displacement operand
686 // 3. call bar - GlobalAddress Operand or External Symbol Operand
687 // 4. in AL, imm - Immediate operand
689 assert(MI->getNumOperands() == 0 ||
690 (MI->getNumOperands() == 1 &&
691 (MI->getOperand(0).isPCRelativeDisp() ||
692 MI->getOperand(0).isGlobalAddress() ||
693 MI->getOperand(0).isExternalSymbol() ||
694 MI->getOperand(0).isImmediate())) &&
695 "Illegal raw instruction!");
696 O << TII.getName(MI->getOpcode()) << " ";
698 bool LeadingComma = printImplDefsBefore(Desc);
700 if (MI->getNumOperands() == 1) {
701 if (LeadingComma) O << ", ";
702 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
705 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
706 printImplUsesAfter(Desc, LeadingComma);
711 case X86II::AddRegFrm: {
712 // There are currently two forms of acceptable AddRegFrm instructions.
713 // Either the instruction JUST takes a single register (like inc, dec, etc),
714 // or it takes a register and an immediate of the same size as the register
715 // (move immediate f.e.). Note that this immediate value might be stored as
716 // an LLVM value, to represent, for example, loading the address of a global
717 // into a register. The initial register might be duplicated if this is a
718 // M_2_ADDR_REG instruction
720 assert(MI->getOperand(0).isRegister() &&
721 (MI->getNumOperands() == 1 ||
722 (MI->getNumOperands() == 2 &&
723 (MI->getOperand(1).getVRegValueOrNull() ||
724 MI->getOperand(1).isImmediate() ||
725 MI->getOperand(1).isRegister() ||
726 MI->getOperand(1).isGlobalAddress() ||
727 MI->getOperand(1).isExternalSymbol()))) &&
728 "Illegal form for AddRegFrm instruction!");
730 unsigned Reg = MI->getOperand(0).getReg();
732 O << TII.getName(MI->getOpcode()) << " ";
734 printImplUsesBefore(Desc); // fcmov*
736 printOp(MI->getOperand(0));
737 if (MI->getNumOperands() == 2 &&
738 (!MI->getOperand(1).isRegister() ||
739 MI->getOperand(1).getVRegValueOrNull() ||
740 MI->getOperand(1).isGlobalAddress() ||
741 MI->getOperand(1).isExternalSymbol())) {
743 printOp(MI->getOperand(1));
745 printImplUsesAfter(Desc);
749 case X86II::MRMDestReg: {
750 // There are three forms of MRMDestReg instructions, those with 2
753 // 2 Operands: this is for things like mov that do not read a
756 // 2 Operands: two address instructions which def&use the first
757 // argument and use the second as input.
759 // 3 Operands: in this form, two address instructions are the same
760 // as in 2 but have a constant argument as well.
762 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
763 assert(MI->getOperand(0).isRegister() &&
764 (MI->getNumOperands() == 2 ||
765 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
766 && "Bad format for MRMDestReg!");
768 O << TII.getName(MI->getOpcode()) << " ";
769 printOp(MI->getOperand(0));
771 printOp(MI->getOperand(1));
772 if (MI->getNumOperands() == 3) {
774 printOp(MI->getOperand(2));
776 printImplUsesAfter(Desc);
781 case X86II::MRMDestMem: {
782 // These instructions are the same as MRMDestReg, but instead of having a
783 // register reference for the mod/rm field, it's a memory reference.
785 assert(isMem(MI, 0) &&
786 (MI->getNumOperands() == 4+1 ||
787 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
788 && "Bad format for MRMDestMem!");
790 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
791 printMemReference(MI, 0);
793 printOp(MI->getOperand(4));
794 if (MI->getNumOperands() == 4+2) {
796 printOp(MI->getOperand(5));
798 printImplUsesAfter(Desc);
803 case X86II::MRMSrcReg: {
804 // There are three forms that are acceptable for MRMSrcReg
805 // instructions, those with 2 or 3 operands:
807 // 2 Operands: this is for things like mov that do not read a
810 // 2 Operands: in this form, the last register is the ModR/M
811 // input. The first operand is a def&use. This is for things
812 // like: add r32, r/m32
814 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
815 // for instructions like the IMULrri instructions.
818 assert(MI->getOperand(0).isRegister() &&
819 MI->getOperand(1).isRegister() &&
820 (MI->getNumOperands() == 2 ||
821 (MI->getNumOperands() == 3 &&
822 (MI->getOperand(2).isImmediate())))
823 && "Bad format for MRMSrcReg!");
825 O << TII.getName(MI->getOpcode()) << " ";
826 printOp(MI->getOperand(0));
828 printOp(MI->getOperand(1));
829 if (MI->getNumOperands() == 3) {
831 printOp(MI->getOperand(2));
837 case X86II::MRMSrcMem: {
838 // These instructions are the same as MRMSrcReg, but instead of having a
839 // register reference for the mod/rm field, it's a memory reference.
841 assert(MI->getOperand(0).isRegister() &&
842 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
843 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
844 && "Bad format for MRMSrcMem!");
845 O << TII.getName(MI->getOpcode()) << " ";
846 printOp(MI->getOperand(0));
847 O << ", " << sizePtr(Desc) << " ";
848 printMemReference(MI, 1);
849 if (MI->getNumOperands() == 2+4) {
851 printOp(MI->getOperand(5));
857 case X86II::MRM0r: case X86II::MRM1r:
858 case X86II::MRM2r: case X86II::MRM3r:
859 case X86II::MRM4r: case X86II::MRM5r:
860 case X86II::MRM6r: case X86II::MRM7r: {
861 // In this form, the following are valid formats:
863 // 2. cmp reg, immediate
864 // 2. shl rdest, rinput <implicit CL or 1>
865 // 3. sbb rdest, rinput, immediate [rdest = rinput]
867 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
868 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
869 assert((MI->getNumOperands() != 2 ||
870 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
871 "Bad MRMSxR format!");
872 assert((MI->getNumOperands() < 3 ||
873 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
874 "Bad MRMSxR format!");
876 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
877 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
880 O << TII.getName(MI->getOpcode()) << " ";
881 printOp(MI->getOperand(0));
882 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
884 printOp(MI->getOperand(MI->getNumOperands()-1));
886 printImplUsesAfter(Desc);
892 case X86II::MRM0m: case X86II::MRM1m:
893 case X86II::MRM2m: case X86II::MRM3m:
894 case X86II::MRM4m: case X86II::MRM5m:
895 case X86II::MRM6m: case X86II::MRM7m: {
896 // In this form, the following are valid formats:
898 // 2. cmp [m], immediate
899 // 2. shl [m], rinput <implicit CL or 1>
900 // 3. sbb [m], immediate
902 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
903 isMem(MI, 0) && "Bad MRMSxM format!");
904 assert((MI->getNumOperands() != 5 ||
905 (MI->getOperand(4).isImmediate() ||
906 MI->getOperand(4).isGlobalAddress())) &&
907 "Bad MRMSxM format!");
909 const MachineOperand &Op3 = MI->getOperand(3);
913 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
914 // is misassembled by gas in intel_syntax mode as its 32-bit
915 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
916 // opcode bytes instead of the instruction.
918 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
919 // misassembled by gas in intel_syntax mode as its 32-bit
920 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
921 // opcode bytes instead of the instruction.
923 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
924 // invalid opcode, saying "64 bit operations are only supported in
925 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
926 // [...]", which is wrong. Workaround: Output the raw opcode bytes
927 // instead of the instruction.
929 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
930 // invalid opcode, saying "64 bit operations are only supported in
931 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
932 // [...]", which is wrong. Workaround: Output the raw opcode bytes
933 // instead of the instruction.
934 if (MI->getOpcode() == X86::FSTP80m ||
935 MI->getOpcode() == X86::FLD80m ||
936 MI->getOpcode() == X86::FILD64m ||
937 MI->getOpcode() == X86::FISTP64m) {
938 GasBugWorkaroundEmitter gwe(O);
939 X86::emitInstruction(gwe, (X86InstrInfo&)TM.getInstrInfo(), *MI);
942 O << TII.getName(MI->getOpcode()) << " ";
943 O << sizePtr(Desc) << " ";
944 printMemReference(MI, 0);
945 if (MI->getNumOperands() == 5) {
947 printOp(MI->getOperand(4));
949 printImplUsesAfter(Desc);
954 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
958 bool Printer::doInitialization(Module &M) {
959 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
961 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
962 // instruction as a reference to the register named sp, and if you try to
963 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
964 // before being looked up in the symbol table. This creates spurious
965 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
966 // mode, and decorate all register names with percent signs.
967 O << "\t.intel_syntax\n";
968 Mang = new Mangler(M, EmitCygwin);
969 return false; // success
972 // SwitchSection - Switch to the specified section of the executable if we are
973 // not already in it!
975 static void SwitchSection(std::ostream &OS, std::string &CurSection,
976 const char *NewSection) {
977 if (CurSection != NewSection) {
978 CurSection = NewSection;
979 if (!CurSection.empty())
980 OS << "\t" << NewSection << "\n";
984 bool Printer::doFinalization(Module &M) {
985 const TargetData &TD = TM.getTargetData();
986 std::string CurSection;
988 // Print out module-level global variables here.
989 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
990 if (I->hasInitializer()) { // External global require no code
992 std::string name = Mang->getValueName(I);
993 Constant *C = I->getInitializer();
994 unsigned Size = TD.getTypeSize(C->getType());
995 unsigned Align = TD.getTypeAlignment(C->getType());
997 if (C->isNullValue() &&
998 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
999 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
1000 SwitchSection(O, CurSection, ".data");
1001 if (I->hasInternalLinkage())
1002 O << "\t.local " << name << "\n";
1004 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
1005 << "," << (unsigned)TD.getTypeAlignment(C->getType());
1007 WriteAsOperand(O, I, true, true, &M);
1010 switch (I->getLinkage()) {
1011 case GlobalValue::LinkOnceLinkage:
1012 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
1013 // Nonnull linkonce -> weak
1014 O << "\t.weak " << name << "\n";
1015 SwitchSection(O, CurSection, "");
1016 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
1019 case GlobalValue::AppendingLinkage:
1020 // FIXME: appending linkage variables should go into a section of
1021 // their name or something. For now, just emit them as external.
1022 case GlobalValue::ExternalLinkage:
1023 // If external or appending, declare as a global symbol
1024 O << "\t.globl " << name << "\n";
1026 case GlobalValue::InternalLinkage:
1027 if (C->isNullValue())
1028 SwitchSection(O, CurSection, ".bss");
1030 SwitchSection(O, CurSection, ".data");
1034 O << "\t.align " << Align << "\n";
1035 O << "\t.type " << name << ",@object\n";
1036 O << "\t.size " << name << "," << Size << "\n";
1037 O << name << ":\t\t\t\t# ";
1038 WriteAsOperand(O, I, true, true, &M);
1040 WriteAsOperand(O, C, false, false, &M);
1042 emitGlobalConstant(C);
1047 return false; // success