xref: /llvm-project/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp (revision 4c47434b25ea4683ff1794e2d1b24eaa16b5e30e)
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/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
22 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalObject.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCSectionCOFF.h"
40 #include "llvm/MC/MCSectionELF.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/MC/MCSectionWasm.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/MCSymbolELF.h"
46 #include "llvm/MC/MCValue.h"
47 #include "llvm/MC/SectionKind.h"
48 #include "llvm/ProfileData/InstrProf.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CodeGen.h"
51 #include "llvm/Support/COFF.h"
52 #include "llvm/Support/Dwarf.h"
53 #include "llvm/Support/ELF.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MachO.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetMachine.h"
58 #include <cassert>
59 #include <string>
60 
61 using namespace llvm;
62 using namespace dwarf;
63 
64 static void GetObjCImageInfo(ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
65                              unsigned &Version, unsigned &Flags,
66                              StringRef &Section) {
67   for (const auto &MFE: ModuleFlags) {
68     // Ignore flags with 'Require' behaviour.
69     if (MFE.Behavior == Module::Require)
70       continue;
71 
72     StringRef Key = MFE.Key->getString();
73     if (Key == "Objective-C Image Info Version") {
74       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
75     } else if (Key == "Objective-C Garbage Collection" ||
76                Key == "Objective-C GC Only" ||
77                Key == "Objective-C Is Simulated" ||
78                Key == "Objective-C Class Properties" ||
79                Key == "Objective-C Image Swift Version") {
80       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
81     } else if (Key == "Objective-C Image Info Section") {
82       Section = cast<MDString>(MFE.Val)->getString();
83     }
84   }
85 }
86 
87 //===----------------------------------------------------------------------===//
88 //                                  ELF
89 //===----------------------------------------------------------------------===//
90 
91 void TargetLoweringObjectFileELF::emitModuleFlags(
92     MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
93     const TargetMachine &TM) const {
94   unsigned Version = 0;
95   unsigned Flags = 0;
96   StringRef Section;
97 
98   GetObjCImageInfo(ModuleFlags, Version, Flags, Section);
99   if (Section.empty())
100     return;
101 
102   auto &C = getContext();
103   auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
104   Streamer.SwitchSection(S);
105   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
106   Streamer.EmitIntValue(Version, 4);
107   Streamer.EmitIntValue(Flags, 4);
108   Streamer.AddBlankLine();
109 }
110 
111 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
112     const GlobalValue *GV, const TargetMachine &TM,
113     MachineModuleInfo *MMI) const {
114   unsigned Encoding = getPersonalityEncoding();
115   if ((Encoding & 0x80) == DW_EH_PE_indirect)
116     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
117                                           TM.getSymbol(GV)->getName());
118   if ((Encoding & 0x70) == DW_EH_PE_absptr)
119     return TM.getSymbol(GV);
120   report_fatal_error("We do not support this DWARF encoding yet!");
121 }
122 
123 void TargetLoweringObjectFileELF::emitPersonalityValue(
124     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
125   SmallString<64> NameData("DW.ref.");
126   NameData += Sym->getName();
127   MCSymbolELF *Label =
128       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
129   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
130   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
131   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
132   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
133                                                    ELF::SHT_PROGBITS, Flags, 0);
134   unsigned Size = DL.getPointerSize();
135   Streamer.SwitchSection(Sec);
136   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
137   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
138   const MCExpr *E = MCConstantExpr::create(Size, getContext());
139   Streamer.emitELFSize(Label, E);
140   Streamer.EmitLabel(Label);
141 
142   Streamer.EmitSymbolValue(Sym, Size);
143 }
144 
145 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
146     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
147     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
148   if (Encoding & DW_EH_PE_indirect) {
149     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
150 
151     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
152 
153     // Add information about the stub reference to ELFMMI so that the stub
154     // gets emitted by the asmprinter.
155     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
156     if (!StubSym.getPointer()) {
157       MCSymbol *Sym = TM.getSymbol(GV);
158       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
159     }
160 
161     return TargetLoweringObjectFile::
162       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
163                         Encoding & ~DW_EH_PE_indirect, Streamer);
164   }
165 
166   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
167                                                            MMI, Streamer);
168 }
169 
170 static SectionKind
171 getELFKindForNamedSection(StringRef Name, SectionKind K) {
172   // N.B.: The defaults used in here are no the same ones used in MC.
173   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
174   // both gas and MC will produce a section with no flags. Given
175   // section(".eh_frame") gcc will produce:
176   //
177   //   .section   .eh_frame,"a",@progbits
178 
179   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
180                                       /*AddSegmentInfo=*/false))
181     return SectionKind::getMetadata();
182 
183   if (Name.empty() || Name[0] != '.') return K;
184 
185   // Some lame default implementation based on some magic section names.
186   if (Name == ".bss" ||
187       Name.startswith(".bss.") ||
188       Name.startswith(".gnu.linkonce.b.") ||
189       Name.startswith(".llvm.linkonce.b.") ||
190       Name == ".sbss" ||
191       Name.startswith(".sbss.") ||
192       Name.startswith(".gnu.linkonce.sb.") ||
193       Name.startswith(".llvm.linkonce.sb."))
194     return SectionKind::getBSS();
195 
196   if (Name == ".tdata" ||
197       Name.startswith(".tdata.") ||
198       Name.startswith(".gnu.linkonce.td.") ||
199       Name.startswith(".llvm.linkonce.td."))
200     return SectionKind::getThreadData();
201 
202   if (Name == ".tbss" ||
203       Name.startswith(".tbss.") ||
204       Name.startswith(".gnu.linkonce.tb.") ||
205       Name.startswith(".llvm.linkonce.tb."))
206     return SectionKind::getThreadBSS();
207 
208   return K;
209 }
210 
211 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
212   // Use SHT_NOTE for section whose name starts with ".note" to allow
213   // emitting ELF notes from C variable declaration.
214   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
215   if (Name.startswith(".note"))
216     return ELF::SHT_NOTE;
217 
218   if (Name == ".init_array")
219     return ELF::SHT_INIT_ARRAY;
220 
221   if (Name == ".fini_array")
222     return ELF::SHT_FINI_ARRAY;
223 
224   if (Name == ".preinit_array")
225     return ELF::SHT_PREINIT_ARRAY;
226 
227   if (K.isBSS() || K.isThreadBSS())
228     return ELF::SHT_NOBITS;
229 
230   return ELF::SHT_PROGBITS;
231 }
232 
233 static unsigned getELFSectionFlags(SectionKind K) {
234   unsigned Flags = 0;
235 
236   if (!K.isMetadata())
237     Flags |= ELF::SHF_ALLOC;
238 
239   if (K.isText())
240     Flags |= ELF::SHF_EXECINSTR;
241 
242   if (K.isExecuteOnly())
243     Flags |= ELF::SHF_ARM_PURECODE;
244 
245   if (K.isWriteable())
246     Flags |= ELF::SHF_WRITE;
247 
248   if (K.isThreadLocal())
249     Flags |= ELF::SHF_TLS;
250 
251   if (K.isMergeableCString() || K.isMergeableConst())
252     Flags |= ELF::SHF_MERGE;
253 
254   if (K.isMergeableCString())
255     Flags |= ELF::SHF_STRINGS;
256 
257   return Flags;
258 }
259 
260 static const Comdat *getELFComdat(const GlobalValue *GV) {
261   const Comdat *C = GV->getComdat();
262   if (!C)
263     return nullptr;
264 
265   if (C->getSelectionKind() != Comdat::Any)
266     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
267                        C->getName() + "' cannot be lowered.");
268 
269   return C;
270 }
271 
272 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
273                                               const TargetMachine &TM) {
274   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
275   if (!MD)
276     return nullptr;
277 
278   const MDOperand &Op = MD->getOperand(0);
279   if (!Op.get())
280     return nullptr;
281 
282   auto *VM = dyn_cast<ValueAsMetadata>(Op);
283   if (!VM)
284     report_fatal_error("MD_associated operand is not ValueAsMetadata");
285 
286   GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
287   return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
288 }
289 
290 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
291     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
292   StringRef SectionName = GO->getSection();
293 
294   // Check if '#pragma clang section' name is applicable.
295   // Note that pragma directive overrides -ffunction-section, -fdata-section
296   // and so section name is exactly as user specified and not uniqued.
297   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
298   if (GV && GV->hasImplicitSection()) {
299     auto Attrs = GV->getAttributes();
300     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
301       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
302     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
303       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
304     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
305       SectionName = Attrs.getAttribute("data-section").getValueAsString();
306     }
307   }
308   const Function *F = dyn_cast<Function>(GO);
309   if (F && F->hasFnAttribute("implicit-section-name")) {
310     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
311   }
312 
313   // Infer section flags from the section name if we can.
314   Kind = getELFKindForNamedSection(SectionName, Kind);
315 
316   StringRef Group = "";
317   unsigned Flags = getELFSectionFlags(Kind);
318   if (const Comdat *C = getELFComdat(GO)) {
319     Group = C->getName();
320     Flags |= ELF::SHF_GROUP;
321   }
322 
323   // A section can have at most one associated section. Put each global with
324   // MD_associated in a unique section.
325   unsigned UniqueID = MCContext::GenericSectionID;
326   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
327   if (AssociatedSymbol) {
328     UniqueID = NextUniqueID++;
329     Flags |= ELF::SHF_LINK_ORDER;
330   }
331 
332   MCSectionELF *Section = getContext().getELFSection(
333       SectionName, getELFSectionType(SectionName, Kind), Flags,
334       /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
335   // Make sure that we did not get some other section with incompatible sh_link.
336   // This should not be possible due to UniqueID code above.
337   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
338   return Section;
339 }
340 
341 /// Return the section prefix name used by options FunctionsSections and
342 /// DataSections.
343 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
344   if (Kind.isText())
345     return ".text";
346   if (Kind.isReadOnly())
347     return ".rodata";
348   if (Kind.isBSS())
349     return ".bss";
350   if (Kind.isThreadData())
351     return ".tdata";
352   if (Kind.isThreadBSS())
353     return ".tbss";
354   if (Kind.isData())
355     return ".data";
356   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
357   return ".data.rel.ro";
358 }
359 
360 static MCSectionELF *selectELFSectionForGlobal(
361     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
362     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
363     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
364   unsigned EntrySize = 0;
365   if (Kind.isMergeableCString()) {
366     if (Kind.isMergeable2ByteCString()) {
367       EntrySize = 2;
368     } else if (Kind.isMergeable4ByteCString()) {
369       EntrySize = 4;
370     } else {
371       EntrySize = 1;
372       assert(Kind.isMergeable1ByteCString() && "unknown string width");
373     }
374   } else if (Kind.isMergeableConst()) {
375     if (Kind.isMergeableConst4()) {
376       EntrySize = 4;
377     } else if (Kind.isMergeableConst8()) {
378       EntrySize = 8;
379     } else if (Kind.isMergeableConst16()) {
380       EntrySize = 16;
381     } else {
382       assert(Kind.isMergeableConst32() && "unknown data width");
383       EntrySize = 32;
384     }
385   }
386 
387   StringRef Group = "";
388   if (const Comdat *C = getELFComdat(GO)) {
389     Flags |= ELF::SHF_GROUP;
390     Group = C->getName();
391   }
392 
393   bool UniqueSectionNames = TM.getUniqueSectionNames();
394   SmallString<128> Name;
395   if (Kind.isMergeableCString()) {
396     // We also need alignment here.
397     // FIXME: this is getting the alignment of the character, not the
398     // alignment of the global!
399     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
400         cast<GlobalVariable>(GO));
401 
402     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
403     Name = SizeSpec + utostr(Align);
404   } else if (Kind.isMergeableConst()) {
405     Name = ".rodata.cst";
406     Name += utostr(EntrySize);
407   } else {
408     Name = getSectionPrefixForGlobal(Kind);
409   }
410 
411   if (const auto *F = dyn_cast<Function>(GO)) {
412     const auto &OptionalPrefix = F->getSectionPrefix();
413     if (OptionalPrefix)
414       Name += *OptionalPrefix;
415   }
416 
417   if (EmitUniqueSection && UniqueSectionNames) {
418     Name.push_back('.');
419     TM.getNameWithPrefix(Name, GO, Mang, true);
420   }
421   unsigned UniqueID = MCContext::GenericSectionID;
422   if (EmitUniqueSection && !UniqueSectionNames) {
423     UniqueID = *NextUniqueID;
424     (*NextUniqueID)++;
425   }
426   // Use 0 as the unique ID for execute-only text
427   if (Kind.isExecuteOnly())
428     UniqueID = 0;
429   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
430                            EntrySize, Group, UniqueID, AssociatedSymbol);
431 }
432 
433 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
434     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
435   unsigned Flags = getELFSectionFlags(Kind);
436 
437   // If we have -ffunction-section or -fdata-section then we should emit the
438   // global value to a uniqued section specifically for it.
439   bool EmitUniqueSection = false;
440   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
441     if (Kind.isText())
442       EmitUniqueSection = TM.getFunctionSections();
443     else
444       EmitUniqueSection = TM.getDataSections();
445   }
446   EmitUniqueSection |= GO->hasComdat();
447 
448   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
449   if (AssociatedSymbol) {
450     EmitUniqueSection = true;
451     Flags |= ELF::SHF_LINK_ORDER;
452   }
453 
454   MCSectionELF *Section = selectELFSectionForGlobal(
455       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
456       &NextUniqueID, AssociatedSymbol);
457   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
458   return Section;
459 }
460 
461 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
462     const Function &F, const TargetMachine &TM) const {
463   // If the function can be removed, produce a unique section so that
464   // the table doesn't prevent the removal.
465   const Comdat *C = F.getComdat();
466   bool EmitUniqueSection = TM.getFunctionSections() || C;
467   if (!EmitUniqueSection)
468     return ReadOnlySection;
469 
470   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
471                                    getMangler(), TM, EmitUniqueSection,
472                                    ELF::SHF_ALLOC, &NextUniqueID,
473                                    /* AssociatedSymbol */ nullptr);
474 }
475 
476 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
477     bool UsesLabelDifference, const Function &F) const {
478   // We can always create relative relocations, so use another section
479   // that can be marked non-executable.
480   return false;
481 }
482 
483 /// Given a mergeable constant with the specified size and relocation
484 /// information, return a section that it should be placed in.
485 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
486     const DataLayout &DL, SectionKind Kind, const Constant *C,
487     unsigned &Align) const {
488   if (Kind.isMergeableConst4() && MergeableConst4Section)
489     return MergeableConst4Section;
490   if (Kind.isMergeableConst8() && MergeableConst8Section)
491     return MergeableConst8Section;
492   if (Kind.isMergeableConst16() && MergeableConst16Section)
493     return MergeableConst16Section;
494   if (Kind.isMergeableConst32() && MergeableConst32Section)
495     return MergeableConst32Section;
496   if (Kind.isReadOnly())
497     return ReadOnlySection;
498 
499   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
500   return DataRelROSection;
501 }
502 
503 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
504                                               bool IsCtor, unsigned Priority,
505                                               const MCSymbol *KeySym) {
506   std::string Name;
507   unsigned Type;
508   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
509   StringRef COMDAT = KeySym ? KeySym->getName() : "";
510 
511   if (KeySym)
512     Flags |= ELF::SHF_GROUP;
513 
514   if (UseInitArray) {
515     if (IsCtor) {
516       Type = ELF::SHT_INIT_ARRAY;
517       Name = ".init_array";
518     } else {
519       Type = ELF::SHT_FINI_ARRAY;
520       Name = ".fini_array";
521     }
522     if (Priority != 65535) {
523       Name += '.';
524       Name += utostr(Priority);
525     }
526   } else {
527     // The default scheme is .ctor / .dtor, so we have to invert the priority
528     // numbering.
529     if (IsCtor)
530       Name = ".ctors";
531     else
532       Name = ".dtors";
533     if (Priority != 65535) {
534       Name += '.';
535       Name += utostr(65535 - Priority);
536     }
537     Type = ELF::SHT_PROGBITS;
538   }
539 
540   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
541 }
542 
543 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
544     unsigned Priority, const MCSymbol *KeySym) const {
545   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
546                                   KeySym);
547 }
548 
549 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
550     unsigned Priority, const MCSymbol *KeySym) const {
551   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
552                                   KeySym);
553 }
554 
555 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
556     const GlobalValue *LHS, const GlobalValue *RHS,
557     const TargetMachine &TM) const {
558   // We may only use a PLT-relative relocation to refer to unnamed_addr
559   // functions.
560   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
561     return nullptr;
562 
563   // Basic sanity checks.
564   if (LHS->getType()->getPointerAddressSpace() != 0 ||
565       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
566       RHS->isThreadLocal())
567     return nullptr;
568 
569   return MCBinaryExpr::createSub(
570       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
571                               getContext()),
572       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
573 }
574 
575 void
576 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
577   UseInitArray = UseInitArray_;
578   MCContext &Ctx = getContext();
579   if (!UseInitArray) {
580     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
581                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
582 
583     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
584                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
585     return;
586   }
587 
588   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
589                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
590   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
591                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
592 }
593 
594 //===----------------------------------------------------------------------===//
595 //                                 MachO
596 //===----------------------------------------------------------------------===//
597 
598 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
599   : TargetLoweringObjectFile() {
600   SupportIndirectSymViaGOTPCRel = true;
601 }
602 
603 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
604                                                const TargetMachine &TM) {
605   TargetLoweringObjectFile::Initialize(Ctx, TM);
606   if (TM.getRelocationModel() == Reloc::Static) {
607     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
608                                             SectionKind::getData());
609     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
610                                             SectionKind::getData());
611   } else {
612     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
613                                             MachO::S_MOD_INIT_FUNC_POINTERS,
614                                             SectionKind::getData());
615     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
616                                             MachO::S_MOD_TERM_FUNC_POINTERS,
617                                             SectionKind::getData());
618   }
619 }
620 
621 /// emitModuleFlags - Perform code emission for module flags.
622 void TargetLoweringObjectFileMachO::emitModuleFlags(
623     MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
624     const TargetMachine &TM) const {
625   MDNode *LinkerOptions = nullptr;
626 
627   for (const auto &MFE : ModuleFlags) {
628     StringRef Key = MFE.Key->getString();
629     if (Key == "Linker Options")
630       LinkerOptions = cast<MDNode>(MFE.Val);
631   }
632 
633   // Emit the linker options if present.
634   if (LinkerOptions) {
635     for (const auto &Option : LinkerOptions->operands()) {
636       SmallVector<std::string, 4> StrOptions;
637       for (const auto &Piece : cast<MDNode>(Option)->operands())
638         StrOptions.push_back(cast<MDString>(Piece)->getString());
639       Streamer.EmitLinkerOptions(StrOptions);
640     }
641   }
642 
643   unsigned VersionVal = 0;
644   unsigned ImageInfoFlags = 0;
645   StringRef SectionVal;
646   GetObjCImageInfo(ModuleFlags, VersionVal, ImageInfoFlags, SectionVal);
647 
648   // The section is mandatory. If we don't have it, then we don't have GC info.
649   if (SectionVal.empty())
650     return;
651 
652   StringRef Segment, Section;
653   unsigned TAA = 0, StubSize = 0;
654   bool TAAParsed;
655   std::string ErrorCode =
656     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
657                                           TAA, TAAParsed, StubSize);
658   if (!ErrorCode.empty())
659     // If invalid, report the error with report_fatal_error.
660     report_fatal_error("Invalid section specifier '" + Section + "': " +
661                        ErrorCode + ".");
662 
663   // Get the section.
664   MCSectionMachO *S = getContext().getMachOSection(
665       Segment, Section, TAA, StubSize, SectionKind::getData());
666   Streamer.SwitchSection(S);
667   Streamer.EmitLabel(getContext().
668                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
669   Streamer.EmitIntValue(VersionVal, 4);
670   Streamer.EmitIntValue(ImageInfoFlags, 4);
671   Streamer.AddBlankLine();
672 }
673 
674 static void checkMachOComdat(const GlobalValue *GV) {
675   const Comdat *C = GV->getComdat();
676   if (!C)
677     return;
678 
679   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
680                      "' cannot be lowered.");
681 }
682 
683 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
684     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
685   // Parse the section specifier and create it if valid.
686   StringRef Segment, Section;
687   unsigned TAA = 0, StubSize = 0;
688   bool TAAParsed;
689 
690   checkMachOComdat(GO);
691 
692   std::string ErrorCode =
693     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
694                                           TAA, TAAParsed, StubSize);
695   if (!ErrorCode.empty()) {
696     // If invalid, report the error with report_fatal_error.
697     report_fatal_error("Global variable '" + GO->getName() +
698                        "' has an invalid section specifier '" +
699                        GO->getSection() + "': " + ErrorCode + ".");
700   }
701 
702   // Get the section.
703   MCSectionMachO *S =
704       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
705 
706   // If TAA wasn't set by ParseSectionSpecifier() above,
707   // use the value returned by getMachOSection() as a default.
708   if (!TAAParsed)
709     TAA = S->getTypeAndAttributes();
710 
711   // Okay, now that we got the section, verify that the TAA & StubSize agree.
712   // If the user declared multiple globals with different section flags, we need
713   // to reject it here.
714   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
715     // If invalid, report the error with report_fatal_error.
716     report_fatal_error("Global variable '" + GO->getName() +
717                        "' section type or attributes does not match previous"
718                        " section specifier");
719   }
720 
721   return S;
722 }
723 
724 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
725     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
726   checkMachOComdat(GO);
727 
728   // Handle thread local data.
729   if (Kind.isThreadBSS()) return TLSBSSSection;
730   if (Kind.isThreadData()) return TLSDataSection;
731 
732   if (Kind.isText())
733     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
734 
735   // If this is weak/linkonce, put this in a coalescable section, either in text
736   // or data depending on if it is writable.
737   if (GO->isWeakForLinker()) {
738     if (Kind.isReadOnly())
739       return ConstTextCoalSection;
740     return DataCoalSection;
741   }
742 
743   // FIXME: Alignment check should be handled by section classifier.
744   if (Kind.isMergeable1ByteCString() &&
745       GO->getParent()->getDataLayout().getPreferredAlignment(
746           cast<GlobalVariable>(GO)) < 32)
747     return CStringSection;
748 
749   // Do not put 16-bit arrays in the UString section if they have an
750   // externally visible label, this runs into issues with certain linker
751   // versions.
752   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
753       GO->getParent()->getDataLayout().getPreferredAlignment(
754           cast<GlobalVariable>(GO)) < 32)
755     return UStringSection;
756 
757   // With MachO only variables whose corresponding symbol starts with 'l' or
758   // 'L' can be merged, so we only try merging GVs with private linkage.
759   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
760     if (Kind.isMergeableConst4())
761       return FourByteConstantSection;
762     if (Kind.isMergeableConst8())
763       return EightByteConstantSection;
764     if (Kind.isMergeableConst16())
765       return SixteenByteConstantSection;
766   }
767 
768   // Otherwise, if it is readonly, but not something we can specially optimize,
769   // just drop it in .const.
770   if (Kind.isReadOnly())
771     return ReadOnlySection;
772 
773   // If this is marked const, put it into a const section.  But if the dynamic
774   // linker needs to write to it, put it in the data segment.
775   if (Kind.isReadOnlyWithRel())
776     return ConstDataSection;
777 
778   // Put zero initialized globals with strong external linkage in the
779   // DATA, __common section with the .zerofill directive.
780   if (Kind.isBSSExtern())
781     return DataCommonSection;
782 
783   // Put zero initialized globals with local linkage in __DATA,__bss directive
784   // with the .zerofill directive (aka .lcomm).
785   if (Kind.isBSSLocal())
786     return DataBSSSection;
787 
788   // Otherwise, just drop the variable in the normal data section.
789   return DataSection;
790 }
791 
792 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
793     const DataLayout &DL, SectionKind Kind, const Constant *C,
794     unsigned &Align) const {
795   // If this constant requires a relocation, we have to put it in the data
796   // segment, not in the text segment.
797   if (Kind.isData() || Kind.isReadOnlyWithRel())
798     return ConstDataSection;
799 
800   if (Kind.isMergeableConst4())
801     return FourByteConstantSection;
802   if (Kind.isMergeableConst8())
803     return EightByteConstantSection;
804   if (Kind.isMergeableConst16())
805     return SixteenByteConstantSection;
806   return ReadOnlySection;  // .const
807 }
808 
809 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
810     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
811     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
812   // The mach-o version of this method defaults to returning a stub reference.
813 
814   if (Encoding & DW_EH_PE_indirect) {
815     MachineModuleInfoMachO &MachOMMI =
816       MMI->getObjFileInfo<MachineModuleInfoMachO>();
817 
818     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
819 
820     // Add information about the stub reference to MachOMMI so that the stub
821     // gets emitted by the asmprinter.
822     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
823     if (!StubSym.getPointer()) {
824       MCSymbol *Sym = TM.getSymbol(GV);
825       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
826     }
827 
828     return TargetLoweringObjectFile::
829       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
830                         Encoding & ~DW_EH_PE_indirect, Streamer);
831   }
832 
833   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
834                                                            MMI, Streamer);
835 }
836 
837 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
838     const GlobalValue *GV, const TargetMachine &TM,
839     MachineModuleInfo *MMI) const {
840   // The mach-o version of this method defaults to returning a stub reference.
841   MachineModuleInfoMachO &MachOMMI =
842     MMI->getObjFileInfo<MachineModuleInfoMachO>();
843 
844   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
845 
846   // Add information about the stub reference to MachOMMI so that the stub
847   // gets emitted by the asmprinter.
848   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
849   if (!StubSym.getPointer()) {
850     MCSymbol *Sym = TM.getSymbol(GV);
851     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
852   }
853 
854   return SSym;
855 }
856 
857 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
858     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
859     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
860   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
861   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
862   // through a non_lazy_ptr stub instead. One advantage is that it allows the
863   // computation of deltas to final external symbols. Example:
864   //
865   //    _extgotequiv:
866   //       .long   _extfoo
867   //
868   //    _delta:
869   //       .long   _extgotequiv-_delta
870   //
871   // is transformed to:
872   //
873   //    _delta:
874   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
875   //
876   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
877   //    L_extfoo$non_lazy_ptr:
878   //       .indirect_symbol        _extfoo
879   //       .long   0
880   //
881   MachineModuleInfoMachO &MachOMMI =
882     MMI->getObjFileInfo<MachineModuleInfoMachO>();
883   MCContext &Ctx = getContext();
884 
885   // The offset must consider the original displacement from the base symbol
886   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
887   Offset = -MV.getConstant();
888   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
889 
890   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
891   // non_lazy_ptr stubs.
892   SmallString<128> Name;
893   StringRef Suffix = "$non_lazy_ptr";
894   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
895   Name += Sym->getName();
896   Name += Suffix;
897   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
898 
899   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
900   if (!StubSym.getPointer())
901     StubSym = MachineModuleInfoImpl::
902       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
903 
904   const MCExpr *BSymExpr =
905     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
906   const MCExpr *LHS =
907     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
908 
909   if (!Offset)
910     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
911 
912   const MCExpr *RHS =
913     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
914   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
915 }
916 
917 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
918                                const MCSection &Section) {
919   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
920     return true;
921 
922   // If it is not dead stripped, it is safe to use private labels.
923   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
924   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
925     return true;
926 
927   return false;
928 }
929 
930 void TargetLoweringObjectFileMachO::getNameWithPrefix(
931     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
932     const TargetMachine &TM) const {
933   bool CannotUsePrivateLabel = true;
934   if (auto *GO = GV->getBaseObject()) {
935     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
936     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
937     CannotUsePrivateLabel =
938         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
939   }
940   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
941 }
942 
943 //===----------------------------------------------------------------------===//
944 //                                  COFF
945 //===----------------------------------------------------------------------===//
946 
947 static unsigned
948 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
949   unsigned Flags = 0;
950   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
951 
952   if (K.isMetadata())
953     Flags |=
954       COFF::IMAGE_SCN_MEM_DISCARDABLE;
955   else if (K.isText())
956     Flags |=
957       COFF::IMAGE_SCN_MEM_EXECUTE |
958       COFF::IMAGE_SCN_MEM_READ |
959       COFF::IMAGE_SCN_CNT_CODE |
960       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
961   else if (K.isBSS())
962     Flags |=
963       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
964       COFF::IMAGE_SCN_MEM_READ |
965       COFF::IMAGE_SCN_MEM_WRITE;
966   else if (K.isThreadLocal())
967     Flags |=
968       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
969       COFF::IMAGE_SCN_MEM_READ |
970       COFF::IMAGE_SCN_MEM_WRITE;
971   else if (K.isReadOnly() || K.isReadOnlyWithRel())
972     Flags |=
973       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
974       COFF::IMAGE_SCN_MEM_READ;
975   else if (K.isWriteable())
976     Flags |=
977       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
978       COFF::IMAGE_SCN_MEM_READ |
979       COFF::IMAGE_SCN_MEM_WRITE;
980 
981   return Flags;
982 }
983 
984 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
985   const Comdat *C = GV->getComdat();
986   assert(C && "expected GV to have a Comdat!");
987 
988   StringRef ComdatGVName = C->getName();
989   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
990   if (!ComdatGV)
991     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
992                        "' does not exist.");
993 
994   if (ComdatGV->getComdat() != C)
995     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
996                        "' is not a key for its COMDAT.");
997 
998   return ComdatGV;
999 }
1000 
1001 static int getSelectionForCOFF(const GlobalValue *GV) {
1002   if (const Comdat *C = GV->getComdat()) {
1003     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1004     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1005       ComdatKey = GA->getBaseObject();
1006     if (ComdatKey == GV) {
1007       switch (C->getSelectionKind()) {
1008       case Comdat::Any:
1009         return COFF::IMAGE_COMDAT_SELECT_ANY;
1010       case Comdat::ExactMatch:
1011         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1012       case Comdat::Largest:
1013         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1014       case Comdat::NoDuplicates:
1015         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1016       case Comdat::SameSize:
1017         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1018       }
1019     } else {
1020       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1021     }
1022   }
1023   return 0;
1024 }
1025 
1026 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1027     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1028   int Selection = 0;
1029   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1030   StringRef Name = GO->getSection();
1031   StringRef COMDATSymName = "";
1032   if (GO->hasComdat()) {
1033     Selection = getSelectionForCOFF(GO);
1034     const GlobalValue *ComdatGV;
1035     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1036       ComdatGV = getComdatGVForCOFF(GO);
1037     else
1038       ComdatGV = GO;
1039 
1040     if (!ComdatGV->hasPrivateLinkage()) {
1041       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1042       COMDATSymName = Sym->getName();
1043       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1044     } else {
1045       Selection = 0;
1046     }
1047   }
1048 
1049   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1050                                      Selection);
1051 }
1052 
1053 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1054   if (Kind.isText())
1055     return ".text";
1056   if (Kind.isBSS())
1057     return ".bss";
1058   if (Kind.isThreadLocal())
1059     return ".tls$";
1060   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1061     return ".rdata";
1062   return ".data";
1063 }
1064 
1065 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1066     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1067   // If we have -ffunction-sections then we should emit the global value to a
1068   // uniqued section specifically for it.
1069   bool EmitUniquedSection;
1070   if (Kind.isText())
1071     EmitUniquedSection = TM.getFunctionSections();
1072   else
1073     EmitUniquedSection = TM.getDataSections();
1074 
1075   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1076     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1077     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1078 
1079     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1080     int Selection = getSelectionForCOFF(GO);
1081     if (!Selection)
1082       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1083     const GlobalValue *ComdatGV;
1084     if (GO->hasComdat())
1085       ComdatGV = getComdatGVForCOFF(GO);
1086     else
1087       ComdatGV = GO;
1088 
1089     unsigned UniqueID = MCContext::GenericSectionID;
1090     if (EmitUniquedSection)
1091       UniqueID = NextUniqueID++;
1092 
1093     if (!ComdatGV->hasPrivateLinkage()) {
1094       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1095       StringRef COMDATSymName = Sym->getName();
1096       return getContext().getCOFFSection(Name, Characteristics, Kind,
1097                                          COMDATSymName, Selection, UniqueID);
1098     } else {
1099       SmallString<256> TmpData;
1100       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1101       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1102                                          Selection, UniqueID);
1103     }
1104   }
1105 
1106   if (Kind.isText())
1107     return TextSection;
1108 
1109   if (Kind.isThreadLocal())
1110     return TLSDataSection;
1111 
1112   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1113     return ReadOnlySection;
1114 
1115   // Note: we claim that common symbols are put in BSSSection, but they are
1116   // really emitted with the magic .comm directive, which creates a symbol table
1117   // entry but not a section.
1118   if (Kind.isBSS() || Kind.isCommon())
1119     return BSSSection;
1120 
1121   return DataSection;
1122 }
1123 
1124 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1125     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1126     const TargetMachine &TM) const {
1127   bool CannotUsePrivateLabel = false;
1128   if (GV->hasPrivateLinkage() &&
1129       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1130        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1131     CannotUsePrivateLabel = true;
1132 
1133   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1134 }
1135 
1136 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1137     const Function &F, const TargetMachine &TM) const {
1138   // If the function can be removed, produce a unique section so that
1139   // the table doesn't prevent the removal.
1140   const Comdat *C = F.getComdat();
1141   bool EmitUniqueSection = TM.getFunctionSections() || C;
1142   if (!EmitUniqueSection)
1143     return ReadOnlySection;
1144 
1145   // FIXME: we should produce a symbol for F instead.
1146   if (F.hasPrivateLinkage())
1147     return ReadOnlySection;
1148 
1149   MCSymbol *Sym = TM.getSymbol(&F);
1150   StringRef COMDATSymName = Sym->getName();
1151 
1152   SectionKind Kind = SectionKind::getReadOnly();
1153   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1154   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1155   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1156   unsigned UniqueID = NextUniqueID++;
1157 
1158   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1159                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1160 }
1161 
1162 void TargetLoweringObjectFileCOFF::emitModuleFlags(
1163     MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1164     const TargetMachine &TM) const {
1165   MDNode *LinkerOptions = nullptr;
1166 
1167   for (const auto &MFE : ModuleFlags) {
1168     StringRef Key = MFE.Key->getString();
1169     if (Key == "Linker Options")
1170       LinkerOptions = cast<MDNode>(MFE.Val);
1171   }
1172 
1173   if (LinkerOptions) {
1174     // Emit the linker options to the linker .drectve section.  According to the
1175     // spec, this section is a space-separated string containing flags for
1176     // linker.
1177     MCSection *Sec = getDrectveSection();
1178     Streamer.SwitchSection(Sec);
1179     for (const auto &Option : LinkerOptions->operands()) {
1180       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1181         // Lead with a space for consistency with our dllexport implementation.
1182         std::string Directive(" ");
1183         Directive.append(cast<MDString>(Piece)->getString());
1184         Streamer.EmitBytes(Directive);
1185       }
1186     }
1187   }
1188 
1189   unsigned Version = 0;
1190   unsigned Flags = 0;
1191   StringRef Section;
1192 
1193   GetObjCImageInfo(ModuleFlags, Version, Flags, Section);
1194   if (Section.empty())
1195     return;
1196 
1197   auto &C = getContext();
1198   auto *S = C.getCOFFSection(
1199       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1200       SectionKind::getReadOnly());
1201   Streamer.SwitchSection(S);
1202   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1203   Streamer.EmitIntValue(Version, 4);
1204   Streamer.EmitIntValue(Flags, 4);
1205   Streamer.AddBlankLine();
1206 }
1207 
1208 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1209                                               const TargetMachine &TM) {
1210   TargetLoweringObjectFile::Initialize(Ctx, TM);
1211   const Triple &T = TM.getTargetTriple();
1212   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1213     StaticCtorSection =
1214         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1215                                            COFF::IMAGE_SCN_MEM_READ,
1216                            SectionKind::getReadOnly());
1217     StaticDtorSection =
1218         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1219                                            COFF::IMAGE_SCN_MEM_READ,
1220                            SectionKind::getReadOnly());
1221   } else {
1222     StaticCtorSection = Ctx.getCOFFSection(
1223         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1224                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1225         SectionKind::getData());
1226     StaticDtorSection = Ctx.getCOFFSection(
1227         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1228                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1229         SectionKind::getData());
1230   }
1231 }
1232 
1233 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1234     unsigned Priority, const MCSymbol *KeySym) const {
1235   return getContext().getAssociativeCOFFSection(
1236       cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1237 }
1238 
1239 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1240     unsigned Priority, const MCSymbol *KeySym) const {
1241   return getContext().getAssociativeCOFFSection(
1242       cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1243 }
1244 
1245 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1246     raw_ostream &OS, const GlobalValue *GV) const {
1247   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1248 }
1249 
1250 //===----------------------------------------------------------------------===//
1251 //                                  Wasm
1252 //===----------------------------------------------------------------------===//
1253 
1254 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1255   const Comdat *C = GV->getComdat();
1256   if (!C)
1257     return nullptr;
1258 
1259   if (C->getSelectionKind() != Comdat::Any)
1260     report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1261                        C->getName() + "' cannot be lowered.");
1262 
1263   return C;
1264 }
1265 
1266 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1267     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1268   llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1269   return nullptr;
1270 }
1271 
1272 static MCSectionWasm *
1273 selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
1274                            SectionKind Kind, Mangler &Mang,
1275                            const TargetMachine &TM, bool EmitUniqueSection,
1276                            unsigned Flags, unsigned *NextUniqueID) {
1277   StringRef Group = "";
1278   if (getWasmComdat(GO))
1279     llvm_unreachable("comdat not yet supported for wasm");
1280 
1281   bool UniqueSectionNames = TM.getUniqueSectionNames();
1282   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1283 
1284   if (const auto *F = dyn_cast<Function>(GO)) {
1285     const auto &OptionalPrefix = F->getSectionPrefix();
1286     if (OptionalPrefix)
1287       Name += *OptionalPrefix;
1288   }
1289 
1290   if (EmitUniqueSection && UniqueSectionNames) {
1291     Name.push_back('.');
1292     TM.getNameWithPrefix(Name, GO, Mang, true);
1293   }
1294   unsigned UniqueID = MCContext::GenericSectionID;
1295   if (EmitUniqueSection && !UniqueSectionNames) {
1296     UniqueID = *NextUniqueID;
1297     (*NextUniqueID)++;
1298   }
1299   return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1300                             Group, UniqueID);
1301 }
1302 
1303 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1304     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1305 
1306   if (Kind.isCommon())
1307     report_fatal_error("mergable sections not supported yet on wasm");
1308 
1309   // If we have -ffunction-section or -fdata-section then we should emit the
1310   // global value to a uniqued section specifically for it.
1311   bool EmitUniqueSection = false;
1312   if (Kind.isText())
1313     EmitUniqueSection = TM.getFunctionSections();
1314   else
1315     EmitUniqueSection = TM.getDataSections();
1316   EmitUniqueSection |= GO->hasComdat();
1317 
1318   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1319                                     EmitUniqueSection, /*Flags=*/0,
1320                                     &NextUniqueID);
1321 }
1322 
1323 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1324     bool UsesLabelDifference, const Function &F) const {
1325   // We can always create relative relocations, so use another section
1326   // that can be marked non-executable.
1327   return false;
1328 }
1329 
1330 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1331     const GlobalValue *LHS, const GlobalValue *RHS,
1332     const TargetMachine &TM) const {
1333   // We may only use a PLT-relative relocation to refer to unnamed_addr
1334   // functions.
1335   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1336     return nullptr;
1337 
1338   // Basic sanity checks.
1339   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1340       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1341       RHS->isThreadLocal())
1342     return nullptr;
1343 
1344   return MCBinaryExpr::createSub(
1345       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1346                               getContext()),
1347       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1348 }
1349 
1350 void
1351 TargetLoweringObjectFileWasm::InitializeWasm() {
1352   // TODO: Initialize StaticCtorSection and StaticDtorSection.
1353 }
1354