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"
35 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
37 // FIXME: This should be automatically picked up by autoconf from the C
39 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
40 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
42 struct Printer : public MachineFunctionPass {
43 /// Output stream on which we're printing assembly code.
47 /// Target machine description which we query for reg. names, data
52 /// Name-mangler for global names.
56 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
58 /// We name each basic block in a Function with a unique number, so
59 /// that we can consistently refer to them later. This is cleared
60 /// at the beginning of each call to runOnMachineFunction().
62 typedef std::map<const Value *, unsigned> ValueMapTy;
63 ValueMapTy NumberForBB;
65 /// Cache of mangled name for current function. This is
66 /// recalculated at the beginning of each call to
67 /// runOnMachineFunction().
69 std::string CurrentFnName;
71 virtual const char *getPassName() const {
72 return "X86 Assembly Printer";
75 void checkImplUses (const TargetInstrDescriptor &Desc);
76 void printMachineInstruction(const MachineInstr *MI);
77 void printOp(const MachineOperand &MO,
78 bool elideOffsetKeyword = false);
79 void printMemReference(const MachineInstr *MI, unsigned Op);
80 void printConstantPool(MachineConstantPool *MCP);
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
84 void emitGlobalConstant(const Constant* CV);
85 void emitConstantValueOnly(const Constant *CV);
87 } // end of anonymous namespace
89 /// createX86CodePrinterPass - Returns a pass that prints the X86
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
94 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
95 return new Printer(o, tm);
98 /// isStringCompatible - Can we treat the specified array as a string?
99 /// Only if it is an array of ubytes or non-negative sbytes.
101 static bool isStringCompatible(const ConstantArray *CVA) {
102 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
103 if (ETy == Type::UByteTy) return true;
104 if (ETy != Type::SByteTy) return false;
106 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
107 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
113 /// toOctal - Convert the low order bits of X into an octal digit.
115 static inline char toOctal(int X) {
119 /// getAsCString - Return the specified array as a C compatible
120 /// string, only if the predicate isStringCompatible is true.
122 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
123 assert(isStringCompatible(CVA) && "Array is not string compatible!");
126 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
127 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
131 } else if (C == '\\') {
133 } else if (isprint(C)) {
137 case '\b': O << "\\b"; break;
138 case '\f': O << "\\f"; break;
139 case '\n': O << "\\n"; break;
140 case '\r': O << "\\r"; break;
141 case '\t': O << "\\t"; break;
144 O << toOctal(C >> 6);
145 O << toOctal(C >> 3);
146 O << toOctal(C >> 0);
154 // Print out the specified constant, without a storage class. Only the
155 // constants valid in constant expressions can occur here.
156 void Printer::emitConstantValueOnly(const Constant *CV) {
157 if (CV->isNullValue())
159 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
160 assert(CB == ConstantBool::True);
162 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
164 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
166 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
167 // This is a constant address for a global variable or function. Use the
168 // name of the variable or function as the address value.
169 O << Mang->getValueName(CPR->getValue());
170 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
171 const TargetData &TD = TM.getTargetData();
172 switch(CE->getOpcode()) {
173 case Instruction::GetElementPtr: {
174 // generate a symbolic expression for the byte address
175 const Constant *ptrVal = CE->getOperand(0);
176 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
177 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
179 emitConstantValueOnly(ptrVal);
180 O << ") + " << Offset;
182 emitConstantValueOnly(ptrVal);
186 case Instruction::Cast: {
187 // Support only non-converting or widening casts for now, that is, ones
188 // that do not involve a change in value. This assertion is really gross,
189 // and may not even be a complete check.
190 Constant *Op = CE->getOperand(0);
191 const Type *OpTy = Op->getType(), *Ty = CE->getType();
193 // Remember, kids, pointers on x86 can be losslessly converted back and
194 // forth into 32-bit or wider integers, regardless of signedness. :-P
195 assert(((isa<PointerType>(OpTy)
196 && (Ty == Type::LongTy || Ty == Type::ULongTy
197 || Ty == Type::IntTy || Ty == Type::UIntTy))
198 || (isa<PointerType>(Ty)
199 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
200 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
201 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
202 && OpTy->isLosslesslyConvertibleTo(Ty))))
203 && "FIXME: Don't yet support this kind of constant cast expr");
205 emitConstantValueOnly(Op);
209 case Instruction::Add:
211 emitConstantValueOnly(CE->getOperand(0));
213 emitConstantValueOnly(CE->getOperand(1));
217 assert(0 && "Unsupported operator!");
220 assert(0 && "Unknown constant value!");
224 // Print a constant value or values, with the appropriate storage class as a
226 void Printer::emitGlobalConstant(const Constant *CV) {
227 const TargetData &TD = TM.getTargetData();
229 if (CV->isNullValue()) {
230 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
232 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
233 if (isStringCompatible(CVA)) {
235 printAsCString(O, CVA);
237 } else { // Not a string. Print the values in successive locations
238 const std::vector<Use> &constValues = CVA->getValues();
239 for (unsigned i=0; i < constValues.size(); i++)
240 emitGlobalConstant(cast<Constant>(constValues[i].get()));
243 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
244 // Print the fields in successive locations. Pad to align if needed!
245 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
246 const std::vector<Use>& constValues = CVS->getValues();
247 unsigned sizeSoFar = 0;
248 for (unsigned i=0, N = constValues.size(); i < N; i++) {
249 const Constant* field = cast<Constant>(constValues[i].get());
251 // Check if padding is needed and insert one or more 0s.
252 unsigned fieldSize = TD.getTypeSize(field->getType());
253 unsigned padSize = ((i == N-1? cvsLayout->StructSize
254 : cvsLayout->MemberOffsets[i+1])
255 - cvsLayout->MemberOffsets[i]) - fieldSize;
256 sizeSoFar += fieldSize + padSize;
258 // Now print the actual field value
259 emitGlobalConstant(field);
261 // Insert the field padding unless it's zero bytes...
263 O << "\t.zero\t " << padSize << "\n";
265 assert(sizeSoFar == cvsLayout->StructSize &&
266 "Layout of constant struct may be incorrect!");
268 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
269 // FP Constants are printed as integer constants to avoid losing
271 double Val = CFP->getValue();
272 switch (CFP->getType()->getPrimitiveID()) {
273 default: assert(0 && "Unknown floating point type!");
274 case Type::FloatTyID: {
275 union FU { // Abide by C TBAA rules
280 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
283 case Type::DoubleTyID: {
284 union DU { // Abide by C TBAA rules
289 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
295 const Type *type = CV->getType();
297 switch (type->getPrimitiveID()) {
298 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
301 case Type::UShortTyID: case Type::ShortTyID:
304 case Type::FloatTyID: case Type::PointerTyID:
305 case Type::UIntTyID: case Type::IntTyID:
308 case Type::DoubleTyID:
309 case Type::ULongTyID: case Type::LongTyID:
313 assert (0 && "Can't handle printing this type of thing");
317 emitConstantValueOnly(CV);
321 /// printConstantPool - Print to the current output stream assembly
322 /// representations of the constants in the constant pool MCP. This is
323 /// used to print out constants which have been "spilled to memory" by
324 /// the code generator.
326 void Printer::printConstantPool(MachineConstantPool *MCP) {
327 const std::vector<Constant*> &CP = MCP->getConstants();
328 const TargetData &TD = TM.getTargetData();
330 if (CP.empty()) return;
332 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
333 O << "\t.section .rodata\n";
334 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
336 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
338 emitGlobalConstant(CP[i]);
342 /// runOnMachineFunction - This uses the printMachineInstruction()
343 /// method to print assembly for each instruction.
345 bool Printer::runOnMachineFunction(MachineFunction &MF) {
346 // BBNumber is used here so that a given Printer will never give two
347 // BBs the same name. (If you have a better way, please let me know!)
348 static unsigned BBNumber = 0;
351 // What's my mangled name?
352 CurrentFnName = Mang->getValueName(MF.getFunction());
354 // Print out constants referenced by the function
355 printConstantPool(MF.getConstantPool());
357 // Print out labels for the function.
359 O << "\t.align 16\n";
360 O << "\t.globl\t" << CurrentFnName << "\n";
362 O << "\t.type\t" << CurrentFnName << ", @function\n";
363 O << CurrentFnName << ":\n";
365 // Number each basic block so that we can consistently refer to them
366 // in PC-relative references.
368 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
370 NumberForBB[I->getBasicBlock()] = BBNumber++;
373 // Print out code for the function.
374 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
376 // Print a label for the basic block.
377 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
378 << I->getBasicBlock()->getName() << "\n";
379 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
381 // Print the assembly for the instruction.
383 printMachineInstruction(*II);
387 // We didn't modify anything.
391 static bool isScale(const MachineOperand &MO) {
392 return MO.isImmediate() &&
393 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
394 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
397 static bool isMem(const MachineInstr *MI, unsigned Op) {
398 if (MI->getOperand(Op).isFrameIndex()) return true;
399 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
400 return Op+4 <= MI->getNumOperands() &&
401 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
402 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
407 void Printer::printOp(const MachineOperand &MO,
408 bool elideOffsetKeyword /* = false */) {
409 const MRegisterInfo &RI = *TM.getRegisterInfo();
410 switch (MO.getType()) {
411 case MachineOperand::MO_VirtualRegister:
412 if (Value *V = MO.getVRegValueOrNull()) {
413 O << "<" << V->getName() << ">";
417 case MachineOperand::MO_MachineRegister:
418 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
419 // Bug Workaround: See note in Printer::doInitialization about %.
420 O << "%" << RI.get(MO.getReg()).Name;
422 O << "%reg" << MO.getReg();
425 case MachineOperand::MO_SignExtendedImmed:
426 case MachineOperand::MO_UnextendedImmed:
427 O << (int)MO.getImmedValue();
429 case MachineOperand::MO_PCRelativeDisp: {
430 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
431 assert (i != NumberForBB.end()
432 && "Could not find a BB in the NumberForBB map!");
433 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
436 case MachineOperand::MO_GlobalAddress:
437 if (!elideOffsetKeyword)
439 O << Mang->getValueName(MO.getGlobal());
441 case MachineOperand::MO_ExternalSymbol:
442 O << MO.getSymbolName();
445 O << "<unknown operand type>"; return;
449 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
450 switch (Desc.TSFlags & X86II::ArgMask) {
451 default: assert(0 && "Unknown arg size!");
452 case X86II::Arg8: return "BYTE PTR";
453 case X86II::Arg16: return "WORD PTR";
454 case X86II::Arg32: return "DWORD PTR";
455 case X86II::Arg64: return "QWORD PTR";
456 case X86II::ArgF32: return "DWORD PTR";
457 case X86II::ArgF64: return "QWORD PTR";
458 case X86II::ArgF80: return "XWORD PTR";
462 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
463 assert(isMem(MI, Op) && "Invalid memory reference!");
465 if (MI->getOperand(Op).isFrameIndex()) {
466 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
467 if (MI->getOperand(Op+3).getImmedValue())
468 O << " + " << MI->getOperand(Op+3).getImmedValue();
471 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
472 O << "[.CPI" << CurrentFnName << "_"
473 << MI->getOperand(Op).getConstantPoolIndex();
474 if (MI->getOperand(Op+3).getImmedValue())
475 O << " + " << MI->getOperand(Op+3).getImmedValue();
480 const MachineOperand &BaseReg = MI->getOperand(Op);
481 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
482 const MachineOperand &IndexReg = MI->getOperand(Op+2);
483 int DispVal = MI->getOperand(Op+3).getImmedValue();
486 bool NeedPlus = false;
487 if (BaseReg.getReg()) {
492 if (IndexReg.getReg()) {
493 if (NeedPlus) O << " + ";
495 O << ScaleVal << "*";
513 /// checkImplUses - Emit the implicit-use registers for the
514 /// instruction described by DESC, if its PrintImplUses flag is set.
516 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
517 const MRegisterInfo &RI = *TM.getRegisterInfo();
518 if (Desc.TSFlags & X86II::PrintImplUses) {
519 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
520 // Bug Workaround: See note in Printer::doInitialization about %.
521 O << ", %" << RI.get(*p).Name;
526 /// printMachineInstruction -- Print out a single X86 LLVM instruction
527 /// MI in Intel syntax to the current output stream.
529 void Printer::printMachineInstruction(const MachineInstr *MI) {
530 unsigned Opcode = MI->getOpcode();
531 const TargetInstrInfo &TII = TM.getInstrInfo();
532 const TargetInstrDescriptor &Desc = TII.get(Opcode);
535 switch (Desc.TSFlags & X86II::FormMask) {
537 // Print pseudo-instructions as comments; either they should have been
538 // turned into real instructions by now, or they don't need to be
539 // seen by the assembler (e.g., IMPLICIT_USEs.)
541 if (Opcode == X86::PHI) {
542 printOp(MI->getOperand(0));
544 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
545 if (i != 1) O << ", ";
547 printOp(MI->getOperand(i));
549 printOp(MI->getOperand(i+1));
554 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
555 printOp(MI->getOperand(0));
559 O << TII.getName(MI->getOpcode());
561 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
563 if (MI->getOperand(i).isDef()) O << "*";
564 printOp(MI->getOperand(i));
565 if (MI->getOperand(i).isDef()) O << "*";
572 // The accepted forms of Raw instructions are:
573 // 1. nop - No operand required
574 // 2. jmp foo - PC relative displacement operand
575 // 3. call bar - GlobalAddress Operand or External Symbol Operand
577 assert(MI->getNumOperands() == 0 ||
578 (MI->getNumOperands() == 1 &&
579 (MI->getOperand(0).isPCRelativeDisp() ||
580 MI->getOperand(0).isGlobalAddress() ||
581 MI->getOperand(0).isExternalSymbol())) &&
582 "Illegal raw instruction!");
583 O << TII.getName(MI->getOpcode()) << " ";
585 if (MI->getNumOperands() == 1) {
586 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
591 case X86II::AddRegFrm: {
592 // There are currently two forms of acceptable AddRegFrm instructions.
593 // Either the instruction JUST takes a single register (like inc, dec, etc),
594 // or it takes a register and an immediate of the same size as the register
595 // (move immediate f.e.). Note that this immediate value might be stored as
596 // an LLVM value, to represent, for example, loading the address of a global
597 // into a register. The initial register might be duplicated if this is a
598 // M_2_ADDR_REG instruction
600 assert(MI->getOperand(0).isRegister() &&
601 (MI->getNumOperands() == 1 ||
602 (MI->getNumOperands() == 2 &&
603 (MI->getOperand(1).getVRegValueOrNull() ||
604 MI->getOperand(1).isImmediate() ||
605 MI->getOperand(1).isRegister() ||
606 MI->getOperand(1).isGlobalAddress() ||
607 MI->getOperand(1).isExternalSymbol()))) &&
608 "Illegal form for AddRegFrm instruction!");
610 unsigned Reg = MI->getOperand(0).getReg();
612 O << TII.getName(MI->getOpCode()) << " ";
613 printOp(MI->getOperand(0));
614 if (MI->getNumOperands() == 2 &&
615 (!MI->getOperand(1).isRegister() ||
616 MI->getOperand(1).getVRegValueOrNull() ||
617 MI->getOperand(1).isGlobalAddress() ||
618 MI->getOperand(1).isExternalSymbol())) {
620 printOp(MI->getOperand(1));
626 case X86II::MRMDestReg: {
627 // There are two acceptable forms of MRMDestReg instructions, those with 2,
630 // 2 Operands: this is for things like mov that do not read a second input
632 // 3 Operands: in this form, the first two registers (the destination, and
633 // the first operand) should be the same, post register allocation. The 3rd
634 // operand is an additional input. This should be for things like add
637 // 4 Operands: This form is for instructions which are 3 operands forms, but
638 // have a constant argument as well.
640 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
641 assert(MI->getOperand(0).isRegister() &&
642 (MI->getNumOperands() == 2 ||
643 (isTwoAddr && MI->getOperand(1).isRegister() &&
644 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
645 (MI->getNumOperands() == 3 ||
646 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
647 && "Bad format for MRMDestReg!");
649 O << TII.getName(MI->getOpCode()) << " ";
650 printOp(MI->getOperand(0));
652 printOp(MI->getOperand(1+isTwoAddr));
653 if (MI->getNumOperands() == 4) {
655 printOp(MI->getOperand(3));
661 case X86II::MRMDestMem: {
662 // These instructions are the same as MRMDestReg, but instead of having a
663 // register reference for the mod/rm field, it's a memory reference.
665 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
666 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
668 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
669 printMemReference(MI, 0);
671 printOp(MI->getOperand(4));
676 case X86II::MRMSrcReg: {
677 // There are three forms that are acceptable for MRMSrcReg instructions,
678 // those with 3 and 2 operands:
680 // 3 Operands: in this form, the last register (the second input) is the
681 // ModR/M input. The first two operands should be the same, post register
682 // allocation. This is for things like: add r32, r/m32
684 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
685 // instructions like the IMULri instructions.
687 // 2 Operands: this is for things like mov that do not read a second input
689 assert(MI->getOperand(0).isRegister() &&
690 MI->getOperand(1).isRegister() &&
691 (MI->getNumOperands() == 2 ||
692 (MI->getNumOperands() == 3 &&
693 (MI->getOperand(2).isRegister() ||
694 MI->getOperand(2).isImmediate())))
695 && "Bad format for MRMSrcReg!");
696 if (MI->getNumOperands() == 3 &&
697 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
700 O << TII.getName(MI->getOpCode()) << " ";
701 printOp(MI->getOperand(0));
703 // If this is IMULri* instructions, print the non-two-address operand.
704 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
706 printOp(MI->getOperand(1));
710 printOp(MI->getOperand(MI->getNumOperands()-1));
715 case X86II::MRMSrcMem: {
716 // These instructions are the same as MRMSrcReg, but instead of having a
717 // register reference for the mod/rm field, it's a memory reference.
719 assert(MI->getOperand(0).isRegister() &&
720 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
721 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
723 && "Bad format for MRMDestReg!");
724 if (MI->getNumOperands() == 2+4 &&
725 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
728 O << TII.getName(MI->getOpCode()) << " ";
729 printOp(MI->getOperand(0));
730 O << ", " << sizePtr(Desc) << " ";
731 printMemReference(MI, MI->getNumOperands()-4);
736 case X86II::MRMS0r: case X86II::MRMS1r:
737 case X86II::MRMS2r: case X86II::MRMS3r:
738 case X86II::MRMS4r: case X86II::MRMS5r:
739 case X86II::MRMS6r: case X86II::MRMS7r: {
740 // In this form, the following are valid formats:
742 // 2. cmp reg, immediate
743 // 2. shl rdest, rinput <implicit CL or 1>
744 // 3. sbb rdest, rinput, immediate [rdest = rinput]
746 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
747 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
748 assert((MI->getNumOperands() != 2 ||
749 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
750 "Bad MRMSxR format!");
751 assert((MI->getNumOperands() < 3 ||
752 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
753 "Bad MRMSxR format!");
755 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
756 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
759 O << TII.getName(MI->getOpCode()) << " ";
760 printOp(MI->getOperand(0));
761 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
763 printOp(MI->getOperand(MI->getNumOperands()-1));
771 case X86II::MRMS0m: case X86II::MRMS1m:
772 case X86II::MRMS2m: case X86II::MRMS3m:
773 case X86II::MRMS4m: case X86II::MRMS5m:
774 case X86II::MRMS6m: case X86II::MRMS7m: {
775 // In this form, the following are valid formats:
777 // 2. cmp [m], immediate
778 // 2. shl [m], rinput <implicit CL or 1>
779 // 3. sbb [m], immediate
781 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
782 isMem(MI, 0) && "Bad MRMSxM format!");
783 assert((MI->getNumOperands() != 5 ||
784 (MI->getOperand(4).isImmediate() ||
785 MI->getOperand(4).isGlobalAddress())) &&
786 "Bad MRMSxM format!");
788 const MachineOperand &Op3 = MI->getOperand(3);
790 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
791 // is misassembled by gas in intel_syntax mode as its 32-bit
792 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
793 // opcode bytes instead of the instruction.
794 if (MI->getOpCode() == X86::FSTPr80) {
795 if ((MI->getOperand(0).getReg() == X86::ESP)
796 && (MI->getOperand(1).getImmedValue() == 1)) {
797 if (Op3.isImmediate() &&
798 Op3.getImmedValue() >= -128 && Op3.getImmedValue() <= 127) {
800 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex
801 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
803 O << ".byte 0xdb, 0xbc, 0x24\n\t";
811 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
812 // misassembled by gas in intel_syntax mode as its 32-bit
813 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
814 // opcode bytes instead of the instruction.
815 if (MI->getOpCode() == X86::FLDr80 &&
816 MI->getOperand(0).getReg() == X86::ESP &&
817 MI->getOperand(1).getImmedValue() == 1) {
818 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
819 Op3.getImmedValue() <= 127) { // 1 byte displacement
820 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex
821 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
823 O << ".byte 0xdb, 0xac, 0x24\n\t";
830 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
831 // invalid opcode, saying "64 bit operations are only supported in
832 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
833 // [...]", which is wrong. Workaround: Output the raw opcode bytes
834 // instead of the instruction.
835 if (MI->getOpCode() == X86::FILDr64 &&
836 MI->getOperand(0).getReg() == X86::ESP &&
837 MI->getOperand(1).getImmedValue() == 1) {
838 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
839 Op3.getImmedValue() <= 127) { // 1 byte displacement
840 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex
841 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
843 O << ".byte 0xdf, 0xac, 0x24\n\t";
846 O << std::dec << "\t# ";
850 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
851 // an invalid opcode, saying "64 bit operations are only
852 // supported in 64 bit modes." libopcodes disassembles it as
853 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
854 // "fistpll DWORD PTR " instead, which is what libopcodes is
856 if (MI->getOpCode() == X86::FISTPr64) {
857 O << "fistpll DWORD PTR ";
858 printMemReference(MI, 0);
859 if (MI->getNumOperands() == 5) {
861 printOp(MI->getOperand(4));
866 O << TII.getName(MI->getOpCode()) << " ";
867 O << sizePtr(Desc) << " ";
868 printMemReference(MI, 0);
869 if (MI->getNumOperands() == 5) {
871 printOp(MI->getOperand(4));
878 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
882 bool Printer::doInitialization(Module &M) {
883 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
885 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
886 // instruction as a reference to the register named sp, and if you try to
887 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
888 // before being looked up in the symbol table. This creates spurious
889 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
890 // mode, and decorate all register names with percent signs.
891 O << "\t.intel_syntax\n";
892 Mang = new Mangler(M, EmitCygwin);
893 return false; // success
896 // SwitchSection - Switch to the specified section of the executable if we are
897 // not already in it!
899 static void SwitchSection(std::ostream &OS, std::string &CurSection,
900 const char *NewSection) {
901 if (CurSection != NewSection) {
902 CurSection = NewSection;
903 if (!CurSection.empty())
904 OS << "\t" << NewSection << "\n";
908 bool Printer::doFinalization(Module &M) {
909 const TargetData &TD = TM.getTargetData();
910 std::string CurSection;
912 // Print out module-level global variables here.
913 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
914 if (I->hasInitializer()) { // External global require no code
916 std::string name = Mang->getValueName(I);
917 Constant *C = I->getInitializer();
918 unsigned Size = TD.getTypeSize(C->getType());
919 unsigned Align = TD.getTypeAlignment(C->getType());
921 if (C->isNullValue() &&
922 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
923 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
924 SwitchSection(O, CurSection, ".data");
925 if (I->hasInternalLinkage())
926 O << "\t.local " << name << "\n";
928 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
929 << "," << (unsigned)TD.getTypeAlignment(C->getType());
931 WriteAsOperand(O, I, true, true, &M);
934 switch (I->getLinkage()) {
935 case GlobalValue::LinkOnceLinkage:
936 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
937 // Nonnull linkonce -> weak
938 O << "\t.weak " << name << "\n";
939 SwitchSection(O, CurSection, "");
940 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
943 case GlobalValue::AppendingLinkage:
944 // FIXME: appending linkage variables should go into a section of
945 // their name or something. For now, just emit them as external.
946 case GlobalValue::ExternalLinkage:
947 // If external or appending, declare as a global symbol
948 O << "\t.globl " << name << "\n";
950 case GlobalValue::InternalLinkage:
951 if (C->isNullValue())
952 SwitchSection(O, CurSection, ".bss");
954 SwitchSection(O, CurSection, ".data");
958 O << "\t.align " << Align << "\n";
959 O << "\t.type " << name << ",@object\n";
960 O << "\t.size " << name << "," << Size << "\n";
961 O << name << ":\t\t\t\t# ";
962 WriteAsOperand(O, I, true, true, &M);
964 WriteAsOperand(O, C, false, false, &M);
966 emitGlobalConstant(C);
971 return false; // success
974 } // End llvm namespace