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);
133  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
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 
171 static SectionKind
173  // N.B.: The defaults used in here are no the same ones used in MC.
174  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
175  // both gas and MC will produce a section with no flags. Given
176  // section(".eh_frame") gcc will produce:
177  //
178  // .section .eh_frame,"a",@progbits
179 
180  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
181  /*AddSegmentInfo=*/false))
182  return SectionKind::getMetadata();
183 
184  if (Name.empty() || Name[0] != '.') return K;
185 
186  // Some lame default implementation based on some magic section names.
187  if (Name == ".bss" ||
188  Name.startswith(".bss.") ||
189  Name.startswith(".gnu.linkonce.b.") ||
190  Name.startswith(".llvm.linkonce.b.") ||
191  Name == ".sbss" ||
192  Name.startswith(".sbss.") ||
193  Name.startswith(".gnu.linkonce.sb.") ||
194  Name.startswith(".llvm.linkonce.sb."))
195  return SectionKind::getBSS();
196 
197  if (Name == ".tdata" ||
198  Name.startswith(".tdata.") ||
199  Name.startswith(".gnu.linkonce.td.") ||
200  Name.startswith(".llvm.linkonce.td."))
202 
203  if (Name == ".tbss" ||
204  Name.startswith(".tbss.") ||
205  Name.startswith(".gnu.linkonce.tb.") ||
206  Name.startswith(".llvm.linkonce.tb."))
207  return SectionKind::getThreadBSS();
208 
209  return K;
210 }
211 
213  // Use SHT_NOTE for section whose name starts with ".note" to allow
214  // emitting ELF notes from C variable declaration.
215  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
216  if (Name.startswith(".note"))
217  return ELF::SHT_NOTE;
218 
219  if (Name == ".init_array")
220  return ELF::SHT_INIT_ARRAY;
221 
222  if (Name == ".fini_array")
223  return ELF::SHT_FINI_ARRAY;
224 
225  if (Name == ".preinit_array")
226  return ELF::SHT_PREINIT_ARRAY;
227 
228  if (K.isBSS() || K.isThreadBSS())
229  return ELF::SHT_NOBITS;
230 
231  return ELF::SHT_PROGBITS;
232 }
233 
234 static unsigned getELFSectionFlags(SectionKind K) {
235  unsigned Flags = 0;
236 
237  if (!K.isMetadata())
238  Flags |= ELF::SHF_ALLOC;
239 
240  if (K.isText())
241  Flags |= ELF::SHF_EXECINSTR;
242 
243  if (K.isExecuteOnly())
244  Flags |= ELF::SHF_ARM_PURECODE;
245 
246  if (K.isWriteable())
247  Flags |= ELF::SHF_WRITE;
248 
249  if (K.isThreadLocal())
250  Flags |= ELF::SHF_TLS;
251 
252  if (K.isMergeableCString() || K.isMergeableConst())
253  Flags |= ELF::SHF_MERGE;
254 
255  if (K.isMergeableCString())
256  Flags |= ELF::SHF_STRINGS;
257 
258  return Flags;
259 }
260 
261 static const Comdat *getELFComdat(const GlobalValue *GV) {
262  const Comdat *C = GV->getComdat();
263  if (!C)
264  return nullptr;
265 
266  if (C->getSelectionKind() != Comdat::Any)
267  report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
268  C->getName() + "' cannot be lowered.");
269 
270  return C;
271 }
272 
274  const TargetMachine &TM) {
276  if (!MD)
277  return nullptr;
278 
279  const MDOperand &Op = MD->getOperand(0);
280  if (!Op.get())
281  return nullptr;
282 
283  auto *VM = dyn_cast<ValueAsMetadata>(Op);
284  if (!VM)
285  report_fatal_error("MD_associated operand is not ValueAsMetadata");
286 
287  GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
288  return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
289 }
290 
292  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
294 
295  // Check if '#pragma clang section' name is applicable.
296  // Note that pragma directive overrides -ffunction-section, -fdata-section
297  // and so section name is exactly as user specified and not uniqued.
298  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
299  if (GV && GV->hasImplicitSection()) {
300  auto Attrs = GV->getAttributes();
301  if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
302  SectionName = Attrs.getAttribute("bss-section").getValueAsString();
303  } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
304  SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
305  } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
306  SectionName = Attrs.getAttribute("data-section").getValueAsString();
307  }
308  }
309  const Function *F = dyn_cast<Function>(GO);
310  if (F && F->hasFnAttribute("implicit-section-name")) {
311  SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
312  }
313 
314  // Infer section flags from the section name if we can.
315  Kind = getELFKindForNamedSection(SectionName, Kind);
316 
317  StringRef Group = "";
318  unsigned Flags = getELFSectionFlags(Kind);
319  if (const Comdat *C = getELFComdat(GO)) {
320  Group = C->getName();
321  Flags |= ELF::SHF_GROUP;
322  }
323 
324  // A section can have at most one associated section. Put each global with
325  // MD_associated in a unique section.
326  unsigned UniqueID = MCContext::GenericSectionID;
327  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
328  if (AssociatedSymbol) {
329  UniqueID = NextUniqueID++;
330  Flags |= ELF::SHF_LINK_ORDER;
331  }
332 
333  MCSectionELF *Section = getContext().getELFSection(
334  SectionName, getELFSectionType(SectionName, Kind), Flags,
335  /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
336  // Make sure that we did not get some other section with incompatible sh_link.
337  // This should not be possible due to UniqueID code above.
338  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
339  return Section;
340 }
341 
342 /// Return the section prefix name used by options FunctionsSections and
343 /// DataSections.
345  if (Kind.isText())
346  return ".text";
347  if (Kind.isReadOnly())
348  return ".rodata";
349  if (Kind.isBSS())
350  return ".bss";
351  if (Kind.isThreadData())
352  return ".tdata";
353  if (Kind.isThreadBSS())
354  return ".tbss";
355  if (Kind.isData())
356  return ".data";
357  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
358  return ".data.rel.ro";
359 }
360 
362  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
363  const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
364  unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
365  unsigned EntrySize = 0;
366  if (Kind.isMergeableCString()) {
367  if (Kind.isMergeable2ByteCString()) {
368  EntrySize = 2;
369  } else if (Kind.isMergeable4ByteCString()) {
370  EntrySize = 4;
371  } else {
372  EntrySize = 1;
373  assert(Kind.isMergeable1ByteCString() && "unknown string width");
374  }
375  } else if (Kind.isMergeableConst()) {
376  if (Kind.isMergeableConst4()) {
377  EntrySize = 4;
378  } else if (Kind.isMergeableConst8()) {
379  EntrySize = 8;
380  } else if (Kind.isMergeableConst16()) {
381  EntrySize = 16;
382  } else {
383  assert(Kind.isMergeableConst32() && "unknown data width");
384  EntrySize = 32;
385  }
386  }
387 
388  StringRef Group = "";
389  if (const Comdat *C = getELFComdat(GO)) {
390  Flags |= ELF::SHF_GROUP;
391  Group = C->getName();
392  }
393 
396  if (Kind.isMergeableCString()) {
397  // We also need alignment here.
398  // FIXME: this is getting the alignment of the character, not the
399  // alignment of the global!
401  cast<GlobalVariable>(GO));
402 
403  std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
404  Name = SizeSpec + utostr(Align);
405  } else if (Kind.isMergeableConst()) {
406  Name = ".rodata.cst";
407  Name += utostr(EntrySize);
408  } else {
409  Name = getSectionPrefixForGlobal(Kind);
410  }
411 
412  if (const auto *F = dyn_cast<Function>(GO)) {
413  const auto &OptionalPrefix = F->getSectionPrefix();
414  if (OptionalPrefix)
415  Name += *OptionalPrefix;
416  }
417 
418  if (EmitUniqueSection && UniqueSectionNames) {
419  Name.push_back('.');
420  TM.getNameWithPrefix(Name, GO, Mang, true);
421  }
422  unsigned UniqueID = MCContext::GenericSectionID;
423  if (EmitUniqueSection && !UniqueSectionNames) {
424  UniqueID = *NextUniqueID;
425  (*NextUniqueID)++;
426  }
427  // Use 0 as the unique ID for execute-only text
428  if (Kind.isExecuteOnly())
429  UniqueID = 0;
430  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
431  EntrySize, Group, UniqueID, AssociatedSymbol);
432 }
433 
435  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
436  unsigned Flags = getELFSectionFlags(Kind);
437 
438  // If we have -ffunction-section or -fdata-section then we should emit the
439  // global value to a uniqued section specifically for it.
440  bool EmitUniqueSection = false;
441  if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
442  if (Kind.isText())
443  EmitUniqueSection = TM.getFunctionSections();
444  else
445  EmitUniqueSection = TM.getDataSections();
446  }
447  EmitUniqueSection |= GO->hasComdat();
448 
449  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
450  if (AssociatedSymbol) {
451  EmitUniqueSection = true;
452  Flags |= ELF::SHF_LINK_ORDER;
453  }
454 
456  getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
457  &NextUniqueID, AssociatedSymbol);
458  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
459  return Section;
460 }
461 
463  const Function &F, const TargetMachine &TM) const {
464  // If the function can be removed, produce a unique section so that
465  // the table doesn't prevent the removal.
466  const Comdat *C = F.getComdat();
467  bool EmitUniqueSection = TM.getFunctionSections() || C;
468  if (!EmitUniqueSection)
469  return ReadOnlySection;
470 
471  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
472  getMangler(), TM, EmitUniqueSection,
473  ELF::SHF_ALLOC, &NextUniqueID,
474  /* AssociatedSymbol */ nullptr);
475 }
476 
478  bool UsesLabelDifference, const Function &F) const {
479  // We can always create relative relocations, so use another section
480  // that can be marked non-executable.
481  return false;
482 }
483 
484 /// Given a mergeable constant with the specified size and relocation
485 /// information, return a section that it should be placed in.
487  const DataLayout &DL, SectionKind Kind, const Constant *C,
488  unsigned &Align) const {
489  if (Kind.isMergeableConst4() && MergeableConst4Section)
490  return MergeableConst4Section;
491  if (Kind.isMergeableConst8() && MergeableConst8Section)
492  return MergeableConst8Section;
493  if (Kind.isMergeableConst16() && MergeableConst16Section)
494  return MergeableConst16Section;
495  if (Kind.isMergeableConst32() && MergeableConst32Section)
496  return MergeableConst32Section;
497  if (Kind.isReadOnly())
498  return ReadOnlySection;
499 
500  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
501  return DataRelROSection;
502 }
503 
504 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
505  bool IsCtor, unsigned Priority,
506  const MCSymbol *KeySym) {
507  std::string Name;
508  unsigned Type;
509  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
510  StringRef COMDAT = KeySym ? KeySym->getName() : "";
511 
512  if (KeySym)
513  Flags |= ELF::SHF_GROUP;
514 
515  if (UseInitArray) {
516  if (IsCtor) {
517  Type = ELF::SHT_INIT_ARRAY;
518  Name = ".init_array";
519  } else {
520  Type = ELF::SHT_FINI_ARRAY;
521  Name = ".fini_array";
522  }
523  if (Priority != 65535) {
524  Name += '.';
525  Name += utostr(Priority);
526  }
527  } else {
528  // The default scheme is .ctor / .dtor, so we have to invert the priority
529  // numbering.
530  if (IsCtor)
531  Name = ".ctors";
532  else
533  Name = ".dtors";
534  if (Priority != 65535) {
535  Name += '.';
536  Name += utostr(65535 - Priority);
537  }
538  Type = ELF::SHT_PROGBITS;
539  }
540 
541  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
542 }
543 
545  unsigned Priority, const MCSymbol *KeySym) const {
546  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
547  KeySym);
548 }
549 
551  unsigned Priority, const MCSymbol *KeySym) const {
552  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
553  KeySym);
554 }
555 
557  const GlobalValue *LHS, const GlobalValue *RHS,
558  const TargetMachine &TM) const {
559  // We may only use a PLT-relative relocation to refer to unnamed_addr
560  // functions.
561  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
562  return nullptr;
563 
564  // Basic sanity checks.
565  if (LHS->getType()->getPointerAddressSpace() != 0 ||
566  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
567  RHS->isThreadLocal())
568  return nullptr;
569 
571  MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
572  getContext()),
573  MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
574 }
575 
576 void
578  UseInitArray = UseInitArray_;
579  MCContext &Ctx = getContext();
580  if (!UseInitArray) {
581  StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
583 
584  StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
586  return;
587  }
588 
589  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
591  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
593 }
594 
595 //===----------------------------------------------------------------------===//
596 // MachO
597 //===----------------------------------------------------------------------===//
598 
602 }
603 
605  const TargetMachine &TM) {
607  if (TM.getRelocationModel() == Reloc::Static) {
608  StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
610  StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
612  } else {
613  StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
616  StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
619  }
620 }
621 
623  MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
624  // Emit the linker options if present.
625  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
626  for (const auto &Option : LinkerOptions->operands()) {
627  SmallVector<std::string, 4> StrOptions;
628  for (const auto &Piece : cast<MDNode>(Option)->operands())
629  StrOptions.push_back(cast<MDString>(Piece)->getString());
630  Streamer.EmitLinkerOptions(StrOptions);
631  }
632  }
633 
634  unsigned VersionVal = 0;
635  unsigned ImageInfoFlags = 0;
636  StringRef SectionVal;
637 
638  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
639 
640  // The section is mandatory. If we don't have it, then we don't have GC info.
641  if (SectionVal.empty())
642  return;
643 
644  StringRef Segment, Section;
645  unsigned TAA = 0, StubSize = 0;
646  bool TAAParsed;
647  std::string ErrorCode =
648  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
649  TAA, TAAParsed, StubSize);
650  if (!ErrorCode.empty())
651  // If invalid, report the error with report_fatal_error.
652  report_fatal_error("Invalid section specifier '" + Section + "': " +
653  ErrorCode + ".");
654 
655  // Get the section.
657  Segment, Section, TAA, StubSize, SectionKind::getData());
658  Streamer.SwitchSection(S);
659  Streamer.EmitLabel(getContext().
660  getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
661  Streamer.EmitIntValue(VersionVal, 4);
662  Streamer.EmitIntValue(ImageInfoFlags, 4);
663  Streamer.AddBlankLine();
664 }
665 
666 static void checkMachOComdat(const GlobalValue *GV) {
667  const Comdat *C = GV->getComdat();
668  if (!C)
669  return;
670 
671  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
672  "' cannot be lowered.");
673 }
674 
676  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
677  // Parse the section specifier and create it if valid.
678  StringRef Segment, Section;
679  unsigned TAA = 0, StubSize = 0;
680  bool TAAParsed;
681 
682  checkMachOComdat(GO);
683 
684  std::string ErrorCode =
686  TAA, TAAParsed, StubSize);
687  if (!ErrorCode.empty()) {
688  // If invalid, report the error with report_fatal_error.
689  report_fatal_error("Global variable '" + GO->getName() +
690  "' has an invalid section specifier '" +
691  GO->getSection() + "': " + ErrorCode + ".");
692  }
693 
694  // Get the section.
695  MCSectionMachO *S =
696  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
697 
698  // If TAA wasn't set by ParseSectionSpecifier() above,
699  // use the value returned by getMachOSection() as a default.
700  if (!TAAParsed)
701  TAA = S->getTypeAndAttributes();
702 
703  // Okay, now that we got the section, verify that the TAA & StubSize agree.
704  // If the user declared multiple globals with different section flags, we need
705  // to reject it here.
706  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
707  // If invalid, report the error with report_fatal_error.
708  report_fatal_error("Global variable '" + GO->getName() +
709  "' section type or attributes does not match previous"
710  " section specifier");
711  }
712 
713  return S;
714 }
715 
717  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
718  checkMachOComdat(GO);
719 
720  // Handle thread local data.
721  if (Kind.isThreadBSS()) return TLSBSSSection;
722  if (Kind.isThreadData()) return TLSDataSection;
723 
724  if (Kind.isText())
726 
727  // If this is weak/linkonce, put this in a coalescable section, either in text
728  // or data depending on if it is writable.
729  if (GO->isWeakForLinker()) {
730  if (Kind.isReadOnly())
731  return ConstTextCoalSection;
732  return DataCoalSection;
733  }
734 
735  // FIXME: Alignment check should be handled by section classifier.
736  if (Kind.isMergeable1ByteCString() &&
738  cast<GlobalVariable>(GO)) < 32)
739  return CStringSection;
740 
741  // Do not put 16-bit arrays in the UString section if they have an
742  // externally visible label, this runs into issues with certain linker
743  // versions.
744  if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
746  cast<GlobalVariable>(GO)) < 32)
747  return UStringSection;
748 
749  // With MachO only variables whose corresponding symbol starts with 'l' or
750  // 'L' can be merged, so we only try merging GVs with private linkage.
751  if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
752  if (Kind.isMergeableConst4())
754  if (Kind.isMergeableConst8())
756  if (Kind.isMergeableConst16())
758  }
759 
760  // Otherwise, if it is readonly, but not something we can specially optimize,
761  // just drop it in .const.
762  if (Kind.isReadOnly())
763  return ReadOnlySection;
764 
765  // If this is marked const, put it into a const section. But if the dynamic
766  // linker needs to write to it, put it in the data segment.
767  if (Kind.isReadOnlyWithRel())
768  return ConstDataSection;
769 
770  // Put zero initialized globals with strong external linkage in the
771  // DATA, __common section with the .zerofill directive.
772  if (Kind.isBSSExtern())
773  return DataCommonSection;
774 
775  // Put zero initialized globals with local linkage in __DATA,__bss directive
776  // with the .zerofill directive (aka .lcomm).
777  if (Kind.isBSSLocal())
778  return DataBSSSection;
779 
780  // Otherwise, just drop the variable in the normal data section.
781  return DataSection;
782 }
783 
785  const DataLayout &DL, SectionKind Kind, const Constant *C,
786  unsigned &Align) const {
787  // If this constant requires a relocation, we have to put it in the data
788  // segment, not in the text segment.
789  if (Kind.isData() || Kind.isReadOnlyWithRel())
790  return ConstDataSection;
791 
792  if (Kind.isMergeableConst4())
794  if (Kind.isMergeableConst8())
796  if (Kind.isMergeableConst16())
798  return ReadOnlySection; // .const
799 }
800 
802  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
803  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
804  // The mach-o version of this method defaults to returning a stub reference.
805 
806  if (Encoding & DW_EH_PE_indirect) {
807  MachineModuleInfoMachO &MachOMMI =
809 
810  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
811 
812  // Add information about the stub reference to MachOMMI so that the stub
813  // gets emitted by the asmprinter.
814  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
815  if (!StubSym.getPointer()) {
816  MCSymbol *Sym = TM.getSymbol(GV);
818  }
819 
822  Encoding & ~DW_EH_PE_indirect, Streamer);
823  }
824 
826  MMI, Streamer);
827 }
828 
830  const GlobalValue *GV, const TargetMachine &TM,
831  MachineModuleInfo *MMI) const {
832  // The mach-o version of this method defaults to returning a stub reference.
833  MachineModuleInfoMachO &MachOMMI =
835 
836  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
837 
838  // Add information about the stub reference to MachOMMI so that the stub
839  // gets emitted by the asmprinter.
840  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
841  if (!StubSym.getPointer()) {
842  MCSymbol *Sym = TM.getSymbol(GV);
844  }
845 
846  return SSym;
847 }
848 
850  const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
851  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
852  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
853  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
854  // through a non_lazy_ptr stub instead. One advantage is that it allows the
855  // computation of deltas to final external symbols. Example:
856  //
857  // _extgotequiv:
858  // .long _extfoo
859  //
860  // _delta:
861  // .long _extgotequiv-_delta
862  //
863  // is transformed to:
864  //
865  // _delta:
866  // .long L_extfoo$non_lazy_ptr-(_delta+0)
867  //
868  // .section __IMPORT,__pointers,non_lazy_symbol_pointers
869  // L_extfoo$non_lazy_ptr:
870  // .indirect_symbol _extfoo
871  // .long 0
872  //
873  MachineModuleInfoMachO &MachOMMI =
875  MCContext &Ctx = getContext();
876 
877  // The offset must consider the original displacement from the base symbol
878  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
879  Offset = -MV.getConstant();
880  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
881 
882  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
883  // non_lazy_ptr stubs.
885  StringRef Suffix = "$non_lazy_ptr";
886  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
887  Name += Sym->getName();
888  Name += Suffix;
889  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
890 
891  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
892  if (!StubSym.getPointer())
893  StubSym = MachineModuleInfoImpl::
894  StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
895 
896  const MCExpr *BSymExpr =
898  const MCExpr *LHS =
900 
901  if (!Offset)
902  return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
903 
904  const MCExpr *RHS =
905  MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
906  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
907 }
908 
909 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
910  const MCSection &Section) {
911  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
912  return true;
913 
914  // If it is not dead stripped, it is safe to use private labels.
915  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
917  return true;
918 
919  return false;
920 }
921 
923  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
924  const TargetMachine &TM) const {
925  bool CannotUsePrivateLabel = true;
926  if (auto *GO = GV->getBaseObject()) {
928  const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
929  CannotUsePrivateLabel =
930  !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
931  }
932  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
933 }
934 
935 //===----------------------------------------------------------------------===//
936 // COFF
937 //===----------------------------------------------------------------------===//
938 
939 static unsigned
941  unsigned Flags = 0;
942  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
943 
944  if (K.isMetadata())
945  Flags |=
947  else if (K.isText())
948  Flags |=
953  else if (K.isBSS())
954  Flags |=
958  else if (K.isThreadLocal())
959  Flags |=
963  else if (K.isReadOnly() || K.isReadOnlyWithRel())
964  Flags |=
967  else if (K.isWriteable())
968  Flags |=
972 
973  return Flags;
974 }
975 
976 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
977  const Comdat *C = GV->getComdat();
978  assert(C && "expected GV to have a Comdat!");
979 
980  StringRef ComdatGVName = C->getName();
981  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
982  if (!ComdatGV)
983  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
984  "' does not exist.");
985 
986  if (ComdatGV->getComdat() != C)
987  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
988  "' is not a key for its COMDAT.");
989 
990  return ComdatGV;
991 }
992 
993 static int getSelectionForCOFF(const GlobalValue *GV) {
994  if (const Comdat *C = GV->getComdat()) {
995  const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
996  if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
997  ComdatKey = GA->getBaseObject();
998  if (ComdatKey == GV) {
999  switch (C->getSelectionKind()) {
1000  case Comdat::Any:
1002  case Comdat::ExactMatch:
1004  case Comdat::Largest:
1006  case Comdat::NoDuplicates:
1008  case Comdat::SameSize:
1010  }
1011  } else {
1013  }
1014  }
1015  return 0;
1016 }
1017 
1019  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1020  int Selection = 0;
1021  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1022  StringRef Name = GO->getSection();
1023  StringRef COMDATSymName = "";
1024  if (GO->hasComdat()) {
1025  Selection = getSelectionForCOFF(GO);
1026  const GlobalValue *ComdatGV;
1027  if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1028  ComdatGV = getComdatGVForCOFF(GO);
1029  else
1030  ComdatGV = GO;
1031 
1032  if (!ComdatGV->hasPrivateLinkage()) {
1033  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1034  COMDATSymName = Sym->getName();
1035  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1036  } else {
1037  Selection = 0;
1038  }
1039  }
1040 
1041  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1042  Selection);
1043 }
1044 
1046  if (Kind.isText())
1047  return ".text";
1048  if (Kind.isBSS())
1049  return ".bss";
1050  if (Kind.isThreadLocal())
1051  return ".tls$";
1052  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1053  return ".rdata";
1054  return ".data";
1055 }
1056 
1058  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1059  // If we have -ffunction-sections then we should emit the global value to a
1060  // uniqued section specifically for it.
1061  bool EmitUniquedSection;
1062  if (Kind.isText())
1063  EmitUniquedSection = TM.getFunctionSections();
1064  else
1065  EmitUniquedSection = TM.getDataSections();
1066 
1067  if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1068  const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1069  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1070 
1071  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1072  int Selection = getSelectionForCOFF(GO);
1073  if (!Selection)
1075  const GlobalValue *ComdatGV;
1076  if (GO->hasComdat())
1077  ComdatGV = getComdatGVForCOFF(GO);
1078  else
1079  ComdatGV = GO;
1080 
1081  unsigned UniqueID = MCContext::GenericSectionID;
1082  if (EmitUniquedSection)
1083  UniqueID = NextUniqueID++;
1084 
1085  if (!ComdatGV->hasPrivateLinkage()) {
1086  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1087  StringRef COMDATSymName = Sym->getName();
1088  return getContext().getCOFFSection(Name, Characteristics, Kind,
1089  COMDATSymName, Selection, UniqueID);
1090  } else {
1091  SmallString<256> TmpData;
1092  getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1093  return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1094  Selection, UniqueID);
1095  }
1096  }
1097 
1098  if (Kind.isText())
1099  return TextSection;
1100 
1101  if (Kind.isThreadLocal())
1102  return TLSDataSection;
1103 
1104  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1105  return ReadOnlySection;
1106 
1107  // Note: we claim that common symbols are put in BSSSection, but they are
1108  // really emitted with the magic .comm directive, which creates a symbol table
1109  // entry but not a section.
1110  if (Kind.isBSS() || Kind.isCommon())
1111  return BSSSection;
1112 
1113  return DataSection;
1114 }
1115 
1117  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1118  const TargetMachine &TM) const {
1119  bool CannotUsePrivateLabel = false;
1120  if (GV->hasPrivateLinkage() &&
1121  ((isa<Function>(GV) && TM.getFunctionSections()) ||
1122  (isa<GlobalVariable>(GV) && TM.getDataSections())))
1123  CannotUsePrivateLabel = true;
1124 
1125  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1126 }
1127 
1129  const Function &F, const TargetMachine &TM) const {
1130  // If the function can be removed, produce a unique section so that
1131  // the table doesn't prevent the removal.
1132  const Comdat *C = F.getComdat();
1133  bool EmitUniqueSection = TM.getFunctionSections() || C;
1134  if (!EmitUniqueSection)
1135  return ReadOnlySection;
1136 
1137  // FIXME: we should produce a symbol for F instead.
1138  if (F.hasPrivateLinkage())
1139  return ReadOnlySection;
1140 
1141  MCSymbol *Sym = TM.getSymbol(&F);
1142  StringRef COMDATSymName = Sym->getName();
1143 
1145  const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1146  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1147  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1148  unsigned UniqueID = NextUniqueID++;
1149 
1150  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1152 }
1153 
1155  MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1156  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1157  // Emit the linker options to the linker .drectve section. According to the
1158  // spec, this section is a space-separated string containing flags for
1159  // linker.
1160  MCSection *Sec = getDrectveSection();
1161  Streamer.SwitchSection(Sec);
1162  for (const auto &Option : LinkerOptions->operands()) {
1163  for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1164  // Lead with a space for consistency with our dllexport implementation.
1165  std::string Directive(" ");
1166  Directive.append(cast<MDString>(Piece)->getString());
1167  Streamer.EmitBytes(Directive);
1168  }
1169  }
1170  }
1171 
1172  unsigned Version = 0;
1173  unsigned Flags = 0;
1175 
1176  GetObjCImageInfo(M, Version, Flags, Section);
1177  if (Section.empty())
1178  return;
1179 
1180  auto &C = getContext();
1181  auto *S = C.getCOFFSection(
1184  Streamer.SwitchSection(S);
1185  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1186  Streamer.EmitIntValue(Version, 4);
1187  Streamer.EmitIntValue(Flags, 4);
1188  Streamer.AddBlankLine();
1189 }
1190 
1192  const TargetMachine &TM) {
1194  const Triple &T = TM.getTargetTriple();
1204  } else {
1213  }
1214 }
1215 
1217  unsigned Priority, const MCSymbol *KeySym) const {
1219  cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1220 }
1221 
1223  unsigned Priority, const MCSymbol *KeySym) const {
1225  cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1226 }
1227 
1229  raw_ostream &OS, const GlobalValue *GV) const {
1231 }
1232 
1233 //===----------------------------------------------------------------------===//
1234 // Wasm
1235 //===----------------------------------------------------------------------===//
1236 
1237 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1238  const Comdat *C = GV->getComdat();
1239  if (!C)
1240  return nullptr;
1241 
1242  if (C->getSelectionKind() != Comdat::Any)
1243  report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1244  C->getName() + "' cannot be lowered.");
1245 
1246  return C;
1247 }
1248 
1250  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1251  llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1252  return nullptr;
1253 }
1254 
1255 static MCSectionWasm *
1257  SectionKind Kind, Mangler &Mang,
1258  const TargetMachine &TM, bool EmitUniqueSection,
1259  unsigned Flags, unsigned *NextUniqueID) {
1260  StringRef Group = "";
1261  if (getWasmComdat(GO))
1262  llvm_unreachable("comdat not yet supported for wasm");
1263 
1266 
1267  if (const auto *F = dyn_cast<Function>(GO)) {
1268  const auto &OptionalPrefix = F->getSectionPrefix();
1269  if (OptionalPrefix)
1270  Name += *OptionalPrefix;
1271  }
1272 
1273  if (EmitUniqueSection && UniqueSectionNames) {
1274  Name.push_back('.');
1275  TM.getNameWithPrefix(Name, GO, Mang, true);
1276  }
1277  unsigned UniqueID = MCContext::GenericSectionID;
1278  if (EmitUniqueSection && !UniqueSectionNames) {
1279  UniqueID = *NextUniqueID;
1280  (*NextUniqueID)++;
1281  }
1282  return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1283  Group, UniqueID);
1284 }
1285 
1287  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1288 
1289  if (Kind.isCommon())
1290  report_fatal_error("mergable sections not supported yet on wasm");
1291 
1292  // If we have -ffunction-section or -fdata-section then we should emit the
1293  // global value to a uniqued section specifically for it.
1294  bool EmitUniqueSection = false;
1295  if (Kind.isText())
1296  EmitUniqueSection = TM.getFunctionSections();
1297  else
1298  EmitUniqueSection = TM.getDataSections();
1299  EmitUniqueSection |= GO->hasComdat();
1300 
1301  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1302  EmitUniqueSection, /*Flags=*/0,
1303  &NextUniqueID);
1304 }
1305 
1307  bool UsesLabelDifference, const Function &F) const {
1308  // We can always create relative relocations, so use another section
1309  // that can be marked non-executable.
1310  return false;
1311 }
1312 
1314  const GlobalValue *LHS, const GlobalValue *RHS,
1315  const TargetMachine &TM) const {
1316  // We may only use a PLT-relative relocation to refer to unnamed_addr
1317  // functions.
1318  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1319  return nullptr;
1320 
1321  // Basic sanity checks.
1322  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1323  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1324  RHS->isThreadLocal())
1325  return nullptr;
1326 
1327  return MCBinaryExpr::createSub(
1329  getContext()),
1331 }
1332 
1333 void
1335  // TODO: Initialize StaticCtorSection and StaticDtorSection.
1336 }
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
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:416
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).
MCSectionWasm * getWasmSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:444
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:415
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:103
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:128
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:295
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:832
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
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:254
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:163
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &TM, const MCSymbol *Sym) const override
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.
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
int64_t getConstant() const
Definition: MCValue.h:46
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:48
A tuple of MDNodes.
Definition: Metadata.h:1316
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:519
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:402
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
#define F(x, y, z)
Definition: MD5.cpp:55
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:281
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.
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
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.
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:527
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
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:93
const char * Name
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:350
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...
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
.hidden (ELF)
Definition: MCDirectives.h:31
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Definition: MachO.h:190
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
static const Comdat * getWasmComdat(const GlobalValue *GV)
No other Module may specify this COMDAT.
Definition: Comdat.h:35
Streaming machine code generation interface.
Definition: MCStreamer.h:167
StringRef getName() const
Definition: Comdat.cpp:24
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:362
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.
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:854
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:842
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...
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
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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)
#define E
Definition: LargeTest.cpp:27
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 MCSectionWasm * selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID)
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:187
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:760
const Comdat * getComdat() const
Definition: Globals.cpp:165
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
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool isReadOnly() const
Definition: SectionKind.h:123
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
const Comdat * getComdat() const
Definition: GlobalObject.h:101
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
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:411
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:218
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:283
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
Definition: MCStreamer.cpp:823
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:262
const Module * getModule() const
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets...
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:255
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())
unsigned getPointerABIAlignment(unsigned AS=0) const
Layout pointer alignment FIXME: The defaults need to be removed once all of the backends/clients are ...
Definition: DataLayout.cpp:587
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:545
bool isData() const
Definition: SectionKind.h:166
bool isThreadLocal() const
Definition: SectionKind.h:149
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:301
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:262
Metadata * get() const
Definition: Metadata.h:720
const char SectionName[]
Definition: AMDGPUPTNote.h:24
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:56
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:233
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:864
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:260
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