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