Fix PR18743.
[oota-llvm.git] / lib / CodeGen / TargetLoweringObjectFileImpl.cpp
1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
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 implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetLowering.h"
40 using namespace llvm;
41 using namespace dwarf;
42
43 //===----------------------------------------------------------------------===//
44 //                                  ELF
45 //===----------------------------------------------------------------------===//
46
47 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49     MachineModuleInfo *MMI) const {
50   unsigned Encoding = getPersonalityEncoding();
51   switch (Encoding & 0x70) {
52   default:
53     report_fatal_error("We do not support this DWARF encoding yet!");
54   case dwarf::DW_EH_PE_absptr:
55     return TM.getTargetLowering()->getSymbol(GV, Mang);
56   case dwarf::DW_EH_PE_pcrel: {
57     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
58                         TM.getTargetLowering()->getSymbol(GV, Mang)->getName());
59   }
60   }
61 }
62
63 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
64                                                        const TargetMachine &TM,
65                                                        const MCSymbol *Sym) const {
66   SmallString<64> NameData("DW.ref.");
67   NameData += Sym->getName();
68   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
69   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
71   StringRef Prefix = ".data.";
72   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
73   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
74   const MCSection *Sec = getContext().getELFSection(NameData,
75                                                     ELF::SHT_PROGBITS,
76                                                     Flags,
77                                                     SectionKind::getDataRel(),
78                                                     0, Label->getName());
79   unsigned Size = TM.getDataLayout()->getPointerSize();
80   Streamer.SwitchSection(Sec);
81   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
82   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
83   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
84   Streamer.EmitELFSize(Label, E);
85   Streamer.EmitLabel(Label);
86
87   Streamer.EmitSymbolValue(Sym, Size);
88 }
89
90 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
91     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
92     const TargetMachine &TM, MachineModuleInfo *MMI,
93     MCStreamer &Streamer) const {
94
95   if (Encoding & dwarf::DW_EH_PE_indirect) {
96     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
97
98     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
99
100     // Add information about the stub reference to ELFMMI so that the stub
101     // gets emitted by the asmprinter.
102     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
103     if (StubSym.getPointer() == 0) {
104       MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
105       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
106     }
107
108     return TargetLoweringObjectFile::
109       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
110                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
111   }
112
113   return TargetLoweringObjectFile::
114     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
115 }
116
117 static SectionKind
118 getELFKindForNamedSection(StringRef Name, SectionKind K) {
119   // N.B.: The defaults used in here are no the same ones used in MC.
120   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
121   // both gas and MC will produce a section with no flags. Given
122   // section(".eh_frame") gcc will produce:
123   //
124   //   .section   .eh_frame,"a",@progbits
125   if (Name.empty() || Name[0] != '.') return K;
126
127   // Some lame default implementation based on some magic section names.
128   if (Name == ".bss" ||
129       Name.startswith(".bss.") ||
130       Name.startswith(".gnu.linkonce.b.") ||
131       Name.startswith(".llvm.linkonce.b.") ||
132       Name == ".sbss" ||
133       Name.startswith(".sbss.") ||
134       Name.startswith(".gnu.linkonce.sb.") ||
135       Name.startswith(".llvm.linkonce.sb."))
136     return SectionKind::getBSS();
137
138   if (Name == ".tdata" ||
139       Name.startswith(".tdata.") ||
140       Name.startswith(".gnu.linkonce.td.") ||
141       Name.startswith(".llvm.linkonce.td."))
142     return SectionKind::getThreadData();
143
144   if (Name == ".tbss" ||
145       Name.startswith(".tbss.") ||
146       Name.startswith(".gnu.linkonce.tb.") ||
147       Name.startswith(".llvm.linkonce.tb."))
148     return SectionKind::getThreadBSS();
149
150   return K;
151 }
152
153
154 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
155
156   if (Name == ".init_array")
157     return ELF::SHT_INIT_ARRAY;
158
159   if (Name == ".fini_array")
160     return ELF::SHT_FINI_ARRAY;
161
162   if (Name == ".preinit_array")
163     return ELF::SHT_PREINIT_ARRAY;
164
165   if (K.isBSS() || K.isThreadBSS())
166     return ELF::SHT_NOBITS;
167
168   return ELF::SHT_PROGBITS;
169 }
170
171
172 static unsigned
173 getELFSectionFlags(SectionKind K) {
174   unsigned Flags = 0;
175
176   if (!K.isMetadata())
177     Flags |= ELF::SHF_ALLOC;
178
179   if (K.isText())
180     Flags |= ELF::SHF_EXECINSTR;
181
182   if (K.isWriteable())
183     Flags |= ELF::SHF_WRITE;
184
185   if (K.isThreadLocal())
186     Flags |= ELF::SHF_TLS;
187
188   // K.isMergeableConst() is left out to honour PR4650
189   if (K.isMergeableCString() || K.isMergeableConst4() ||
190       K.isMergeableConst8() || K.isMergeableConst16())
191     Flags |= ELF::SHF_MERGE;
192
193   if (K.isMergeableCString())
194     Flags |= ELF::SHF_STRINGS;
195
196   return Flags;
197 }
198
199 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
200     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
201     const TargetMachine &TM) const {
202   StringRef SectionName = GV->getSection();
203
204   // Infer section flags from the section name if we can.
205   Kind = getELFKindForNamedSection(SectionName, Kind);
206
207   return getContext().getELFSection(SectionName,
208                                     getELFSectionType(SectionName, Kind),
209                                     getELFSectionFlags(Kind), Kind);
210 }
211
212 /// getSectionPrefixForGlobal - Return the section prefix name used by options
213 /// FunctionsSections and DataSections.
214 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
215   if (Kind.isText())                 return ".text.";
216   if (Kind.isReadOnly())             return ".rodata.";
217   if (Kind.isBSS())                  return ".bss.";
218
219   if (Kind.isThreadData())           return ".tdata.";
220   if (Kind.isThreadBSS())            return ".tbss.";
221
222   if (Kind.isDataNoRel())            return ".data.";
223   if (Kind.isDataRelLocal())         return ".data.rel.local.";
224   if (Kind.isDataRel())              return ".data.rel.";
225   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
226
227   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
228   return ".data.rel.ro.";
229 }
230
231
232 const MCSection *TargetLoweringObjectFileELF::
233 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
234                        Mangler &Mang, const TargetMachine &TM) const {
235   // If we have -ffunction-section or -fdata-section then we should emit the
236   // global value to a uniqued section specifically for it.
237   bool EmitUniquedSection;
238   if (Kind.isText())
239     EmitUniquedSection = TM.getFunctionSections();
240   else
241     EmitUniquedSection = TM.getDataSections();
242
243   // If this global is linkonce/weak and the target handles this by emitting it
244   // into a 'uniqued' section name, create and return the section now.
245   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
246       !Kind.isCommon()) {
247     const char *Prefix;
248     Prefix = getSectionPrefixForGlobal(Kind);
249
250     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
251     MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
252     Name.append(Sym->getName().begin(), Sym->getName().end());
253     StringRef Group = "";
254     unsigned Flags = getELFSectionFlags(Kind);
255     if (GV->isWeakForLinker()) {
256       Group = Sym->getName();
257       Flags |= ELF::SHF_GROUP;
258     }
259
260     return getContext().getELFSection(Name.str(),
261                                       getELFSectionType(Name.str(), Kind),
262                                       Flags, Kind, 0, Group);
263   }
264
265   if (Kind.isText()) return TextSection;
266
267   if (Kind.isMergeable1ByteCString() ||
268       Kind.isMergeable2ByteCString() ||
269       Kind.isMergeable4ByteCString()) {
270
271     // We also need alignment here.
272     // FIXME: this is getting the alignment of the character, not the
273     // alignment of the global!
274     unsigned Align =
275       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
276
277     const char *SizeSpec = ".rodata.str1.";
278     if (Kind.isMergeable2ByteCString())
279       SizeSpec = ".rodata.str2.";
280     else if (Kind.isMergeable4ByteCString())
281       SizeSpec = ".rodata.str4.";
282     else
283       assert(Kind.isMergeable1ByteCString() && "unknown string width");
284
285
286     std::string Name = SizeSpec + utostr(Align);
287     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
288                                       ELF::SHF_ALLOC |
289                                       ELF::SHF_MERGE |
290                                       ELF::SHF_STRINGS,
291                                       Kind);
292   }
293
294   if (Kind.isMergeableConst()) {
295     if (Kind.isMergeableConst4() && MergeableConst4Section)
296       return MergeableConst4Section;
297     if (Kind.isMergeableConst8() && MergeableConst8Section)
298       return MergeableConst8Section;
299     if (Kind.isMergeableConst16() && MergeableConst16Section)
300       return MergeableConst16Section;
301     return ReadOnlySection;  // .const
302   }
303
304   if (Kind.isReadOnly())             return ReadOnlySection;
305
306   if (Kind.isThreadData())           return TLSDataSection;
307   if (Kind.isThreadBSS())            return TLSBSSSection;
308
309   // Note: we claim that common symbols are put in BSSSection, but they are
310   // really emitted with the magic .comm directive, which creates a symbol table
311   // entry but not a section.
312   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
313
314   if (Kind.isDataNoRel())            return DataSection;
315   if (Kind.isDataRelLocal())         return DataRelLocalSection;
316   if (Kind.isDataRel())              return DataRelSection;
317   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
318
319   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
320   return DataRelROSection;
321 }
322
323 /// getSectionForConstant - Given a mergeable constant with the
324 /// specified size and relocation information, return a section that it
325 /// should be placed in.
326 const MCSection *TargetLoweringObjectFileELF::
327 getSectionForConstant(SectionKind Kind) const {
328   if (Kind.isMergeableConst4() && MergeableConst4Section)
329     return MergeableConst4Section;
330   if (Kind.isMergeableConst8() && MergeableConst8Section)
331     return MergeableConst8Section;
332   if (Kind.isMergeableConst16() && MergeableConst16Section)
333     return MergeableConst16Section;
334   if (Kind.isReadOnly())
335     return ReadOnlySection;
336
337   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
338   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
339   return DataRelROSection;
340 }
341
342 const MCSection *
343 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
344   // The default scheme is .ctor / .dtor, so we have to invert the priority
345   // numbering.
346   if (Priority == 65535)
347     return StaticCtorSection;
348
349   if (UseInitArray) {
350     std::string Name = std::string(".init_array.") + utostr(Priority);
351     return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
352                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
353                                       SectionKind::getDataRel());
354   } else {
355     std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
356     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
357                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
358                                       SectionKind::getDataRel());
359   }
360 }
361
362 const MCSection *
363 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
364   // The default scheme is .ctor / .dtor, so we have to invert the priority
365   // numbering.
366   if (Priority == 65535)
367     return StaticDtorSection;
368
369   if (UseInitArray) {
370     std::string Name = std::string(".fini_array.") + utostr(Priority);
371     return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
372                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
373                                       SectionKind::getDataRel());
374   } else {
375     std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
376     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
377                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
378                                       SectionKind::getDataRel());
379   }
380 }
381
382 void
383 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
384   UseInitArray = UseInitArray_;
385   if (!UseInitArray)
386     return;
387
388   StaticCtorSection =
389     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
390                                ELF::SHF_WRITE |
391                                ELF::SHF_ALLOC,
392                                SectionKind::getDataRel());
393   StaticDtorSection =
394     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
395                                ELF::SHF_WRITE |
396                                ELF::SHF_ALLOC,
397                                SectionKind::getDataRel());
398 }
399
400 //===----------------------------------------------------------------------===//
401 //                                 MachO
402 //===----------------------------------------------------------------------===//
403
404 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
405 /// option string. Returns StringRef() if the option does not specify a library.
406 StringRef TargetLoweringObjectFileMachO::
407 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
408   const char *LibCmd = "-l";
409   if (LinkerOption.startswith(LibCmd))
410     return LinkerOption.substr(strlen(LibCmd));
411   return StringRef();
412 }
413
414 /// emitModuleFlags - Perform code emission for module flags.
415 void TargetLoweringObjectFileMachO::
416 emitModuleFlags(MCStreamer &Streamer,
417                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
418                 Mangler &Mang, const TargetMachine &TM) const {
419   unsigned VersionVal = 0;
420   unsigned ImageInfoFlags = 0;
421   MDNode *LinkerOptions = 0;
422   StringRef SectionVal;
423
424   for (ArrayRef<Module::ModuleFlagEntry>::iterator
425          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
426     const Module::ModuleFlagEntry &MFE = *i;
427
428     // Ignore flags with 'Require' behavior.
429     if (MFE.Behavior == Module::Require)
430       continue;
431
432     StringRef Key = MFE.Key->getString();
433     Value *Val = MFE.Val;
434
435     if (Key == "Objective-C Image Info Version") {
436       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
437     } else if (Key == "Objective-C Garbage Collection" ||
438                Key == "Objective-C GC Only" ||
439                Key == "Objective-C Is Simulated") {
440       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
441     } else if (Key == "Objective-C Image Info Section") {
442       SectionVal = cast<MDString>(Val)->getString();
443     } else if (Key == "Linker Options") {
444       LinkerOptions = cast<MDNode>(Val);
445     }
446   }
447
448   // Emit the linker options if present.
449   if (LinkerOptions) {
450     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
451       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
452       SmallVector<std::string, 4> StrOptions;
453
454       // Convert to strings.
455       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
456         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
457         StrOptions.push_back(MDOption->getString());
458       }
459
460       Streamer.EmitLinkerOptions(StrOptions);
461     }
462   }
463
464   // The section is mandatory. If we don't have it, then we don't have GC info.
465   if (SectionVal.empty()) return;
466
467   StringRef Segment, Section;
468   unsigned TAA = 0, StubSize = 0;
469   bool TAAParsed;
470   std::string ErrorCode =
471     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
472                                           TAA, TAAParsed, StubSize);
473   if (!ErrorCode.empty())
474     // If invalid, report the error with report_fatal_error.
475     report_fatal_error("Invalid section specifier '" + Section + "': " +
476                        ErrorCode + ".");
477
478   // Get the section.
479   const MCSectionMachO *S =
480     getContext().getMachOSection(Segment, Section, TAA, StubSize,
481                                  SectionKind::getDataNoRel());
482   Streamer.SwitchSection(S);
483   Streamer.EmitLabel(getContext().
484                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
485   Streamer.EmitIntValue(VersionVal, 4);
486   Streamer.EmitIntValue(ImageInfoFlags, 4);
487   Streamer.AddBlankLine();
488 }
489
490 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
491     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
492     const TargetMachine &TM) const {
493   // Parse the section specifier and create it if valid.
494   StringRef Segment, Section;
495   unsigned TAA = 0, StubSize = 0;
496   bool TAAParsed;
497   std::string ErrorCode =
498     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
499                                           TAA, TAAParsed, StubSize);
500   if (!ErrorCode.empty()) {
501     // If invalid, report the error with report_fatal_error.
502     report_fatal_error("Global variable '" + GV->getName() +
503                        "' has an invalid section specifier '" +
504                        GV->getSection() + "': " + ErrorCode + ".");
505   }
506
507   // Get the section.
508   const MCSectionMachO *S =
509     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
510
511   // If TAA wasn't set by ParseSectionSpecifier() above,
512   // use the value returned by getMachOSection() as a default.
513   if (!TAAParsed)
514     TAA = S->getTypeAndAttributes();
515
516   // Okay, now that we got the section, verify that the TAA & StubSize agree.
517   // If the user declared multiple globals with different section flags, we need
518   // to reject it here.
519   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
520     // If invalid, report the error with report_fatal_error.
521     report_fatal_error("Global variable '" + GV->getName() +
522                        "' section type or attributes does not match previous"
523                        " section specifier");
524   }
525
526   return S;
527 }
528
529 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
530     const MCSection &Section) const {
531     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
532
533     // Sections holding 1 byte strings are atomized based on the data
534     // they contain.
535     // Sections holding 2 byte strings require symbols in order to be
536     // atomized.
537     // There is no dedicated section for 4 byte strings.
538     if (SMO.getKind().isMergeable1ByteCString())
539       return false;
540
541     if (SMO.getSegmentName() == "__DATA" &&
542         SMO.getSectionName() == "__cfstring")
543       return false;
544
545     switch (SMO.getType()) {
546     default:
547       return true;
548
549       // These sections are atomized at the element boundaries without using
550       // symbols.
551     case MCSectionMachO::S_4BYTE_LITERALS:
552     case MCSectionMachO::S_8BYTE_LITERALS:
553     case MCSectionMachO::S_16BYTE_LITERALS:
554     case MCSectionMachO::S_LITERAL_POINTERS:
555     case MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS:
556     case MCSectionMachO::S_LAZY_SYMBOL_POINTERS:
557     case MCSectionMachO::S_MOD_INIT_FUNC_POINTERS:
558     case MCSectionMachO::S_MOD_TERM_FUNC_POINTERS:
559     case MCSectionMachO::S_INTERPOSING:
560       return false;
561     }
562 }
563
564 const MCSection *TargetLoweringObjectFileMachO::
565 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
566                        Mangler &Mang, const TargetMachine &TM) const {
567
568   // Handle thread local data.
569   if (Kind.isThreadBSS()) return TLSBSSSection;
570   if (Kind.isThreadData()) return TLSDataSection;
571
572   if (Kind.isText())
573     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
574
575   // If this is weak/linkonce, put this in a coalescable section, either in text
576   // or data depending on if it is writable.
577   if (GV->isWeakForLinker()) {
578     if (Kind.isReadOnly())
579       return ConstTextCoalSection;
580     return DataCoalSection;
581   }
582
583   // FIXME: Alignment check should be handled by section classifier.
584   if (Kind.isMergeable1ByteCString() &&
585       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
586     return CStringSection;
587
588   // Do not put 16-bit arrays in the UString section if they have an
589   // externally visible label, this runs into issues with certain linker
590   // versions.
591   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
592       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
593     return UStringSection;
594
595   if (Kind.isMergeableConst()) {
596     if (Kind.isMergeableConst4())
597       return FourByteConstantSection;
598     if (Kind.isMergeableConst8())
599       return EightByteConstantSection;
600     if (Kind.isMergeableConst16())
601       return SixteenByteConstantSection;
602   }
603
604   // Otherwise, if it is readonly, but not something we can specially optimize,
605   // just drop it in .const.
606   if (Kind.isReadOnly())
607     return ReadOnlySection;
608
609   // If this is marked const, put it into a const section.  But if the dynamic
610   // linker needs to write to it, put it in the data segment.
611   if (Kind.isReadOnlyWithRel())
612     return ConstDataSection;
613
614   // Put zero initialized globals with strong external linkage in the
615   // DATA, __common section with the .zerofill directive.
616   if (Kind.isBSSExtern())
617     return DataCommonSection;
618
619   // Put zero initialized globals with local linkage in __DATA,__bss directive
620   // with the .zerofill directive (aka .lcomm).
621   if (Kind.isBSSLocal())
622     return DataBSSSection;
623
624   // Otherwise, just drop the variable in the normal data section.
625   return DataSection;
626 }
627
628 const MCSection *
629 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
630   // If this constant requires a relocation, we have to put it in the data
631   // segment, not in the text segment.
632   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
633     return ConstDataSection;
634
635   if (Kind.isMergeableConst4())
636     return FourByteConstantSection;
637   if (Kind.isMergeableConst8())
638     return EightByteConstantSection;
639   if (Kind.isMergeableConst16())
640     return SixteenByteConstantSection;
641   return ReadOnlySection;  // .const
642 }
643
644 /// This hook allows targets to selectively decide not to emit the UsedDirective
645 /// for some symbols in llvm.used.
646 // FIXME: REMOVE this (rdar://7071300)
647 bool TargetLoweringObjectFileMachO::shouldEmitUsedDirectiveFor(
648     const GlobalValue *GV, Mangler &Mang, TargetMachine &TM) const {
649   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
650   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
651     // FIXME: ObjC metadata is currently emitted as internal symbols that have
652     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
653     // this horrible hack can go away.
654     MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
655     if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
656       return false;
657   }
658
659   return true;
660 }
661
662 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
663     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
664     const TargetMachine &TM, MachineModuleInfo *MMI,
665     MCStreamer &Streamer) const {
666   // The mach-o version of this method defaults to returning a stub reference.
667
668   if (Encoding & DW_EH_PE_indirect) {
669     MachineModuleInfoMachO &MachOMMI =
670       MMI->getObjFileInfo<MachineModuleInfoMachO>();
671
672     MCSymbol *SSym =
673         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
674
675     // Add information about the stub reference to MachOMMI so that the stub
676     // gets emitted by the asmprinter.
677     MachineModuleInfoImpl::StubValueTy &StubSym =
678       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
679                                   MachOMMI.getGVStubEntry(SSym);
680     if (StubSym.getPointer() == 0) {
681       MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
682       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
683     }
684
685     return TargetLoweringObjectFile::
686       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
687                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
688   }
689
690   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
691                                                            TM, MMI, Streamer);
692 }
693
694 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
695     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
696     MachineModuleInfo *MMI) const {
697   // The mach-o version of this method defaults to returning a stub reference.
698   MachineModuleInfoMachO &MachOMMI =
699     MMI->getObjFileInfo<MachineModuleInfoMachO>();
700
701   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
702
703   // Add information about the stub reference to MachOMMI so that the stub
704   // gets emitted by the asmprinter.
705   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
706   if (StubSym.getPointer() == 0) {
707     MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
708     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
709   }
710
711   return SSym;
712 }
713
714 //===----------------------------------------------------------------------===//
715 //                                  COFF
716 //===----------------------------------------------------------------------===//
717
718 static unsigned
719 getCOFFSectionFlags(SectionKind K) {
720   unsigned Flags = 0;
721
722   if (K.isMetadata())
723     Flags |=
724       COFF::IMAGE_SCN_MEM_DISCARDABLE;
725   else if (K.isText())
726     Flags |=
727       COFF::IMAGE_SCN_MEM_EXECUTE |
728       COFF::IMAGE_SCN_MEM_READ |
729       COFF::IMAGE_SCN_CNT_CODE;
730   else if (K.isBSS ())
731     Flags |=
732       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
733       COFF::IMAGE_SCN_MEM_READ |
734       COFF::IMAGE_SCN_MEM_WRITE;
735   else if (K.isThreadLocal())
736     Flags |=
737       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
738       COFF::IMAGE_SCN_MEM_READ |
739       COFF::IMAGE_SCN_MEM_WRITE;
740   else if (K.isReadOnly())
741     Flags |=
742       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
743       COFF::IMAGE_SCN_MEM_READ;
744   else if (K.isWriteable())
745     Flags |=
746       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
747       COFF::IMAGE_SCN_MEM_READ |
748       COFF::IMAGE_SCN_MEM_WRITE;
749
750   return Flags;
751 }
752
753 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
754     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
755     const TargetMachine &TM) const {
756   int Selection = 0;
757   unsigned Characteristics = getCOFFSectionFlags(Kind);
758   StringRef Name = GV->getSection();
759   StringRef COMDATSymName = "";
760   if (GV->isWeakForLinker()) {
761     Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
762     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
763     MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
764     COMDATSymName = Sym->getName();
765   }
766   return getContext().getCOFFSection(Name,
767                                      Characteristics,
768                                      Kind,
769                                      COMDATSymName,
770                                      Selection);
771 }
772
773 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
774   if (Kind.isText())
775     return ".text";
776   if (Kind.isBSS ())
777     return ".bss";
778   if (Kind.isThreadLocal())
779     return ".tls$";
780   if (Kind.isWriteable())
781     return ".data";
782   return ".rdata";
783 }
784
785
786 const MCSection *TargetLoweringObjectFileCOFF::
787 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
788                        Mangler &Mang, const TargetMachine &TM) const {
789
790   // If this global is linkonce/weak and the target handles this by emitting it
791   // into a 'uniqued' section name, create and return the section now.
792   if (GV->isWeakForLinker()) {
793     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
794     unsigned Characteristics = getCOFFSectionFlags(Kind);
795
796     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
797     MCSymbol *Sym = TM.getTargetLowering()->getSymbol(GV, Mang);
798     return getContext().getCOFFSection(Name, Characteristics,
799                                        Kind, Sym->getName(),
800                                        COFF::IMAGE_COMDAT_SELECT_ANY);
801   }
802
803   if (Kind.isText())
804     return TextSection;
805
806   if (Kind.isThreadLocal())
807     return TLSDataSection;
808
809   if (Kind.isReadOnly())
810     return ReadOnlySection;
811
812   if (Kind.isBSS())
813     return BSSSection;
814
815   return DataSection;
816 }
817
818 StringRef TargetLoweringObjectFileCOFF::
819 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
820   const char *LibCmd = "/DEFAULTLIB:";
821   if (LinkerOption.startswith(LibCmd))
822     return LinkerOption.substr(strlen(LibCmd));
823   return StringRef();
824 }
825
826 void TargetLoweringObjectFileCOFF::
827 emitModuleFlags(MCStreamer &Streamer,
828                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
829                 Mangler &Mang, const TargetMachine &TM) const {
830   MDNode *LinkerOptions = 0;
831
832   // Look for the "Linker Options" flag, since it's the only one we support.
833   for (ArrayRef<Module::ModuleFlagEntry>::iterator
834        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
835     const Module::ModuleFlagEntry &MFE = *i;
836     StringRef Key = MFE.Key->getString();
837     Value *Val = MFE.Val;
838     if (Key == "Linker Options") {
839       LinkerOptions = cast<MDNode>(Val);
840       break;
841     }
842   }
843   if (!LinkerOptions)
844     return;
845
846   // Emit the linker options to the linker .drectve section.  According to the
847   // spec, this section is a space-separated string containing flags for linker.
848   const MCSection *Sec = getDrectveSection();
849   Streamer.SwitchSection(Sec);
850   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
851     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
852     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
853       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
854       StringRef Op = MDOption->getString();
855       // Lead with a space for consistency with our dllexport implementation.
856       std::string Escaped(" ");
857       if (Op.find(" ") != StringRef::npos) {
858         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
859         // how to escape quotes, but it probably uses this algorithm:
860         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
861         // FIXME: Reuse escaping code from Support/Windows/Program.inc
862         Escaped.push_back('\"');
863         Escaped.append(Op);
864         Escaped.push_back('\"');
865       } else {
866         Escaped.append(Op);
867       }
868       Streamer.EmitBytes(Escaped);
869     }
870   }
871 }