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