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