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