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