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 not a
190 Constant *Op = CE->getOperand(0);
191 const Type *OpTy = Op->getType(), *Ty = CE->getType();
193 assert(((isa<PointerType>(OpTy)
194 && (Ty == Type::LongTy || Ty == Type::ULongTy))
195 || (isa<PointerType>(Ty)
196 && (OpTy == Type::LongTy || OpTy == Type::ULongTy))
197 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
198 && OpTy->isLosslesslyConvertibleTo(Ty))))
199 && "FIXME: Don't yet support this kind of constant cast expr");
201 emitConstantValueOnly(Op);
205 case Instruction::Add:
207 emitConstantValueOnly(CE->getOperand(0));
209 emitConstantValueOnly(CE->getOperand(1));
213 assert(0 && "Unsupported operator!");
216 assert(0 && "Unknown constant value!");
220 // Print a constant value or values, with the appropriate storage class as a
222 void Printer::emitGlobalConstant(const Constant *CV) {
223 const TargetData &TD = TM.getTargetData();
225 if (CV->isNullValue()) {
226 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
228 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
229 if (isStringCompatible(CVA)) {
231 printAsCString(O, CVA);
233 } else { // Not a string. Print the values in successive locations
234 const std::vector<Use> &constValues = CVA->getValues();
235 for (unsigned i=0; i < constValues.size(); i++)
236 emitGlobalConstant(cast<Constant>(constValues[i].get()));
239 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
240 // Print the fields in successive locations. Pad to align if needed!
241 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
242 const std::vector<Use>& constValues = CVS->getValues();
243 unsigned sizeSoFar = 0;
244 for (unsigned i=0, N = constValues.size(); i < N; i++) {
245 const Constant* field = cast<Constant>(constValues[i].get());
247 // Check if padding is needed and insert one or more 0s.
248 unsigned fieldSize = TD.getTypeSize(field->getType());
249 unsigned padSize = ((i == N-1? cvsLayout->StructSize
250 : cvsLayout->MemberOffsets[i+1])
251 - cvsLayout->MemberOffsets[i]) - fieldSize;
252 sizeSoFar += fieldSize + padSize;
254 // Now print the actual field value
255 emitGlobalConstant(field);
257 // Insert the field padding unless it's zero bytes...
259 O << "\t.zero\t " << padSize << "\n";
261 assert(sizeSoFar == cvsLayout->StructSize &&
262 "Layout of constant struct may be incorrect!");
264 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
265 // FP Constants are printed as integer constants to avoid losing
267 double Val = CFP->getValue();
268 switch (CFP->getType()->getPrimitiveID()) {
269 default: assert(0 && "Unknown floating point type!");
270 case Type::FloatTyID: {
271 union FU { // Abide by C TBAA rules
276 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
279 case Type::DoubleTyID: {
280 union DU { // Abide by C TBAA rules
285 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
291 const Type *type = CV->getType();
293 switch (type->getPrimitiveID()) {
294 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
297 case Type::UShortTyID: case Type::ShortTyID:
300 case Type::FloatTyID: case Type::PointerTyID:
301 case Type::UIntTyID: case Type::IntTyID:
304 case Type::DoubleTyID:
305 case Type::ULongTyID: case Type::LongTyID:
309 assert (0 && "Can't handle printing this type of thing");
313 emitConstantValueOnly(CV);
317 /// printConstantPool - Print to the current output stream assembly
318 /// representations of the constants in the constant pool MCP. This is
319 /// used to print out constants which have been "spilled to memory" by
320 /// the code generator.
322 void Printer::printConstantPool(MachineConstantPool *MCP) {
323 const std::vector<Constant*> &CP = MCP->getConstants();
324 const TargetData &TD = TM.getTargetData();
326 if (CP.empty()) return;
328 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
329 O << "\t.section .rodata\n";
330 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
332 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
334 emitGlobalConstant(CP[i]);
338 /// runOnMachineFunction - This uses the printMachineInstruction()
339 /// method to print assembly for each instruction.
341 bool Printer::runOnMachineFunction(MachineFunction &MF) {
342 // BBNumber is used here so that a given Printer will never give two
343 // BBs the same name. (If you have a better way, please let me know!)
344 static unsigned BBNumber = 0;
347 // What's my mangled name?
348 CurrentFnName = Mang->getValueName(MF.getFunction());
350 // Print out constants referenced by the function
351 printConstantPool(MF.getConstantPool());
353 // Print out labels for the function.
355 O << "\t.align 16\n";
356 O << "\t.globl\t" << CurrentFnName << "\n";
358 O << "\t.type\t" << CurrentFnName << ", @function\n";
359 O << CurrentFnName << ":\n";
361 // Number each basic block so that we can consistently refer to them
362 // in PC-relative references.
364 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
366 NumberForBB[I->getBasicBlock()] = BBNumber++;
369 // Print out code for the function.
370 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
372 // Print a label for the basic block.
373 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
374 << I->getBasicBlock()->getName() << "\n";
375 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
377 // Print the assembly for the instruction.
379 printMachineInstruction(*II);
383 // We didn't modify anything.
387 static bool isScale(const MachineOperand &MO) {
388 return MO.isImmediate() &&
389 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
390 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
393 static bool isMem(const MachineInstr *MI, unsigned Op) {
394 if (MI->getOperand(Op).isFrameIndex()) return true;
395 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
396 return Op+4 <= MI->getNumOperands() &&
397 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
398 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
403 void Printer::printOp(const MachineOperand &MO,
404 bool elideOffsetKeyword /* = false */) {
405 const MRegisterInfo &RI = *TM.getRegisterInfo();
406 switch (MO.getType()) {
407 case MachineOperand::MO_VirtualRegister:
408 if (Value *V = MO.getVRegValueOrNull()) {
409 O << "<" << V->getName() << ">";
413 case MachineOperand::MO_MachineRegister:
414 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
415 // Bug Workaround: See note in Printer::doInitialization about %.
416 O << "%" << RI.get(MO.getReg()).Name;
418 O << "%reg" << MO.getReg();
421 case MachineOperand::MO_SignExtendedImmed:
422 case MachineOperand::MO_UnextendedImmed:
423 O << (int)MO.getImmedValue();
425 case MachineOperand::MO_PCRelativeDisp: {
426 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
427 assert (i != NumberForBB.end()
428 && "Could not find a BB in the NumberForBB map!");
429 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
432 case MachineOperand::MO_GlobalAddress:
433 if (!elideOffsetKeyword)
435 O << Mang->getValueName(MO.getGlobal());
437 case MachineOperand::MO_ExternalSymbol:
438 O << MO.getSymbolName();
441 O << "<unknown operand type>"; return;
445 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
446 switch (Desc.TSFlags & X86II::ArgMask) {
447 default: assert(0 && "Unknown arg size!");
448 case X86II::Arg8: return "BYTE PTR";
449 case X86II::Arg16: return "WORD PTR";
450 case X86II::Arg32: return "DWORD PTR";
451 case X86II::Arg64: return "QWORD PTR";
452 case X86II::ArgF32: return "DWORD PTR";
453 case X86II::ArgF64: return "QWORD PTR";
454 case X86II::ArgF80: return "XWORD PTR";
458 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
459 assert(isMem(MI, Op) && "Invalid memory reference!");
461 if (MI->getOperand(Op).isFrameIndex()) {
462 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
463 if (MI->getOperand(Op+3).getImmedValue())
464 O << " + " << MI->getOperand(Op+3).getImmedValue();
467 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
468 O << "[.CPI" << CurrentFnName << "_"
469 << MI->getOperand(Op).getConstantPoolIndex();
470 if (MI->getOperand(Op+3).getImmedValue())
471 O << " + " << MI->getOperand(Op+3).getImmedValue();
476 const MachineOperand &BaseReg = MI->getOperand(Op);
477 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
478 const MachineOperand &IndexReg = MI->getOperand(Op+2);
479 int DispVal = MI->getOperand(Op+3).getImmedValue();
482 bool NeedPlus = false;
483 if (BaseReg.getReg()) {
488 if (IndexReg.getReg()) {
489 if (NeedPlus) O << " + ";
491 O << ScaleVal << "*";
509 /// checkImplUses - Emit the implicit-use registers for the
510 /// instruction described by DESC, if its PrintImplUses flag is set.
512 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
513 const MRegisterInfo &RI = *TM.getRegisterInfo();
514 if (Desc.TSFlags & X86II::PrintImplUses) {
515 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
516 // Bug Workaround: See note in Printer::doInitialization about %.
517 O << ", %" << RI.get(*p).Name;
522 /// printMachineInstruction -- Print out a single X86 LLVM instruction
523 /// MI in Intel syntax to the current output stream.
525 void Printer::printMachineInstruction(const MachineInstr *MI) {
526 unsigned Opcode = MI->getOpcode();
527 const TargetInstrInfo &TII = TM.getInstrInfo();
528 const TargetInstrDescriptor &Desc = TII.get(Opcode);
531 switch (Desc.TSFlags & X86II::FormMask) {
533 // Print pseudo-instructions as comments; either they should have been
534 // turned into real instructions by now, or they don't need to be
535 // seen by the assembler (e.g., IMPLICIT_USEs.)
537 if (Opcode == X86::PHI) {
538 printOp(MI->getOperand(0));
540 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
541 if (i != 1) O << ", ";
543 printOp(MI->getOperand(i));
545 printOp(MI->getOperand(i+1));
550 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
551 MI->getOperand(0).opIsDefAndUse())) {
552 printOp(MI->getOperand(0));
556 O << TII.getName(MI->getOpcode());
558 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
560 if (MI->getOperand(i).opIsDefOnly() ||
561 MI->getOperand(i).opIsDefAndUse()) O << "*";
562 printOp(MI->getOperand(i));
563 if (MI->getOperand(i).opIsDefOnly() ||
564 MI->getOperand(i).opIsDefAndUse()) O << "*";
571 // The accepted forms of Raw instructions are:
572 // 1. nop - No operand required
573 // 2. jmp foo - PC relative displacement operand
574 // 3. call bar - GlobalAddress Operand or External Symbol Operand
576 assert(MI->getNumOperands() == 0 ||
577 (MI->getNumOperands() == 1 &&
578 (MI->getOperand(0).isPCRelativeDisp() ||
579 MI->getOperand(0).isGlobalAddress() ||
580 MI->getOperand(0).isExternalSymbol())) &&
581 "Illegal raw instruction!");
582 O << TII.getName(MI->getOpcode()) << " ";
584 if (MI->getNumOperands() == 1) {
585 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
590 case X86II::AddRegFrm: {
591 // There are currently two forms of acceptable AddRegFrm instructions.
592 // Either the instruction JUST takes a single register (like inc, dec, etc),
593 // or it takes a register and an immediate of the same size as the register
594 // (move immediate f.e.). Note that this immediate value might be stored as
595 // an LLVM value, to represent, for example, loading the address of a global
596 // into a register. The initial register might be duplicated if this is a
597 // M_2_ADDR_REG instruction
599 assert(MI->getOperand(0).isRegister() &&
600 (MI->getNumOperands() == 1 ||
601 (MI->getNumOperands() == 2 &&
602 (MI->getOperand(1).getVRegValueOrNull() ||
603 MI->getOperand(1).isImmediate() ||
604 MI->getOperand(1).isRegister() ||
605 MI->getOperand(1).isGlobalAddress() ||
606 MI->getOperand(1).isExternalSymbol()))) &&
607 "Illegal form for AddRegFrm instruction!");
609 unsigned Reg = MI->getOperand(0).getReg();
611 O << TII.getName(MI->getOpCode()) << " ";
612 printOp(MI->getOperand(0));
613 if (MI->getNumOperands() == 2 &&
614 (!MI->getOperand(1).isRegister() ||
615 MI->getOperand(1).getVRegValueOrNull() ||
616 MI->getOperand(1).isGlobalAddress() ||
617 MI->getOperand(1).isExternalSymbol())) {
619 printOp(MI->getOperand(1));
625 case X86II::MRMDestReg: {
626 // There are two acceptable forms of MRMDestReg instructions, those with 2,
629 // 2 Operands: this is for things like mov that do not read a second input
631 // 3 Operands: in this form, the first two registers (the destination, and
632 // the first operand) should be the same, post register allocation. The 3rd
633 // operand is an additional input. This should be for things like add
636 // 4 Operands: This form is for instructions which are 3 operands forms, but
637 // have a constant argument as well.
639 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
640 assert(MI->getOperand(0).isRegister() &&
641 (MI->getNumOperands() == 2 ||
642 (isTwoAddr && MI->getOperand(1).isRegister() &&
643 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
644 (MI->getNumOperands() == 3 ||
645 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
646 && "Bad format for MRMDestReg!");
648 O << TII.getName(MI->getOpCode()) << " ";
649 printOp(MI->getOperand(0));
651 printOp(MI->getOperand(1+isTwoAddr));
652 if (MI->getNumOperands() == 4) {
654 printOp(MI->getOperand(3));
660 case X86II::MRMDestMem: {
661 // These instructions are the same as MRMDestReg, but instead of having a
662 // register reference for the mod/rm field, it's a memory reference.
664 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
665 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
667 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
668 printMemReference(MI, 0);
670 printOp(MI->getOperand(4));
675 case X86II::MRMSrcReg: {
676 // There are three forms that are acceptable for MRMSrcReg instructions,
677 // those with 3 and 2 operands:
679 // 3 Operands: in this form, the last register (the second input) is the
680 // ModR/M input. The first two operands should be the same, post register
681 // allocation. This is for things like: add r32, r/m32
683 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
684 // instructions like the IMULri instructions.
686 // 2 Operands: this is for things like mov that do not read a second input
688 assert(MI->getOperand(0).isRegister() &&
689 MI->getOperand(1).isRegister() &&
690 (MI->getNumOperands() == 2 ||
691 (MI->getNumOperands() == 3 &&
692 (MI->getOperand(2).isRegister() ||
693 MI->getOperand(2).isImmediate())))
694 && "Bad format for MRMSrcReg!");
695 if (MI->getNumOperands() == 3 &&
696 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
699 O << TII.getName(MI->getOpCode()) << " ";
700 printOp(MI->getOperand(0));
702 // If this is IMULri* instructions, print the non-two-address operand.
703 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
705 printOp(MI->getOperand(1));
709 printOp(MI->getOperand(MI->getNumOperands()-1));
714 case X86II::MRMSrcMem: {
715 // These instructions are the same as MRMSrcReg, but instead of having a
716 // register reference for the mod/rm field, it's a memory reference.
718 assert(MI->getOperand(0).isRegister() &&
719 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
720 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
722 && "Bad format for MRMDestReg!");
723 if (MI->getNumOperands() == 2+4 &&
724 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
727 O << TII.getName(MI->getOpCode()) << " ";
728 printOp(MI->getOperand(0));
729 O << ", " << sizePtr(Desc) << " ";
730 printMemReference(MI, MI->getNumOperands()-4);
735 case X86II::MRMS0r: case X86II::MRMS1r:
736 case X86II::MRMS2r: case X86II::MRMS3r:
737 case X86II::MRMS4r: case X86II::MRMS5r:
738 case X86II::MRMS6r: case X86II::MRMS7r: {
739 // In this form, the following are valid formats:
741 // 2. cmp reg, immediate
742 // 2. shl rdest, rinput <implicit CL or 1>
743 // 3. sbb rdest, rinput, immediate [rdest = rinput]
745 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
746 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
747 assert((MI->getNumOperands() != 2 ||
748 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
749 "Bad MRMSxR format!");
750 assert((MI->getNumOperands() < 3 ||
751 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
752 "Bad MRMSxR format!");
754 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
755 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
758 O << TII.getName(MI->getOpCode()) << " ";
759 printOp(MI->getOperand(0));
760 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
762 printOp(MI->getOperand(MI->getNumOperands()-1));
770 case X86II::MRMS0m: case X86II::MRMS1m:
771 case X86II::MRMS2m: case X86II::MRMS3m:
772 case X86II::MRMS4m: case X86II::MRMS5m:
773 case X86II::MRMS6m: case X86II::MRMS7m: {
774 // In this form, the following are valid formats:
776 // 2. cmp [m], immediate
777 // 2. shl [m], rinput <implicit CL or 1>
778 // 3. sbb [m], immediate
780 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
781 isMem(MI, 0) && "Bad MRMSxM format!");
782 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
783 "Bad MRMSxM format!");
784 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
785 // is misassembled by gas in intel_syntax mode as its 32-bit
786 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
787 // opcode bytes instead of the instruction.
788 if (MI->getOpCode() == X86::FSTPr80) {
789 if ((MI->getOperand(0).getReg() == X86::ESP)
790 && (MI->getOperand(1).getImmedValue() == 1)) {
791 int DispVal = MI->getOperand(3).getImmedValue();
792 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
793 unsigned int val = (unsigned int) DispVal;
794 O << ".byte 0xdb, 0xbc, 0x24\n\t";
795 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
796 } else { // 1 byte disp.
797 unsigned char val = (unsigned char) DispVal;
798 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
799 << std::dec << "\t# ";
803 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
804 // misassembled by gas in intel_syntax mode as its 32-bit
805 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
806 // opcode bytes instead of the instruction.
807 if (MI->getOpCode() == X86::FLDr80) {
808 if ((MI->getOperand(0).getReg() == X86::ESP)
809 && (MI->getOperand(1).getImmedValue() == 1)) {
810 int DispVal = MI->getOperand(3).getImmedValue();
811 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
812 unsigned int val = (unsigned int) DispVal;
813 O << ".byte 0xdb, 0xac, 0x24\n\t";
814 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
815 } else { // 1 byte disp.
816 unsigned char val = (unsigned char) DispVal;
817 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
818 << std::dec << "\t# ";
822 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
823 // invalid opcode, saying "64 bit operations are only supported in
824 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
825 // [...]", which is wrong. Workaround: Output the raw opcode bytes
826 // instead of the instruction.
827 if (MI->getOpCode() == X86::FILDr64) {
828 if ((MI->getOperand(0).getReg() == X86::ESP)
829 && (MI->getOperand(1).getImmedValue() == 1)) {
830 int DispVal = MI->getOperand(3).getImmedValue();
831 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
832 unsigned int val = (unsigned int) DispVal;
833 O << ".byte 0xdf, 0xac, 0x24\n\t";
834 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
835 } else { // 1 byte disp.
836 unsigned char val = (unsigned char) DispVal;
837 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
838 << std::dec << "\t# ";
842 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
843 // an invalid opcode, saying "64 bit operations are only
844 // supported in 64 bit modes." libopcodes disassembles it as
845 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
846 // "fistpll DWORD PTR " instead, which is what libopcodes is
848 if (MI->getOpCode() == X86::FISTPr64) {
849 O << "fistpll DWORD PTR ";
850 printMemReference(MI, 0);
851 if (MI->getNumOperands() == 5) {
853 printOp(MI->getOperand(4));
858 O << TII.getName(MI->getOpCode()) << " ";
859 O << sizePtr(Desc) << " ";
860 printMemReference(MI, 0);
861 if (MI->getNumOperands() == 5) {
863 printOp(MI->getOperand(4));
870 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
874 bool Printer::doInitialization(Module &M) {
875 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
877 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
878 // instruction as a reference to the register named sp, and if you try to
879 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
880 // before being looked up in the symbol table. This creates spurious
881 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
882 // mode, and decorate all register names with percent signs.
883 O << "\t.intel_syntax\n";
884 Mang = new Mangler(M, EmitCygwin);
885 return false; // success
888 // SwitchSection - Switch to the specified section of the executable if we are
889 // not already in it!
891 static void SwitchSection(std::ostream &OS, std::string &CurSection,
892 const char *NewSection) {
893 if (CurSection != NewSection) {
894 CurSection = NewSection;
895 if (!CurSection.empty())
896 OS << "\t" << NewSection << "\n";
900 bool Printer::doFinalization(Module &M) {
901 const TargetData &TD = TM.getTargetData();
902 std::string CurSection;
904 // Print out module-level global variables here.
905 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
906 if (I->hasInitializer()) { // External global require no code
908 std::string name = Mang->getValueName(I);
909 Constant *C = I->getInitializer();
910 unsigned Size = TD.getTypeSize(C->getType());
911 unsigned Align = TD.getTypeAlignment(C->getType());
913 if (C->isNullValue() &&
914 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
915 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
916 SwitchSection(O, CurSection, ".data");
917 if (I->hasInternalLinkage())
918 O << "\t.local " << name << "\n";
920 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
921 << "," << (unsigned)TD.getTypeAlignment(C->getType());
923 WriteAsOperand(O, I, true, true, &M);
926 switch (I->getLinkage()) {
927 case GlobalValue::LinkOnceLinkage:
928 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
929 // Nonnull linkonce -> weak
930 O << "\t.weak " << name << "\n";
931 SwitchSection(O, CurSection, "");
932 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
935 case GlobalValue::AppendingLinkage:
936 // FIXME: appending linkage variables should go into a section of
937 // their name or something. For now, just emit them as external.
938 case GlobalValue::ExternalLinkage:
939 // If external or appending, declare as a global symbol
940 O << "\t.globl " << name << "\n";
942 case GlobalValue::InternalLinkage:
943 if (C->isNullValue())
944 SwitchSection(O, CurSection, ".bss");
946 SwitchSection(O, CurSection, ".data");
950 O << "\t.align " << Align << "\n";
951 O << "\t.type " << name << ",@object\n";
952 O << "\t.size " << name << "," << Size << "\n";
953 O << name << ":\t\t\t\t# ";
954 WriteAsOperand(O, I, true, true, &M);
956 WriteAsOperand(O, C, false, false, &M);
958 emitGlobalConstant(C);
963 return false; // success
966 } // End llvm namespace