Finally, the entire instruction asmprinter is now generated from tblgen, woo!
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to Intel assembly -------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to Intel-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
13 // on X86.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
33 #include "Support/CommandLine.h"
34 using namespace llvm;
35
36 namespace {
37   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
38
39   // FIXME: This should be automatically picked up by autoconf from the C
40   // frontend
41   cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
42          cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
43
44   struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
45     GasBugWorkaroundEmitter(std::ostream& o) 
46       : O(o), OldFlags(O.flags()), firstByte(true) {
47       O << std::hex;
48     }
49
50     ~GasBugWorkaroundEmitter() {
51       O.flags(OldFlags);
52     }
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 X86AsmPrinter : 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     X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
89
90     /// Cache of mangled name for current function. This is
91     /// recalculated at the beginning of each call to
92     /// runOnMachineFunction().
93     ///
94     std::string CurrentFnName;
95
96     virtual const char *getPassName() const {
97       return "X86 Assembly Printer";
98     }
99
100     /// printInstruction - This method is automatically generated by tablegen
101     /// from the instruction set description.  This method returns true if the
102     /// machine instruction was sufficiently described to print it, otherwise it
103     /// returns false.
104     bool printInstruction(const MachineInstr *MI);
105
106     // This method is used by the tablegen'erated instruction printer.
107     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
108       const MachineOperand &MO = MI->getOperand(OpNo);
109       if (MO.getType() == MachineOperand::MO_MachineRegister) {
110         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
111         // Bug Workaround: See note in Printer::doInitialization about %.
112         O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
113       } else {
114         printOp(MO);
115       }
116     }
117
118     void printCallOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
119       printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
120     }
121
122     void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
123                             MVT::ValueType VT) {
124       switch (VT) {
125       default: assert(0 && "Unknown arg size!");
126       case MVT::i8:   O << "BYTE PTR "; break;
127       case MVT::i16:  O << "WORD PTR "; break;
128       case MVT::i32:
129       case MVT::f32:  O << "DWORD PTR "; break;
130       case MVT::i64:
131       case MVT::f64:  O << "QWORD PTR "; break;
132       case MVT::f80:  O << "XWORD PTR "; break;
133       }
134       printMemReference(MI, OpNo);
135     }
136
137     bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
138     void printMachineInstruction(const MachineInstr *MI);
139     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
140     void printMemReference(const MachineInstr *MI, unsigned Op);
141     void printConstantPool(MachineConstantPool *MCP);
142     bool runOnMachineFunction(MachineFunction &F);    
143     bool doInitialization(Module &M);
144     bool doFinalization(Module &M);
145     void emitGlobalConstant(const Constant* CV);
146     void emitConstantValueOnly(const Constant *CV);
147   };
148 } // end of anonymous namespace
149
150 /// createX86CodePrinterPass - Returns a pass that prints the X86
151 /// assembly code for a MachineFunction to the given output stream,
152 /// using the given target machine description.  This should work
153 /// regardless of whether the function is in SSA form.
154 ///
155 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
156   return new X86AsmPrinter(o, tm);
157 }
158
159
160 // Include the auto-generated portion of the assembly writer.
161 #include "X86GenAsmWriter.inc"
162
163
164 /// toOctal - Convert the low order bits of X into an octal digit.
165 ///
166 static inline char toOctal(int X) {
167   return (X&7)+'0';
168 }
169
170 /// getAsCString - Return the specified array as a C compatible
171 /// string, only if the predicate isStringCompatible is true.
172 ///
173 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
174   assert(CVA->isString() && "Array is not string compatible!");
175
176   O << "\"";
177   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
178     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
179
180     if (C == '"') {
181       O << "\\\"";
182     } else if (C == '\\') {
183       O << "\\\\";
184     } else if (isprint(C)) {
185       O << C;
186     } else {
187       switch(C) {
188       case '\b': O << "\\b"; break;
189       case '\f': O << "\\f"; break;
190       case '\n': O << "\\n"; break;
191       case '\r': O << "\\r"; break;
192       case '\t': O << "\\t"; break;
193       default:
194         O << '\\';
195         O << toOctal(C >> 6);
196         O << toOctal(C >> 3);
197         O << toOctal(C >> 0);
198         break;
199       }
200     }
201   }
202   O << "\"";
203 }
204
205 // Print out the specified constant, without a storage class.  Only the
206 // constants valid in constant expressions can occur here.
207 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
208   if (CV->isNullValue())
209     O << "0";
210   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
211     assert(CB == ConstantBool::True);
212     O << "1";
213   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
214     if (((CI->getValue() << 32) >> 32) == CI->getValue())
215       O << CI->getValue();
216     else
217       O << (unsigned long long)CI->getValue();
218   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
219     O << CI->getValue();
220   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
221     // This is a constant address for a global variable or function.  Use the
222     // name of the variable or function as the address value.
223     O << Mang->getValueName(GV);
224   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
225     const TargetData &TD = TM.getTargetData();
226     switch(CE->getOpcode()) {
227     case Instruction::GetElementPtr: {
228       // generate a symbolic expression for the byte address
229       const Constant *ptrVal = CE->getOperand(0);
230       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
231       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
232         O << "(";
233         emitConstantValueOnly(ptrVal);
234         O << ") + " << Offset;
235       } else {
236         emitConstantValueOnly(ptrVal);
237       }
238       break;
239     }
240     case Instruction::Cast: {
241       // Support only non-converting or widening casts for now, that is, ones
242       // that do not involve a change in value.  This assertion is really gross,
243       // and may not even be a complete check.
244       Constant *Op = CE->getOperand(0);
245       const Type *OpTy = Op->getType(), *Ty = CE->getType();
246
247       // Remember, kids, pointers on x86 can be losslessly converted back and
248       // forth into 32-bit or wider integers, regardless of signedness. :-P
249       assert(((isa<PointerType>(OpTy)
250                && (Ty == Type::LongTy || Ty == Type::ULongTy
251                    || Ty == Type::IntTy || Ty == Type::UIntTy))
252               || (isa<PointerType>(Ty)
253                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
254                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
255               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
256                    && OpTy->isLosslesslyConvertibleTo(Ty))))
257              && "FIXME: Don't yet support this kind of constant cast expr");
258       O << "(";
259       emitConstantValueOnly(Op);
260       O << ")";
261       break;
262     }
263     case Instruction::Add:
264       O << "(";
265       emitConstantValueOnly(CE->getOperand(0));
266       O << ") + (";
267       emitConstantValueOnly(CE->getOperand(1));
268       O << ")";
269       break;
270     default:
271       assert(0 && "Unsupported operator!");
272     }
273   } else {
274     assert(0 && "Unknown constant value!");
275   }
276 }
277
278 // Print a constant value or values, with the appropriate storage class as a
279 // prefix.
280 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {  
281   const TargetData &TD = TM.getTargetData();
282
283   if (CV->isNullValue()) {
284     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
285     return;
286   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
287     if (CVA->isString()) {
288       O << "\t.ascii\t";
289       printAsCString(O, CVA);
290       O << "\n";
291     } else { // Not a string.  Print the values in successive locations
292       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
293         emitGlobalConstant(CVA->getOperand(i));
294     }
295     return;
296   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
297     // Print the fields in successive locations. Pad to align if needed!
298     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
299     unsigned sizeSoFar = 0;
300     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
301       const Constant* field = CVS->getOperand(i);
302
303       // Check if padding is needed and insert one or more 0s.
304       unsigned fieldSize = TD.getTypeSize(field->getType());
305       unsigned padSize = ((i == e-1? cvsLayout->StructSize
306                            : cvsLayout->MemberOffsets[i+1])
307                           - cvsLayout->MemberOffsets[i]) - fieldSize;
308       sizeSoFar += fieldSize + padSize;
309
310       // Now print the actual field value
311       emitGlobalConstant(field);
312
313       // Insert the field padding unless it's zero bytes...
314       if (padSize)
315         O << "\t.zero\t " << padSize << "\n";      
316     }
317     assert(sizeSoFar == cvsLayout->StructSize &&
318            "Layout of constant struct may be incorrect!");
319     return;
320   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
321     // FP Constants are printed as integer constants to avoid losing
322     // precision...
323     double Val = CFP->getValue();
324     switch (CFP->getType()->getTypeID()) {
325     default: assert(0 && "Unknown floating point type!");
326     case Type::FloatTyID: {
327       union FU {                            // Abide by C TBAA rules
328         float FVal;
329         unsigned UVal;
330       } U;
331       U.FVal = Val;
332       O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
333       return;
334     }
335     case Type::DoubleTyID: {
336       union DU {                            // Abide by C TBAA rules
337         double FVal;
338         uint64_t UVal;
339       } U;
340       U.FVal = Val;
341       O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
342       return;
343     }
344     }
345   }
346
347   const Type *type = CV->getType();
348   O << "\t";
349   switch (type->getTypeID()) {
350   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
351     O << ".byte";
352     break;
353   case Type::UShortTyID: case Type::ShortTyID:
354     O << ".word";
355     break;
356   case Type::FloatTyID: case Type::PointerTyID:
357   case Type::UIntTyID: case Type::IntTyID:
358     O << ".long";
359     break;
360   case Type::DoubleTyID:
361   case Type::ULongTyID: case Type::LongTyID:
362     O << ".quad";
363     break;
364   default:
365     assert (0 && "Can't handle printing this type of thing");
366     break;
367   }
368   O << "\t";
369   emitConstantValueOnly(CV);
370   O << "\n";
371 }
372
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
377 ///
378 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
379   const std::vector<Constant*> &CP = MCP->getConstants();
380   const TargetData &TD = TM.getTargetData();
381  
382   if (CP.empty()) return;
383
384   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385     O << "\t.section .rodata\n";
386     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
387       << "\n";
388     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
389       << *CP[i] << "\n";
390     emitGlobalConstant(CP[i]);
391   }
392 }
393
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
396 ///
397 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
398   O << "\n\n";
399   // What's my mangled name?
400   CurrentFnName = Mang->getValueName(MF.getFunction());
401
402   // Print out constants referenced by the function
403   printConstantPool(MF.getConstantPool());
404
405   // Print out labels for the function.
406   O << "\t.text\n";
407   O << "\t.align 16\n";
408   O << "\t.globl\t" << CurrentFnName << "\n";
409   if (!EmitCygwin)
410     O << "\t.type\t" << CurrentFnName << ", @function\n";
411   O << CurrentFnName << ":\n";
412
413   // Print out code for the function.
414   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
415        I != E; ++I) {
416     // Print a label for the basic block.
417     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
418       << I->getBasicBlock()->getName() << "\n";
419     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
420          II != E; ++II) {
421       // Print the assembly for the instruction.
422       O << "\t";
423       printMachineInstruction(II);
424     }
425   }
426
427   // We didn't modify anything.
428   return false;
429 }
430
431 static bool isScale(const MachineOperand &MO) {
432   return MO.isImmediate() &&
433     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
434      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
435 }
436
437 static bool isMem(const MachineInstr *MI, unsigned Op) {
438   if (MI->getOperand(Op).isFrameIndex()) return true;
439   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
440   return Op+4 <= MI->getNumOperands() &&
441     MI->getOperand(Op  ).isRegister() && isScale(MI->getOperand(Op+1)) &&
442     MI->getOperand(Op+2).isRegister() && MI->getOperand(Op+3).isImmediate();
443 }
444
445
446
447 void X86AsmPrinter::printOp(const MachineOperand &MO,
448                             bool elideOffsetKeyword /* = false */) {
449   const MRegisterInfo &RI = *TM.getRegisterInfo();
450   switch (MO.getType()) {
451   case MachineOperand::MO_VirtualRegister:
452     if (Value *V = MO.getVRegValueOrNull()) {
453       O << "<" << V->getName() << ">";
454       return;
455     }
456     // FALLTHROUGH
457   case MachineOperand::MO_MachineRegister:
458     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
459       // Bug Workaround: See note in Printer::doInitialization about %.
460       O << "%" << RI.get(MO.getReg()).Name;
461     else
462       O << "%reg" << MO.getReg();
463     return;
464
465   case MachineOperand::MO_SignExtendedImmed:
466   case MachineOperand::MO_UnextendedImmed:
467     O << (int)MO.getImmedValue();
468     return;
469   case MachineOperand::MO_MachineBasicBlock: {
470     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
471     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
472       << "_" << MBBOp->getNumber () << "\t# "
473       << MBBOp->getBasicBlock ()->getName ();
474     return;
475   }
476   case MachineOperand::MO_PCRelativeDisp:
477     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
478     abort ();
479     return;
480   case MachineOperand::MO_GlobalAddress:
481     if (!elideOffsetKeyword)
482       O << "OFFSET ";
483     O << Mang->getValueName(MO.getGlobal());
484     return;
485   case MachineOperand::MO_ExternalSymbol:
486     O << MO.getSymbolName();
487     return;
488   default:
489     O << "<unknown operand type>"; return;    
490   }
491 }
492
493 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
494   assert(isMem(MI, Op) && "Invalid memory reference!");
495
496   if (MI->getOperand(Op).isFrameIndex()) {
497     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
498     if (MI->getOperand(Op+3).getImmedValue())
499       O << " + " << MI->getOperand(Op+3).getImmedValue();
500     O << "]";
501     return;
502   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
503     O << "[.CPI" << CurrentFnName << "_"
504       << MI->getOperand(Op).getConstantPoolIndex();
505     if (MI->getOperand(Op+3).getImmedValue())
506       O << " + " << MI->getOperand(Op+3).getImmedValue();
507     O << "]";
508     return;
509   }
510
511   const MachineOperand &BaseReg  = MI->getOperand(Op);
512   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
513   const MachineOperand &IndexReg = MI->getOperand(Op+2);
514   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
515
516   O << "[";
517   bool NeedPlus = false;
518   if (BaseReg.getReg()) {
519     printOp(BaseReg);
520     NeedPlus = true;
521   }
522
523   if (IndexReg.getReg()) {
524     if (NeedPlus) O << " + ";
525     if (ScaleVal != 1)
526       O << ScaleVal << "*";
527     printOp(IndexReg);
528     NeedPlus = true;
529   }
530
531   if (DispVal) {
532     if (NeedPlus)
533       if (DispVal > 0)
534         O << " + ";
535       else {
536         O << " - ";
537         DispVal = -DispVal;
538       }
539     O << DispVal;
540   }
541   O << "]";
542 }
543
544 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
545 /// described by DESC, if its PrintImplUsesAfter flag is set.
546 ///
547 /// Inputs:
548 ///   Comma - List of registers will need a leading comma.
549 ///   Desc  - Description of the Instruction.
550 ///
551 /// Return value:
552 ///   true  - Emitted one or more registers.
553 ///   false - Emitted no registers.
554 ///
555 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
556                                        const bool Comma = true) {
557   const MRegisterInfo &RI = *TM.getRegisterInfo();
558   if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
559     bool emitted = false;
560     const unsigned *p = Desc.ImplicitUses;
561     if (*p) {
562       O << (Comma ? ", %" : "%") << RI.get (*p).Name;
563       emitted = true;
564       ++p;
565     }
566     while (*p) {
567       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
568       O << ", %" << RI.get(*p).Name;
569       ++p;
570     }
571     return emitted;
572   }
573   return false;
574 }
575
576 /// printMachineInstruction -- Print out a single X86 LLVM instruction
577 /// MI in Intel syntax to the current output stream.
578 ///
579 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
580   ++EmittedInsts;
581
582   // gas bugs:
583   //
584   // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"  is misassembled
585   // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR
586   // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
587   //
588   // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas
589   // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR
590   // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
591   //
592   // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode,
593   // saying "64 bit operations are only supported in 64 bit modes." libopcodes
594   // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround:
595   // Output the raw opcode bytes instead of the instruction.
596   //
597   // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode,
598   // saying "64 bit operations are only supported in 64 bit modes." libopcodes
599   // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround:
600   // Output the raw opcode bytes instead of the instruction.
601   switch (MI->getOpcode()) {
602   case X86::FSTP80m:
603   case X86::FLD80m:
604   case X86::FILD64m:
605   case X86::FISTP64m:
606     GasBugWorkaroundEmitter gwe(O);
607     X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
608     O << "\t# ";
609   }
610
611   // Call the autogenerated instruction printer routines.
612   bool Handled = printInstruction(MI);
613   if (!Handled) {
614     MI->dump();
615     assert(0 && "Do not know how to print this instruction!");
616     abort();
617   }
618 }
619
620 bool X86AsmPrinter::doInitialization(Module &M) {
621   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
622   //
623   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
624   // instruction as a reference to the register named sp, and if you try to
625   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
626   // before being looked up in the symbol table. This creates spurious
627   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
628   // mode, and decorate all register names with percent signs.
629   O << "\t.intel_syntax\n";
630   Mang = new Mangler(M, EmitCygwin);
631   return false; // success
632 }
633
634 // SwitchSection - Switch to the specified section of the executable if we are
635 // not already in it!
636 //
637 static void SwitchSection(std::ostream &OS, std::string &CurSection,
638                           const char *NewSection) {
639   if (CurSection != NewSection) {
640     CurSection = NewSection;
641     if (!CurSection.empty())
642       OS << "\t" << NewSection << "\n";
643   }
644 }
645
646 bool X86AsmPrinter::doFinalization(Module &M) {
647   const TargetData &TD = TM.getTargetData();
648   std::string CurSection;
649
650   // Print out module-level global variables here.
651   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
652     if (I->hasInitializer()) {   // External global require no code
653       O << "\n\n";
654       std::string name = Mang->getValueName(I);
655       Constant *C = I->getInitializer();
656       unsigned Size = TD.getTypeSize(C->getType());
657       unsigned Align = TD.getTypeAlignment(C->getType());
658
659       if (C->isNullValue() && 
660           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
661            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
662         SwitchSection(O, CurSection, ".data");
663         if (I->hasInternalLinkage())
664           O << "\t.local " << name << "\n";
665         
666         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
667           << "," << (unsigned)TD.getTypeAlignment(C->getType());
668         O << "\t\t# ";
669         WriteAsOperand(O, I, true, true, &M);
670         O << "\n";
671       } else {
672         switch (I->getLinkage()) {
673         case GlobalValue::LinkOnceLinkage:
674         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
675           // Nonnull linkonce -> weak
676           O << "\t.weak " << name << "\n";
677           SwitchSection(O, CurSection, "");
678           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
679           break;
680         
681         case GlobalValue::AppendingLinkage:
682           // FIXME: appending linkage variables should go into a section of
683           // their name or something.  For now, just emit them as external.
684         case GlobalValue::ExternalLinkage:
685           // If external or appending, declare as a global symbol
686           O << "\t.globl " << name << "\n";
687           // FALL THROUGH
688         case GlobalValue::InternalLinkage:
689           if (C->isNullValue())
690             SwitchSection(O, CurSection, ".bss");
691           else
692             SwitchSection(O, CurSection, ".data");
693           break;
694         }
695
696         O << "\t.align " << Align << "\n";
697         O << "\t.type " << name << ",@object\n";
698         O << "\t.size " << name << "," << Size << "\n";
699         O << name << ":\t\t\t\t# ";
700         WriteAsOperand(O, I, true, true, &M);
701         O << " = ";
702         WriteAsOperand(O, C, false, false, &M);
703         O << "\n";
704         emitGlobalConstant(C);
705       }
706     }
707
708   delete Mang;
709   return false; // success
710 }