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