LLVM  6.0.0svn
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
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 
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"
23 #include "llvm/BinaryFormat/ELF.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"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
58 #include <cassert>
59 #include <string>
60 
61 using namespace llvm;
62 using namespace dwarf;
63 
64 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
65  StringRef &Section) {
67  M.getModuleFlagsMetadata(ModuleFlags);
68 
69  for (const auto &MFE: ModuleFlags) {
70  // Ignore flags with 'Require' behaviour.
71  if (MFE.Behavior == Module::Require)
72  continue;
73 
74  StringRef Key = MFE.Key->getString();
75  if (Key == "Objective-C Image Info Version") {
76  Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
77  } else if (Key == "Objective-C Garbage Collection" ||
78  Key == "Objective-C GC Only" ||
79  Key == "Objective-C Is Simulated" ||
80  Key == "Objective-C Class Properties" ||
81  Key == "Objective-C Image Swift Version") {
82  Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
83  } else if (Key == "Objective-C Image Info Section") {
84  Section = cast<MDString>(MFE.Val)->getString();
85  }
86  }
87 }
88 
89 //===----------------------------------------------------------------------===//
90 // ELF
91 //===----------------------------------------------------------------------===//
92 
94  MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
95  unsigned Version = 0;
96  unsigned Flags = 0;
98 
99  GetObjCImageInfo(M, Version, Flags, Section);
100  if (Section.empty())
101  return;
102 
103  auto &C = getContext();
104  auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
105  Streamer.SwitchSection(S);
106  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
107  Streamer.EmitIntValue(Version, 4);
108  Streamer.EmitIntValue(Flags, 4);
109  Streamer.AddBlankLine();
110 }
111 
113  const GlobalValue *GV, const TargetMachine &TM,
114  MachineModuleInfo *MMI) const {
115  unsigned Encoding = getPersonalityEncoding();
116  if ((Encoding & 0x80) == DW_EH_PE_indirect)
117  return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
118  TM.getSymbol(GV)->getName());
119  if ((Encoding & 0x70) == DW_EH_PE_absptr)
120  return TM.getSymbol(GV);
121  report_fatal_error("We do not support this DWARF encoding yet!");
122 }
123 
125  MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
126  SmallString<64> NameData("DW.ref.");
127  NameData += Sym->getName();
128  MCSymbolELF *Label =
129  cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
130  Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
131  Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
132  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
133  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
134  ELF::SHT_PROGBITS, Flags, 0);
135  unsigned Size = DL.getPointerSize();
136  Streamer.SwitchSection(Sec);
138  Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
139  const MCExpr *E = MCConstantExpr::create(Size, getContext());
140  Streamer.emitELFSize(Label, E);
141  Streamer.EmitLabel(Label);
142 
143  Streamer.EmitSymbolValue(Sym, Size);
144 }
145 
147  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
148  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
149  if (Encoding & DW_EH_PE_indirect) {
151 
152  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
153 
154  // Add information about the stub reference to ELFMMI so that the stub
155  // gets emitted by the asmprinter.
156  MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
157  if (!StubSym.getPointer()) {
158  MCSymbol *Sym = TM.getSymbol(GV);
160  }
161 
163  getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
164  Encoding & ~DW_EH_PE_indirect, Streamer);
165  }
166 
168  MMI, Streamer);
169 }
170 
172  // N.B.: The defaults used in here are no the same ones used in MC.
173  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
174  // both gas and MC will produce a section with no flags. Given
175  // section(".eh_frame") gcc will produce:
176  //
177  // .section .eh_frame,"a",@progbits
178 
179  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
180  /*AddSegmentInfo=*/false))
181  return SectionKind::getMetadata();
182 
183  if (Name.empty() || Name[0] != '.') return K;
184 
185  // Some lame default implementation based on some magic section names.
186  if (Name == ".bss" ||
187  Name.startswith(".bss.") ||
188  Name.startswith(".gnu.linkonce.b.") ||
189  Name.startswith(".llvm.linkonce.b.") ||
190  Name == ".sbss" ||
191  Name.startswith(".sbss.") ||
192  Name.startswith(".gnu.linkonce.sb.") ||
193  Name.startswith(".llvm.linkonce.sb."))
194  return SectionKind::getBSS();
195 
196  if (Name == ".tdata" ||
197  Name.startswith(".tdata.") ||
198  Name.startswith(".gnu.linkonce.td.") ||
199  Name.startswith(".llvm.linkonce.td."))
201 
202  if (Name == ".tbss" ||
203  Name.startswith(".tbss.") ||
204  Name.startswith(".gnu.linkonce.tb.") ||
205  Name.startswith(".llvm.linkonce.tb."))
206  return SectionKind::getThreadBSS();
207 
208  return K;
209 }
210 
212  // Use SHT_NOTE for section whose name starts with ".note" to allow
213  // emitting ELF notes from C variable declaration.
214  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
215  if (Name.startswith(".note"))
216  return ELF::SHT_NOTE;
217 
218  if (Name == ".init_array")
219  return ELF::SHT_INIT_ARRAY;
220 
221  if (Name == ".fini_array")
222  return ELF::SHT_FINI_ARRAY;
223 
224  if (Name == ".preinit_array")
225  return ELF::SHT_PREINIT_ARRAY;
226 
227  if (K.isBSS() || K.isThreadBSS())
228  return ELF::SHT_NOBITS;
229 
230  return ELF::SHT_PROGBITS;
231 }
232 
233 static unsigned getELFSectionFlags(SectionKind K) {
234  unsigned Flags = 0;
235 
236  if (!K.isMetadata())
237  Flags |= ELF::SHF_ALLOC;
238 
239  if (K.isText())
240  Flags |= ELF::SHF_EXECINSTR;
241 
242  if (K.isExecuteOnly())
243  Flags |= ELF::SHF_ARM_PURECODE;
244 
245  if (K.isWriteable())
246  Flags |= ELF::SHF_WRITE;
247 
248  if (K.isThreadLocal())
249  Flags |= ELF::SHF_TLS;
250 
251  if (K.isMergeableCString() || K.isMergeableConst())
252  Flags |= ELF::SHF_MERGE;
253 
254  if (K.isMergeableCString())
255  Flags |= ELF::SHF_STRINGS;
256 
257  return Flags;
258 }
259 
260 static const Comdat *getELFComdat(const GlobalValue *GV) {
261  const Comdat *C = GV->getComdat();
262  if (!C)
263  return nullptr;
264 
265  if (C->getSelectionKind() != Comdat::Any)
266  report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
267  C->getName() + "' cannot be lowered.");
268 
269  return C;
270 }
271 
273  const TargetMachine &TM) {
275  if (!MD)
276  return nullptr;
277 
278  const MDOperand &Op = MD->getOperand(0);
279  if (!Op.get())
280  return nullptr;
281 
282  auto *VM = dyn_cast<ValueAsMetadata>(Op);
283  if (!VM)
284  report_fatal_error("MD_associated operand is not ValueAsMetadata");
285 
286  GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
287  return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
288 }
289 
291  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
293 
294  // Check if '#pragma clang section' name is applicable.
295  // Note that pragma directive overrides -ffunction-section, -fdata-section
296  // and so section name is exactly as user specified and not uniqued.
297  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
298  if (GV && GV->hasImplicitSection()) {
299  auto Attrs = GV->getAttributes();
300  if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
301  SectionName = Attrs.getAttribute("bss-section").getValueAsString();
302  } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
303  SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
304  } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
305  SectionName = Attrs.getAttribute("data-section").getValueAsString();
306  }
307  }
308  const Function *F = dyn_cast<Function>(GO);
309  if (F && F->hasFnAttribute("implicit-section-name")) {
310  SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
311  }
312 
313  // Infer section flags from the section name if we can.
314  Kind = getELFKindForNamedSection(SectionName, Kind);
315 
316  StringRef Group = "";
317  unsigned Flags = getELFSectionFlags(Kind);
318  if (const Comdat *C = getELFComdat(GO)) {
319  Group = C->getName();
320  Flags |= ELF::SHF_GROUP;
321  }
322 
323  // A section can have at most one associated section. Put each global with
324  // MD_associated in a unique section.
325  unsigned UniqueID = MCContext::GenericSectionID;
326  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
327  if (AssociatedSymbol) {
328  UniqueID = NextUniqueID++;
329  Flags |= ELF::SHF_LINK_ORDER;
330  }
331 
332  MCSectionELF *Section = getContext().getELFSection(
333  SectionName, getELFSectionType(SectionName, Kind), Flags,
334  /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
335  // Make sure that we did not get some other section with incompatible sh_link.
336  // This should not be possible due to UniqueID code above.
337  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
338  return Section;
339 }
340 
341 /// Return the section prefix name used by options FunctionsSections and
342 /// DataSections.
344  if (Kind.isText())
345  return ".text";
346  if (Kind.isReadOnly())
347  return ".rodata";
348  if (Kind.isBSS())
349  return ".bss";
350  if (Kind.isThreadData())
351  return ".tdata";
352  if (Kind.isThreadBSS())
353  return ".tbss";
354  if (Kind.isData())
355  return ".data";
356  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
357  return ".data.rel.ro";
358 }
359 
361  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
362  const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
363  unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
364  unsigned EntrySize = 0;
365  if (Kind.isMergeableCString()) {
366  if (Kind.isMergeable2ByteCString()) {
367  EntrySize = 2;
368  } else if (Kind.isMergeable4ByteCString()) {
369  EntrySize = 4;
370  } else {
371  EntrySize = 1;
372  assert(Kind.isMergeable1ByteCString() && "unknown string width");
373  }
374  } else if (Kind.isMergeableConst()) {
375  if (Kind.isMergeableConst4()) {
376  EntrySize = 4;
377  } else if (Kind.isMergeableConst8()) {
378  EntrySize = 8;
379  } else if (Kind.isMergeableConst16()) {
380  EntrySize = 16;
381  } else {
382  assert(Kind.isMergeableConst32() && "unknown data width");
383  EntrySize = 32;
384  }
385  }
386 
387  StringRef Group = "";
388  if (const Comdat *C = getELFComdat(GO)) {
389  Flags |= ELF::SHF_GROUP;
390  Group = C->getName();
391  }
392 
395  if (Kind.isMergeableCString()) {
396  // We also need alignment here.
397  // FIXME: this is getting the alignment of the character, not the
398  // alignment of the global!
400  cast<GlobalVariable>(GO));
401 
402  std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
403  Name = SizeSpec + utostr(Align);
404  } else if (Kind.isMergeableConst()) {
405  Name = ".rodata.cst";
406  Name += utostr(EntrySize);
407  } else {
408  Name = getSectionPrefixForGlobal(Kind);
409  }
410 
411  if (const auto *F = dyn_cast<Function>(GO)) {
412  const auto &OptionalPrefix = F->getSectionPrefix();
413  if (OptionalPrefix)
414  Name += *OptionalPrefix;
415  }
416 
417  if (EmitUniqueSection && UniqueSectionNames) {
418  Name.push_back('.');
419  TM.getNameWithPrefix(Name, GO, Mang, true);
420  }
421  unsigned UniqueID = MCContext::GenericSectionID;
422  if (EmitUniqueSection && !UniqueSectionNames) {
423  UniqueID = *NextUniqueID;
424  (*NextUniqueID)++;
425  }
426  // Use 0 as the unique ID for execute-only text
427  if (Kind.isExecuteOnly())
428  UniqueID = 0;
429  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
430  EntrySize, Group, UniqueID, AssociatedSymbol);
431 }
432 
434  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
435  unsigned Flags = getELFSectionFlags(Kind);
436 
437  // If we have -ffunction-section or -fdata-section then we should emit the
438  // global value to a uniqued section specifically for it.
439  bool EmitUniqueSection = false;
440  if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
441  if (Kind.isText())
442  EmitUniqueSection = TM.getFunctionSections();
443  else
444  EmitUniqueSection = TM.getDataSections();
445  }
446  EmitUniqueSection |= GO->hasComdat();
447 
448  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
449  if (AssociatedSymbol) {
450  EmitUniqueSection = true;
451  Flags |= ELF::SHF_LINK_ORDER;
452  }
453 
455  getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
456  &NextUniqueID, AssociatedSymbol);
457  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
458  return Section;
459 }
460 
462  const Function &F, const TargetMachine &TM) const {
463  // If the function can be removed, produce a unique section so that
464  // the table doesn't prevent the removal.
465  const Comdat *C = F.getComdat();
466  bool EmitUniqueSection = TM.getFunctionSections() || C;
467  if (!EmitUniqueSection)
468  return ReadOnlySection;
469 
470  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
471  getMangler(), TM, EmitUniqueSection,
472  ELF::SHF_ALLOC, &NextUniqueID,
473  /* AssociatedSymbol */ nullptr);
474 }
475 
477  bool UsesLabelDifference, const Function &F) const {
478  // We can always create relative relocations, so use another section
479  // that can be marked non-executable.
480  return false;
481 }
482 
483 /// Given a mergeable constant with the specified size and relocation
484 /// information, return a section that it should be placed in.
486  const DataLayout &DL, SectionKind Kind, const Constant *C,
487  unsigned &Align) const {
488  if (Kind.isMergeableConst4() && MergeableConst4Section)
489  return MergeableConst4Section;
490  if (Kind.isMergeableConst8() && MergeableConst8Section)
491  return MergeableConst8Section;
492  if (Kind.isMergeableConst16() && MergeableConst16Section)
493  return MergeableConst16Section;
494  if (Kind.isMergeableConst32() && MergeableConst32Section)
495  return MergeableConst32Section;
496  if (Kind.isReadOnly())
497  return ReadOnlySection;
498 
499  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
500  return DataRelROSection;
501 }
502 
503 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
504  bool IsCtor, unsigned Priority,
505  const MCSymbol *KeySym) {
506  std::string Name;
507  unsigned Type;
508  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
509  StringRef COMDAT = KeySym ? KeySym->getName() : "";
510 
511  if (KeySym)
512  Flags |= ELF::SHF_GROUP;
513 
514  if (UseInitArray) {
515  if (IsCtor) {
516  Type = ELF::SHT_INIT_ARRAY;
517  Name = ".init_array";
518  } else {
519  Type = ELF::SHT_FINI_ARRAY;
520  Name = ".fini_array";
521  }
522  if (Priority != 65535) {
523  Name += '.';
524  Name += utostr(Priority);
525  }
526  } else {
527  // The default scheme is .ctor / .dtor, so we have to invert the priority
528  // numbering.
529  if (IsCtor)
530  Name = ".ctors";
531  else
532  Name = ".dtors";
533  if (Priority != 65535) {
534  Name += '.';
535  Name += utostr(65535 - Priority);
536  }
537  Type = ELF::SHT_PROGBITS;
538  }
539 
540  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
541 }
542 
544  unsigned Priority, const MCSymbol *KeySym) const {
545  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
546  KeySym);
547 }
548 
550  unsigned Priority, const MCSymbol *KeySym) const {
551  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
552  KeySym);
553 }
554 
556  const GlobalValue *LHS, const GlobalValue *RHS,
557  const TargetMachine &TM) const {
558  // We may only use a PLT-relative relocation to refer to unnamed_addr
559  // functions.
560  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
561  return nullptr;
562 
563  // Basic sanity checks.
564  if (LHS->getType()->getPointerAddressSpace() != 0 ||
565  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
566  RHS->isThreadLocal())
567  return nullptr;
568 
570  MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
571  getContext()),
572  MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
573 }
574 
575 void
577  UseInitArray = UseInitArray_;
578  MCContext &Ctx = getContext();
579  if (!UseInitArray) {
580  StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
582 
583  StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
585  return;
586  }
587 
588  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
590  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
592 }
593 
594 //===----------------------------------------------------------------------===//
595 // MachO
596 //===----------------------------------------------------------------------===//
597 
601 }
602 
604  const TargetMachine &TM) {
606  if (TM.getRelocationModel() == Reloc::Static) {
607  StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
609  StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
611  } else {
612  StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
615  StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
618  }
619 }
620 
622  MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
623  // Emit the linker options if present.
624  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
625  for (const auto &Option : LinkerOptions->operands()) {
626  SmallVector<std::string, 4> StrOptions;
627  for (const auto &Piece : cast<MDNode>(Option)->operands())
628  StrOptions.push_back(cast<MDString>(Piece)->getString());
629  Streamer.EmitLinkerOptions(StrOptions);
630  }
631  }
632 
633  unsigned VersionVal = 0;
634  unsigned ImageInfoFlags = 0;
635  StringRef SectionVal;
636 
637  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
638 
639  // The section is mandatory. If we don't have it, then we don't have GC info.
640  if (SectionVal.empty())
641  return;
642 
643  StringRef Segment, Section;
644  unsigned TAA = 0, StubSize = 0;
645  bool TAAParsed;
646  std::string ErrorCode =
647  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
648  TAA, TAAParsed, StubSize);
649  if (!ErrorCode.empty())
650  // If invalid, report the error with report_fatal_error.
651  report_fatal_error("Invalid section specifier '" + Section + "': " +
652  ErrorCode + ".");
653 
654  // Get the section.
656  Segment, Section, TAA, StubSize, SectionKind::getData());
657  Streamer.SwitchSection(S);
658  Streamer.EmitLabel(getContext().
659  getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
660  Streamer.EmitIntValue(VersionVal, 4);
661  Streamer.EmitIntValue(ImageInfoFlags, 4);
662  Streamer.AddBlankLine();
663 }
664 
665 static void checkMachOComdat(const GlobalValue *GV) {
666  const Comdat *C = GV->getComdat();
667  if (!C)
668  return;
669 
670  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
671  "' cannot be lowered.");
672 }
673 
675  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
676  // Parse the section specifier and create it if valid.
677  StringRef Segment, Section;
678  unsigned TAA = 0, StubSize = 0;
679  bool TAAParsed;
680 
681  checkMachOComdat(GO);
682 
683  std::string ErrorCode =
685  TAA, TAAParsed, StubSize);
686  if (!ErrorCode.empty()) {
687  // If invalid, report the error with report_fatal_error.
688  report_fatal_error("Global variable '" + GO->getName() +
689  "' has an invalid section specifier '" +
690  GO->getSection() + "': " + ErrorCode + ".");
691  }
692 
693  // Get the section.
694  MCSectionMachO *S =
695  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
696 
697  // If TAA wasn't set by ParseSectionSpecifier() above,
698  // use the value returned by getMachOSection() as a default.
699  if (!TAAParsed)
700  TAA = S->getTypeAndAttributes();
701 
702  // Okay, now that we got the section, verify that the TAA & StubSize agree.
703  // If the user declared multiple globals with different section flags, we need
704  // to reject it here.
705  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
706  // If invalid, report the error with report_fatal_error.
707  report_fatal_error("Global variable '" + GO->getName() +
708  "' section type or attributes does not match previous"
709  " section specifier");
710  }
711 
712  return S;
713 }
714 
716  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
717  checkMachOComdat(GO);
718 
719  // Handle thread local data.
720  if (Kind.isThreadBSS()) return TLSBSSSection;
721  if (Kind.isThreadData()) return TLSDataSection;
722 
723  if (Kind.isText())
725 
726  // If this is weak/linkonce, put this in a coalescable section, either in text
727  // or data depending on if it is writable.
728  if (GO->isWeakForLinker()) {
729  if (Kind.isReadOnly())
730  return ConstTextCoalSection;
731  return DataCoalSection;
732  }
733 
734  // FIXME: Alignment check should be handled by section classifier.
735  if (Kind.isMergeable1ByteCString() &&
737  cast<GlobalVariable>(GO)) < 32)
738  return CStringSection;
739 
740  // Do not put 16-bit arrays in the UString section if they have an
741  // externally visible label, this runs into issues with certain linker
742  // versions.
743  if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
745  cast<GlobalVariable>(GO)) < 32)
746  return UStringSection;
747 
748  // With MachO only variables whose corresponding symbol starts with 'l' or
749  // 'L' can be merged, so we only try merging GVs with private linkage.
750  if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
751  if (Kind.isMergeableConst4())
753  if (Kind.isMergeableConst8())
755  if (Kind.isMergeableConst16())
757  }
758 
759  // Otherwise, if it is readonly, but not something we can specially optimize,
760  // just drop it in .const.
761  if (Kind.isReadOnly())
762  return ReadOnlySection;
763 
764  // If this is marked const, put it into a const section. But if the dynamic
765  // linker needs to write to it, put it in the data segment.
766  if (Kind.isReadOnlyWithRel())
767  return ConstDataSection;
768 
769  // Put zero initialized globals with strong external linkage in the
770  // DATA, __common section with the .zerofill directive.
771  if (Kind.isBSSExtern())
772  return DataCommonSection;
773 
774  // Put zero initialized globals with local linkage in __DATA,__bss directive
775  // with the .zerofill directive (aka .lcomm).
776  if (Kind.isBSSLocal())
777  return DataBSSSection;
778 
779  // Otherwise, just drop the variable in the normal data section.
780  return DataSection;
781 }
782 
784  const DataLayout &DL, SectionKind Kind, const Constant *C,
785  unsigned &Align) const {
786  // If this constant requires a relocation, we have to put it in the data
787  // segment, not in the text segment.
788  if (Kind.isData() || Kind.isReadOnlyWithRel())
789  return ConstDataSection;
790 
791  if (Kind.isMergeableConst4())
793  if (Kind.isMergeableConst8())
795  if (Kind.isMergeableConst16())
797  return ReadOnlySection; // .const
798 }
799 
801  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
802  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
803  // The mach-o version of this method defaults to returning a stub reference.
804 
805  if (Encoding & DW_EH_PE_indirect) {
806  MachineModuleInfoMachO &MachOMMI =
808 
809  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
810 
811  // Add information about the stub reference to MachOMMI so that the stub
812  // gets emitted by the asmprinter.
813  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
814  if (!StubSym.getPointer()) {
815  MCSymbol *Sym = TM.getSymbol(GV);
817  }
818 
821  Encoding & ~DW_EH_PE_indirect, Streamer);
822  }
823 
825  MMI, Streamer);
826 }
827 
829  const GlobalValue *GV, const TargetMachine &TM,
830  MachineModuleInfo *MMI) const {
831  // The mach-o version of this method defaults to returning a stub reference.
832  MachineModuleInfoMachO &MachOMMI =
834 
835  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
836 
837  // Add information about the stub reference to MachOMMI so that the stub
838  // gets emitted by the asmprinter.
839  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
840  if (!StubSym.getPointer()) {
841  MCSymbol *Sym = TM.getSymbol(GV);
843  }
844 
845  return SSym;
846 }
847 
849  const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
850  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
851  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
852  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
853  // through a non_lazy_ptr stub instead. One advantage is that it allows the
854  // computation of deltas to final external symbols. Example:
855  //
856  // _extgotequiv:
857  // .long _extfoo
858  //
859  // _delta:
860  // .long _extgotequiv-_delta
861  //
862  // is transformed to:
863  //
864  // _delta:
865  // .long L_extfoo$non_lazy_ptr-(_delta+0)
866  //
867  // .section __IMPORT,__pointers,non_lazy_symbol_pointers
868  // L_extfoo$non_lazy_ptr:
869  // .indirect_symbol _extfoo
870  // .long 0
871  //
872  MachineModuleInfoMachO &MachOMMI =
874  MCContext &Ctx = getContext();
875 
876  // The offset must consider the original displacement from the base symbol
877  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
878  Offset = -MV.getConstant();
879  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
880 
881  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
882  // non_lazy_ptr stubs.
884  StringRef Suffix = "$non_lazy_ptr";
885  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
886  Name += Sym->getName();
887  Name += Suffix;
888  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
889 
890  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
891  if (!StubSym.getPointer())
892  StubSym = MachineModuleInfoImpl::
893  StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
894 
895  const MCExpr *BSymExpr =
897  const MCExpr *LHS =
899 
900  if (!Offset)
901  return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
902 
903  const MCExpr *RHS =
904  MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
905  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
906 }
907 
908 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
909  const MCSection &Section) {
910  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
911  return true;
912 
913  // If it is not dead stripped, it is safe to use private labels.
914  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
916  return true;
917 
918  return false;
919 }
920 
922  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
923  const TargetMachine &TM) const {
924  bool CannotUsePrivateLabel = true;
925  if (auto *GO = GV->getBaseObject()) {
927  const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
928  CannotUsePrivateLabel =
929  !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
930  }
931  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
932 }
933 
934 //===----------------------------------------------------------------------===//
935 // COFF
936 //===----------------------------------------------------------------------===//
937 
938 static unsigned
940  unsigned Flags = 0;
941  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
942 
943  if (K.isMetadata())
944  Flags |=
946  else if (K.isText())
947  Flags |=
952  else if (K.isBSS())
953  Flags |=
957  else if (K.isThreadLocal())
958  Flags |=
962  else if (K.isReadOnly() || K.isReadOnlyWithRel())
963  Flags |=
966  else if (K.isWriteable())
967  Flags |=
971 
972  return Flags;
973 }
974 
975 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
976  const Comdat *C = GV->getComdat();
977  assert(C && "expected GV to have a Comdat!");
978 
979  StringRef ComdatGVName = C->getName();
980  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
981  if (!ComdatGV)
982  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
983  "' does not exist.");
984 
985  if (ComdatGV->getComdat() != C)
986  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
987  "' is not a key for its COMDAT.");
988 
989  return ComdatGV;
990 }
991 
992 static int getSelectionForCOFF(const GlobalValue *GV) {
993  if (const Comdat *C = GV->getComdat()) {
994  const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
995  if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
996  ComdatKey = GA->getBaseObject();
997  if (ComdatKey == GV) {
998  switch (C->getSelectionKind()) {
999  case Comdat::Any:
1001  case Comdat::ExactMatch:
1003  case Comdat::Largest:
1005  case Comdat::NoDuplicates:
1007  case Comdat::SameSize:
1009  }
1010  } else {
1012  }
1013  }
1014  return 0;
1015 }
1016 
1018  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1019  int Selection = 0;
1020  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1021  StringRef Name = GO->getSection();
1022  StringRef COMDATSymName = "";
1023  if (GO->hasComdat()) {
1024  Selection = getSelectionForCOFF(GO);
1025  const GlobalValue *ComdatGV;
1026  if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1027  ComdatGV = getComdatGVForCOFF(GO);
1028  else
1029  ComdatGV = GO;
1030 
1031  if (!ComdatGV->hasPrivateLinkage()) {
1032  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1033  COMDATSymName = Sym->getName();
1034  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1035  } else {
1036  Selection = 0;
1037  }
1038  }
1039 
1040  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1041  Selection);
1042 }
1043 
1045  if (Kind.isText())
1046  return ".text";
1047  if (Kind.isBSS())
1048  return ".bss";
1049  if (Kind.isThreadLocal())
1050  return ".tls$";
1051  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1052  return ".rdata";
1053  return ".data";
1054 }
1055 
1057  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1058  // If we have -ffunction-sections then we should emit the global value to a
1059  // uniqued section specifically for it.
1060  bool EmitUniquedSection;
1061  if (Kind.isText())
1062  EmitUniquedSection = TM.getFunctionSections();
1063  else
1064  EmitUniquedSection = TM.getDataSections();
1065 
1066  if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1067  const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1068  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1069 
1070  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1071  int Selection = getSelectionForCOFF(GO);
1072  if (!Selection)
1074  const GlobalValue *ComdatGV;
1075  if (GO->hasComdat())
1076  ComdatGV = getComdatGVForCOFF(GO);
1077  else
1078  ComdatGV = GO;
1079 
1080  unsigned UniqueID = MCContext::GenericSectionID;
1081  if (EmitUniquedSection)
1082  UniqueID = NextUniqueID++;
1083 
1084  if (!ComdatGV->hasPrivateLinkage()) {
1085  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1086  StringRef COMDATSymName = Sym->getName();
1087  return getContext().getCOFFSection(Name, Characteristics, Kind,
1088  COMDATSymName, Selection, UniqueID);
1089  } else {
1090  SmallString<256> TmpData;
1091  getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1092  return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1093  Selection, UniqueID);
1094  }
1095  }
1096 
1097  if (Kind.isText())
1098  return TextSection;
1099 
1100  if (Kind.isThreadLocal())
1101  return TLSDataSection;
1102 
1103  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1104  return ReadOnlySection;
1105 
1106  // Note: we claim that common symbols are put in BSSSection, but they are
1107  // really emitted with the magic .comm directive, which creates a symbol table
1108  // entry but not a section.
1109  if (Kind.isBSS() || Kind.isCommon())
1110  return BSSSection;
1111 
1112  return DataSection;
1113 }
1114 
1116  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1117  const TargetMachine &TM) const {
1118  bool CannotUsePrivateLabel = false;
1119  if (GV->hasPrivateLinkage() &&
1120  ((isa<Function>(GV) && TM.getFunctionSections()) ||
1121  (isa<GlobalVariable>(GV) && TM.getDataSections())))
1122  CannotUsePrivateLabel = true;
1123 
1124  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1125 }
1126 
1128  const Function &F, const TargetMachine &TM) const {
1129  // If the function can be removed, produce a unique section so that
1130  // the table doesn't prevent the removal.
1131  const Comdat *C = F.getComdat();
1132  bool EmitUniqueSection = TM.getFunctionSections() || C;
1133  if (!EmitUniqueSection)
1134  return ReadOnlySection;
1135 
1136  // FIXME: we should produce a symbol for F instead.
1137  if (F.hasPrivateLinkage())
1138  return ReadOnlySection;
1139 
1140  MCSymbol *Sym = TM.getSymbol(&F);
1141  StringRef COMDATSymName = Sym->getName();
1142 
1144  const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1145  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1146  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1147  unsigned UniqueID = NextUniqueID++;
1148 
1149  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1151 }
1152 
1154  MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1155  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1156  // Emit the linker options to the linker .drectve section. According to the
1157  // spec, this section is a space-separated string containing flags for
1158  // linker.
1159  MCSection *Sec = getDrectveSection();
1160  Streamer.SwitchSection(Sec);
1161  for (const auto &Option : LinkerOptions->operands()) {
1162  for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1163  // Lead with a space for consistency with our dllexport implementation.
1164  std::string Directive(" ");
1165  Directive.append(cast<MDString>(Piece)->getString());
1166  Streamer.EmitBytes(Directive);
1167  }
1168  }
1169  }
1170 
1171  unsigned Version = 0;
1172  unsigned Flags = 0;
1174 
1175  GetObjCImageInfo(M, Version, Flags, Section);
1176  if (Section.empty())
1177  return;
1178 
1179  auto &C = getContext();
1180  auto *S = C.getCOFFSection(
1183  Streamer.SwitchSection(S);
1184  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1185  Streamer.EmitIntValue(Version, 4);
1186  Streamer.EmitIntValue(Flags, 4);
1187  Streamer.AddBlankLine();
1188 }
1189 
1191  const TargetMachine &TM) {
1193  const Triple &T = TM.getTargetTriple();
1203  } else {
1212  }
1213 }
1214 
1216  unsigned Priority, const MCSymbol *KeySym) const {
1218  cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1219 }
1220 
1222  unsigned Priority, const MCSymbol *KeySym) const {
1224  cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1225 }
1226 
1228  raw_ostream &OS, const GlobalValue *GV) const {
1230 }
1231 
1232 //===----------------------------------------------------------------------===//
1233 // Wasm
1234 //===----------------------------------------------------------------------===//
1235 
1236 static void checkWasmComdat(const GlobalValue *GV) {
1237  const Comdat *C = GV->getComdat();
1238  if (!C)
1239  return;
1240 
1241  // TODO(sbc): At some point we may need COMDAT support but currently
1242  // they are not supported.
1243  report_fatal_error("WebAssembly doesn't support COMDATs, '" + C->getName() +
1244  "' cannot be lowered.");
1245 }
1246 
1248  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1249  StringRef Name = GO->getSection();
1250  checkWasmComdat(GO);
1252 }
1253 
1255  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1256  const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1257  StringRef Group = "";
1258  checkWasmComdat(GO);
1259 
1262 
1263  if (const auto *F = dyn_cast<Function>(GO)) {
1264  const auto &OptionalPrefix = F->getSectionPrefix();
1265  if (OptionalPrefix)
1266  Name += *OptionalPrefix;
1267  }
1268 
1269  if (EmitUniqueSection && UniqueSectionNames) {
1270  Name.push_back('.');
1271  TM.getNameWithPrefix(Name, GO, Mang, true);
1272  }
1273  unsigned UniqueID = MCContext::GenericSectionID;
1274  if (EmitUniqueSection && !UniqueSectionNames) {
1275  UniqueID = *NextUniqueID;
1276  (*NextUniqueID)++;
1277  }
1278  return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1279 }
1280 
1282  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1283 
1284  if (Kind.isCommon())
1285  report_fatal_error("mergable sections not supported yet on wasm");
1286 
1287  // If we have -ffunction-section or -fdata-section then we should emit the
1288  // global value to a uniqued section specifically for it.
1289  bool EmitUniqueSection = false;
1290  if (Kind.isText())
1291  EmitUniqueSection = TM.getFunctionSections();
1292  else
1293  EmitUniqueSection = TM.getDataSections();
1294  EmitUniqueSection |= GO->hasComdat();
1295 
1296  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1297  EmitUniqueSection, &NextUniqueID);
1298 }
1299 
1301  bool UsesLabelDifference, const Function &F) const {
1302  // We can always create relative relocations, so use another section
1303  // that can be marked non-executable.
1304  return false;
1305 }
1306 
1308  const GlobalValue *LHS, const GlobalValue *RHS,
1309  const TargetMachine &TM) const {
1310  // We may only use a PLT-relative relocation to refer to unnamed_addr
1311  // functions.
1312  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1313  return nullptr;
1314 
1315  // Basic sanity checks.
1316  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1317  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1318  RHS->isThreadLocal())
1319  return nullptr;
1320 
1321  return MCBinaryExpr::createSub(
1323  getContext()),
1325 }
1326 
1329  getContext().getWasmSection(".init_array", SectionKind::getData());
1331  getContext().getWasmSection(".fini_array", SectionKind::getData());
1332 }
AttributeSet getAttributes() const
Return the attribute set for this global.
uint64_t CallInst * C
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
bool isBSSExtern() const
Definition: SectionKind.h:162
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:90
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:39
void push_back(const T &Elt)
Definition: SmallVector.h:212
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:709
static SectionKind getData()
Definition: SectionKind.h:202
static MCSectionELF * selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol)
bool isThreadData() const
Definition: SectionKind.h:154
bool hasLocalLinkage() const
Definition: GlobalValue.h:427
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
bool hasAttribute(unsigned Value) const
This represents a section on a Mach-O system (used by Mac OS X).
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
cl::opt< bool > UniqueSectionNames("unique-section-names", cl::desc("Give unique names to every section"), cl::init(true))
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:305
bool hasPrivateLinkage() const
Definition: GlobalValue.h:426
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
PointerTy getPointer() const
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:127
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
This represents an "assembler immediate".
Definition: MCValue.h:40
bool isWriteable() const
Definition: SectionKind.h:145
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:281
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
void emitLinkerFlagsForGlobal(raw_ostream &OS, const GlobalValue *GV) const override
virtual void AddBlankLine()
AddBlankLine - Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:303
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * SixteenByteConstantSection
MCSection * TextSection
Section directive for standard text.
MCSection * StaticCtorSection
This section contains the static constructor pointer list.
MCSection * ConstTextCoalSection
virtual void EmitBytes(StringRef Data)
Emit the bytes in Data into the output.
Definition: MCStreamer.cpp:915
static void checkMachOComdat(const GlobalValue *GV)
This file contains the declarations for metadata subclasses.
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
static void checkWasmComdat(const GlobalValue *GV)
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K)
Definition: MCContext.h:444
bool isMergeableConst8() const
Definition: SectionKind.h:141
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:262
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:36
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
bool isMergeableCString() const
Definition: SectionKind.h:128
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
Metadata node.
Definition: Metadata.h:862
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:165
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym) const override
F(f)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const override
Given a constant with the SectionKind, return a section that it should be placed in.
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
const MCExpr * getIndirectSymViaGOTPCRel(const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Get MachO PC relative GOT entry relocation.
unsigned getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
Definition: DataLayout.cpp:587
static bool isThumb(const MCSubtargetInfo &STI)
unsigned getTypeAndAttributes() const
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:420
bool isMergeable2ByteCString() const
Definition: SectionKind.h:133
MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=GenericSectionID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym...
Definition: MCContext.cpp:468
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:127
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
static MCSectionWasm * selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID)
int64_t getConstant() const
Definition: MCValue.h:47
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:49
A tuple of MDNodes.
Definition: Metadata.h:1323
static SectionKind getBSS()
Definition: SectionKind.h:198
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
bool isKnownWindowsMSVCEnvironment() const
Checks if the environment is MSVC.
Definition: Triple.h:530
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1431
The linker may choose any COMDAT.
Definition: Comdat.h:32
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * EightByteConstantSection
S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for termination.
Definition: MachO.h:143
MCSection * TLSDataSection
Section directive for Thread Local data. ELF, MachO, COFF, and Wasm.
static const GlobalValue * getComdatGVForCOFF(const GlobalValue *GV)
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Context object for machine code objects.
Definition: MCContext.h:59
bool hasExternalLinkage() const
Definition: GlobalValue.h:413
Key
PAL metadata keys.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
bool isText() const
Definition: SectionKind.h:119
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:528
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:271
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:285
MCSection * StaticDtorSection
This section contains the static destructor pointer list.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, StringRef &Section)
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:112
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
bool isBSSLocal() const
Definition: SectionKind.h:161
bool isMergeableConst32() const
Definition: SectionKind.h:143
bool hasImplicitSection() const
Check if section name is present.
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Definition: MachO.h:190
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
void emitModuleMetadata(MCStreamer &Streamer, Module &M, const TargetMachine &TM) const override
Emit the module flags that specify the garbage collection information.
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:337
static SectionKind getThreadData()
Definition: SectionKind.h:197
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:443
bool isWindowsItaniumEnvironment() const
Definition: Triple.h:538
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:362
virtual void EmitIntValue(uint64_t Value, unsigned Size)
Special case of EmitValue that avoids the client having to pass in a MCExpr for constant integers...
Definition: MCStreamer.cpp:88
MCSection * DataSection
Section directive for standard data.
bool getDataSections() const
Return true if data objects should be emitted into their own section, corresponds to -fdata-sections...
SectionCharacteristics
Definition: COFF.h:281
bool isReadOnlyWithRel() const
Definition: SectionKind.h:168
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:361
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
.hidden (ELF)
Definition: MCDirectives.h:31
void emitModuleMetadata(MCStreamer &Streamer, Module &M, const TargetMachine &TM) const override
Emit Obj-C garbage collection and linker options.
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:282
No other Module may specify this COMDAT.
Definition: Comdat.h:35
Streaming machine code generation interface.
Definition: MCStreamer.h:169
StringRef getName() const
Definition: Comdat.cpp:24
static std::string ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
PointerIntPair - This class implements a pair of a pointer and small integer.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:605
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
Definition: MCStreamer.cpp:937
This represents a section on wasm.
Definition: MCSectionWasm.h:28
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Return an MCExpr to use for a reference to the specified type info global variable from exception han...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K)
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
MCSymbol * getSymbol(const GlobalValue *GV) const
virtual bool isSectionAtomizableBySymbols(const MCSection &Section) const
True if the section is atomized using the symbols in it.
Definition: MCAsmInfo.cpp:63
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
Definition: MCStreamer.cpp:925
virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
Add the given Attribute to Symbol.
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:177
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
const Triple & getTargetTriple() const
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
AMDGPU DAG DAG Pattern Instruction Selection
bool isMergeableConst16() const
Definition: SectionKind.h:142
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const override
Given a constant with the SectionKind, return a section that it should be placed in.
Ty & getObjFileInfo()
Keep track of various per-function pieces of information for backends that would like to do so...
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:33
StubValueTy & getGVStubEntry(MCSymbol *Sym)
static const char * getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
StubValueTy & getGVStubEntry(MCSymbol *Sym)
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool isThreadBSS() const
Definition: SectionKind.h:153
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
MCSection * getDrectveSection() const
bool isBSS() const
Definition: SectionKind.h:160
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
The mach-o version of this method defaults to returning a stub reference.
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
bool isMergeableConst4() const
Definition: SectionKind.h:140
static const MCSymbolELF * getAssociatedSymbol(const GlobalObject *GO, const TargetMachine &TM)
static SectionKind getThreadBSS()
Definition: SectionKind.h:196
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
const MCSymbol & getSymbol() const
Definition: MCExpr.h:318
bool isMergeable4ByteCString() const
Definition: SectionKind.h:134
bool isCommon() const
Definition: SectionKind.h:164
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
static SectionKind getMetadata()
Definition: SectionKind.h:179
bool isMetadata() const
Definition: SectionKind.h:117
const Triple & getTargetTriple() const
static const Comdat * getELFComdat(const GlobalValue *GV)
The linker will choose the largest COMDAT.
Definition: Comdat.h:34
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:192
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:174
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:760
This file contains constants used for implementing Dwarf debug support.
const Comdat * getComdat() const
Definition: Globals.cpp:166
static StringRef getSectionPrefixForGlobal(SectionKind Kind)
Return the section prefix name used by options FunctionsSections and DataSections.
MCSection * FourByteConstantSection
bool hasComdat() const
Definition: GlobalObject.h:100
bool isReadOnly() const
Definition: SectionKind.h:123
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
const Comdat * getComdat() const
Definition: GlobalObject.h:101
bool isMergeableConst() const
Definition: SectionKind.h:136
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:212
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
virtual void EmitLinkerOptions(ArrayRef< std::string > Kind)
Emit the given list Options of strings as linker options into the output.
Definition: MCStreamer.h:419
bool getUniqueSectionNames() const
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:195
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
static int getSelectionForCOFF(const GlobalValue *GV)
void emitModuleMetadata(MCStreamer &Streamer, Module &M, const TargetMachine &TM) const override
Emit Obj-C garbage collection and linker options.
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:323
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
Definition: MCStreamer.cpp:906
static unsigned getCOFFSectionFlags(SectionKind K, const TargetMachine &TM)
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:28
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Type * getValueType() const
Definition: GlobalValue.h:267
const Module * getModule() const
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets...
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:256
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:203
const unsigned Kind
MCSection * TLSBSSSection
Section directive for Thread Local uninitialized data.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:379
static MCSectionELF * getStaticStructorSection(MCContext &Ctx, bool UseInitArray, bool IsCtor, unsigned Priority, const MCSymbol *KeySym)
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:556
bool isData() const
Definition: SectionKind.h:166
bool isThreadLocal() const
Definition: SectionKind.h:149
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool isMergeable1ByteCString() const
Definition: SectionKind.h:132
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:300
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:270
Metadata * get() const
Definition: Metadata.h:720
bool isExecuteOnly() const
Definition: SectionKind.h:121
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:57
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:109
MCSection * BSSSection
Section that is default initialized to zero.
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:238
const MCSymbol * getAssociatedSymbol() const
Definition: MCSectionELF.h:90
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
static unsigned getELFSectionFlags(SectionKind K)
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:140
static SectionKind getReadOnly()
Definition: SectionKind.h:182
const uint64_t Version
Definition: InstrProf.h:867
static unsigned getELFSectionType(StringRef Name, SectionKind K)
This class can be derived from and used by targets to hold private target-specific information for ea...
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:159
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:265
This class contains meta information specific to a module.
SelectionKind getSelectionKind() const
Definition: Comdat.h:42
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override