3e9fbb09c91d61657ff1bdc80a502de6e3248005
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 X86 machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86AsmPrinter.h"
16 #include "AsmPrinter/X86ATTInstPrinter.h"
17 #include "AsmPrinter/X86IntelInstPrinter.h"
18 #include "X86MCInstLower.h"
19 #include "X86.h"
20 #include "X86COFFMachineModuleInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
37 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
38 #include "llvm/Support/COFF.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/Mangler.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/ADT/SmallString.h"
44 using namespace llvm;
45
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
49
50 void X86AsmPrinter::PrintPICBaseSymbol(raw_ostream &O) const {
51   const TargetLowering *TLI = TM.getTargetLowering();
52   O << *static_cast<const X86TargetLowering*>(TLI)->getPICBaseSymbol(MF,
53                                                                     OutContext);
54 }
55
56 /// runOnMachineFunction - Emit the function body.
57 ///
58 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
59   SetupMachineFunction(MF);
60
61   if (Subtarget->isTargetCOFF()) {
62     bool Intrn = MF.getFunction()->hasInternalLinkage();
63     OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
64     OutStreamer.EmitCOFFSymbolStorageClass(Intrn ? COFF::IMAGE_SYM_CLASS_STATIC 
65                                               : COFF::IMAGE_SYM_CLASS_EXTERNAL);
66     OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
67                                                << COFF::SCT_COMPLEX_TYPE_SHIFT);
68     OutStreamer.EndCOFFSymbolDef();
69   }
70
71   // Have common code print out the function header with linkage info etc.
72   EmitFunctionHeader();
73
74   // Emit the rest of the function body.
75   EmitFunctionBody();
76
77   // We didn't modify anything.
78   return false;
79 }
80
81 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
82 /// jump tables, constant pools, global address and external symbols, all of
83 /// which print to a label with various suffixes for relocation types etc.
84 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO,
85                                        raw_ostream &O) {
86   switch (MO.getType()) {
87   default: llvm_unreachable("unknown symbol type!");
88   case MachineOperand::MO_JumpTableIndex:
89     O << *GetJTISymbol(MO.getIndex());
90     break;
91   case MachineOperand::MO_ConstantPoolIndex:
92     O << *GetCPISymbol(MO.getIndex());
93     printOffset(MO.getOffset(), O);
94     break;
95   case MachineOperand::MO_GlobalAddress: {
96     const GlobalValue *GV = MO.getGlobal();
97     
98     MCSymbol *GVSym;
99     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
100       GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
101     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
102              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
103              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
104       GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
105     else
106       GVSym = Mang->getSymbol(GV);
107
108     // Handle dllimport linkage.
109     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
110       GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
111     
112     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
113         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
114       MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
115       MachineModuleInfoImpl::StubValueTy &StubSym = 
116         MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
117       if (StubSym.getPointer() == 0)
118         StubSym = MachineModuleInfoImpl::
119           StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
120     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
121       MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
122       MachineModuleInfoImpl::StubValueTy &StubSym =
123         MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
124       if (StubSym.getPointer() == 0)
125         StubSym = MachineModuleInfoImpl::
126           StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
127     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
128       MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
129       MachineModuleInfoImpl::StubValueTy &StubSym =
130         MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
131       if (StubSym.getPointer() == 0)
132         StubSym = MachineModuleInfoImpl::
133           StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
134     }
135     
136     // If the name begins with a dollar-sign, enclose it in parens.  We do this
137     // to avoid having it look like an integer immediate to the assembler.
138     if (GVSym->getName()[0] != '$')
139       O << *GVSym;
140     else
141       O << '(' << *GVSym << ')';
142     printOffset(MO.getOffset(), O);
143     break;
144   }
145   case MachineOperand::MO_ExternalSymbol: {
146     const MCSymbol *SymToPrint;
147     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
148       SmallString<128> TempNameStr;
149       TempNameStr += StringRef(MO.getSymbolName());
150       TempNameStr += StringRef("$stub");
151       
152       MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
153       MachineModuleInfoImpl::StubValueTy &StubSym =
154         MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
155       if (StubSym.getPointer() == 0) {
156         TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
157         StubSym = MachineModuleInfoImpl::
158           StubValueTy(OutContext.GetOrCreateSymbol(TempNameStr.str()),
159                       true);
160       }
161       SymToPrint = StubSym.getPointer();
162     } else {
163       SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
164     }
165     
166     // If the name begins with a dollar-sign, enclose it in parens.  We do this
167     // to avoid having it look like an integer immediate to the assembler.
168     if (SymToPrint->getName()[0] != '$') 
169       O << *SymToPrint;
170     else
171       O << '(' << *SymToPrint << '(';
172     break;
173   }
174   }
175   
176   switch (MO.getTargetFlags()) {
177   default:
178     llvm_unreachable("Unknown target flag on GV operand");
179   case X86II::MO_NO_FLAG:    // No flag.
180     break;
181   case X86II::MO_DARWIN_NONLAZY:
182   case X86II::MO_DLLIMPORT:
183   case X86II::MO_DARWIN_STUB:
184     // These affect the name of the symbol, not any suffix.
185     break;
186   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
187     O << " + [.-";
188     PrintPICBaseSymbol(O);
189     O << ']';
190     break;      
191   case X86II::MO_PIC_BASE_OFFSET:
192   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
193   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
194     O << '-';
195     PrintPICBaseSymbol(O);
196     break;
197   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
198   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
199   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
200   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
201   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
202   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
203   case X86II::MO_GOT:       O << "@GOT";       break;
204   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
205   case X86II::MO_PLT:       O << "@PLT";       break;
206   case X86II::MO_TLVP:      O << "@TLVP";      break;
207   case X86II::MO_TLVP_PIC_BASE:
208     O << "@TLVP" << '-';
209     PrintPICBaseSymbol(O);
210     break;
211   }
212 }
213
214 /// print_pcrel_imm - This is used to print an immediate value that ends up
215 /// being encoded as a pc-relative value.  These print slightly differently, for
216 /// example, a $ is not emitted.
217 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo,
218                                     raw_ostream &O) {
219   const MachineOperand &MO = MI->getOperand(OpNo);
220   switch (MO.getType()) {
221   default: llvm_unreachable("Unknown pcrel immediate operand");
222   case MachineOperand::MO_Register:
223     // pc-relativeness was handled when computing the value in the reg.
224     printOperand(MI, OpNo, O);
225     return;
226   case MachineOperand::MO_Immediate:
227     O << MO.getImm();
228     return;
229   case MachineOperand::MO_MachineBasicBlock:
230     O << *MO.getMBB()->getSymbol();
231     return;
232   case MachineOperand::MO_GlobalAddress:
233   case MachineOperand::MO_ExternalSymbol:
234     printSymbolOperand(MO, O);
235     return;
236   }
237 }
238
239
240 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
241                                  raw_ostream &O, const char *Modifier) {
242   const MachineOperand &MO = MI->getOperand(OpNo);
243   switch (MO.getType()) {
244   default: llvm_unreachable("unknown operand type!");
245   case MachineOperand::MO_Register: {
246     O << '%';
247     unsigned Reg = MO.getReg();
248     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
249       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
250         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
251                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
252       Reg = getX86SubSuperRegister(Reg, VT);
253     }
254     O << X86ATTInstPrinter::getRegisterName(Reg);
255     return;
256   }
257
258   case MachineOperand::MO_Immediate:
259     O << '$' << MO.getImm();
260     return;
261
262   case MachineOperand::MO_JumpTableIndex:
263   case MachineOperand::MO_ConstantPoolIndex:
264   case MachineOperand::MO_GlobalAddress: 
265   case MachineOperand::MO_ExternalSymbol: {
266     O << '$';
267     printSymbolOperand(MO, O);
268     break;
269   }
270   }
271 }
272
273 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op,
274                                raw_ostream &O) {
275   unsigned char value = MI->getOperand(Op).getImm();
276   assert(value <= 7 && "Invalid ssecc argument!");
277   switch (value) {
278   case 0: O << "eq"; break;
279   case 1: O << "lt"; break;
280   case 2: O << "le"; break;
281   case 3: O << "unord"; break;
282   case 4: O << "neq"; break;
283   case 5: O << "nlt"; break;
284   case 6: O << "nle"; break;
285   case 7: O << "ord"; break;
286   }
287 }
288
289 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
290                                          raw_ostream &O, const char *Modifier) {
291   const MachineOperand &BaseReg  = MI->getOperand(Op);
292   const MachineOperand &IndexReg = MI->getOperand(Op+2);
293   const MachineOperand &DispSpec = MI->getOperand(Op+3);
294
295   // If we really don't want to print out (rip), don't.
296   bool HasBaseReg = BaseReg.getReg() != 0;
297   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
298       BaseReg.getReg() == X86::RIP)
299     HasBaseReg = false;
300   
301   // HasParenPart - True if we will print out the () part of the mem ref.
302   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
303   
304   if (DispSpec.isImm()) {
305     int DispVal = DispSpec.getImm();
306     if (DispVal || !HasParenPart)
307       O << DispVal;
308   } else {
309     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
310            DispSpec.isJTI() || DispSpec.isSymbol());
311     printSymbolOperand(MI->getOperand(Op+3), O);
312   }
313
314   if (HasParenPart) {
315     assert(IndexReg.getReg() != X86::ESP &&
316            "X86 doesn't allow scaling by ESP");
317
318     O << '(';
319     if (HasBaseReg)
320       printOperand(MI, Op, O, Modifier);
321
322     if (IndexReg.getReg()) {
323       O << ',';
324       printOperand(MI, Op+2, O, Modifier);
325       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
326       if (ScaleVal != 1)
327         O << ',' << ScaleVal;
328     }
329     O << ')';
330   }
331 }
332
333 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
334                                       raw_ostream &O, const char *Modifier) {
335   assert(isMem(MI, Op) && "Invalid memory reference!");
336   const MachineOperand &Segment = MI->getOperand(Op+4);
337   if (Segment.getReg()) {
338     printOperand(MI, Op+4, O, Modifier);
339     O << ':';
340   }
341   printLeaMemReference(MI, Op, O, Modifier);
342 }
343
344 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op,
345                                   raw_ostream &O) {
346   PrintPICBaseSymbol(O);
347   O << '\n';
348   PrintPICBaseSymbol(O);
349   O << ':';
350 }
351
352 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode,
353                                       raw_ostream &O) {
354   unsigned Reg = MO.getReg();
355   switch (Mode) {
356   default: return true;  // Unknown mode.
357   case 'b': // Print QImode register
358     Reg = getX86SubSuperRegister(Reg, MVT::i8);
359     break;
360   case 'h': // Print QImode high register
361     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
362     break;
363   case 'w': // Print HImode register
364     Reg = getX86SubSuperRegister(Reg, MVT::i16);
365     break;
366   case 'k': // Print SImode register
367     Reg = getX86SubSuperRegister(Reg, MVT::i32);
368     break;
369   case 'q': // Print DImode register
370     Reg = getX86SubSuperRegister(Reg, MVT::i64);
371     break;
372   }
373
374   O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
375   return false;
376 }
377
378 /// PrintAsmOperand - Print out an operand for an inline asm expression.
379 ///
380 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
381                                     unsigned AsmVariant,
382                                     const char *ExtraCode, raw_ostream &O) {
383   // Does this asm operand have a single letter operand modifier?
384   if (ExtraCode && ExtraCode[0]) {
385     if (ExtraCode[1] != 0) return true; // Unknown modifier.
386
387     const MachineOperand &MO = MI->getOperand(OpNo);
388     
389     switch (ExtraCode[0]) {
390     default: return true;  // Unknown modifier.
391     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
392       if (MO.isImm()) {
393         O << MO.getImm();
394         return false;
395       } 
396       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
397         printSymbolOperand(MO, O);
398         if (Subtarget->isPICStyleRIPRel())
399           O << "(%rip)";
400         return false;
401       }
402       if (MO.isReg()) {
403         O << '(';
404         printOperand(MI, OpNo, O);
405         O << ')';
406         return false;
407       }
408       return true;
409
410     case 'c': // Don't print "$" before a global var name or constant.
411       if (MO.isImm())
412         O << MO.getImm();
413       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
414         printSymbolOperand(MO, O);
415       else
416         printOperand(MI, OpNo, O);
417       return false;
418
419     case 'A': // Print '*' before a register (it must be a register)
420       if (MO.isReg()) {
421         O << '*';
422         printOperand(MI, OpNo, O);
423         return false;
424       }
425       return true;
426
427     case 'b': // Print QImode register
428     case 'h': // Print QImode high register
429     case 'w': // Print HImode register
430     case 'k': // Print SImode register
431     case 'q': // Print DImode register
432       if (MO.isReg())
433         return printAsmMRegister(MO, ExtraCode[0], O);
434       printOperand(MI, OpNo, O);
435       return false;
436
437     case 'P': // This is the operand of a call, treat specially.
438       print_pcrel_imm(MI, OpNo, O);
439       return false;
440
441     case 'n':  // Negate the immediate or print a '-' before the operand.
442       // Note: this is a temporary solution. It should be handled target
443       // independently as part of the 'MC' work.
444       if (MO.isImm()) {
445         O << -MO.getImm();
446         return false;
447       }
448       O << '-';
449     }
450   }
451
452   printOperand(MI, OpNo, O);
453   return false;
454 }
455
456 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
457                                           unsigned OpNo, unsigned AsmVariant,
458                                           const char *ExtraCode,
459                                           raw_ostream &O) {
460   if (ExtraCode && ExtraCode[0]) {
461     if (ExtraCode[1] != 0) return true; // Unknown modifier.
462
463     switch (ExtraCode[0]) {
464     default: return true;  // Unknown modifier.
465     case 'b': // Print QImode register
466     case 'h': // Print QImode high register
467     case 'w': // Print HImode register
468     case 'k': // Print SImode register
469     case 'q': // Print SImode register
470       // These only apply to registers, ignore on mem.
471       break;
472     case 'P': // Don't print @PLT, but do print as memory.
473       printMemReference(MI, OpNo, O, "no-rip");
474       return false;
475     }
476   }
477   printMemReference(MI, OpNo, O);
478   return false;
479 }
480
481 void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
482   if (Subtarget->isTargetDarwin())
483     OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
484 }
485
486
487 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
488   if (Subtarget->isTargetDarwin()) {
489     // All darwin targets use mach-o.
490     MachineModuleInfoMachO &MMIMacho =
491       MMI->getObjFileInfo<MachineModuleInfoMachO>();
492     
493     // Output stubs for dynamically-linked functions.
494     MachineModuleInfoMachO::SymbolListTy Stubs;
495
496     Stubs = MMIMacho.GetFnStubList();
497     if (!Stubs.empty()) {
498       const MCSection *TheSection = 
499         OutContext.getMachOSection("__IMPORT", "__jump_table",
500                                    MCSectionMachO::S_SYMBOL_STUBS |
501                                    MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
502                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
503                                    5, SectionKind::getMetadata());
504       OutStreamer.SwitchSection(TheSection);
505
506       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
507         // L_foo$stub:
508         OutStreamer.EmitLabel(Stubs[i].first);
509         //   .indirect_symbol _foo
510         OutStreamer.EmitSymbolAttribute(Stubs[i].second.getPointer(),
511                                         MCSA_IndirectSymbol);
512         // hlt; hlt; hlt; hlt; hlt     hlt = 0xf4 = -12.
513         const char HltInsts[] = { -12, -12, -12, -12, -12 };
514         OutStreamer.EmitBytes(StringRef(HltInsts, 5), 0/*addrspace*/);
515       }
516       
517       Stubs.clear();
518       OutStreamer.AddBlankLine();
519     }
520
521     // Output stubs for external and common global variables.
522     Stubs = MMIMacho.GetGVStubList();
523     if (!Stubs.empty()) {
524       const MCSection *TheSection = 
525         OutContext.getMachOSection("__IMPORT", "__pointers",
526                                    MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
527                                    SectionKind::getMetadata());
528       OutStreamer.SwitchSection(TheSection);
529
530       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
531         // L_foo$non_lazy_ptr:
532         OutStreamer.EmitLabel(Stubs[i].first);
533         // .indirect_symbol _foo
534         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
535         OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),
536                                         MCSA_IndirectSymbol);
537         // .long 0
538         if (MCSym.getInt())
539           // External to current translation unit.
540           OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
541         else
542           // Internal to current translation unit.
543           //
544           // When we place the LSDA into the TEXT section, the type info
545           // pointers need to be indirect and pc-rel. We accomplish this by
546           // using NLPs.  However, sometimes the types are local to the file. So
547           // we need to fill in the value for the NLP in those cases.
548           OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
549                                                         OutContext),
550                                 4/*size*/, 0/*addrspace*/);
551       }
552       Stubs.clear();
553       OutStreamer.AddBlankLine();
554     }
555
556     Stubs = MMIMacho.GetHiddenGVStubList();
557     if (!Stubs.empty()) {
558       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
559       EmitAlignment(2);
560
561       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
562         // L_foo$non_lazy_ptr:
563         OutStreamer.EmitLabel(Stubs[i].first);
564         // .long _foo
565         OutStreamer.EmitValue(MCSymbolRefExpr::
566                               Create(Stubs[i].second.getPointer(),
567                                      OutContext),
568                               4/*size*/, 0/*addrspace*/);
569       }
570       Stubs.clear();
571       OutStreamer.AddBlankLine();
572     }
573
574     // Funny Darwin hack: This flag tells the linker that no global symbols
575     // contain code that falls through to other global symbols (e.g. the obvious
576     // implementation of multiple entry points).  If this doesn't occur, the
577     // linker can safely perform dead code stripping.  Since LLVM never
578     // generates code that does this, it is always safe to set.
579     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
580   }
581
582   if (Subtarget->isTargetCOFF()) {
583     X86COFFMachineModuleInfo &COFFMMI =
584       MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
585
586     // Emit type information for external functions
587     typedef X86COFFMachineModuleInfo::externals_iterator externals_iterator;
588     for (externals_iterator I = COFFMMI.externals_begin(),
589                             E = COFFMMI.externals_end();
590                             I != E; ++I) {
591       OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
592       OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
593       OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
594                                                << COFF::SCT_COMPLEX_TYPE_SHIFT);
595       OutStreamer.EndCOFFSymbolDef();
596     }
597
598     // Necessary for dllexport support
599     std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
600
601     const TargetLoweringObjectFileCOFF &TLOFCOFF =
602       static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
603
604     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
605       if (I->hasDLLExportLinkage())
606         DLLExportedFns.push_back(Mang->getSymbol(I));
607
608     for (Module::const_global_iterator I = M.global_begin(),
609            E = M.global_end(); I != E; ++I)
610       if (I->hasDLLExportLinkage())
611         DLLExportedGlobals.push_back(Mang->getSymbol(I));
612
613     // Output linker support code for dllexported globals on windows.
614     if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
615       OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
616       SmallString<128> name;
617       for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
618         if (Subtarget->isTargetWindows())
619           name = " /EXPORT:";
620         else
621           name = " -export:";
622         name += DLLExportedGlobals[i]->getName();
623         if (Subtarget->isTargetWindows())
624           name += ",DATA";
625         else
626         name += ",data";
627         OutStreamer.EmitBytes(name, 0);
628       }
629
630       for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
631         if (Subtarget->isTargetWindows())
632           name = " /EXPORT:";
633         else
634           name = " -export:";
635         name += DLLExportedFns[i]->getName();
636         OutStreamer.EmitBytes(name, 0);
637       }
638     }
639   }
640
641   if (Subtarget->isTargetELF()) {
642     const TargetLoweringObjectFileELF &TLOFELF =
643       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
644
645     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
646
647     // Output stubs for external and common global variables.
648     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
649     if (!Stubs.empty()) {
650       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
651       const TargetData *TD = TM.getTargetData();
652
653       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
654         OutStreamer.EmitLabel(Stubs[i].first);
655         OutStreamer.EmitSymbolValue(Stubs[i].second.getPointer(),
656                                     TD->getPointerSize(), 0);
657       }
658       Stubs.clear();
659     }
660   }
661 }
662
663 MachineLocation 
664 X86AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
665   MachineLocation Location;
666   assert (MI->getNumOperands() == 7 && "Invalid no. of machine operands!");
667   // Frame address.  Currently handles register +- offset only.
668   
669   if (MI->getOperand(0).isReg() && MI->getOperand(3).isImm())
670     Location.set(MI->getOperand(0).getReg(), MI->getOperand(3).getImm());
671   return Location;
672 }
673
674 void X86AsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
675                                            raw_ostream &O) {
676   // Only the target-dependent form of DBG_VALUE should get here.
677   // Referencing the offset and metadata as NOps-2 and NOps-1 is
678   // probably portable to other targets; frame pointer location is not.
679   unsigned NOps = MI->getNumOperands();
680   assert(NOps==7);
681   O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
682   // cast away const; DIetc do not take const operands for some reason.
683   DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
684   if (V.getContext().isSubprogram())
685     O << DISubprogram(V.getContext()).getDisplayName() << ":";
686   O << V.getName();
687   O << " <- ";
688   // Frame address.  Currently handles register +- offset only.
689   O << '['; 
690   if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
691     printOperand(MI, 0, O); 
692   else
693     O << "undef";
694   O << '+'; printOperand(MI, 3, O);
695   O << ']';
696   O << "+";
697   printOperand(MI, NOps-2, O);
698 }
699
700
701
702 //===----------------------------------------------------------------------===//
703 // Target Registry Stuff
704 //===----------------------------------------------------------------------===//
705
706 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
707                                              unsigned SyntaxVariant,
708                                              const MCAsmInfo &MAI) {
709   if (SyntaxVariant == 0)
710     return new X86ATTInstPrinter(MAI);
711   if (SyntaxVariant == 1)
712     return new X86IntelInstPrinter(MAI);
713   return 0;
714 }
715
716 // Force static initialization.
717 extern "C" void LLVMInitializeX86AsmPrinter() { 
718   RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
719   RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
720   
721   TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
722   TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
723 }