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