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