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