X86AsmPrinter.cpp revision 8863f1814ba2c26910edb30857d10a8587f2f7de
1//===-- X86/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===// 2// 3// The LLVM Compiler Infrastructure 4// 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. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains a printer that converts from our internal representation 11// of machine-dependent LLVM code to Intel-format assembly language. This 12// printer is the output mechanism used by `llc' and `lli -print-machineinstrs' 13// on X86. 14// 15//===----------------------------------------------------------------------===// 16 17#include "X86.h" 18#include "X86InstrInfo.h" 19#include "X86TargetMachine.h" 20#include "llvm/Constants.h" 21#include "llvm/DerivedTypes.h" 22#include "llvm/Module.h" 23#include "llvm/Assembly/Writer.h" 24#include "llvm/CodeGen/MachineCodeEmitter.h" 25#include "llvm/CodeGen/MachineConstantPool.h" 26#include "llvm/CodeGen/MachineFunctionPass.h" 27#include "llvm/CodeGen/MachineInstr.h" 28#include "llvm/Target/TargetMachine.h" 29#include "llvm/Support/Mangler.h" 30#include "Support/Statistic.h" 31#include "Support/StringExtras.h" 32#include "Support/CommandLine.h" 33using namespace llvm; 34 35namespace { 36 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed"); 37 38 // FIXME: This should be automatically picked up by autoconf from the C 39 // frontend 40 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden, 41 cl::desc("Emit X86 assembly code suitable for consumption by cygwin")); 42 43 struct GasBugWorkaroundEmitter : public MachineCodeEmitter { 44 GasBugWorkaroundEmitter(std::ostream& o) 45 : O(o), OldFlags(O.flags()), firstByte(true) { 46 O << std::hex; 47 } 48 49 ~GasBugWorkaroundEmitter() { 50 O.flags(OldFlags); 51 O << "\t# "; 52 } 53 54 virtual void emitByte(unsigned char B) { 55 if (!firstByte) O << "\n\t"; 56 firstByte = false; 57 O << ".byte 0x" << (unsigned) B; 58 } 59 60 // These should never be called 61 virtual void emitWord(unsigned W) { assert(0); } 62 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); } 63 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); } 64 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); } 65 virtual uint64_t getCurrentPCValue() { abort(); } 66 virtual uint64_t forceCompilationOf(Function *F) { abort(); } 67 68 private: 69 std::ostream& O; 70 std::ios::fmtflags OldFlags; 71 bool firstByte; 72 }; 73 74 struct Printer : public MachineFunctionPass { 75 /// Output stream on which we're printing assembly code. 76 /// 77 std::ostream &O; 78 79 /// Target machine description which we query for reg. names, data 80 /// layout, etc. 81 /// 82 TargetMachine &TM; 83 84 /// Name-mangler for global names. 85 /// 86 Mangler *Mang; 87 88 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { } 89 90 /// Cache of mangled name for current function. This is 91 /// recalculated at the beginning of each call to 92 /// runOnMachineFunction(). 93 /// 94 std::string CurrentFnName; 95 96 virtual const char *getPassName() const { 97 return "X86 Assembly Printer"; 98 } 99 100 void printImplUsesBefore(const TargetInstrDescriptor &Desc); 101 bool printImplDefsBefore(const TargetInstrDescriptor &Desc); 102 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC); 103 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC); 104 void printMachineInstruction(const MachineInstr *MI); 105 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false); 106 void printMemReference(const MachineInstr *MI, unsigned Op); 107 void printConstantPool(MachineConstantPool *MCP); 108 bool runOnMachineFunction(MachineFunction &F); 109 bool doInitialization(Module &M); 110 bool doFinalization(Module &M); 111 void emitGlobalConstant(const Constant* CV); 112 void emitConstantValueOnly(const Constant *CV); 113 }; 114} // end of anonymous namespace 115 116/// createX86CodePrinterPass - Returns a pass that prints the X86 117/// assembly code for a MachineFunction to the given output stream, 118/// using the given target machine description. This should work 119/// regardless of whether the function is in SSA form. 120/// 121FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){ 122 return new Printer(o, tm); 123} 124 125/// toOctal - Convert the low order bits of X into an octal digit. 126/// 127static inline char toOctal(int X) { 128 return (X&7)+'0'; 129} 130 131/// getAsCString - Return the specified array as a C compatible 132/// string, only if the predicate isStringCompatible is true. 133/// 134static void printAsCString(std::ostream &O, const ConstantArray *CVA) { 135 assert(CVA->isString() && "Array is not string compatible!"); 136 137 O << "\""; 138 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) { 139 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue(); 140 141 if (C == '"') { 142 O << "\\\""; 143 } else if (C == '\\') { 144 O << "\\\\"; 145 } else if (isprint(C)) { 146 O << C; 147 } else { 148 switch(C) { 149 case '\b': O << "\\b"; break; 150 case '\f': O << "\\f"; break; 151 case '\n': O << "\\n"; break; 152 case '\r': O << "\\r"; break; 153 case '\t': O << "\\t"; break; 154 default: 155 O << '\\'; 156 O << toOctal(C >> 6); 157 O << toOctal(C >> 3); 158 O << toOctal(C >> 0); 159 break; 160 } 161 } 162 } 163 O << "\""; 164} 165 166// Print out the specified constant, without a storage class. Only the 167// constants valid in constant expressions can occur here. 168void Printer::emitConstantValueOnly(const Constant *CV) { 169 if (CV->isNullValue()) 170 O << "0"; 171 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) { 172 assert(CB == ConstantBool::True); 173 O << "1"; 174 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) 175 if (((CI->getValue() << 32) >> 32) == CI->getValue()) 176 O << CI->getValue(); 177 else 178 O << (unsigned long long)CI->getValue(); 179 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) 180 O << CI->getValue(); 181 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 182 // This is a constant address for a global variable or function. Use the 183 // name of the variable or function as the address value. 184 O << Mang->getValueName(GV); 185 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 186 const TargetData &TD = TM.getTargetData(); 187 switch(CE->getOpcode()) { 188 case Instruction::GetElementPtr: { 189 // generate a symbolic expression for the byte address 190 const Constant *ptrVal = CE->getOperand(0); 191 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end()); 192 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) { 193 O << "("; 194 emitConstantValueOnly(ptrVal); 195 O << ") + " << Offset; 196 } else { 197 emitConstantValueOnly(ptrVal); 198 } 199 break; 200 } 201 case Instruction::Cast: { 202 // Support only non-converting or widening casts for now, that is, ones 203 // that do not involve a change in value. This assertion is really gross, 204 // and may not even be a complete check. 205 Constant *Op = CE->getOperand(0); 206 const Type *OpTy = Op->getType(), *Ty = CE->getType(); 207 208 // Remember, kids, pointers on x86 can be losslessly converted back and 209 // forth into 32-bit or wider integers, regardless of signedness. :-P 210 assert(((isa<PointerType>(OpTy) 211 && (Ty == Type::LongTy || Ty == Type::ULongTy 212 || Ty == Type::IntTy || Ty == Type::UIntTy)) 213 || (isa<PointerType>(Ty) 214 && (OpTy == Type::LongTy || OpTy == Type::ULongTy 215 || OpTy == Type::IntTy || OpTy == Type::UIntTy)) 216 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy)) 217 && OpTy->isLosslesslyConvertibleTo(Ty)))) 218 && "FIXME: Don't yet support this kind of constant cast expr"); 219 O << "("; 220 emitConstantValueOnly(Op); 221 O << ")"; 222 break; 223 } 224 case Instruction::Add: 225 O << "("; 226 emitConstantValueOnly(CE->getOperand(0)); 227 O << ") + ("; 228 emitConstantValueOnly(CE->getOperand(1)); 229 O << ")"; 230 break; 231 default: 232 assert(0 && "Unsupported operator!"); 233 } 234 } else { 235 assert(0 && "Unknown constant value!"); 236 } 237} 238 239// Print a constant value or values, with the appropriate storage class as a 240// prefix. 241void Printer::emitGlobalConstant(const Constant *CV) { 242 const TargetData &TD = TM.getTargetData(); 243 244 if (CV->isNullValue()) { 245 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n"; 246 return; 247 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) { 248 if (CVA->isString()) { 249 O << "\t.ascii\t"; 250 printAsCString(O, CVA); 251 O << "\n"; 252 } else { // Not a string. Print the values in successive locations 253 const std::vector<Use> &constValues = CVA->getValues(); 254 for (unsigned i=0; i < constValues.size(); i++) 255 emitGlobalConstant(cast<Constant>(constValues[i].get())); 256 } 257 return; 258 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) { 259 // Print the fields in successive locations. Pad to align if needed! 260 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType()); 261 const std::vector<Use>& constValues = CVS->getValues(); 262 unsigned sizeSoFar = 0; 263 for (unsigned i=0, N = constValues.size(); i < N; i++) { 264 const Constant* field = cast<Constant>(constValues[i].get()); 265 266 // Check if padding is needed and insert one or more 0s. 267 unsigned fieldSize = TD.getTypeSize(field->getType()); 268 unsigned padSize = ((i == N-1? cvsLayout->StructSize 269 : cvsLayout->MemberOffsets[i+1]) 270 - cvsLayout->MemberOffsets[i]) - fieldSize; 271 sizeSoFar += fieldSize + padSize; 272 273 // Now print the actual field value 274 emitGlobalConstant(field); 275 276 // Insert the field padding unless it's zero bytes... 277 if (padSize) 278 O << "\t.zero\t " << padSize << "\n"; 279 } 280 assert(sizeSoFar == cvsLayout->StructSize && 281 "Layout of constant struct may be incorrect!"); 282 return; 283 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 284 // FP Constants are printed as integer constants to avoid losing 285 // precision... 286 double Val = CFP->getValue(); 287 switch (CFP->getType()->getTypeID()) { 288 default: assert(0 && "Unknown floating point type!"); 289 case Type::FloatTyID: { 290 union FU { // Abide by C TBAA rules 291 float FVal; 292 unsigned UVal; 293 } U; 294 U.FVal = Val; 295 O << ".long\t" << U.UVal << "\t# float " << Val << "\n"; 296 return; 297 } 298 case Type::DoubleTyID: { 299 union DU { // Abide by C TBAA rules 300 double FVal; 301 uint64_t UVal; 302 } U; 303 U.FVal = Val; 304 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n"; 305 return; 306 } 307 } 308 } 309 310 const Type *type = CV->getType(); 311 O << "\t"; 312 switch (type->getTypeID()) { 313 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID: 314 O << ".byte"; 315 break; 316 case Type::UShortTyID: case Type::ShortTyID: 317 O << ".word"; 318 break; 319 case Type::FloatTyID: case Type::PointerTyID: 320 case Type::UIntTyID: case Type::IntTyID: 321 O << ".long"; 322 break; 323 case Type::DoubleTyID: 324 case Type::ULongTyID: case Type::LongTyID: 325 O << ".quad"; 326 break; 327 default: 328 assert (0 && "Can't handle printing this type of thing"); 329 break; 330 } 331 O << "\t"; 332 emitConstantValueOnly(CV); 333 O << "\n"; 334} 335 336/// printConstantPool - Print to the current output stream assembly 337/// representations of the constants in the constant pool MCP. This is 338/// used to print out constants which have been "spilled to memory" by 339/// the code generator. 340/// 341void Printer::printConstantPool(MachineConstantPool *MCP) { 342 const std::vector<Constant*> &CP = MCP->getConstants(); 343 const TargetData &TD = TM.getTargetData(); 344 345 if (CP.empty()) return; 346 347 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 348 O << "\t.section .rodata\n"; 349 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType()) 350 << "\n"; 351 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#" 352 << *CP[i] << "\n"; 353 emitGlobalConstant(CP[i]); 354 } 355} 356 357/// runOnMachineFunction - This uses the printMachineInstruction() 358/// method to print assembly for each instruction. 359/// 360bool Printer::runOnMachineFunction(MachineFunction &MF) { 361 O << "\n\n"; 362 // What's my mangled name? 363 CurrentFnName = Mang->getValueName(MF.getFunction()); 364 365 // Print out constants referenced by the function 366 printConstantPool(MF.getConstantPool()); 367 368 // Print out labels for the function. 369 O << "\t.text\n"; 370 O << "\t.align 16\n"; 371 O << "\t.globl\t" << CurrentFnName << "\n"; 372 if (!EmitCygwin) 373 O << "\t.type\t" << CurrentFnName << ", @function\n"; 374 O << CurrentFnName << ":\n"; 375 376 // Print out code for the function. 377 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); 378 I != E; ++I) { 379 // Print a label for the basic block. 380 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# " 381 << I->getBasicBlock()->getName() << "\n"; 382 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end(); 383 II != E; ++II) { 384 // Print the assembly for the instruction. 385 O << "\t"; 386 printMachineInstruction(II); 387 } 388 } 389 390 // We didn't modify anything. 391 return false; 392} 393 394static bool isScale(const MachineOperand &MO) { 395 return MO.isImmediate() && 396 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 || 397 MO.getImmedValue() == 4 || MO.getImmedValue() == 8); 398} 399 400static bool isMem(const MachineInstr *MI, unsigned Op) { 401 if (MI->getOperand(Op).isFrameIndex()) return true; 402 if (MI->getOperand(Op).isConstantPoolIndex()) return true; 403 return Op+4 <= MI->getNumOperands() && 404 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) && 405 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate(); 406} 407 408 409 410void Printer::printOp(const MachineOperand &MO, 411 bool elideOffsetKeyword /* = false */) { 412 const MRegisterInfo &RI = *TM.getRegisterInfo(); 413 switch (MO.getType()) { 414 case MachineOperand::MO_VirtualRegister: 415 if (Value *V = MO.getVRegValueOrNull()) { 416 O << "<" << V->getName() << ">"; 417 return; 418 } 419 // FALLTHROUGH 420 case MachineOperand::MO_MachineRegister: 421 if (MRegisterInfo::isPhysicalRegister(MO.getReg())) 422 // Bug Workaround: See note in Printer::doInitialization about %. 423 O << "%" << RI.get(MO.getReg()).Name; 424 else 425 O << "%reg" << MO.getReg(); 426 return; 427 428 case MachineOperand::MO_SignExtendedImmed: 429 case MachineOperand::MO_UnextendedImmed: 430 O << (int)MO.getImmedValue(); 431 return; 432 case MachineOperand::MO_MachineBasicBlock: { 433 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock(); 434 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction()) 435 << "_" << MBBOp->getNumber () << "\t# " 436 << MBBOp->getBasicBlock ()->getName (); 437 return; 438 } 439 case MachineOperand::MO_PCRelativeDisp: 440 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs"; 441 abort (); 442 return; 443 case MachineOperand::MO_GlobalAddress: 444 if (!elideOffsetKeyword) 445 O << "OFFSET "; 446 O << Mang->getValueName(MO.getGlobal()); 447 return; 448 case MachineOperand::MO_ExternalSymbol: 449 O << MO.getSymbolName(); 450 return; 451 default: 452 O << "<unknown operand type>"; return; 453 } 454} 455 456static const char* const sizePtr(const TargetInstrDescriptor &Desc) { 457 switch (Desc.TSFlags & X86II::MemMask) { 458 default: assert(0 && "Unknown arg size!"); 459 case X86II::Mem8: return "BYTE PTR"; 460 case X86II::Mem16: return "WORD PTR"; 461 case X86II::Mem32: return "DWORD PTR"; 462 case X86II::Mem64: return "QWORD PTR"; 463 case X86II::Mem80: return "XWORD PTR"; 464 } 465} 466 467void Printer::printMemReference(const MachineInstr *MI, unsigned Op) { 468 assert(isMem(MI, Op) && "Invalid memory reference!"); 469 470 if (MI->getOperand(Op).isFrameIndex()) { 471 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex(); 472 if (MI->getOperand(Op+3).getImmedValue()) 473 O << " + " << MI->getOperand(Op+3).getImmedValue(); 474 O << "]"; 475 return; 476 } else if (MI->getOperand(Op).isConstantPoolIndex()) { 477 O << "[.CPI" << CurrentFnName << "_" 478 << MI->getOperand(Op).getConstantPoolIndex(); 479 if (MI->getOperand(Op+3).getImmedValue()) 480 O << " + " << MI->getOperand(Op+3).getImmedValue(); 481 O << "]"; 482 return; 483 } 484 485 const MachineOperand &BaseReg = MI->getOperand(Op); 486 int ScaleVal = MI->getOperand(Op+1).getImmedValue(); 487 const MachineOperand &IndexReg = MI->getOperand(Op+2); 488 int DispVal = MI->getOperand(Op+3).getImmedValue(); 489 490 O << "["; 491 bool NeedPlus = false; 492 if (BaseReg.getReg()) { 493 printOp(BaseReg); 494 NeedPlus = true; 495 } 496 497 if (IndexReg.getReg()) { 498 if (NeedPlus) O << " + "; 499 if (ScaleVal != 1) 500 O << ScaleVal << "*"; 501 printOp(IndexReg); 502 NeedPlus = true; 503 } 504 505 if (DispVal) { 506 if (NeedPlus) 507 if (DispVal > 0) 508 O << " + "; 509 else { 510 O << " - "; 511 DispVal = -DispVal; 512 } 513 O << DispVal; 514 } 515 O << "]"; 516} 517 518 519/// printImplUsesBefore - Emit the implicit-use registers for the instruction 520/// described by DESC, if its PrintImplUsesBefore flag is set. 521/// 522void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) { 523 const MRegisterInfo &RI = *TM.getRegisterInfo(); 524 if (Desc.TSFlags & X86II::PrintImplUsesBefore) { 525 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) { 526 // Bug Workaround: See note in Printer::doInitialization about %. 527 O << "%" << RI.get(*p).Name << ", "; 528 } 529 } 530} 531 532/// printImplDefsBefore - Emit the implicit-def registers for the instruction 533/// described by DESC, if its PrintImplUsesBefore flag is set. Return true if 534/// we printed any registers. 535/// 536bool Printer::printImplDefsBefore(const TargetInstrDescriptor &Desc) { 537 bool Printed = false; 538 const MRegisterInfo &RI = *TM.getRegisterInfo(); 539 if (Desc.TSFlags & X86II::PrintImplDefsBefore) { 540 const unsigned *p = Desc.ImplicitDefs; 541 if (*p) { 542 O << (Printed ? ", %" : "%") << RI.get (*p).Name; 543 Printed = true; 544 ++p; 545 } 546 while (*p) { 547 // Bug Workaround: See note in Printer::doInitialization about %. 548 O << ", %" << RI.get(*p).Name; 549 ++p; 550 } 551 } 552 return Printed; 553} 554 555 556/// printImplUsesAfter - Emit the implicit-use registers for the instruction 557/// described by DESC, if its PrintImplUsesAfter flag is set. 558/// 559/// Inputs: 560/// Comma - List of registers will need a leading comma. 561/// Desc - Description of the Instruction. 562/// 563/// Return value: 564/// true - Emitted one or more registers. 565/// false - Emitted no registers. 566/// 567bool Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc, 568 const bool Comma = true) { 569 const MRegisterInfo &RI = *TM.getRegisterInfo(); 570 if (Desc.TSFlags & X86II::PrintImplUsesAfter) { 571 bool emitted = false; 572 const unsigned *p = Desc.ImplicitUses; 573 if (*p) { 574 O << (Comma ? ", %" : "%") << RI.get (*p).Name; 575 emitted = true; 576 ++p; 577 } 578 while (*p) { 579 // Bug Workaround: See note in Printer::doInitialization about %. 580 O << ", %" << RI.get(*p).Name; 581 ++p; 582 } 583 return emitted; 584 } 585 return false; 586} 587 588/// printImplDefsAfter - Emit the implicit-definition registers for the 589/// instruction described by DESC, if its PrintImplDefsAfter flag is set. 590/// 591/// Inputs: 592/// Comma - List of registers will need a leading comma. 593/// Desc - Description of the Instruction 594/// 595/// Return value: 596/// true - Emitted one or more registers. 597/// false - Emitted no registers. 598/// 599bool Printer::printImplDefsAfter(const TargetInstrDescriptor &Desc, 600 const bool Comma = true) { 601 const MRegisterInfo &RI = *TM.getRegisterInfo(); 602 if (Desc.TSFlags & X86II::PrintImplDefsAfter) { 603 bool emitted = false; 604 const unsigned *p = Desc.ImplicitDefs; 605 if (*p) { 606 O << (Comma ? ", %" : "%") << RI.get (*p).Name; 607 emitted = true; 608 ++p; 609 } 610 while (*p) { 611 // Bug Workaround: See note in Printer::doInitialization about %. 612 O << ", %" << RI.get(*p).Name; 613 ++p; 614 } 615 return emitted; 616 } 617 return false; 618} 619 620/// printMachineInstruction -- Print out a single X86 LLVM instruction 621/// MI in Intel syntax to the current output stream. 622/// 623void Printer::printMachineInstruction(const MachineInstr *MI) { 624 unsigned Opcode = MI->getOpcode(); 625 const TargetInstrInfo &TII = *TM.getInstrInfo(); 626 const TargetInstrDescriptor &Desc = TII.get(Opcode); 627 628 ++EmittedInsts; 629 switch (Desc.TSFlags & X86II::FormMask) { 630 case X86II::Pseudo: 631 // Print pseudo-instructions as comments; either they should have been 632 // turned into real instructions by now, or they don't need to be 633 // seen by the assembler (e.g., IMPLICIT_USEs.) 634 O << "# "; 635 if (Opcode == X86::PHI) { 636 printOp(MI->getOperand(0)); 637 O << " = phi "; 638 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) { 639 if (i != 1) O << ", "; 640 O << "["; 641 printOp(MI->getOperand(i)); 642 O << ", "; 643 printOp(MI->getOperand(i+1)); 644 O << "]"; 645 } 646 } else { 647 unsigned i = 0; 648 if (MI->getNumOperands() && MI->getOperand(0).isDef()) { 649 printOp(MI->getOperand(0)); 650 O << " = "; 651 ++i; 652 } 653 O << TII.getName(MI->getOpcode()); 654 655 for (unsigned e = MI->getNumOperands(); i != e; ++i) { 656 O << " "; 657 if (MI->getOperand(i).isDef()) O << "*"; 658 printOp(MI->getOperand(i)); 659 if (MI->getOperand(i).isDef()) O << "*"; 660 } 661 } 662 O << "\n"; 663 return; 664 665 case X86II::RawFrm: 666 { 667 // The accepted forms of Raw instructions are: 668 // 1. nop - No operand required 669 // 2. jmp foo - MachineBasicBlock operand 670 // 3. call bar - GlobalAddress Operand or External Symbol Operand 671 // 4. in AL, imm - Immediate operand 672 // 673 assert(MI->getNumOperands() == 0 || 674 (MI->getNumOperands() == 1 && 675 (MI->getOperand(0).isMachineBasicBlock() || 676 MI->getOperand(0).isGlobalAddress() || 677 MI->getOperand(0).isExternalSymbol() || 678 MI->getOperand(0).isImmediate())) && 679 "Illegal raw instruction!"); 680 O << TII.getName(MI->getOpcode()) << " "; 681 682 bool LeadingComma = printImplDefsBefore(Desc); 683 684 if (MI->getNumOperands() == 1) { 685 if (LeadingComma) O << ", "; 686 printOp(MI->getOperand(0), true); // Don't print "OFFSET"... 687 LeadingComma = true; 688 } 689 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma; 690 printImplUsesAfter(Desc, LeadingComma); 691 O << "\n"; 692 return; 693 } 694 695 case X86II::AddRegFrm: { 696 // There are currently two forms of acceptable AddRegFrm instructions. 697 // Either the instruction JUST takes a single register (like inc, dec, etc), 698 // or it takes a register and an immediate of the same size as the register 699 // (move immediate f.e.). Note that this immediate value might be stored as 700 // an LLVM value, to represent, for example, loading the address of a global 701 // into a register. The initial register might be duplicated if this is a 702 // M_2_ADDR_REG instruction 703 // 704 assert(MI->getOperand(0).isRegister() && 705 (MI->getNumOperands() == 1 || 706 (MI->getNumOperands() == 2 && 707 (MI->getOperand(1).getVRegValueOrNull() || 708 MI->getOperand(1).isImmediate() || 709 MI->getOperand(1).isRegister() || 710 MI->getOperand(1).isGlobalAddress() || 711 MI->getOperand(1).isExternalSymbol()))) && 712 "Illegal form for AddRegFrm instruction!"); 713 714 unsigned Reg = MI->getOperand(0).getReg(); 715 716 O << TII.getName(MI->getOpcode()) << " "; 717 718 printImplUsesBefore(Desc); // fcmov* 719 720 printOp(MI->getOperand(0)); 721 if (MI->getNumOperands() == 2 && 722 (!MI->getOperand(1).isRegister() || 723 MI->getOperand(1).getVRegValueOrNull() || 724 MI->getOperand(1).isGlobalAddress() || 725 MI->getOperand(1).isExternalSymbol())) { 726 O << ", "; 727 printOp(MI->getOperand(1)); 728 } 729 printImplUsesAfter(Desc); 730 O << "\n"; 731 return; 732 } 733 case X86II::MRMDestReg: { 734 // There are three forms of MRMDestReg instructions, those with 2 735 // or 3 operands: 736 // 737 // 2 Operands: this is for things like mov that do not read a 738 // second input. 739 // 740 // 2 Operands: two address instructions which def&use the first 741 // argument and use the second as input. 742 // 743 // 3 Operands: in this form, two address instructions are the same 744 // as in 2 but have a constant argument as well. 745 // 746 bool isTwoAddr = TII.isTwoAddrInstr(Opcode); 747 assert(MI->getOperand(0).isRegister() && 748 (MI->getNumOperands() == 2 || 749 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate())) 750 && "Bad format for MRMDestReg!"); 751 752 O << TII.getName(MI->getOpcode()) << " "; 753 printOp(MI->getOperand(0)); 754 O << ", "; 755 printOp(MI->getOperand(1)); 756 if (MI->getNumOperands() == 3) { 757 O << ", "; 758 printOp(MI->getOperand(2)); 759 } 760 printImplUsesAfter(Desc); 761 O << "\n"; 762 return; 763 } 764 765 case X86II::MRMDestMem: { 766 // These instructions are the same as MRMDestReg, but instead of having a 767 // register reference for the mod/rm field, it's a memory reference. 768 // 769 assert(isMem(MI, 0) && 770 (MI->getNumOperands() == 4+1 || 771 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate())) 772 && "Bad format for MRMDestMem!"); 773 774 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " "; 775 printMemReference(MI, 0); 776 O << ", "; 777 printOp(MI->getOperand(4)); 778 if (MI->getNumOperands() == 4+2) { 779 O << ", "; 780 printOp(MI->getOperand(5)); 781 } 782 printImplUsesAfter(Desc); 783 O << "\n"; 784 return; 785 } 786 787 case X86II::MRMSrcReg: { 788 // There are three forms that are acceptable for MRMSrcReg 789 // instructions, those with 2 or 3 operands: 790 // 791 // 2 Operands: this is for things like mov that do not read a 792 // second input. 793 // 794 // 2 Operands: in this form, the last register is the ModR/M 795 // input. The first operand is a def&use. This is for things 796 // like: add r32, r/m32 797 // 798 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used 799 // for instructions like the IMULrri instructions. 800 // 801 // 802 assert(MI->getOperand(0).isRegister() && 803 MI->getOperand(1).isRegister() && 804 (MI->getNumOperands() == 2 || 805 (MI->getNumOperands() == 3 && 806 (MI->getOperand(2).isImmediate()))) 807 && "Bad format for MRMSrcReg!"); 808 809 O << TII.getName(MI->getOpcode()) << " "; 810 printOp(MI->getOperand(0)); 811 O << ", "; 812 printOp(MI->getOperand(1)); 813 if (MI->getNumOperands() == 3) { 814 O << ", "; 815 printOp(MI->getOperand(2)); 816 } 817 O << "\n"; 818 return; 819 } 820 821 case X86II::MRMSrcMem: { 822 // These instructions are the same as MRMSrcReg, but instead of having a 823 // register reference for the mod/rm field, it's a memory reference. 824 // 825 assert(MI->getOperand(0).isRegister() && 826 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 827 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && 828 isMem(MI, 1))) 829 && "Bad format for MRMSrcMem!"); 830 O << TII.getName(MI->getOpcode()) << " "; 831 printOp(MI->getOperand(0)); 832 O << ", " << sizePtr(Desc) << " "; 833 printMemReference(MI, 1); 834 if (MI->getNumOperands() == 2+4) { 835 O << ", "; 836 printOp(MI->getOperand(5)); 837 } 838 O << "\n"; 839 return; 840 } 841 842 case X86II::MRM0r: case X86II::MRM1r: 843 case X86II::MRM2r: case X86II::MRM3r: 844 case X86II::MRM4r: case X86II::MRM5r: 845 case X86II::MRM6r: case X86II::MRM7r: { 846 // In this form, the following are valid formats: 847 // 1. sete r 848 // 2. cmp reg, immediate 849 // 2. shl rdest, rinput <implicit CL or 1> 850 // 3. sbb rdest, rinput, immediate [rdest = rinput] 851 // 852 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 && 853 MI->getOperand(0).isRegister() && "Bad MRMSxR format!"); 854 assert((MI->getNumOperands() != 2 || 855 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&& 856 "Bad MRMSxR format!"); 857 assert((MI->getNumOperands() < 3 || 858 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) && 859 "Bad MRMSxR format!"); 860 861 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 862 MI->getOperand(0).getReg() != MI->getOperand(1).getReg()) 863 O << "**"; 864 865 O << TII.getName(MI->getOpcode()) << " "; 866 printOp(MI->getOperand(0)); 867 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) { 868 O << ", "; 869 printOp(MI->getOperand(MI->getNumOperands()-1)); 870 } 871 printImplUsesAfter(Desc); 872 O << "\n"; 873 874 return; 875 } 876 877 case X86II::MRM0m: case X86II::MRM1m: 878 case X86II::MRM2m: case X86II::MRM3m: 879 case X86II::MRM4m: case X86II::MRM5m: 880 case X86II::MRM6m: case X86II::MRM7m: { 881 // In this form, the following are valid formats: 882 // 1. sete [m] 883 // 2. cmp [m], immediate 884 // 2. shl [m], rinput <implicit CL or 1> 885 // 3. sbb [m], immediate 886 // 887 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 && 888 isMem(MI, 0) && "Bad MRMSxM format!"); 889 assert((MI->getNumOperands() != 5 || 890 (MI->getOperand(4).isImmediate() || 891 MI->getOperand(4).isGlobalAddress())) && 892 "Bad MRMSxM format!"); 893 894 const MachineOperand &Op3 = MI->getOperand(3); 895 896 // gas bugs: 897 // 898 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]" 899 // is misassembled by gas in intel_syntax mode as its 32-bit 900 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw 901 // opcode bytes instead of the instruction. 902 // 903 // The 80-bit FP load instruction "fld XWORD PTR [...]" is 904 // misassembled by gas in intel_syntax mode as its 32-bit 905 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw 906 // opcode bytes instead of the instruction. 907 // 908 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an 909 // invalid opcode, saying "64 bit operations are only supported in 910 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR 911 // [...]", which is wrong. Workaround: Output the raw opcode bytes 912 // instead of the instruction. 913 // 914 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an 915 // invalid opcode, saying "64 bit operations are only supported in 916 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR 917 // [...]", which is wrong. Workaround: Output the raw opcode bytes 918 // instead of the instruction. 919 if (MI->getOpcode() == X86::FSTP80m || 920 MI->getOpcode() == X86::FLD80m || 921 MI->getOpcode() == X86::FILD64m || 922 MI->getOpcode() == X86::FISTP64m) { 923 GasBugWorkaroundEmitter gwe(O); 924 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI); 925 } 926 927 O << TII.getName(MI->getOpcode()) << " "; 928 O << sizePtr(Desc) << " "; 929 printMemReference(MI, 0); 930 if (MI->getNumOperands() == 5) { 931 O << ", "; 932 printOp(MI->getOperand(4)); 933 } 934 printImplUsesAfter(Desc); 935 O << "\n"; 936 return; 937 } 938 default: 939 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break; 940 } 941} 942 943bool Printer::doInitialization(Module &M) { 944 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly. 945 // 946 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an 947 // instruction as a reference to the register named sp, and if you try to 948 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased 949 // before being looked up in the symbol table. This creates spurious 950 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix' 951 // mode, and decorate all register names with percent signs. 952 O << "\t.intel_syntax\n"; 953 Mang = new Mangler(M, EmitCygwin); 954 return false; // success 955} 956 957// SwitchSection - Switch to the specified section of the executable if we are 958// not already in it! 959// 960static void SwitchSection(std::ostream &OS, std::string &CurSection, 961 const char *NewSection) { 962 if (CurSection != NewSection) { 963 CurSection = NewSection; 964 if (!CurSection.empty()) 965 OS << "\t" << NewSection << "\n"; 966 } 967} 968 969bool Printer::doFinalization(Module &M) { 970 const TargetData &TD = TM.getTargetData(); 971 std::string CurSection; 972 973 // Print out module-level global variables here. 974 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) 975 if (I->hasInitializer()) { // External global require no code 976 O << "\n\n"; 977 std::string name = Mang->getValueName(I); 978 Constant *C = I->getInitializer(); 979 unsigned Size = TD.getTypeSize(C->getType()); 980 unsigned Align = TD.getTypeAlignment(C->getType()); 981 982 if (C->isNullValue() && 983 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() || 984 I->hasWeakLinkage() /* FIXME: Verify correct */)) { 985 SwitchSection(O, CurSection, ".data"); 986 if (I->hasInternalLinkage()) 987 O << "\t.local " << name << "\n"; 988 989 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType()) 990 << "," << (unsigned)TD.getTypeAlignment(C->getType()); 991 O << "\t\t# "; 992 WriteAsOperand(O, I, true, true, &M); 993 O << "\n"; 994 } else { 995 switch (I->getLinkage()) { 996 case GlobalValue::LinkOnceLinkage: 997 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak. 998 // Nonnull linkonce -> weak 999 O << "\t.weak " << name << "\n"; 1000 SwitchSection(O, CurSection, ""); 1001 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"; 1002 break; 1003 1004 case GlobalValue::AppendingLinkage: 1005 // FIXME: appending linkage variables should go into a section of 1006 // their name or something. For now, just emit them as external. 1007 case GlobalValue::ExternalLinkage: 1008 // If external or appending, declare as a global symbol 1009 O << "\t.globl " << name << "\n"; 1010 // FALL THROUGH 1011 case GlobalValue::InternalLinkage: 1012 if (C->isNullValue()) 1013 SwitchSection(O, CurSection, ".bss"); 1014 else 1015 SwitchSection(O, CurSection, ".data"); 1016 break; 1017 } 1018 1019 O << "\t.align " << Align << "\n"; 1020 O << "\t.type " << name << ",@object\n"; 1021 O << "\t.size " << name << "," << Size << "\n"; 1022 O << name << ":\t\t\t\t# "; 1023 WriteAsOperand(O, I, true, true, &M); 1024 O << " = "; 1025 WriteAsOperand(O, C, false, false, &M); 1026 O << "\n"; 1027 emitGlobalConstant(C); 1028 } 1029 } 1030 1031 delete Mang; 1032 return false; // success 1033} 1034