041eb9af301d018dd8d52f36ffec1cc57735403b
[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/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/MCExpr.h"
34 #include "llvm/MC/MCSectionMachO.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/COFF.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetOptions.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 static void printSymbolOperand(X86AsmPrinter &P, 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 << *P.GetJTISymbol(MO.getIndex());
83     break;
84   case MachineOperand::MO_ConstantPoolIndex:
85     O << *P.GetCPISymbol(MO.getIndex());
86     P.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 = P.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 = P.GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
98     else
99       GVSym = P.getSymbol(GV);
100
101     // Handle dllimport linkage.
102     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
103       GVSym =
104           P.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 = P.GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
109       MachineModuleInfoImpl::StubValueTy &StubSym =
110           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
111       if (StubSym.getPointer() == 0)
112         StubSym = MachineModuleInfoImpl::
113           StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
114     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
115       MCSymbol *Sym = P.GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
116       MachineModuleInfoImpl::StubValueTy &StubSym =
117           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(
118               Sym);
119       if (StubSym.getPointer() == 0)
120         StubSym = MachineModuleInfoImpl::
121           StubValueTy(P.getSymbol(GV), !GV->hasInternalLinkage());
122     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
123       MCSymbol *Sym = P.GetSymbolWithGlobalValueBase(GV, "$stub");
124       MachineModuleInfoImpl::StubValueTy &StubSym =
125           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
126       if (StubSym.getPointer() == 0)
127         StubSym = MachineModuleInfoImpl::
128           StubValueTy(P.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     P.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 = P.GetExternalSymbolSymbol(TempNameStr.str());
148       MachineModuleInfoImpl::StubValueTy &StubSym =
149           P.MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
150       if (StubSym.getPointer() == 0) {
151         TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
152         StubSym = MachineModuleInfoImpl::
153           StubValueTy(P.OutContext.GetOrCreateSymbol(TempNameStr.str()),
154                       true);
155       }
156       SymToPrint = StubSym.getPointer();
157     } else {
158       SymToPrint = P.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 << " + [.-" << *P.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 << '-' << *P.MF->getPICBaseSymbol();
188     break;
189   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
190   case X86II::MO_TLSLD:     O << "@TLSLD";     break;
191   case X86II::MO_TLSLDM:    O << "@TLSLDM";    break;
192   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
193   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
194   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
195   case X86II::MO_DTPOFF:    O << "@DTPOFF";    break;
196   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
197   case X86II::MO_GOTNTPOFF: O << "@GOTNTPOFF"; break;
198   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
199   case X86II::MO_GOT:       O << "@GOT";       break;
200   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
201   case X86II::MO_PLT:       O << "@PLT";       break;
202   case X86II::MO_TLVP:      O << "@TLVP";      break;
203   case X86II::MO_TLVP_PIC_BASE:
204     O << "@TLVP" << '-' << *P.MF->getPICBaseSymbol();
205     break;
206   case X86II::MO_SECREL:    O << "@SECREL32";  break;
207   }
208 }
209
210 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
211                          unsigned OpNo, raw_ostream &O,
212                          const char *Modifier = 0, unsigned AsmVariant = 0);
213
214 /// printPCRelImm - This is used to print an immediate value that ends up
215 /// being encoded as a pc-relative value.  These print slightly differently, for
216 /// example, a $ is not emitted.
217 static void printPCRelImm(X86AsmPrinter &P, const MachineInstr *MI,
218                           unsigned OpNo, raw_ostream &O) {
219   const MachineOperand &MO = MI->getOperand(OpNo);
220   switch (MO.getType()) {
221   default: llvm_unreachable("Unknown pcrel immediate operand");
222   case MachineOperand::MO_Register:
223     // pc-relativeness was handled when computing the value in the reg.
224     printOperand(P, MI, OpNo, O);
225     return;
226   case MachineOperand::MO_Immediate:
227     O << MO.getImm();
228     return;
229   case MachineOperand::MO_GlobalAddress:
230     printSymbolOperand(P, MO, O);
231     return;
232   }
233 }
234
235 static void printOperand(X86AsmPrinter &P, const MachineInstr *MI,
236                          unsigned OpNo, 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       MVT::SimpleValueType 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     if (AsmVariant == 0) O << '$';
257     O << MO.getImm();
258     return;
259
260   case MachineOperand::MO_GlobalAddress: {
261     if (AsmVariant == 0) O << '$';
262     printSymbolOperand(P, MO, O);
263     break;
264   }
265   }
266 }
267
268 static void printLeaMemReference(X86AsmPrinter &P, const MachineInstr *MI,
269                                  unsigned Op, raw_ostream &O,
270                                  const char *Modifier = NULL) {
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   switch (DispSpec.getType()) {
285   default:
286     llvm_unreachable("unknown operand type!");
287   case MachineOperand::MO_Immediate: {
288     int DispVal = DispSpec.getImm();
289     if (DispVal || !HasParenPart)
290       O << DispVal;
291     break;
292   }
293   case MachineOperand::MO_GlobalAddress:
294   case MachineOperand::MO_ConstantPoolIndex:
295   case MachineOperand::MO_JumpTableIndex:
296   case MachineOperand::MO_ExternalSymbol:
297     printSymbolOperand(P, MI->getOperand(Op + 3), O);
298   }
299
300   if (Modifier && strcmp(Modifier, "H") == 0)
301     O << "+8";
302
303   if (HasParenPart) {
304     assert(IndexReg.getReg() != X86::ESP &&
305            "X86 doesn't allow scaling by ESP");
306
307     O << '(';
308     if (HasBaseReg)
309       printOperand(P, MI, Op, O, Modifier);
310
311     if (IndexReg.getReg()) {
312       O << ',';
313       printOperand(P, MI, Op+2, O, Modifier);
314       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
315       if (ScaleVal != 1)
316         O << ',' << ScaleVal;
317     }
318     O << ')';
319   }
320 }
321
322 static void printMemReference(X86AsmPrinter &P, const MachineInstr *MI,
323                               unsigned Op, raw_ostream &O,
324                               const char *Modifier = NULL) {
325   assert(isMem(MI, Op) && "Invalid memory reference!");
326   const MachineOperand &Segment = MI->getOperand(Op+4);
327   if (Segment.getReg()) {
328     printOperand(P, MI, Op+4, O, Modifier);
329     O << ':';
330   }
331   printLeaMemReference(P, MI, Op, O, Modifier);
332 }
333
334 static void printIntelMemReference(X86AsmPrinter &P, const MachineInstr *MI,
335                                    unsigned Op, raw_ostream &O,
336                                    const char *Modifier = NULL,
337                                    unsigned AsmVariant = 1) {
338   const MachineOperand &BaseReg  = MI->getOperand(Op);
339   unsigned ScaleVal = MI->getOperand(Op+1).getImm();
340   const MachineOperand &IndexReg = MI->getOperand(Op+2);
341   const MachineOperand &DispSpec = MI->getOperand(Op+3);
342   const MachineOperand &SegReg   = MI->getOperand(Op+4);
343
344   // If this has a segment register, print it.
345   if (SegReg.getReg()) {
346     printOperand(P, MI, Op+4, O, Modifier, AsmVariant);
347     O << ':';
348   }
349
350   O << '[';
351
352   bool NeedPlus = false;
353   if (BaseReg.getReg()) {
354     printOperand(P, MI, Op, O, Modifier, AsmVariant);
355     NeedPlus = true;
356   }
357
358   if (IndexReg.getReg()) {
359     if (NeedPlus) O << " + ";
360     if (ScaleVal != 1)
361       O << ScaleVal << '*';
362     printOperand(P, MI, Op+2, O, Modifier, AsmVariant);
363     NeedPlus = true;
364   }
365
366   if (!DispSpec.isImm()) {
367     if (NeedPlus) O << " + ";
368     printOperand(P, MI, Op+3, O, Modifier, AsmVariant);
369   } else {
370     int64_t DispVal = DispSpec.getImm();
371     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg())) {
372       if (NeedPlus) {
373         if (DispVal > 0)
374           O << " + ";
375         else {
376           O << " - ";
377           DispVal = -DispVal;
378         }
379       }
380       O << DispVal;
381     }
382   }
383   O << ']';
384 }
385
386 static bool printAsmMRegister(X86AsmPrinter &P, const MachineOperand &MO,
387                               char Mode, raw_ostream &O) {
388   unsigned Reg = MO.getReg();
389   switch (Mode) {
390   default: return true;  // Unknown mode.
391   case 'b': // Print QImode register
392     Reg = getX86SubSuperRegister(Reg, MVT::i8);
393     break;
394   case 'h': // Print QImode high register
395     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
396     break;
397   case 'w': // Print HImode register
398     Reg = getX86SubSuperRegister(Reg, MVT::i16);
399     break;
400   case 'k': // Print SImode register
401     Reg = getX86SubSuperRegister(Reg, MVT::i32);
402     break;
403   case 'q': // Print DImode register
404     // FIXME: gcc will actually print e instead of r for 32-bit.
405     Reg = getX86SubSuperRegister(Reg, MVT::i64);
406     break;
407   }
408
409   O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
410   return false;
411 }
412
413 /// PrintAsmOperand - Print out an operand for an inline asm expression.
414 ///
415 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
416                                     unsigned AsmVariant,
417                                     const char *ExtraCode, raw_ostream &O) {
418   // Does this asm operand have a single letter operand modifier?
419   if (ExtraCode && ExtraCode[0]) {
420     if (ExtraCode[1] != 0) return true; // Unknown modifier.
421
422     const MachineOperand &MO = MI->getOperand(OpNo);
423
424     switch (ExtraCode[0]) {
425     default:
426       // See if this is a generic print operand
427       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
428     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
429       switch (MO.getType()) {
430       default:
431         return true;
432       case MachineOperand::MO_Immediate:
433         O << MO.getImm();
434         return false;
435       case MachineOperand::MO_GlobalAddress:
436       case MachineOperand::MO_ConstantPoolIndex:
437       case MachineOperand::MO_JumpTableIndex:
438       case MachineOperand::MO_ExternalSymbol:
439         printSymbolOperand(*this, MO, O);
440         if (Subtarget->isPICStyleRIPRel())
441           O << "(%rip)";
442         return false;
443       case MachineOperand::MO_Register:
444         O << '(';
445         printOperand(*this, MI, OpNo, O);
446         O << ')';
447         return false;
448       }
449
450     case 'c': // Don't print "$" before a global var name or constant.
451       switch (MO.getType()) {
452       default:
453         printOperand(*this, MI, OpNo, O);
454         break;
455       case MachineOperand::MO_Immediate:
456         O << MO.getImm();
457         break;
458       case MachineOperand::MO_GlobalAddress:
459       case MachineOperand::MO_ConstantPoolIndex:
460       case MachineOperand::MO_JumpTableIndex:
461       case MachineOperand::MO_ExternalSymbol:
462         printSymbolOperand(*this, MO, O);
463         break;
464       }
465       return false;
466
467     case 'A': // Print '*' before a register (it must be a register)
468       if (MO.isReg()) {
469         O << '*';
470         printOperand(*this, MI, OpNo, O);
471         return false;
472       }
473       return true;
474
475     case 'b': // Print QImode register
476     case 'h': // Print QImode high register
477     case 'w': // Print HImode register
478     case 'k': // Print SImode register
479     case 'q': // Print DImode register
480       if (MO.isReg())
481         return printAsmMRegister(*this, MO, ExtraCode[0], O);
482       printOperand(*this, MI, OpNo, O);
483       return false;
484
485     case 'P': // This is the operand of a call, treat specially.
486       printPCRelImm(*this, MI, OpNo, O);
487       return false;
488
489     case 'n':  // Negate the immediate or print a '-' before the operand.
490       // Note: this is a temporary solution. It should be handled target
491       // independently as part of the 'MC' work.
492       if (MO.isImm()) {
493         O << -MO.getImm();
494         return false;
495       }
496       O << '-';
497     }
498   }
499
500   printOperand(*this, MI, OpNo, O, /*Modifier*/ 0, AsmVariant);
501   return false;
502 }
503
504 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
505                                           unsigned OpNo, unsigned AsmVariant,
506                                           const char *ExtraCode,
507                                           raw_ostream &O) {
508   if (AsmVariant) {
509     printIntelMemReference(*this, MI, OpNo, O);
510     return false;
511   }
512
513   if (ExtraCode && ExtraCode[0]) {
514     if (ExtraCode[1] != 0) return true; // Unknown modifier.
515
516     switch (ExtraCode[0]) {
517     default: return true;  // Unknown modifier.
518     case 'b': // Print QImode register
519     case 'h': // Print QImode high register
520     case 'w': // Print HImode register
521     case 'k': // Print SImode register
522     case 'q': // Print SImode register
523       // These only apply to registers, ignore on mem.
524       break;
525     case 'H':
526       printMemReference(*this, MI, OpNo, O, "H");
527       return false;
528     case 'P': // Don't print @PLT, but do print as memory.
529       printMemReference(*this, MI, OpNo, O, "no-rip");
530       return false;
531     }
532   }
533   printMemReference(*this, MI, OpNo, O);
534   return false;
535 }
536
537 void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
538   if (Subtarget->isTargetEnvMacho())
539     OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
540
541   if (Subtarget->isTargetCOFF()) {
542     // Emit an absolute @feat.00 symbol.  This appears to be some kind of
543     // compiler features bitfield read by link.exe.
544     if (!Subtarget->is64Bit()) {
545       MCSymbol *S = MMI->getContext().GetOrCreateSymbol(StringRef("@feat.00"));
546       OutStreamer.BeginCOFFSymbolDef(S);
547       OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_STATIC);
548       OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_NULL);
549       OutStreamer.EndCOFFSymbolDef();
550       // According to the PE-COFF spec, the LSB of this value marks the object
551       // for "registered SEH".  This means that all SEH handler entry points
552       // must be registered in .sxdata.  Use of any unregistered handlers will
553       // cause the process to terminate immediately.  LLVM does not know how to
554       // register any SEH handlers, so its object files should be safe.
555       S->setAbsolute();
556       OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
557       OutStreamer.EmitAssignment(
558           S, MCConstantExpr::Create(int64_t(1), MMI->getContext()));
559     }
560   }
561 }
562
563
564 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
565   if (Subtarget->isTargetEnvMacho()) {
566     // All darwin targets use mach-o.
567     MachineModuleInfoMachO &MMIMacho =
568       MMI->getObjFileInfo<MachineModuleInfoMachO>();
569
570     // Output stubs for dynamically-linked functions.
571     MachineModuleInfoMachO::SymbolListTy Stubs;
572
573     Stubs = MMIMacho.GetFnStubList();
574     if (!Stubs.empty()) {
575       const MCSection *TheSection =
576         OutContext.getMachOSection("__IMPORT", "__jump_table",
577                                    MCSectionMachO::S_SYMBOL_STUBS |
578                                    MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
579                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
580                                    5, SectionKind::getMetadata());
581       OutStreamer.SwitchSection(TheSection);
582
583       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
584         // L_foo$stub:
585         OutStreamer.EmitLabel(Stubs[i].first);
586         //   .indirect_symbol _foo
587         OutStreamer.EmitSymbolAttribute(Stubs[i].second.getPointer(),
588                                         MCSA_IndirectSymbol);
589         // hlt; hlt; hlt; hlt; hlt     hlt = 0xf4.
590         const char HltInsts[] = "\xf4\xf4\xf4\xf4\xf4";
591         OutStreamer.EmitBytes(StringRef(HltInsts, 5));
592       }
593
594       Stubs.clear();
595       OutStreamer.AddBlankLine();
596     }
597
598     // Output stubs for external and common global variables.
599     Stubs = MMIMacho.GetGVStubList();
600     if (!Stubs.empty()) {
601       const MCSection *TheSection =
602         OutContext.getMachOSection("__IMPORT", "__pointers",
603                                    MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
604                                    SectionKind::getMetadata());
605       OutStreamer.SwitchSection(TheSection);
606
607       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
608         // L_foo$non_lazy_ptr:
609         OutStreamer.EmitLabel(Stubs[i].first);
610         // .indirect_symbol _foo
611         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
612         OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),
613                                         MCSA_IndirectSymbol);
614         // .long 0
615         if (MCSym.getInt())
616           // External to current translation unit.
617           OutStreamer.EmitIntValue(0, 4/*size*/);
618         else
619           // Internal to current translation unit.
620           //
621           // When we place the LSDA into the TEXT section, the type info
622           // pointers need to be indirect and pc-rel. We accomplish this by
623           // using NLPs.  However, sometimes the types are local to the file. So
624           // we need to fill in the value for the NLP in those cases.
625           OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
626                                                         OutContext), 4/*size*/);
627       }
628       Stubs.clear();
629       OutStreamer.AddBlankLine();
630     }
631
632     Stubs = MMIMacho.GetHiddenGVStubList();
633     if (!Stubs.empty()) {
634       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
635       EmitAlignment(2);
636
637       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
638         // L_foo$non_lazy_ptr:
639         OutStreamer.EmitLabel(Stubs[i].first);
640         // .long _foo
641         OutStreamer.EmitValue(MCSymbolRefExpr::
642                               Create(Stubs[i].second.getPointer(),
643                                      OutContext), 4/*size*/);
644       }
645       Stubs.clear();
646       OutStreamer.AddBlankLine();
647     }
648
649     SM.serializeToStackMapSection();
650
651     // Funny Darwin hack: This flag tells the linker that no global symbols
652     // contain code that falls through to other global symbols (e.g. the obvious
653     // implementation of multiple entry points).  If this doesn't occur, the
654     // linker can safely perform dead code stripping.  Since LLVM never
655     // generates code that does this, it is always safe to set.
656     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
657   }
658
659   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing() &&
660       MMI->usesVAFloatArgument()) {
661     StringRef SymbolName = Subtarget->is64Bit() ? "_fltused" : "__fltused";
662     MCSymbol *S = MMI->getContext().GetOrCreateSymbol(SymbolName);
663     OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
664   }
665
666   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) {
667     X86COFFMachineModuleInfo &COFFMMI =
668       MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
669
670     // Emit type information for external functions
671     typedef X86COFFMachineModuleInfo::externals_iterator externals_iterator;
672     for (externals_iterator I = COFFMMI.externals_begin(),
673                             E = COFFMMI.externals_end();
674                             I != E; ++I) {
675       OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
676       OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
677       OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
678                                                << COFF::SCT_COMPLEX_TYPE_SHIFT);
679       OutStreamer.EndCOFFSymbolDef();
680     }
681
682     // Necessary for dllexport support
683     std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
684
685     const TargetLoweringObjectFileCOFF &TLOFCOFF =
686       static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
687
688     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
689       if (I->hasDLLExportLinkage())
690         DLLExportedFns.push_back(getSymbol(I));
691
692     for (Module::const_global_iterator I = M.global_begin(),
693            E = M.global_end(); I != E; ++I)
694       if (I->hasDLLExportLinkage())
695         DLLExportedGlobals.push_back(getSymbol(I));
696
697     // Output linker support code for dllexported globals on windows.
698     if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
699       OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
700       SmallString<128> name;
701       for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
702         if (Subtarget->isTargetWindows())
703           name = " /EXPORT:";
704         else
705           name = " -export:";
706         name += DLLExportedGlobals[i]->getName();
707         if (Subtarget->isTargetWindows())
708           name += ",DATA";
709         else
710         name += ",data";
711         OutStreamer.EmitBytes(name);
712       }
713
714       for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
715         if (Subtarget->isTargetWindows())
716           name = " /EXPORT:";
717         else
718           name = " -export:";
719         name += DLLExportedFns[i]->getName();
720         OutStreamer.EmitBytes(name);
721       }
722     }
723   }
724
725   if (Subtarget->isTargetELF()) {
726     const TargetLoweringObjectFileELF &TLOFELF =
727       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
728
729     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
730
731     // Output stubs for external and common global variables.
732     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
733     if (!Stubs.empty()) {
734       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
735       const DataLayout *TD = TM.getDataLayout();
736
737       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
738         OutStreamer.EmitLabel(Stubs[i].first);
739         OutStreamer.EmitSymbolValue(Stubs[i].second.getPointer(),
740                                     TD->getPointerSize());
741       }
742       Stubs.clear();
743     }
744   }
745 }
746
747 //===----------------------------------------------------------------------===//
748 // Target Registry Stuff
749 //===----------------------------------------------------------------------===//
750
751 // Force static initialization.
752 extern "C" void LLVMInitializeX86AsmPrinter() {
753   RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
754   RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
755 }