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