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
11 // representation of machine-dependent LLVM code to Intel-format
12 // assembly language. This printer is the output mechanism used
13 // by `llc' and `lli -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Mangler.h"
28 #include "Support/Statistic.h"
29 #include "Support/StringExtras.h"
30 #include "Support/CommandLine.h"
34 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
36 // FIXME: This should be automatically picked up by autoconf from the C
38 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
39 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
41 struct Printer : public MachineFunctionPass {
42 /// Output stream on which we're printing assembly code.
46 /// Target machine description which we query for reg. names, data
51 /// Name-mangler for global names.
55 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
57 /// We name each basic block in a Function with a unique number, so
58 /// that we can consistently refer to them later. This is cleared
59 /// at the beginning of each call to runOnMachineFunction().
61 typedef std::map<const Value *, unsigned> ValueMapTy;
62 ValueMapTy NumberForBB;
64 /// Cache of mangled name for current function. This is
65 /// recalculated at the beginning of each call to
66 /// runOnMachineFunction().
68 std::string CurrentFnName;
70 virtual const char *getPassName() const {
71 return "X86 Assembly Printer";
74 void checkImplUses (const TargetInstrDescriptor &Desc);
75 void printMachineInstruction(const MachineInstr *MI);
76 void printOp(const MachineOperand &MO,
77 bool elideOffsetKeyword = false);
78 void printMemReference(const MachineInstr *MI, unsigned Op);
79 void printConstantPool(MachineConstantPool *MCP);
80 bool runOnMachineFunction(MachineFunction &F);
81 bool doInitialization(Module &M);
82 bool doFinalization(Module &M);
83 void emitGlobalConstant(const Constant* CV);
84 void emitConstantValueOnly(const Constant *CV);
86 } // end of anonymous namespace
88 /// createX86CodePrinterPass - Returns a pass that prints the X86
89 /// assembly code for a MachineFunction to the given output stream,
90 /// using the given target machine description. This should work
91 /// regardless of whether the function is in SSA form.
93 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
94 return new Printer(o, tm);
97 /// toOctal - Convert the low order bits of X into an octal digit.
99 static inline char toOctal(int X) {
103 /// getAsCString - Return the specified array as a C compatible
104 /// string, only if the predicate isStringCompatible is true.
106 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
107 assert(CVA->isString() && "Array is not string compatible!");
110 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
111 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
115 } else if (C == '\\') {
117 } else if (isprint(C)) {
121 case '\b': O << "\\b"; break;
122 case '\f': O << "\\f"; break;
123 case '\n': O << "\\n"; break;
124 case '\r': O << "\\r"; break;
125 case '\t': O << "\\t"; break;
128 O << toOctal(C >> 6);
129 O << toOctal(C >> 3);
130 O << toOctal(C >> 0);
138 // Print out the specified constant, without a storage class. Only the
139 // constants valid in constant expressions can occur here.
140 void Printer::emitConstantValueOnly(const Constant *CV) {
141 if (CV->isNullValue())
143 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
144 assert(CB == ConstantBool::True);
146 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
148 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
150 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
151 // This is a constant address for a global variable or function. Use the
152 // name of the variable or function as the address value.
153 O << Mang->getValueName(CPR->getValue());
154 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
155 const TargetData &TD = TM.getTargetData();
156 switch(CE->getOpcode()) {
157 case Instruction::GetElementPtr: {
158 // generate a symbolic expression for the byte address
159 const Constant *ptrVal = CE->getOperand(0);
160 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
161 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
163 emitConstantValueOnly(ptrVal);
164 O << ") + " << Offset;
166 emitConstantValueOnly(ptrVal);
170 case Instruction::Cast: {
171 // Support only non-converting or widening casts for now, that is, ones
172 // that do not involve a change in value. This assertion is really gross,
173 // and may not even be a complete check.
174 Constant *Op = CE->getOperand(0);
175 const Type *OpTy = Op->getType(), *Ty = CE->getType();
177 // Remember, kids, pointers on x86 can be losslessly converted back and
178 // forth into 32-bit or wider integers, regardless of signedness. :-P
179 assert(((isa<PointerType>(OpTy)
180 && (Ty == Type::LongTy || Ty == Type::ULongTy
181 || Ty == Type::IntTy || Ty == Type::UIntTy))
182 || (isa<PointerType>(Ty)
183 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
184 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
185 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
186 && OpTy->isLosslesslyConvertibleTo(Ty))))
187 && "FIXME: Don't yet support this kind of constant cast expr");
189 emitConstantValueOnly(Op);
193 case Instruction::Add:
195 emitConstantValueOnly(CE->getOperand(0));
197 emitConstantValueOnly(CE->getOperand(1));
201 assert(0 && "Unsupported operator!");
204 assert(0 && "Unknown constant value!");
208 // Print a constant value or values, with the appropriate storage class as a
210 void Printer::emitGlobalConstant(const Constant *CV) {
211 const TargetData &TD = TM.getTargetData();
213 if (CV->isNullValue()) {
214 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
216 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
217 if (CVA->isString()) {
219 printAsCString(O, CVA);
221 } else { // Not a string. Print the values in successive locations
222 const std::vector<Use> &constValues = CVA->getValues();
223 for (unsigned i=0; i < constValues.size(); i++)
224 emitGlobalConstant(cast<Constant>(constValues[i].get()));
227 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
228 // Print the fields in successive locations. Pad to align if needed!
229 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
230 const std::vector<Use>& constValues = CVS->getValues();
231 unsigned sizeSoFar = 0;
232 for (unsigned i=0, N = constValues.size(); i < N; i++) {
233 const Constant* field = cast<Constant>(constValues[i].get());
235 // Check if padding is needed and insert one or more 0s.
236 unsigned fieldSize = TD.getTypeSize(field->getType());
237 unsigned padSize = ((i == N-1? cvsLayout->StructSize
238 : cvsLayout->MemberOffsets[i+1])
239 - cvsLayout->MemberOffsets[i]) - fieldSize;
240 sizeSoFar += fieldSize + padSize;
242 // Now print the actual field value
243 emitGlobalConstant(field);
245 // Insert the field padding unless it's zero bytes...
247 O << "\t.zero\t " << padSize << "\n";
249 assert(sizeSoFar == cvsLayout->StructSize &&
250 "Layout of constant struct may be incorrect!");
252 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
253 // FP Constants are printed as integer constants to avoid losing
255 double Val = CFP->getValue();
256 switch (CFP->getType()->getPrimitiveID()) {
257 default: assert(0 && "Unknown floating point type!");
258 case Type::FloatTyID: {
259 union FU { // Abide by C TBAA rules
264 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
267 case Type::DoubleTyID: {
268 union DU { // Abide by C TBAA rules
273 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
279 const Type *type = CV->getType();
281 switch (type->getPrimitiveID()) {
282 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
285 case Type::UShortTyID: case Type::ShortTyID:
288 case Type::FloatTyID: case Type::PointerTyID:
289 case Type::UIntTyID: case Type::IntTyID:
292 case Type::DoubleTyID:
293 case Type::ULongTyID: case Type::LongTyID:
297 assert (0 && "Can't handle printing this type of thing");
301 emitConstantValueOnly(CV);
305 /// printConstantPool - Print to the current output stream assembly
306 /// representations of the constants in the constant pool MCP. This is
307 /// used to print out constants which have been "spilled to memory" by
308 /// the code generator.
310 void Printer::printConstantPool(MachineConstantPool *MCP) {
311 const std::vector<Constant*> &CP = MCP->getConstants();
312 const TargetData &TD = TM.getTargetData();
314 if (CP.empty()) return;
316 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
317 O << "\t.section .rodata\n";
318 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
320 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
322 emitGlobalConstant(CP[i]);
326 /// runOnMachineFunction - This uses the printMachineInstruction()
327 /// method to print assembly for each instruction.
329 bool Printer::runOnMachineFunction(MachineFunction &MF) {
330 // BBNumber is used here so that a given Printer will never give two
331 // BBs the same name. (If you have a better way, please let me know!)
332 static unsigned BBNumber = 0;
335 // What's my mangled name?
336 CurrentFnName = Mang->getValueName(MF.getFunction());
338 // Print out constants referenced by the function
339 printConstantPool(MF.getConstantPool());
341 // Print out labels for the function.
343 O << "\t.align 16\n";
344 O << "\t.globl\t" << CurrentFnName << "\n";
346 O << "\t.type\t" << CurrentFnName << ", @function\n";
347 O << CurrentFnName << ":\n";
349 // Number each basic block so that we can consistently refer to them
350 // in PC-relative references.
352 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
354 NumberForBB[I->getBasicBlock()] = BBNumber++;
357 // Print out code for the function.
358 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
360 // Print a label for the basic block.
361 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
362 << I->getBasicBlock()->getName() << "\n";
363 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
365 // Print the assembly for the instruction.
367 printMachineInstruction(II);
371 // We didn't modify anything.
375 static bool isScale(const MachineOperand &MO) {
376 return MO.isImmediate() &&
377 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
378 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
381 static bool isMem(const MachineInstr *MI, unsigned Op) {
382 if (MI->getOperand(Op).isFrameIndex()) return true;
383 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
384 return Op+4 <= MI->getNumOperands() &&
385 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
386 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
391 void Printer::printOp(const MachineOperand &MO,
392 bool elideOffsetKeyword /* = false */) {
393 const MRegisterInfo &RI = *TM.getRegisterInfo();
394 switch (MO.getType()) {
395 case MachineOperand::MO_VirtualRegister:
396 if (Value *V = MO.getVRegValueOrNull()) {
397 O << "<" << V->getName() << ">";
401 case MachineOperand::MO_MachineRegister:
402 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
403 // Bug Workaround: See note in Printer::doInitialization about %.
404 O << "%" << RI.get(MO.getReg()).Name;
406 O << "%reg" << MO.getReg();
409 case MachineOperand::MO_SignExtendedImmed:
410 case MachineOperand::MO_UnextendedImmed:
411 O << (int)MO.getImmedValue();
413 case MachineOperand::MO_PCRelativeDisp: {
414 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
415 assert (i != NumberForBB.end()
416 && "Could not find a BB in the NumberForBB map!");
417 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
420 case MachineOperand::MO_GlobalAddress:
421 if (!elideOffsetKeyword)
423 O << Mang->getValueName(MO.getGlobal());
425 case MachineOperand::MO_ExternalSymbol:
426 O << MO.getSymbolName();
429 O << "<unknown operand type>"; return;
433 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
434 switch (Desc.TSFlags & X86II::ArgMask) {
435 default: assert(0 && "Unknown arg size!");
436 case X86II::Arg8: return "BYTE PTR";
437 case X86II::Arg16: return "WORD PTR";
438 case X86II::Arg32: return "DWORD PTR";
439 case X86II::Arg64: return "QWORD PTR";
440 case X86II::ArgF32: return "DWORD PTR";
441 case X86II::ArgF64: return "QWORD PTR";
442 case X86II::ArgF80: return "XWORD PTR";
446 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
447 assert(isMem(MI, Op) && "Invalid memory reference!");
449 if (MI->getOperand(Op).isFrameIndex()) {
450 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
451 if (MI->getOperand(Op+3).getImmedValue())
452 O << " + " << MI->getOperand(Op+3).getImmedValue();
455 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
456 O << "[.CPI" << CurrentFnName << "_"
457 << MI->getOperand(Op).getConstantPoolIndex();
458 if (MI->getOperand(Op+3).getImmedValue())
459 O << " + " << MI->getOperand(Op+3).getImmedValue();
464 const MachineOperand &BaseReg = MI->getOperand(Op);
465 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
466 const MachineOperand &IndexReg = MI->getOperand(Op+2);
467 int DispVal = MI->getOperand(Op+3).getImmedValue();
470 bool NeedPlus = false;
471 if (BaseReg.getReg()) {
476 if (IndexReg.getReg()) {
477 if (NeedPlus) O << " + ";
479 O << ScaleVal << "*";
497 /// checkImplUses - Emit the implicit-use registers for the
498 /// instruction described by DESC, if its PrintImplUses flag is set.
500 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
501 const MRegisterInfo &RI = *TM.getRegisterInfo();
502 if (Desc.TSFlags & X86II::PrintImplUses) {
503 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
504 // Bug Workaround: See note in Printer::doInitialization about %.
505 O << ", %" << RI.get(*p).Name;
510 /// printMachineInstruction -- Print out a single X86 LLVM instruction
511 /// MI in Intel syntax to the current output stream.
513 void Printer::printMachineInstruction(const MachineInstr *MI) {
514 unsigned Opcode = MI->getOpcode();
515 const TargetInstrInfo &TII = TM.getInstrInfo();
516 const TargetInstrDescriptor &Desc = TII.get(Opcode);
519 switch (Desc.TSFlags & X86II::FormMask) {
521 // Print pseudo-instructions as comments; either they should have been
522 // turned into real instructions by now, or they don't need to be
523 // seen by the assembler (e.g., IMPLICIT_USEs.)
525 if (Opcode == X86::PHI) {
526 printOp(MI->getOperand(0));
528 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
529 if (i != 1) O << ", ";
531 printOp(MI->getOperand(i));
533 printOp(MI->getOperand(i+1));
538 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
539 printOp(MI->getOperand(0));
543 O << TII.getName(MI->getOpcode());
545 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
547 if (MI->getOperand(i).isDef()) O << "*";
548 printOp(MI->getOperand(i));
549 if (MI->getOperand(i).isDef()) O << "*";
556 // The accepted forms of Raw instructions are:
557 // 1. nop - No operand required
558 // 2. jmp foo - PC relative displacement operand
559 // 3. call bar - GlobalAddress Operand or External Symbol Operand
561 assert(MI->getNumOperands() == 0 ||
562 (MI->getNumOperands() == 1 &&
563 (MI->getOperand(0).isPCRelativeDisp() ||
564 MI->getOperand(0).isGlobalAddress() ||
565 MI->getOperand(0).isExternalSymbol())) &&
566 "Illegal raw instruction!");
567 O << TII.getName(MI->getOpcode()) << " ";
569 if (MI->getNumOperands() == 1) {
570 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
575 case X86II::AddRegFrm: {
576 // There are currently two forms of acceptable AddRegFrm instructions.
577 // Either the instruction JUST takes a single register (like inc, dec, etc),
578 // or it takes a register and an immediate of the same size as the register
579 // (move immediate f.e.). Note that this immediate value might be stored as
580 // an LLVM value, to represent, for example, loading the address of a global
581 // into a register. The initial register might be duplicated if this is a
582 // M_2_ADDR_REG instruction
584 assert(MI->getOperand(0).isRegister() &&
585 (MI->getNumOperands() == 1 ||
586 (MI->getNumOperands() == 2 &&
587 (MI->getOperand(1).getVRegValueOrNull() ||
588 MI->getOperand(1).isImmediate() ||
589 MI->getOperand(1).isRegister() ||
590 MI->getOperand(1).isGlobalAddress() ||
591 MI->getOperand(1).isExternalSymbol()))) &&
592 "Illegal form for AddRegFrm instruction!");
594 unsigned Reg = MI->getOperand(0).getReg();
596 O << TII.getName(MI->getOpcode()) << " ";
597 printOp(MI->getOperand(0));
598 if (MI->getNumOperands() == 2 &&
599 (!MI->getOperand(1).isRegister() ||
600 MI->getOperand(1).getVRegValueOrNull() ||
601 MI->getOperand(1).isGlobalAddress() ||
602 MI->getOperand(1).isExternalSymbol())) {
604 printOp(MI->getOperand(1));
610 case X86II::MRMDestReg: {
611 // There are three forms of MRMDestReg instructions, those with 2
614 // 2 Operands: this is for things like mov that do not read a
617 // 2 Operands: two address instructions which def&use the first
618 // argument and use the second as input.
620 // 3 Operands: in this form, two address instructions are the same
621 // as in 2 but have a constant argument as well.
623 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
624 assert(MI->getOperand(0).isRegister() &&
625 (MI->getNumOperands() == 2 ||
626 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
627 && "Bad format for MRMDestReg!");
629 O << TII.getName(MI->getOpcode()) << " ";
630 printOp(MI->getOperand(0));
632 printOp(MI->getOperand(1));
633 if (MI->getNumOperands() == 3) {
635 printOp(MI->getOperand(2));
641 case X86II::MRMDestMem: {
642 // These instructions are the same as MRMDestReg, but instead of having a
643 // register reference for the mod/rm field, it's a memory reference.
645 assert(isMem(MI, 0) &&
646 (MI->getNumOperands() == 4+1 ||
647 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
648 && "Bad format for MRMDestMem!");
650 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
651 printMemReference(MI, 0);
653 printOp(MI->getOperand(4));
654 if (MI->getNumOperands() == 4+2) {
656 printOp(MI->getOperand(5));
662 case X86II::MRMSrcReg: {
663 // There are three forms that are acceptable for MRMSrcReg
664 // instructions, those with 2 or 3 operands:
666 // 2 Operands: this is for things like mov that do not read a
669 // 2 Operands: in this form, the last register is the ModR/M
670 // input. The first operand is a def&use. This is for things
671 // like: add r32, r/m32
673 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
674 // for instructions like the IMULrri instructions.
677 assert(MI->getOperand(0).isRegister() &&
678 MI->getOperand(1).isRegister() &&
679 (MI->getNumOperands() == 2 ||
680 (MI->getNumOperands() == 3 &&
681 (MI->getOperand(2).isImmediate())))
682 && "Bad format for MRMSrcReg!");
684 O << TII.getName(MI->getOpcode()) << " ";
685 printOp(MI->getOperand(0));
687 printOp(MI->getOperand(1));
688 if (MI->getNumOperands() == 3) {
690 printOp(MI->getOperand(2));
696 case X86II::MRMSrcMem: {
697 // These instructions are the same as MRMSrcReg, but instead of having a
698 // register reference for the mod/rm field, it's a memory reference.
700 assert(MI->getOperand(0).isRegister() &&
701 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
702 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
704 && "Bad format for MRMSrcMem!");
705 if (MI->getNumOperands() == 2+4 &&
706 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
709 O << TII.getName(MI->getOpcode()) << " ";
710 printOp(MI->getOperand(0));
711 O << ", " << sizePtr(Desc) << " ";
712 printMemReference(MI, MI->getNumOperands()-4);
717 case X86II::MRMS0r: case X86II::MRMS1r:
718 case X86II::MRMS2r: case X86II::MRMS3r:
719 case X86II::MRMS4r: case X86II::MRMS5r:
720 case X86II::MRMS6r: case X86II::MRMS7r: {
721 // In this form, the following are valid formats:
723 // 2. cmp reg, immediate
724 // 2. shl rdest, rinput <implicit CL or 1>
725 // 3. sbb rdest, rinput, immediate [rdest = rinput]
727 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
728 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
729 assert((MI->getNumOperands() != 2 ||
730 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
731 "Bad MRMSxR format!");
732 assert((MI->getNumOperands() < 3 ||
733 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
734 "Bad MRMSxR format!");
736 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
737 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
740 O << TII.getName(MI->getOpcode()) << " ";
741 printOp(MI->getOperand(0));
742 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
744 printOp(MI->getOperand(MI->getNumOperands()-1));
752 case X86II::MRMS0m: case X86II::MRMS1m:
753 case X86II::MRMS2m: case X86II::MRMS3m:
754 case X86II::MRMS4m: case X86II::MRMS5m:
755 case X86II::MRMS6m: case X86II::MRMS7m: {
756 // In this form, the following are valid formats:
758 // 2. cmp [m], immediate
759 // 2. shl [m], rinput <implicit CL or 1>
760 // 3. sbb [m], immediate
762 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
763 isMem(MI, 0) && "Bad MRMSxM format!");
764 assert((MI->getNumOperands() != 5 ||
765 (MI->getOperand(4).isImmediate() ||
766 MI->getOperand(4).isGlobalAddress())) &&
767 "Bad MRMSxM format!");
769 const MachineOperand &Op3 = MI->getOperand(3);
771 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
772 // is misassembled by gas in intel_syntax mode as its 32-bit
773 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
774 // opcode bytes instead of the instruction.
775 if (MI->getOpcode() == X86::FSTPr80) {
776 if ((MI->getOperand(0).getReg() == X86::ESP)
777 && (MI->getOperand(1).getImmedValue() == 1)) {
778 if (Op3.isImmediate() &&
779 Op3.getImmedValue() >= -128 && Op3.getImmedValue() <= 127) {
781 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex
782 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
784 O << ".byte 0xdb, 0xbc, 0x24\n\t";
792 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
793 // misassembled by gas in intel_syntax mode as its 32-bit
794 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
795 // opcode bytes instead of the instruction.
796 if (MI->getOpcode() == X86::FLDr80 &&
797 MI->getOperand(0).getReg() == X86::ESP &&
798 MI->getOperand(1).getImmedValue() == 1) {
799 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
800 Op3.getImmedValue() <= 127) { // 1 byte displacement
801 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex
802 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
804 O << ".byte 0xdb, 0xac, 0x24\n\t";
811 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
812 // invalid opcode, saying "64 bit operations are only supported in
813 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
814 // [...]", which is wrong. Workaround: Output the raw opcode bytes
815 // instead of the instruction.
816 if (MI->getOpcode() == X86::FILDr64 &&
817 MI->getOperand(0).getReg() == X86::ESP &&
818 MI->getOperand(1).getImmedValue() == 1) {
819 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
820 Op3.getImmedValue() <= 127) { // 1 byte displacement
821 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex
822 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
824 O << ".byte 0xdf, 0xac, 0x24\n\t";
827 O << std::dec << "\t# ";
831 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
832 // an invalid opcode, saying "64 bit operations are only
833 // supported in 64 bit modes." libopcodes disassembles it as
834 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
835 // "fistpll DWORD PTR " instead, which is what libopcodes is
837 if (MI->getOpcode() == X86::FISTPr64) {
838 O << "fistpll DWORD PTR ";
839 printMemReference(MI, 0);
840 if (MI->getNumOperands() == 5) {
842 printOp(MI->getOperand(4));
847 O << TII.getName(MI->getOpcode()) << " ";
848 O << sizePtr(Desc) << " ";
849 printMemReference(MI, 0);
850 if (MI->getNumOperands() == 5) {
852 printOp(MI->getOperand(4));
859 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
863 bool Printer::doInitialization(Module &M) {
864 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
866 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
867 // instruction as a reference to the register named sp, and if you try to
868 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
869 // before being looked up in the symbol table. This creates spurious
870 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
871 // mode, and decorate all register names with percent signs.
872 O << "\t.intel_syntax\n";
873 Mang = new Mangler(M, EmitCygwin);
874 return false; // success
877 // SwitchSection - Switch to the specified section of the executable if we are
878 // not already in it!
880 static void SwitchSection(std::ostream &OS, std::string &CurSection,
881 const char *NewSection) {
882 if (CurSection != NewSection) {
883 CurSection = NewSection;
884 if (!CurSection.empty())
885 OS << "\t" << NewSection << "\n";
889 bool Printer::doFinalization(Module &M) {
890 const TargetData &TD = TM.getTargetData();
891 std::string CurSection;
893 // Print out module-level global variables here.
894 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
895 if (I->hasInitializer()) { // External global require no code
897 std::string name = Mang->getValueName(I);
898 Constant *C = I->getInitializer();
899 unsigned Size = TD.getTypeSize(C->getType());
900 unsigned Align = TD.getTypeAlignment(C->getType());
902 if (C->isNullValue() &&
903 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
904 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
905 SwitchSection(O, CurSection, ".data");
906 if (I->hasInternalLinkage())
907 O << "\t.local " << name << "\n";
909 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
910 << "," << (unsigned)TD.getTypeAlignment(C->getType());
912 WriteAsOperand(O, I, true, true, &M);
915 switch (I->getLinkage()) {
916 case GlobalValue::LinkOnceLinkage:
917 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
918 // Nonnull linkonce -> weak
919 O << "\t.weak " << name << "\n";
920 SwitchSection(O, CurSection, "");
921 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
924 case GlobalValue::AppendingLinkage:
925 // FIXME: appending linkage variables should go into a section of
926 // their name or something. For now, just emit them as external.
927 case GlobalValue::ExternalLinkage:
928 // If external or appending, declare as a global symbol
929 O << "\t.globl " << name << "\n";
931 case GlobalValue::InternalLinkage:
932 if (C->isNullValue())
933 SwitchSection(O, CurSection, ".bss");
935 SwitchSection(O, CurSection, ".data");
939 O << "\t.align " << Align << "\n";
940 O << "\t.type " << name << ",@object\n";
941 O << "\t.size " << name << "," << Size << "\n";
942 O << name << ":\t\t\t\t# ";
943 WriteAsOperand(O, I, true, true, &M);
945 WriteAsOperand(O, C, false, false, &M);
947 emitGlobalConstant(C);
952 return false; // success