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