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