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