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"
33 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35 // FIXME: This should be automatically picked up by autoconf from the C
37 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
38 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
40 struct Printer : public MachineFunctionPass {
41 /// Output stream on which we're printing assembly code.
45 /// Target machine description which we query for reg. names, data
50 /// Name-mangler for global names.
54 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
56 /// We name each basic block in a Function with a unique number, so
57 /// that we can consistently refer to them later. This is cleared
58 /// at the beginning of each call to runOnMachineFunction().
60 typedef std::map<const Value *, unsigned> ValueMapTy;
61 ValueMapTy NumberForBB;
63 /// Cache of mangled name for current function. This is
64 /// recalculated at the beginning of each call to
65 /// runOnMachineFunction().
67 std::string CurrentFnName;
69 virtual const char *getPassName() const {
70 return "X86 Assembly Printer";
73 void checkImplUses (const TargetInstrDescriptor &Desc);
74 void printMachineInstruction(const MachineInstr *MI);
75 void printOp(const MachineOperand &MO,
76 bool elideOffsetKeyword = false);
77 void printMemReference(const MachineInstr *MI, unsigned Op);
78 void printConstantPool(MachineConstantPool *MCP);
79 bool runOnMachineFunction(MachineFunction &F);
80 bool doInitialization(Module &M);
81 bool doFinalization(Module &M);
82 void emitGlobalConstant(const Constant* CV);
83 void emitConstantValueOnly(const Constant *CV);
85 } // end of anonymous namespace
87 /// createX86CodePrinterPass - Returns a pass that prints the X86
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description. This should work
90 /// regardless of whether the function is in SSA form.
92 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
93 return new Printer(o, tm);
96 /// isStringCompatible - Can we treat the specified array as a string?
97 /// Only if it is an array of ubytes or non-negative sbytes.
99 static bool isStringCompatible(const ConstantArray *CVA) {
100 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
101 if (ETy == Type::UByteTy) return true;
102 if (ETy != Type::SByteTy) return false;
104 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
105 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
111 /// toOctal - Convert the low order bits of X into an octal digit.
113 static inline char toOctal(int X) {
117 /// getAsCString - Return the specified array as a C compatible
118 /// string, only if the predicate isStringCompatible is true.
120 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
121 assert(isStringCompatible(CVA) && "Array is not string compatible!");
124 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
125 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
129 } else if (C == '\\') {
131 } else if (isprint(C)) {
135 case '\b': O << "\\b"; break;
136 case '\f': O << "\\f"; break;
137 case '\n': O << "\\n"; break;
138 case '\r': O << "\\r"; break;
139 case '\t': O << "\\t"; break;
142 O << toOctal(C >> 6);
143 O << toOctal(C >> 3);
144 O << toOctal(C >> 0);
152 // Print out the specified constant, without a storage class. Only the
153 // constants valid in constant expressions can occur here.
154 void Printer::emitConstantValueOnly(const Constant *CV) {
155 if (CV->isNullValue())
157 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
158 assert(CB == ConstantBool::True);
160 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
162 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
164 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
165 // This is a constant address for a global variable or function. Use the
166 // name of the variable or function as the address value.
167 O << Mang->getValueName(CPR->getValue());
168 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
169 const TargetData &TD = TM.getTargetData();
170 switch(CE->getOpcode()) {
171 case Instruction::GetElementPtr: {
172 // generate a symbolic expression for the byte address
173 const Constant *ptrVal = CE->getOperand(0);
174 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
175 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
177 emitConstantValueOnly(ptrVal);
178 O << ") + " << Offset;
180 emitConstantValueOnly(ptrVal);
184 case Instruction::Cast: {
185 // Support only non-converting or widening casts for now, that is, ones
186 // that do not involve a change in value. This assertion is not a
188 Constant *Op = CE->getOperand(0);
189 const Type *OpTy = Op->getType(), *Ty = CE->getType();
191 assert(((isa<PointerType>(OpTy)
192 && (Ty == Type::LongTy || Ty == Type::ULongTy))
193 || (isa<PointerType>(Ty)
194 && (OpTy == Type::LongTy || OpTy == Type::ULongTy))
195 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
196 && OpTy->isLosslesslyConvertibleTo(Ty))))
197 && "FIXME: Don't yet support this kind of constant cast expr");
199 emitConstantValueOnly(Op);
203 case Instruction::Add:
205 emitConstantValueOnly(CE->getOperand(0));
207 emitConstantValueOnly(CE->getOperand(1));
211 assert(0 && "Unsupported operator!");
214 assert(0 && "Unknown constant value!");
218 // Print a constant value or values, with the appropriate storage class as a
220 void Printer::emitGlobalConstant(const Constant *CV) {
221 const TargetData &TD = TM.getTargetData();
223 if (CV->isNullValue()) {
224 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
226 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
227 if (isStringCompatible(CVA)) {
229 printAsCString(O, CVA);
231 } else { // Not a string. Print the values in successive locations
232 const std::vector<Use> &constValues = CVA->getValues();
233 for (unsigned i=0; i < constValues.size(); i++)
234 emitGlobalConstant(cast<Constant>(constValues[i].get()));
237 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
238 // Print the fields in successive locations. Pad to align if needed!
239 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
240 const std::vector<Use>& constValues = CVS->getValues();
241 unsigned sizeSoFar = 0;
242 for (unsigned i=0, N = constValues.size(); i < N; i++) {
243 const Constant* field = cast<Constant>(constValues[i].get());
245 // Check if padding is needed and insert one or more 0s.
246 unsigned fieldSize = TD.getTypeSize(field->getType());
247 unsigned padSize = ((i == N-1? cvsLayout->StructSize
248 : cvsLayout->MemberOffsets[i+1])
249 - cvsLayout->MemberOffsets[i]) - fieldSize;
250 sizeSoFar += fieldSize + padSize;
252 // Now print the actual field value
253 emitGlobalConstant(field);
255 // Insert the field padding unless it's zero bytes...
257 O << "\t.zero\t " << padSize << "\n";
259 assert(sizeSoFar == cvsLayout->StructSize &&
260 "Layout of constant struct may be incorrect!");
262 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
263 // FP Constants are printed as integer constants to avoid losing
265 double Val = CFP->getValue();
266 switch (CFP->getType()->getPrimitiveID()) {
267 default: assert(0 && "Unknown floating point type!");
268 case Type::FloatTyID: {
269 union FU { // Abide by C TBAA rules
274 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
277 case Type::DoubleTyID: {
278 union DU { // Abide by C TBAA rules
283 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
289 const Type *type = CV->getType();
291 switch (type->getPrimitiveID()) {
292 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
295 case Type::UShortTyID: case Type::ShortTyID:
298 case Type::FloatTyID: case Type::PointerTyID:
299 case Type::UIntTyID: case Type::IntTyID:
302 case Type::DoubleTyID:
303 case Type::ULongTyID: case Type::LongTyID:
307 assert (0 && "Can't handle printing this type of thing");
311 emitConstantValueOnly(CV);
315 /// printConstantPool - Print to the current output stream assembly
316 /// representations of the constants in the constant pool MCP. This is
317 /// used to print out constants which have been "spilled to memory" by
318 /// the code generator.
320 void Printer::printConstantPool(MachineConstantPool *MCP) {
321 const std::vector<Constant*> &CP = MCP->getConstants();
322 const TargetData &TD = TM.getTargetData();
324 if (CP.empty()) return;
326 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
327 O << "\t.section .rodata\n";
328 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
330 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
332 emitGlobalConstant(CP[i]);
336 /// runOnMachineFunction - This uses the printMachineInstruction()
337 /// method to print assembly for each instruction.
339 bool Printer::runOnMachineFunction(MachineFunction &MF) {
340 // BBNumber is used here so that a given Printer will never give two
341 // BBs the same name. (If you have a better way, please let me know!)
342 static unsigned BBNumber = 0;
345 // What's my mangled name?
346 CurrentFnName = Mang->getValueName(MF.getFunction());
348 // Print out constants referenced by the function
349 printConstantPool(MF.getConstantPool());
351 // Print out labels for the function.
353 O << "\t.align 16\n";
354 O << "\t.globl\t" << CurrentFnName << "\n";
356 O << "\t.type\t" << CurrentFnName << ", @function\n";
357 O << CurrentFnName << ":\n";
359 // Number each basic block so that we can consistently refer to them
360 // in PC-relative references.
362 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
364 NumberForBB[I->getBasicBlock()] = BBNumber++;
367 // Print out code for the function.
368 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
370 // Print a label for the basic block.
371 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
372 << I->getBasicBlock()->getName() << "\n";
373 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
375 // Print the assembly for the instruction.
377 printMachineInstruction(*II);
381 // We didn't modify anything.
385 static bool isScale(const MachineOperand &MO) {
386 return MO.isImmediate() &&
387 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
388 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
391 static bool isMem(const MachineInstr *MI, unsigned Op) {
392 if (MI->getOperand(Op).isFrameIndex()) return true;
393 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
394 return Op+4 <= MI->getNumOperands() &&
395 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
396 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
401 void Printer::printOp(const MachineOperand &MO,
402 bool elideOffsetKeyword /* = false */) {
403 const MRegisterInfo &RI = *TM.getRegisterInfo();
404 switch (MO.getType()) {
405 case MachineOperand::MO_VirtualRegister:
406 if (Value *V = MO.getVRegValueOrNull()) {
407 O << "<" << V->getName() << ">";
411 case MachineOperand::MO_MachineRegister:
412 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
413 // Bug Workaround: See note in Printer::doInitialization about %.
414 O << "%" << RI.get(MO.getReg()).Name;
416 O << "%reg" << MO.getReg();
419 case MachineOperand::MO_SignExtendedImmed:
420 case MachineOperand::MO_UnextendedImmed:
421 O << (int)MO.getImmedValue();
423 case MachineOperand::MO_PCRelativeDisp: {
424 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
425 assert (i != NumberForBB.end()
426 && "Could not find a BB in the NumberForBB map!");
427 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
430 case MachineOperand::MO_GlobalAddress:
431 if (!elideOffsetKeyword)
433 O << Mang->getValueName(MO.getGlobal());
435 case MachineOperand::MO_ExternalSymbol:
436 O << MO.getSymbolName();
439 O << "<unknown operand type>"; return;
443 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
444 switch (Desc.TSFlags & X86II::ArgMask) {
445 default: assert(0 && "Unknown arg size!");
446 case X86II::Arg8: return "BYTE PTR";
447 case X86II::Arg16: return "WORD PTR";
448 case X86II::Arg32: return "DWORD PTR";
449 case X86II::Arg64: return "QWORD PTR";
450 case X86II::ArgF32: return "DWORD PTR";
451 case X86II::ArgF64: return "QWORD PTR";
452 case X86II::ArgF80: return "XWORD PTR";
456 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
457 assert(isMem(MI, Op) && "Invalid memory reference!");
459 if (MI->getOperand(Op).isFrameIndex()) {
460 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
461 if (MI->getOperand(Op+3).getImmedValue())
462 O << " + " << MI->getOperand(Op+3).getImmedValue();
465 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
466 O << "[.CPI" << CurrentFnName << "_"
467 << MI->getOperand(Op).getConstantPoolIndex();
468 if (MI->getOperand(Op+3).getImmedValue())
469 O << " + " << MI->getOperand(Op+3).getImmedValue();
474 const MachineOperand &BaseReg = MI->getOperand(Op);
475 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
476 const MachineOperand &IndexReg = MI->getOperand(Op+2);
477 int DispVal = MI->getOperand(Op+3).getImmedValue();
480 bool NeedPlus = false;
481 if (BaseReg.getReg()) {
486 if (IndexReg.getReg()) {
487 if (NeedPlus) O << " + ";
489 O << ScaleVal << "*";
507 /// checkImplUses - Emit the implicit-use registers for the
508 /// instruction described by DESC, if its PrintImplUses flag is set.
510 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
511 const MRegisterInfo &RI = *TM.getRegisterInfo();
512 if (Desc.TSFlags & X86II::PrintImplUses) {
513 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
514 // Bug Workaround: See note in Printer::doInitialization about %.
515 O << ", %" << RI.get(*p).Name;
520 /// printMachineInstruction -- Print out a single X86 LLVM instruction
521 /// MI in Intel syntax to the current output stream.
523 void Printer::printMachineInstruction(const MachineInstr *MI) {
524 unsigned Opcode = MI->getOpcode();
525 const TargetInstrInfo &TII = TM.getInstrInfo();
526 const TargetInstrDescriptor &Desc = TII.get(Opcode);
529 switch (Desc.TSFlags & X86II::FormMask) {
531 // Print pseudo-instructions as comments; either they should have been
532 // turned into real instructions by now, or they don't need to be
533 // seen by the assembler (e.g., IMPLICIT_USEs.)
535 if (Opcode == X86::PHI) {
536 printOp(MI->getOperand(0));
538 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
539 if (i != 1) O << ", ";
541 printOp(MI->getOperand(i));
543 printOp(MI->getOperand(i+1));
548 if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() ||
549 MI->getOperand(0).opIsDefAndUse())) {
550 printOp(MI->getOperand(0));
554 O << TII.getName(MI->getOpcode());
556 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
558 if (MI->getOperand(i).opIsDefOnly() ||
559 MI->getOperand(i).opIsDefAndUse()) O << "*";
560 printOp(MI->getOperand(i));
561 if (MI->getOperand(i).opIsDefOnly() ||
562 MI->getOperand(i).opIsDefAndUse()) O << "*";
569 // The accepted forms of Raw instructions are:
570 // 1. nop - No operand required
571 // 2. jmp foo - PC relative displacement operand
572 // 3. call bar - GlobalAddress Operand or External Symbol Operand
574 assert(MI->getNumOperands() == 0 ||
575 (MI->getNumOperands() == 1 &&
576 (MI->getOperand(0).isPCRelativeDisp() ||
577 MI->getOperand(0).isGlobalAddress() ||
578 MI->getOperand(0).isExternalSymbol())) &&
579 "Illegal raw instruction!");
580 O << TII.getName(MI->getOpcode()) << " ";
582 if (MI->getNumOperands() == 1) {
583 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
588 case X86II::AddRegFrm: {
589 // There are currently two forms of acceptable AddRegFrm instructions.
590 // Either the instruction JUST takes a single register (like inc, dec, etc),
591 // or it takes a register and an immediate of the same size as the register
592 // (move immediate f.e.). Note that this immediate value might be stored as
593 // an LLVM value, to represent, for example, loading the address of a global
594 // into a register. The initial register might be duplicated if this is a
595 // M_2_ADDR_REG instruction
597 assert(MI->getOperand(0).isRegister() &&
598 (MI->getNumOperands() == 1 ||
599 (MI->getNumOperands() == 2 &&
600 (MI->getOperand(1).getVRegValueOrNull() ||
601 MI->getOperand(1).isImmediate() ||
602 MI->getOperand(1).isRegister() ||
603 MI->getOperand(1).isGlobalAddress() ||
604 MI->getOperand(1).isExternalSymbol()))) &&
605 "Illegal form for AddRegFrm instruction!");
607 unsigned Reg = MI->getOperand(0).getReg();
609 O << TII.getName(MI->getOpCode()) << " ";
610 printOp(MI->getOperand(0));
611 if (MI->getNumOperands() == 2 &&
612 (!MI->getOperand(1).isRegister() ||
613 MI->getOperand(1).getVRegValueOrNull() ||
614 MI->getOperand(1).isGlobalAddress() ||
615 MI->getOperand(1).isExternalSymbol())) {
617 printOp(MI->getOperand(1));
623 case X86II::MRMDestReg: {
624 // There are two acceptable forms of MRMDestReg instructions, those with 2,
627 // 2 Operands: this is for things like mov that do not read a second input
629 // 3 Operands: in this form, the first two registers (the destination, and
630 // the first operand) should be the same, post register allocation. The 3rd
631 // operand is an additional input. This should be for things like add
634 // 4 Operands: This form is for instructions which are 3 operands forms, but
635 // have a constant argument as well.
637 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
638 assert(MI->getOperand(0).isRegister() &&
639 (MI->getNumOperands() == 2 ||
640 (isTwoAddr && MI->getOperand(1).isRegister() &&
641 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
642 (MI->getNumOperands() == 3 ||
643 (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
644 && "Bad format for MRMDestReg!");
646 O << TII.getName(MI->getOpCode()) << " ";
647 printOp(MI->getOperand(0));
649 printOp(MI->getOperand(1+isTwoAddr));
650 if (MI->getNumOperands() == 4) {
652 printOp(MI->getOperand(3));
658 case X86II::MRMDestMem: {
659 // These instructions are the same as MRMDestReg, but instead of having a
660 // register reference for the mod/rm field, it's a memory reference.
662 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
663 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
665 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
666 printMemReference(MI, 0);
668 printOp(MI->getOperand(4));
673 case X86II::MRMSrcReg: {
674 // There are three forms that are acceptable for MRMSrcReg instructions,
675 // those with 3 and 2 operands:
677 // 3 Operands: in this form, the last register (the second input) is the
678 // ModR/M input. The first two operands should be the same, post register
679 // allocation. This is for things like: add r32, r/m32
681 // 3 Operands: in this form, we can have 'INST R, R, imm', which is used for
682 // instructions like the IMULri instructions.
684 // 2 Operands: this is for things like mov that do not read a second input
686 assert(MI->getOperand(0).isRegister() &&
687 MI->getOperand(1).isRegister() &&
688 (MI->getNumOperands() == 2 ||
689 (MI->getNumOperands() == 3 &&
690 (MI->getOperand(2).isRegister() ||
691 MI->getOperand(2).isImmediate())))
692 && "Bad format for MRMSrcReg!");
693 if (MI->getNumOperands() == 3 &&
694 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
697 O << TII.getName(MI->getOpCode()) << " ";
698 printOp(MI->getOperand(0));
700 // If this is IMULri* instructions, print the non-two-address operand.
701 if (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()) {
703 printOp(MI->getOperand(1));
707 printOp(MI->getOperand(MI->getNumOperands()-1));
712 case X86II::MRMSrcMem: {
713 // These instructions are the same as MRMSrcReg, but instead of having a
714 // register reference for the mod/rm field, it's a memory reference.
716 assert(MI->getOperand(0).isRegister() &&
717 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
718 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
720 && "Bad format for MRMDestReg!");
721 if (MI->getNumOperands() == 2+4 &&
722 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
725 O << TII.getName(MI->getOpCode()) << " ";
726 printOp(MI->getOperand(0));
727 O << ", " << sizePtr(Desc) << " ";
728 printMemReference(MI, MI->getNumOperands()-4);
733 case X86II::MRMS0r: case X86II::MRMS1r:
734 case X86II::MRMS2r: case X86II::MRMS3r:
735 case X86II::MRMS4r: case X86II::MRMS5r:
736 case X86II::MRMS6r: case X86II::MRMS7r: {
737 // In this form, the following are valid formats:
739 // 2. cmp reg, immediate
740 // 2. shl rdest, rinput <implicit CL or 1>
741 // 3. sbb rdest, rinput, immediate [rdest = rinput]
743 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
744 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
745 assert((MI->getNumOperands() != 2 ||
746 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
747 "Bad MRMSxR format!");
748 assert((MI->getNumOperands() < 3 ||
749 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
750 "Bad MRMSxR format!");
752 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
753 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
756 O << TII.getName(MI->getOpCode()) << " ";
757 printOp(MI->getOperand(0));
758 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
760 printOp(MI->getOperand(MI->getNumOperands()-1));
768 case X86II::MRMS0m: case X86II::MRMS1m:
769 case X86II::MRMS2m: case X86II::MRMS3m:
770 case X86II::MRMS4m: case X86II::MRMS5m:
771 case X86II::MRMS6m: case X86II::MRMS7m: {
772 // In this form, the following are valid formats:
774 // 2. cmp [m], immediate
775 // 2. shl [m], rinput <implicit CL or 1>
776 // 3. sbb [m], immediate
778 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
779 isMem(MI, 0) && "Bad MRMSxM format!");
780 assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
781 "Bad MRMSxM format!");
782 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
783 // is misassembled by gas in intel_syntax mode as its 32-bit
784 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
785 // opcode bytes instead of the instruction.
786 if (MI->getOpCode() == X86::FSTPr80) {
787 if ((MI->getOperand(0).getReg() == X86::ESP)
788 && (MI->getOperand(1).getImmedValue() == 1)) {
789 int DispVal = MI->getOperand(3).getImmedValue();
790 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
791 unsigned int val = (unsigned int) DispVal;
792 O << ".byte 0xdb, 0xbc, 0x24\n\t";
793 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
794 } else { // 1 byte disp.
795 unsigned char val = (unsigned char) DispVal;
796 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex << (unsigned) val
797 << std::dec << "\t# ";
801 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
802 // misassembled by gas in intel_syntax mode as its 32-bit
803 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
804 // opcode bytes instead of the instruction.
805 if (MI->getOpCode() == X86::FLDr80) {
806 if ((MI->getOperand(0).getReg() == X86::ESP)
807 && (MI->getOperand(1).getImmedValue() == 1)) {
808 int DispVal = MI->getOperand(3).getImmedValue();
809 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
810 unsigned int val = (unsigned int) DispVal;
811 O << ".byte 0xdb, 0xac, 0x24\n\t";
812 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
813 } else { // 1 byte disp.
814 unsigned char val = (unsigned char) DispVal;
815 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
816 << std::dec << "\t# ";
820 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
821 // invalid opcode, saying "64 bit operations are only supported in
822 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
823 // [...]", which is wrong. Workaround: Output the raw opcode bytes
824 // instead of the instruction.
825 if (MI->getOpCode() == X86::FILDr64) {
826 if ((MI->getOperand(0).getReg() == X86::ESP)
827 && (MI->getOperand(1).getImmedValue() == 1)) {
828 int DispVal = MI->getOperand(3).getImmedValue();
829 if ((DispVal < -128) || (DispVal > 127)) { // 4 byte disp.
830 unsigned int val = (unsigned int) DispVal;
831 O << ".byte 0xdf, 0xac, 0x24\n\t";
832 O << ".long 0x" << std::hex << (unsigned) val << std::dec << "\t# ";
833 } else { // 1 byte disp.
834 unsigned char val = (unsigned char) DispVal;
835 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex << (unsigned) val
836 << std::dec << "\t# ";
840 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
841 // an invalid opcode, saying "64 bit operations are only
842 // supported in 64 bit modes." libopcodes disassembles it as
843 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
844 // "fistpll DWORD PTR " instead, which is what libopcodes is
846 if (MI->getOpCode() == X86::FISTPr64) {
847 O << "fistpll DWORD PTR ";
848 printMemReference(MI, 0);
849 if (MI->getNumOperands() == 5) {
851 printOp(MI->getOperand(4));
856 O << TII.getName(MI->getOpCode()) << " ";
857 O << sizePtr(Desc) << " ";
858 printMemReference(MI, 0);
859 if (MI->getNumOperands() == 5) {
861 printOp(MI->getOperand(4));
868 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
872 bool Printer::doInitialization(Module &M) {
873 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
875 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
876 // instruction as a reference to the register named sp, and if you try to
877 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
878 // before being looked up in the symbol table. This creates spurious
879 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
880 // mode, and decorate all register names with percent signs.
881 O << "\t.intel_syntax\n";
882 Mang = new Mangler(M, EmitCygwin);
883 return false; // success
886 // SwitchSection - Switch to the specified section of the executable if we are
887 // not already in it!
889 static void SwitchSection(std::ostream &OS, std::string &CurSection,
890 const char *NewSection) {
891 if (CurSection != NewSection) {
892 CurSection = NewSection;
893 if (!CurSection.empty())
894 OS << "\t" << NewSection << "\n";
898 bool Printer::doFinalization(Module &M) {
899 const TargetData &TD = TM.getTargetData();
900 std::string CurSection;
902 // Print out module-level global variables here.
903 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
904 if (I->hasInitializer()) { // External global require no code
906 std::string name = Mang->getValueName(I);
907 Constant *C = I->getInitializer();
908 unsigned Size = TD.getTypeSize(C->getType());
909 unsigned Align = TD.getTypeAlignment(C->getType());
911 if (C->isNullValue() &&
912 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
913 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
914 SwitchSection(O, CurSection, ".data");
915 if (I->hasInternalLinkage())
916 O << "\t.local " << name << "\n";
918 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
919 << "," << (unsigned)TD.getTypeAlignment(C->getType());
921 WriteAsOperand(O, I, true, true, &M);
924 switch (I->getLinkage()) {
925 case GlobalValue::LinkOnceLinkage:
926 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
927 // Nonnull linkonce -> weak
928 O << "\t.weak " << name << "\n";
929 SwitchSection(O, CurSection, "");
930 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
933 case GlobalValue::AppendingLinkage:
934 // FIXME: appending linkage variables should go into a section of
935 // their name or something. For now, just emit them as external.
936 case GlobalValue::ExternalLinkage:
937 // If external or appending, declare as a global symbol
938 O << "\t.globl " << name << "\n";
940 case GlobalValue::InternalLinkage:
941 if (C->isNullValue())
942 SwitchSection(O, CurSection, ".bss");
944 SwitchSection(O, CurSection, ".data");
948 O << "\t.align " << Align << "\n";
949 O << "\t.type " << name << ",@object\n";
950 O << "\t.size " << name << "," << Size << "\n";
951 O << name << ":\t\t\t\t# ";
952 WriteAsOperand(O, I, true, true, &M);
954 WriteAsOperand(O, C, false, false, &M);
956 emitGlobalConstant(C);
961 return false; // success