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/DebugInfo.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Module.h"
26#include "llvm/Type.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"
44using namespace llvm;
45
46//===----------------------------------------------------------------------===//
47// Primitive Helper Functions.
48//===----------------------------------------------------------------------===//
49
50/// runOnMachineFunction - Emit the function body.
51///
52bool 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.
78void 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.
212void 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
235void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
236                                 raw_ostream &O, const char *Modifier,
237                                 unsigned AsmVariant) {
238  const MachineOperand &MO = MI->getOperand(OpNo);
239  switch (MO.getType()) {
240  default: llvm_unreachable("unknown operand type!");
241  case MachineOperand::MO_Register: {
242    // FIXME: Enumerating AsmVariant, so we can remove magic number.
243    if (AsmVariant == 0) O << '%';
244    unsigned Reg = MO.getReg();
245    if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
246      EVT VT = (strcmp(Modifier+6,"64") == 0) ?
247        MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
248                    ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
249      Reg = getX86SubSuperRegister(Reg, VT);
250    }
251    O << X86ATTInstPrinter::getRegisterName(Reg);
252    return;
253  }
254
255  case MachineOperand::MO_Immediate:
256    O << '$' << MO.getImm();
257    return;
258
259  case MachineOperand::MO_JumpTableIndex:
260  case MachineOperand::MO_ConstantPoolIndex:
261  case MachineOperand::MO_GlobalAddress:
262  case MachineOperand::MO_ExternalSymbol: {
263    O << '$';
264    printSymbolOperand(MO, O);
265    break;
266  }
267  }
268}
269
270void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op,
271                               raw_ostream &O) {
272  unsigned char value = MI->getOperand(Op).getImm();
273  switch (value) {
274  default: llvm_unreachable("Invalid ssecc argument!");
275  case    0: O << "eq"; break;
276  case    1: O << "lt"; break;
277  case    2: O << "le"; break;
278  case    3: O << "unord"; break;
279  case    4: O << "neq"; break;
280  case    5: O << "nlt"; break;
281  case    6: O << "nle"; break;
282  case    7: O << "ord"; break;
283  case    8: O << "eq_uq"; break;
284  case    9: O << "nge"; break;
285  case  0xa: O << "ngt"; break;
286  case  0xb: O << "false"; break;
287  case  0xc: O << "neq_oq"; break;
288  case  0xd: O << "ge"; break;
289  case  0xe: O << "gt"; break;
290  case  0xf: O << "true"; break;
291  case 0x10: O << "eq_os"; break;
292  case 0x11: O << "lt_oq"; break;
293  case 0x12: O << "le_oq"; break;
294  case 0x13: O << "unord_s"; break;
295  case 0x14: O << "neq_us"; break;
296  case 0x15: O << "nlt_uq"; break;
297  case 0x16: O << "nle_uq"; break;
298  case 0x17: O << "ord_s"; break;
299  case 0x18: O << "eq_us"; break;
300  case 0x19: O << "nge_uq"; break;
301  case 0x1a: O << "ngt_uq"; break;
302  case 0x1b: O << "false_os"; break;
303  case 0x1c: O << "neq_os"; break;
304  case 0x1d: O << "ge_oq"; break;
305  case 0x1e: O << "gt_oq"; break;
306  case 0x1f: O << "true_us"; break;
307  }
308}
309
310void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
311                                         raw_ostream &O, const char *Modifier) {
312  const MachineOperand &BaseReg  = MI->getOperand(Op);
313  const MachineOperand &IndexReg = MI->getOperand(Op+2);
314  const MachineOperand &DispSpec = MI->getOperand(Op+3);
315
316  // If we really don't want to print out (rip), don't.
317  bool HasBaseReg = BaseReg.getReg() != 0;
318  if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
319      BaseReg.getReg() == X86::RIP)
320    HasBaseReg = false;
321
322  // HasParenPart - True if we will print out the () part of the mem ref.
323  bool HasParenPart = IndexReg.getReg() || HasBaseReg;
324
325  if (DispSpec.isImm()) {
326    int DispVal = DispSpec.getImm();
327    if (DispVal || !HasParenPart)
328      O << DispVal;
329  } else {
330    assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
331           DispSpec.isJTI() || DispSpec.isSymbol());
332    printSymbolOperand(MI->getOperand(Op+3), O);
333  }
334
335  if (Modifier && strcmp(Modifier, "H") == 0)
336    O << "+8";
337
338  if (HasParenPart) {
339    assert(IndexReg.getReg() != X86::ESP &&
340           "X86 doesn't allow scaling by ESP");
341
342    O << '(';
343    if (HasBaseReg)
344      printOperand(MI, Op, O, Modifier);
345
346    if (IndexReg.getReg()) {
347      O << ',';
348      printOperand(MI, Op+2, O, Modifier);
349      unsigned ScaleVal = MI->getOperand(Op+1).getImm();
350      if (ScaleVal != 1)
351        O << ',' << ScaleVal;
352    }
353    O << ')';
354  }
355}
356
357void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
358                                      raw_ostream &O, const char *Modifier) {
359  assert(isMem(MI, Op) && "Invalid memory reference!");
360  const MachineOperand &Segment = MI->getOperand(Op+4);
361  if (Segment.getReg()) {
362    printOperand(MI, Op+4, O, Modifier);
363    O << ':';
364  }
365  printLeaMemReference(MI, Op, O, Modifier);
366}
367
368void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op,
369                                  raw_ostream &O) {
370  O << *MF->getPICBaseSymbol() << '\n';
371  O << *MF->getPICBaseSymbol() << ':';
372}
373
374bool 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///
402bool 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      print_pcrel_imm(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
480bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
481                                          unsigned OpNo, unsigned AsmVariant,
482                                          const char *ExtraCode,
483                                          raw_ostream &O) {
484  if (ExtraCode && ExtraCode[0]) {
485    if (ExtraCode[1] != 0) return true; // Unknown modifier.
486
487    switch (ExtraCode[0]) {
488    default: return true;  // Unknown modifier.
489    case 'b': // Print QImode register
490    case 'h': // Print QImode high register
491    case 'w': // Print HImode register
492    case 'k': // Print SImode register
493    case 'q': // Print SImode register
494      // These only apply to registers, ignore on mem.
495      break;
496    case 'H':
497      printMemReference(MI, OpNo, O, "H");
498      return false;
499    case 'P': // Don't print @PLT, but do print as memory.
500      printMemReference(MI, OpNo, O, "no-rip");
501      return false;
502    }
503  }
504  printMemReference(MI, OpNo, O);
505  return false;
506}
507
508void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
509  if (Subtarget->isTargetEnvMacho())
510    OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
511}
512
513
514void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
515  if (Subtarget->isTargetEnvMacho()) {
516    // All darwin targets use mach-o.
517    MachineModuleInfoMachO &MMIMacho =
518      MMI->getObjFileInfo<MachineModuleInfoMachO>();
519
520    // Output stubs for dynamically-linked functions.
521    MachineModuleInfoMachO::SymbolListTy Stubs;
522
523    Stubs = MMIMacho.GetFnStubList();
524    if (!Stubs.empty()) {
525      const MCSection *TheSection =
526        OutContext.getMachOSection("__IMPORT", "__jump_table",
527                                   MCSectionMachO::S_SYMBOL_STUBS |
528                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
529                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
530                                   5, SectionKind::getMetadata());
531      OutStreamer.SwitchSection(TheSection);
532
533      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
534        // L_foo$stub:
535        OutStreamer.EmitLabel(Stubs[i].first);
536        //   .indirect_symbol _foo
537        OutStreamer.EmitSymbolAttribute(Stubs[i].second.getPointer(),
538                                        MCSA_IndirectSymbol);
539        // hlt; hlt; hlt; hlt; hlt     hlt = 0xf4.
540        const char HltInsts[] = "\xf4\xf4\xf4\xf4\xf4";
541        OutStreamer.EmitBytes(StringRef(HltInsts, 5), 0/*addrspace*/);
542      }
543
544      Stubs.clear();
545      OutStreamer.AddBlankLine();
546    }
547
548    // Output stubs for external and common global variables.
549    Stubs = MMIMacho.GetGVStubList();
550    if (!Stubs.empty()) {
551      const MCSection *TheSection =
552        OutContext.getMachOSection("__IMPORT", "__pointers",
553                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
554                                   SectionKind::getMetadata());
555      OutStreamer.SwitchSection(TheSection);
556
557      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
558        // L_foo$non_lazy_ptr:
559        OutStreamer.EmitLabel(Stubs[i].first);
560        // .indirect_symbol _foo
561        MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
562        OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),
563                                        MCSA_IndirectSymbol);
564        // .long 0
565        if (MCSym.getInt())
566          // External to current translation unit.
567          OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
568        else
569          // Internal to current translation unit.
570          //
571          // When we place the LSDA into the TEXT section, the type info
572          // pointers need to be indirect and pc-rel. We accomplish this by
573          // using NLPs.  However, sometimes the types are local to the file. So
574          // we need to fill in the value for the NLP in those cases.
575          OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
576                                                        OutContext),
577                                4/*size*/, 0/*addrspace*/);
578      }
579      Stubs.clear();
580      OutStreamer.AddBlankLine();
581    }
582
583    Stubs = MMIMacho.GetHiddenGVStubList();
584    if (!Stubs.empty()) {
585      OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
586      EmitAlignment(2);
587
588      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
589        // L_foo$non_lazy_ptr:
590        OutStreamer.EmitLabel(Stubs[i].first);
591        // .long _foo
592        OutStreamer.EmitValue(MCSymbolRefExpr::
593                              Create(Stubs[i].second.getPointer(),
594                                     OutContext),
595                              4/*size*/, 0/*addrspace*/);
596      }
597      Stubs.clear();
598      OutStreamer.AddBlankLine();
599    }
600
601    // Funny Darwin hack: This flag tells the linker that no global symbols
602    // contain code that falls through to other global symbols (e.g. the obvious
603    // implementation of multiple entry points).  If this doesn't occur, the
604    // linker can safely perform dead code stripping.  Since LLVM never
605    // generates code that does this, it is always safe to set.
606    OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
607  }
608
609  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing() &&
610      MMI->usesVAFloatArgument()) {
611    StringRef SymbolName = Subtarget->is64Bit() ? "_fltused" : "__fltused";
612    MCSymbol *S = MMI->getContext().GetOrCreateSymbol(SymbolName);
613    OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
614  }
615
616  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) {
617    X86COFFMachineModuleInfo &COFFMMI =
618      MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
619
620    // Emit type information for external functions
621    typedef X86COFFMachineModuleInfo::externals_iterator externals_iterator;
622    for (externals_iterator I = COFFMMI.externals_begin(),
623                            E = COFFMMI.externals_end();
624                            I != E; ++I) {
625      OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
626      OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
627      OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
628                                               << COFF::SCT_COMPLEX_TYPE_SHIFT);
629      OutStreamer.EndCOFFSymbolDef();
630    }
631
632    // Necessary for dllexport support
633    std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
634
635    const TargetLoweringObjectFileCOFF &TLOFCOFF =
636      static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
637
638    for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
639      if (I->hasDLLExportLinkage())
640        DLLExportedFns.push_back(Mang->getSymbol(I));
641
642    for (Module::const_global_iterator I = M.global_begin(),
643           E = M.global_end(); I != E; ++I)
644      if (I->hasDLLExportLinkage())
645        DLLExportedGlobals.push_back(Mang->getSymbol(I));
646
647    // Output linker support code for dllexported globals on windows.
648    if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
649      OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
650      SmallString<128> name;
651      for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
652        if (Subtarget->isTargetWindows())
653          name = " /EXPORT:";
654        else
655          name = " -export:";
656        name += DLLExportedGlobals[i]->getName();
657        if (Subtarget->isTargetWindows())
658          name += ",DATA";
659        else
660        name += ",data";
661        OutStreamer.EmitBytes(name, 0);
662      }
663
664      for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
665        if (Subtarget->isTargetWindows())
666          name = " /EXPORT:";
667        else
668          name = " -export:";
669        name += DLLExportedFns[i]->getName();
670        OutStreamer.EmitBytes(name, 0);
671      }
672    }
673  }
674
675  if (Subtarget->isTargetELF()) {
676    const TargetLoweringObjectFileELF &TLOFELF =
677      static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
678
679    MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
680
681    // Output stubs for external and common global variables.
682    MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
683    if (!Stubs.empty()) {
684      OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
685      const TargetData *TD = TM.getTargetData();
686
687      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
688        OutStreamer.EmitLabel(Stubs[i].first);
689        OutStreamer.EmitSymbolValue(Stubs[i].second.getPointer(),
690                                    TD->getPointerSize(), 0);
691      }
692      Stubs.clear();
693    }
694  }
695}
696
697MachineLocation
698X86AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
699  MachineLocation Location;
700  assert (MI->getNumOperands() == 7 && "Invalid no. of machine operands!");
701  // Frame address.  Currently handles register +- offset only.
702
703  if (MI->getOperand(0).isReg() && MI->getOperand(3).isImm())
704    Location.set(MI->getOperand(0).getReg(), MI->getOperand(3).getImm());
705  else {
706    DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
707  }
708  return Location;
709}
710
711void X86AsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
712                                           raw_ostream &O) {
713  // Only the target-dependent form of DBG_VALUE should get here.
714  // Referencing the offset and metadata as NOps-2 and NOps-1 is
715  // probably portable to other targets; frame pointer location is not.
716  unsigned NOps = MI->getNumOperands();
717  assert(NOps==7);
718  O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
719  // cast away const; DIetc do not take const operands for some reason.
720  DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
721  if (V.getContext().isSubprogram())
722    O << DISubprogram(V.getContext()).getDisplayName() << ":";
723  O << V.getName();
724  O << " <- ";
725  // Frame address.  Currently handles register +- offset only.
726  O << '[';
727  if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
728    printOperand(MI, 0, O);
729  else
730    O << "undef";
731  O << '+'; printOperand(MI, 3, O);
732  O << ']';
733  O << "+";
734  printOperand(MI, NOps-2, O);
735}
736
737
738
739//===----------------------------------------------------------------------===//
740// Target Registry Stuff
741//===----------------------------------------------------------------------===//
742
743// Force static initialization.
744extern "C" void LLVMInitializeX86AsmPrinter() {
745  RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
746  RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
747}
748