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