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