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