LLVM  8.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"
55 #include "llvm/Support/Format.h"
59 #include <cassert>
60 #include <string>
61 
62 using namespace llvm;
63 using namespace dwarf;
64 
65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
66  StringRef &Section) {
68  M.getModuleFlagsMetadata(ModuleFlags);
69 
70  for (const auto &MFE: ModuleFlags) {
71  // Ignore flags with 'Require' behaviour.
72  if (MFE.Behavior == Module::Require)
73  continue;
74 
75  StringRef Key = MFE.Key->getString();
76  if (Key == "Objective-C Image Info Version") {
77  Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78  } else if (Key == "Objective-C Garbage Collection" ||
79  Key == "Objective-C GC Only" ||
80  Key == "Objective-C Is Simulated" ||
81  Key == "Objective-C Class Properties" ||
82  Key == "Objective-C Image Swift Version") {
83  Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84  } else if (Key == "Objective-C Image Info Section") {
85  Section = cast<MDString>(MFE.Val)->getString();
86  }
87  }
88 }
89 
90 //===----------------------------------------------------------------------===//
91 // ELF
92 //===----------------------------------------------------------------------===//
93 
95  const TargetMachine &TgtM) {
97  TM = &TgtM;
98 
99  CodeModel::Model CM = TgtM.getCodeModel();
100 
101  switch (TgtM.getTargetTriple().getArch()) {
102  case Triple::arm:
103  case Triple::armeb:
104  case Triple::thumb:
105  case Triple::thumbeb:
107  break;
108  // Fallthrough if not using EHABI
110  case Triple::ppc:
111  case Triple::x86:
112  PersonalityEncoding = isPositionIndependent()
117  LSDAEncoding = isPositionIndependent()
120  TTypeEncoding = isPositionIndependent()
124  break;
125  case Triple::x86_64:
126  if (isPositionIndependent()) {
127  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
128  ((CM == CodeModel::Small || CM == CodeModel::Medium)
130  LSDAEncoding = dwarf::DW_EH_PE_pcrel |
131  (CM == CodeModel::Small
134  ((CM == CodeModel::Small || CM == CodeModel::Medium)
135  ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
136  } else {
137  PersonalityEncoding =
138  (CM == CodeModel::Small || CM == CodeModel::Medium)
140  LSDAEncoding = (CM == CodeModel::Small)
142  TTypeEncoding = (CM == CodeModel::Small)
144  }
145  break;
146  case Triple::hexagon:
147  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
148  LSDAEncoding = dwarf::DW_EH_PE_absptr;
149  TTypeEncoding = dwarf::DW_EH_PE_absptr;
150  if (isPositionIndependent()) {
151  PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
152  LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
154  }
155  break;
156  case Triple::aarch64:
157  case Triple::aarch64_be:
158  // The small model guarantees static code/data size < 4GB, but not where it
159  // will be in memory. Most of these could end up >2GB away so even a signed
160  // pc-relative 32-bit address is insufficient, theoretically.
161  if (isPositionIndependent()) {
162  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
167  } else {
168  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
169  LSDAEncoding = dwarf::DW_EH_PE_absptr;
170  TTypeEncoding = dwarf::DW_EH_PE_absptr;
171  }
172  break;
173  case Triple::lanai:
174  LSDAEncoding = dwarf::DW_EH_PE_absptr;
175  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
176  TTypeEncoding = dwarf::DW_EH_PE_absptr;
177  break;
178  case Triple::mips:
179  case Triple::mipsel:
180  case Triple::mips64:
181  case Triple::mips64el:
182  // MIPS uses indirect pointer to refer personality functions and types, so
183  // that the eh_frame section can be read-only. DW.ref.personality will be
184  // generated for relocation.
185  PersonalityEncoding = dwarf::DW_EH_PE_indirect;
186  // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
187  // identify N64 from just a triple.
190  // We don't support PC-relative LSDA references in GAS so we use the default
191  // DW_EH_PE_absptr for those.
192 
193  // FreeBSD must be explicit about the data size and using pcrel since it's
194  // assembler/linker won't do the automatic conversion that the Linux tools
195  // do.
196  if (TgtM.getTargetTriple().isOSFreeBSD()) {
197  PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
199  }
200  break;
201  case Triple::ppc64:
202  case Triple::ppc64le:
203  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
208  break;
209  case Triple::sparcel:
210  case Triple::sparc:
211  if (isPositionIndependent()) {
213  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
217  } else {
218  LSDAEncoding = dwarf::DW_EH_PE_absptr;
219  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
220  TTypeEncoding = dwarf::DW_EH_PE_absptr;
221  }
222  break;
223  case Triple::sparcv9:
225  if (isPositionIndependent()) {
226  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
230  } else {
231  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
232  TTypeEncoding = dwarf::DW_EH_PE_absptr;
233  }
234  break;
235  case Triple::systemz:
236  // All currently-defined code models guarantee that 4-byte PC-relative
237  // values will be in range.
238  if (isPositionIndependent()) {
239  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
244  } else {
245  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
246  LSDAEncoding = dwarf::DW_EH_PE_absptr;
247  TTypeEncoding = dwarf::DW_EH_PE_absptr;
248  }
249  break;
250  default:
251  break;
252  }
253 }
254 
256  Module &M) const {
257  auto &C = getContext();
258 
259  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
260  auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
262 
263  Streamer.SwitchSection(S);
264 
265  for (const auto &Operand : LinkerOptions->operands()) {
266  if (cast<MDNode>(Operand)->getNumOperands() != 2)
267  report_fatal_error("invalid llvm.linker.options");
268  for (const auto &Option : cast<MDNode>(Operand)->operands()) {
269  Streamer.EmitBytes(cast<MDString>(Option)->getString());
270  Streamer.EmitIntValue(0, 1);
271  }
272  }
273  }
274 
275  unsigned Version = 0;
276  unsigned Flags = 0;
278 
279  GetObjCImageInfo(M, Version, Flags, Section);
280  if (!Section.empty()) {
281  auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
282  Streamer.SwitchSection(S);
283  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
284  Streamer.EmitIntValue(Version, 4);
285  Streamer.EmitIntValue(Flags, 4);
286  Streamer.AddBlankLine();
287  }
288 
290  M.getModuleFlagsMetadata(ModuleFlags);
291 
292  MDNode *CFGProfile = nullptr;
293 
294  for (const auto &MFE : ModuleFlags) {
295  StringRef Key = MFE.Key->getString();
296  if (Key == "CG Profile") {
297  CFGProfile = cast<MDNode>(MFE.Val);
298  break;
299  }
300  }
301 
302  if (!CFGProfile)
303  return;
304 
305  auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
306  if (!MDO)
307  return nullptr;
308  auto V = cast<ValueAsMetadata>(MDO);
309  const Function *F = cast<Function>(V->getValue());
310  return TM->getSymbol(F);
311  };
312 
313  for (const auto &Edge : CFGProfile->operands()) {
314  MDNode *E = cast<MDNode>(Edge);
315  const MCSymbol *From = GetSym(E->getOperand(0));
316  const MCSymbol *To = GetSym(E->getOperand(1));
317  // Skip null functions. This can happen if functions are dead stripped after
318  // the CGProfile pass has been run.
319  if (!From || !To)
320  continue;
321  uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
322  ->getValue()
323  ->getUniqueInteger()
324  .getZExtValue();
325  Streamer.emitCGProfileEntry(
328  }
329 }
330 
332  const GlobalValue *GV, const TargetMachine &TM,
333  MachineModuleInfo *MMI) const {
334  unsigned Encoding = getPersonalityEncoding();
335  if ((Encoding & 0x80) == DW_EH_PE_indirect)
336  return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
337  TM.getSymbol(GV)->getName());
338  if ((Encoding & 0x70) == DW_EH_PE_absptr)
339  return TM.getSymbol(GV);
340  report_fatal_error("We do not support this DWARF encoding yet!");
341 }
342 
344  MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
345  SmallString<64> NameData("DW.ref.");
346  NameData += Sym->getName();
347  MCSymbolELF *Label =
348  cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
349  Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
350  Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
351  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
352  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
353  ELF::SHT_PROGBITS, Flags, 0);
354  unsigned Size = DL.getPointerSize();
355  Streamer.SwitchSection(Sec);
357  Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
358  const MCExpr *E = MCConstantExpr::create(Size, getContext());
359  Streamer.emitELFSize(Label, E);
360  Streamer.EmitLabel(Label);
361 
362  Streamer.EmitSymbolValue(Sym, Size);
363 }
364 
366  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
367  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
368  if (Encoding & DW_EH_PE_indirect) {
370 
371  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
372 
373  // Add information about the stub reference to ELFMMI so that the stub
374  // gets emitted by the asmprinter.
375  MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
376  if (!StubSym.getPointer()) {
377  MCSymbol *Sym = TM.getSymbol(GV);
379  }
380 
382  getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
383  Encoding & ~DW_EH_PE_indirect, Streamer);
384  }
385 
387  MMI, Streamer);
388 }
389 
391  // N.B.: The defaults used in here are not the same ones used in MC.
392  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
393  // both gas and MC will produce a section with no flags. Given
394  // section(".eh_frame") gcc will produce:
395  //
396  // .section .eh_frame,"a",@progbits
397 
398  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
399  /*AddSegmentInfo=*/false))
400  return SectionKind::getMetadata();
401 
402  if (Name.empty() || Name[0] != '.') return K;
403 
404  // Default implementation based on some magic section names.
405  if (Name == ".bss" ||
406  Name.startswith(".bss.") ||
407  Name.startswith(".gnu.linkonce.b.") ||
408  Name.startswith(".llvm.linkonce.b.") ||
409  Name == ".sbss" ||
410  Name.startswith(".sbss.") ||
411  Name.startswith(".gnu.linkonce.sb.") ||
412  Name.startswith(".llvm.linkonce.sb."))
413  return SectionKind::getBSS();
414 
415  if (Name == ".tdata" ||
416  Name.startswith(".tdata.") ||
417  Name.startswith(".gnu.linkonce.td.") ||
418  Name.startswith(".llvm.linkonce.td."))
420 
421  if (Name == ".tbss" ||
422  Name.startswith(".tbss.") ||
423  Name.startswith(".gnu.linkonce.tb.") ||
424  Name.startswith(".llvm.linkonce.tb."))
425  return SectionKind::getThreadBSS();
426 
427  return K;
428 }
429 
431  // Use SHT_NOTE for section whose name starts with ".note" to allow
432  // emitting ELF notes from C variable declaration.
433  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
434  if (Name.startswith(".note"))
435  return ELF::SHT_NOTE;
436 
437  if (Name == ".init_array")
438  return ELF::SHT_INIT_ARRAY;
439 
440  if (Name == ".fini_array")
441  return ELF::SHT_FINI_ARRAY;
442 
443  if (Name == ".preinit_array")
444  return ELF::SHT_PREINIT_ARRAY;
445 
446  if (K.isBSS() || K.isThreadBSS())
447  return ELF::SHT_NOBITS;
448 
449  return ELF::SHT_PROGBITS;
450 }
451 
452 static unsigned getELFSectionFlags(SectionKind K) {
453  unsigned Flags = 0;
454 
455  if (!K.isMetadata())
456  Flags |= ELF::SHF_ALLOC;
457 
458  if (K.isText())
459  Flags |= ELF::SHF_EXECINSTR;
460 
461  if (K.isExecuteOnly())
462  Flags |= ELF::SHF_ARM_PURECODE;
463 
464  if (K.isWriteable())
465  Flags |= ELF::SHF_WRITE;
466 
467  if (K.isThreadLocal())
468  Flags |= ELF::SHF_TLS;
469 
470  if (K.isMergeableCString() || K.isMergeableConst())
471  Flags |= ELF::SHF_MERGE;
472 
473  if (K.isMergeableCString())
474  Flags |= ELF::SHF_STRINGS;
475 
476  return Flags;
477 }
478 
479 static const Comdat *getELFComdat(const GlobalValue *GV) {
480  const Comdat *C = GV->getComdat();
481  if (!C)
482  return nullptr;
483 
484  if (C->getSelectionKind() != Comdat::Any)
485  report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
486  C->getName() + "' cannot be lowered.");
487 
488  return C;
489 }
490 
492  const TargetMachine &TM) {
494  if (!MD)
495  return nullptr;
496 
497  const MDOperand &Op = MD->getOperand(0);
498  if (!Op.get())
499  return nullptr;
500 
501  auto *VM = dyn_cast<ValueAsMetadata>(Op);
502  if (!VM)
503  report_fatal_error("MD_associated operand is not ValueAsMetadata");
504 
505  GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
506  return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
507 }
508 
510  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
512 
513  // Check if '#pragma clang section' name is applicable.
514  // Note that pragma directive overrides -ffunction-section, -fdata-section
515  // and so section name is exactly as user specified and not uniqued.
516  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
517  if (GV && GV->hasImplicitSection()) {
518  auto Attrs = GV->getAttributes();
519  if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
520  SectionName = Attrs.getAttribute("bss-section").getValueAsString();
521  } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
522  SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
523  } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
524  SectionName = Attrs.getAttribute("data-section").getValueAsString();
525  }
526  }
527  const Function *F = dyn_cast<Function>(GO);
528  if (F && F->hasFnAttribute("implicit-section-name")) {
529  SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
530  }
531 
532  // Infer section flags from the section name if we can.
533  Kind = getELFKindForNamedSection(SectionName, Kind);
534 
535  StringRef Group = "";
536  unsigned Flags = getELFSectionFlags(Kind);
537  if (const Comdat *C = getELFComdat(GO)) {
538  Group = C->getName();
539  Flags |= ELF::SHF_GROUP;
540  }
541 
542  // A section can have at most one associated section. Put each global with
543  // MD_associated in a unique section.
544  unsigned UniqueID = MCContext::GenericSectionID;
545  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
546  if (AssociatedSymbol) {
547  UniqueID = NextUniqueID++;
548  Flags |= ELF::SHF_LINK_ORDER;
549  }
550 
551  MCSectionELF *Section = getContext().getELFSection(
552  SectionName, getELFSectionType(SectionName, Kind), Flags,
553  /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
554  // Make sure that we did not get some other section with incompatible sh_link.
555  // This should not be possible due to UniqueID code above.
556  assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
557  "Associated symbol mismatch between sections");
558  return Section;
559 }
560 
561 /// Return the section prefix name used by options FunctionsSections and
562 /// DataSections.
564  if (Kind.isText())
565  return ".text";
566  if (Kind.isReadOnly())
567  return ".rodata";
568  if (Kind.isBSS())
569  return ".bss";
570  if (Kind.isThreadData())
571  return ".tdata";
572  if (Kind.isThreadBSS())
573  return ".tbss";
574  if (Kind.isData())
575  return ".data";
576  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
577  return ".data.rel.ro";
578 }
579 
581  if (Kind.isMergeable1ByteCString())
582  return 1;
583  else if (Kind.isMergeable2ByteCString())
584  return 2;
585  else if (Kind.isMergeable4ByteCString())
586  return 4;
587  else if (Kind.isMergeableConst4())
588  return 4;
589  else if (Kind.isMergeableConst8())
590  return 8;
591  else if (Kind.isMergeableConst16())
592  return 16;
593  else if (Kind.isMergeableConst32())
594  return 32;
595  else {
596  // We shouldn't have mergeable C strings or mergeable constants that we
597  // didn't handle above.
598  assert(!Kind.isMergeableCString() && "unknown string width");
599  assert(!Kind.isMergeableConst() && "unknown data width");
600  return 0;
601  }
602 }
603 
605  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
606  const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
607  unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
608 
609  StringRef Group = "";
610  if (const Comdat *C = getELFComdat(GO)) {
611  Flags |= ELF::SHF_GROUP;
612  Group = C->getName();
613  }
614 
615  // Get the section entry size based on the kind.
616  unsigned EntrySize = getEntrySizeForKind(Kind);
617 
619  if (Kind.isMergeableCString()) {
620  // We also need alignment here.
621  // FIXME: this is getting the alignment of the character, not the
622  // alignment of the global!
624  cast<GlobalVariable>(GO));
625 
626  std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
627  Name = SizeSpec + utostr(Align);
628  } else if (Kind.isMergeableConst()) {
629  Name = ".rodata.cst";
630  Name += utostr(EntrySize);
631  } else {
632  Name = getSectionPrefixForGlobal(Kind);
633  }
634 
635  if (const auto *F = dyn_cast<Function>(GO)) {
636  const auto &OptionalPrefix = F->getSectionPrefix();
637  if (OptionalPrefix)
638  Name += *OptionalPrefix;
639  }
640 
641  unsigned UniqueID = MCContext::GenericSectionID;
642  if (EmitUniqueSection) {
643  if (TM.getUniqueSectionNames()) {
644  Name.push_back('.');
645  TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
646  } else {
647  UniqueID = *NextUniqueID;
648  (*NextUniqueID)++;
649  }
650  }
651  // Use 0 as the unique ID for execute-only text.
652  if (Kind.isExecuteOnly())
653  UniqueID = 0;
654  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
655  EntrySize, Group, UniqueID, AssociatedSymbol);
656 }
657 
659  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
660  unsigned Flags = getELFSectionFlags(Kind);
661 
662  // If we have -ffunction-section or -fdata-section then we should emit the
663  // global value to a uniqued section specifically for it.
664  bool EmitUniqueSection = false;
665  if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
666  if (Kind.isText())
667  EmitUniqueSection = TM.getFunctionSections();
668  else
669  EmitUniqueSection = TM.getDataSections();
670  }
671  EmitUniqueSection |= GO->hasComdat();
672 
673  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
674  if (AssociatedSymbol) {
675  EmitUniqueSection = true;
676  Flags |= ELF::SHF_LINK_ORDER;
677  }
678 
680  getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
681  &NextUniqueID, AssociatedSymbol);
682  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
683  return Section;
684 }
685 
687  const Function &F, const TargetMachine &TM) const {
688  // If the function can be removed, produce a unique section so that
689  // the table doesn't prevent the removal.
690  const Comdat *C = F.getComdat();
691  bool EmitUniqueSection = TM.getFunctionSections() || C;
692  if (!EmitUniqueSection)
693  return ReadOnlySection;
694 
695  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
696  getMangler(), TM, EmitUniqueSection,
697  ELF::SHF_ALLOC, &NextUniqueID,
698  /* AssociatedSymbol */ nullptr);
699 }
700 
702  bool UsesLabelDifference, const Function &F) const {
703  // We can always create relative relocations, so use another section
704  // that can be marked non-executable.
705  return false;
706 }
707 
708 /// Given a mergeable constant with the specified size and relocation
709 /// information, return a section that it should be placed in.
711  const DataLayout &DL, SectionKind Kind, const Constant *C,
712  unsigned &Align) const {
713  if (Kind.isMergeableConst4() && MergeableConst4Section)
714  return MergeableConst4Section;
715  if (Kind.isMergeableConst8() && MergeableConst8Section)
716  return MergeableConst8Section;
717  if (Kind.isMergeableConst16() && MergeableConst16Section)
718  return MergeableConst16Section;
719  if (Kind.isMergeableConst32() && MergeableConst32Section)
720  return MergeableConst32Section;
721  if (Kind.isReadOnly())
722  return ReadOnlySection;
723 
724  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
725  return DataRelROSection;
726 }
727 
728 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
729  bool IsCtor, unsigned Priority,
730  const MCSymbol *KeySym) {
731  std::string Name;
732  unsigned Type;
733  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
734  StringRef COMDAT = KeySym ? KeySym->getName() : "";
735 
736  if (KeySym)
737  Flags |= ELF::SHF_GROUP;
738 
739  if (UseInitArray) {
740  if (IsCtor) {
741  Type = ELF::SHT_INIT_ARRAY;
742  Name = ".init_array";
743  } else {
744  Type = ELF::SHT_FINI_ARRAY;
745  Name = ".fini_array";
746  }
747  if (Priority != 65535) {
748  Name += '.';
749  Name += utostr(Priority);
750  }
751  } else {
752  // The default scheme is .ctor / .dtor, so we have to invert the priority
753  // numbering.
754  if (IsCtor)
755  Name = ".ctors";
756  else
757  Name = ".dtors";
758  if (Priority != 65535)
759  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
760  Type = ELF::SHT_PROGBITS;
761  }
762 
763  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
764 }
765 
767  unsigned Priority, const MCSymbol *KeySym) const {
768  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
769  KeySym);
770 }
771 
773  unsigned Priority, const MCSymbol *KeySym) const {
774  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
775  KeySym);
776 }
777 
779  const GlobalValue *LHS, const GlobalValue *RHS,
780  const TargetMachine &TM) const {
781  // We may only use a PLT-relative relocation to refer to unnamed_addr
782  // functions.
783  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
784  return nullptr;
785 
786  // Basic sanity checks.
787  if (LHS->getType()->getPointerAddressSpace() != 0 ||
788  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
789  RHS->isThreadLocal())
790  return nullptr;
791 
793  MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
794  getContext()),
795  MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
796 }
797 
798 void
800  UseInitArray = UseInitArray_;
801  MCContext &Ctx = getContext();
802  if (!UseInitArray) {
803  StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
805 
806  StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
808  return;
809  }
810 
811  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
813  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
815 }
816 
817 //===----------------------------------------------------------------------===//
818 // MachO
819 //===----------------------------------------------------------------------===//
820 
824 }
825 
827  const TargetMachine &TM) {
829  if (TM.getRelocationModel() == Reloc::Static) {
830  StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
832  StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
834  } else {
835  StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
838  StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
841  }
842 
846  TTypeEncoding =
848 }
849 
851  Module &M) const {
852  // Emit the linker options if present.
853  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
854  for (const auto &Option : LinkerOptions->operands()) {
855  SmallVector<std::string, 4> StrOptions;
856  for (const auto &Piece : cast<MDNode>(Option)->operands())
857  StrOptions.push_back(cast<MDString>(Piece)->getString());
858  Streamer.EmitLinkerOptions(StrOptions);
859  }
860  }
861 
862  unsigned VersionVal = 0;
863  unsigned ImageInfoFlags = 0;
864  StringRef SectionVal;
865 
866  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
867 
868  // The section is mandatory. If we don't have it, then we don't have GC info.
869  if (SectionVal.empty())
870  return;
871 
872  StringRef Segment, Section;
873  unsigned TAA = 0, StubSize = 0;
874  bool TAAParsed;
875  std::string ErrorCode =
876  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
877  TAA, TAAParsed, StubSize);
878  if (!ErrorCode.empty())
879  // If invalid, report the error with report_fatal_error.
880  report_fatal_error("Invalid section specifier '" + Section + "': " +
881  ErrorCode + ".");
882 
883  // Get the section.
885  Segment, Section, TAA, StubSize, SectionKind::getData());
886  Streamer.SwitchSection(S);
887  Streamer.EmitLabel(getContext().
888  getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
889  Streamer.EmitIntValue(VersionVal, 4);
890  Streamer.EmitIntValue(ImageInfoFlags, 4);
891  Streamer.AddBlankLine();
892 }
893 
894 static void checkMachOComdat(const GlobalValue *GV) {
895  const Comdat *C = GV->getComdat();
896  if (!C)
897  return;
898 
899  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
900  "' cannot be lowered.");
901 }
902 
904  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
905  // Parse the section specifier and create it if valid.
906  StringRef Segment, Section;
907  unsigned TAA = 0, StubSize = 0;
908  bool TAAParsed;
909 
910  checkMachOComdat(GO);
911 
912  std::string ErrorCode =
914  TAA, TAAParsed, StubSize);
915  if (!ErrorCode.empty()) {
916  // If invalid, report the error with report_fatal_error.
917  report_fatal_error("Global variable '" + GO->getName() +
918  "' has an invalid section specifier '" +
919  GO->getSection() + "': " + ErrorCode + ".");
920  }
921 
922  // Get the section.
923  MCSectionMachO *S =
924  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
925 
926  // If TAA wasn't set by ParseSectionSpecifier() above,
927  // use the value returned by getMachOSection() as a default.
928  if (!TAAParsed)
929  TAA = S->getTypeAndAttributes();
930 
931  // Okay, now that we got the section, verify that the TAA & StubSize agree.
932  // If the user declared multiple globals with different section flags, we need
933  // to reject it here.
934  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
935  // If invalid, report the error with report_fatal_error.
936  report_fatal_error("Global variable '" + GO->getName() +
937  "' section type or attributes does not match previous"
938  " section specifier");
939  }
940 
941  return S;
942 }
943 
945  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
946  checkMachOComdat(GO);
947 
948  // Handle thread local data.
949  if (Kind.isThreadBSS()) return TLSBSSSection;
950  if (Kind.isThreadData()) return TLSDataSection;
951 
952  if (Kind.isText())
954 
955  // If this is weak/linkonce, put this in a coalescable section, either in text
956  // or data depending on if it is writable.
957  if (GO->isWeakForLinker()) {
958  if (Kind.isReadOnly())
959  return ConstTextCoalSection;
960  if (Kind.isReadOnlyWithRel())
961  return ConstDataCoalSection;
962  return DataCoalSection;
963  }
964 
965  // FIXME: Alignment check should be handled by section classifier.
966  if (Kind.isMergeable1ByteCString() &&
968  cast<GlobalVariable>(GO)) < 32)
969  return CStringSection;
970 
971  // Do not put 16-bit arrays in the UString section if they have an
972  // externally visible label, this runs into issues with certain linker
973  // versions.
974  if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
976  cast<GlobalVariable>(GO)) < 32)
977  return UStringSection;
978 
979  // With MachO only variables whose corresponding symbol starts with 'l' or
980  // 'L' can be merged, so we only try merging GVs with private linkage.
981  if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
982  if (Kind.isMergeableConst4())
984  if (Kind.isMergeableConst8())
986  if (Kind.isMergeableConst16())
988  }
989 
990  // Otherwise, if it is readonly, but not something we can specially optimize,
991  // just drop it in .const.
992  if (Kind.isReadOnly())
993  return ReadOnlySection;
994 
995  // If this is marked const, put it into a const section. But if the dynamic
996  // linker needs to write to it, put it in the data segment.
997  if (Kind.isReadOnlyWithRel())
998  return ConstDataSection;
999 
1000  // Put zero initialized globals with strong external linkage in the
1001  // DATA, __common section with the .zerofill directive.
1002  if (Kind.isBSSExtern())
1003  return DataCommonSection;
1004 
1005  // Put zero initialized globals with local linkage in __DATA,__bss directive
1006  // with the .zerofill directive (aka .lcomm).
1007  if (Kind.isBSSLocal())
1008  return DataBSSSection;
1009 
1010  // Otherwise, just drop the variable in the normal data section.
1011  return DataSection;
1012 }
1013 
1015  const DataLayout &DL, SectionKind Kind, const Constant *C,
1016  unsigned &Align) const {
1017  // If this constant requires a relocation, we have to put it in the data
1018  // segment, not in the text segment.
1019  if (Kind.isData() || Kind.isReadOnlyWithRel())
1020  return ConstDataSection;
1021 
1022  if (Kind.isMergeableConst4())
1023  return FourByteConstantSection;
1024  if (Kind.isMergeableConst8())
1025  return EightByteConstantSection;
1026  if (Kind.isMergeableConst16())
1028  return ReadOnlySection; // .const
1029 }
1030 
1032  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1033  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1034  // The mach-o version of this method defaults to returning a stub reference.
1035 
1036  if (Encoding & DW_EH_PE_indirect) {
1037  MachineModuleInfoMachO &MachOMMI =
1039 
1040  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1041 
1042  // Add information about the stub reference to MachOMMI so that the stub
1043  // gets emitted by the asmprinter.
1044  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1045  if (!StubSym.getPointer()) {
1046  MCSymbol *Sym = TM.getSymbol(GV);
1047  StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1048  }
1049 
1052  Encoding & ~DW_EH_PE_indirect, Streamer);
1053  }
1054 
1055  return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1056  MMI, Streamer);
1057 }
1058 
1060  const GlobalValue *GV, const TargetMachine &TM,
1061  MachineModuleInfo *MMI) const {
1062  // The mach-o version of this method defaults to returning a stub reference.
1063  MachineModuleInfoMachO &MachOMMI =
1065 
1066  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1067 
1068  // Add information about the stub reference to MachOMMI so that the stub
1069  // gets emitted by the asmprinter.
1070  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1071  if (!StubSym.getPointer()) {
1072  MCSymbol *Sym = TM.getSymbol(GV);
1073  StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1074  }
1075 
1076  return SSym;
1077 }
1078 
1080  const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
1081  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1082  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1083  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1084  // through a non_lazy_ptr stub instead. One advantage is that it allows the
1085  // computation of deltas to final external symbols. Example:
1086  //
1087  // _extgotequiv:
1088  // .long _extfoo
1089  //
1090  // _delta:
1091  // .long _extgotequiv-_delta
1092  //
1093  // is transformed to:
1094  //
1095  // _delta:
1096  // .long L_extfoo$non_lazy_ptr-(_delta+0)
1097  //
1098  // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1099  // L_extfoo$non_lazy_ptr:
1100  // .indirect_symbol _extfoo
1101  // .long 0
1102  //
1103  MachineModuleInfoMachO &MachOMMI =
1105  MCContext &Ctx = getContext();
1106 
1107  // The offset must consider the original displacement from the base symbol
1108  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1109  Offset = -MV.getConstant();
1110  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1111 
1112  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1113  // non_lazy_ptr stubs.
1115  StringRef Suffix = "$non_lazy_ptr";
1116  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1117  Name += Sym->getName();
1118  Name += Suffix;
1119  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1120 
1121  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1122  if (!StubSym.getPointer())
1123  StubSym = MachineModuleInfoImpl::
1124  StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
1125 
1126  const MCExpr *BSymExpr =
1128  const MCExpr *LHS =
1130 
1131  if (!Offset)
1132  return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1133 
1134  const MCExpr *RHS =
1135  MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1136  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1137 }
1138 
1139 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1140  const MCSection &Section) {
1141  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1142  return true;
1143 
1144  // If it is not dead stripped, it is safe to use private labels.
1145  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1147  return true;
1148 
1149  return false;
1150 }
1151 
1153  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1154  const TargetMachine &TM) const {
1155  bool CannotUsePrivateLabel = true;
1156  if (auto *GO = GV->getBaseObject()) {
1158  const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1159  CannotUsePrivateLabel =
1160  !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1161  }
1162  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1163 }
1164 
1165 //===----------------------------------------------------------------------===//
1166 // COFF
1167 //===----------------------------------------------------------------------===//
1168 
1169 static unsigned
1171  unsigned Flags = 0;
1172  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1173 
1174  if (K.isMetadata())
1175  Flags |=
1177  else if (K.isText())
1178  Flags |=
1183  else if (K.isBSS())
1184  Flags |=
1188  else if (K.isThreadLocal())
1189  Flags |=
1193  else if (K.isReadOnly() || K.isReadOnlyWithRel())
1194  Flags |=
1197  else if (K.isWriteable())
1198  Flags |=
1202 
1203  return Flags;
1204 }
1205 
1206 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1207  const Comdat *C = GV->getComdat();
1208  assert(C && "expected GV to have a Comdat!");
1209 
1210  StringRef ComdatGVName = C->getName();
1211  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1212  if (!ComdatGV)
1213  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1214  "' does not exist.");
1215 
1216  if (ComdatGV->getComdat() != C)
1217  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1218  "' is not a key for its COMDAT.");
1219 
1220  return ComdatGV;
1221 }
1222 
1223 static int getSelectionForCOFF(const GlobalValue *GV) {
1224  if (const Comdat *C = GV->getComdat()) {
1225  const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1226  if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1227  ComdatKey = GA->getBaseObject();
1228  if (ComdatKey == GV) {
1229  switch (C->getSelectionKind()) {
1230  case Comdat::Any:
1232  case Comdat::ExactMatch:
1234  case Comdat::Largest:
1236  case Comdat::NoDuplicates:
1238  case Comdat::SameSize:
1240  }
1241  } else {
1243  }
1244  }
1245  return 0;
1246 }
1247 
1249  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1250  int Selection = 0;
1251  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1252  StringRef Name = GO->getSection();
1253  StringRef COMDATSymName = "";
1254  if (GO->hasComdat()) {
1255  Selection = getSelectionForCOFF(GO);
1256  const GlobalValue *ComdatGV;
1257  if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1258  ComdatGV = getComdatGVForCOFF(GO);
1259  else
1260  ComdatGV = GO;
1261 
1262  if (!ComdatGV->hasPrivateLinkage()) {
1263  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1264  COMDATSymName = Sym->getName();
1265  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1266  } else {
1267  Selection = 0;
1268  }
1269  }
1270 
1271  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1272  Selection);
1273 }
1274 
1276  if (Kind.isText())
1277  return ".text";
1278  if (Kind.isBSS())
1279  return ".bss";
1280  if (Kind.isThreadLocal())
1281  return ".tls$";
1282  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1283  return ".rdata";
1284  return ".data";
1285 }
1286 
1288  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1289  // If we have -ffunction-sections then we should emit the global value to a
1290  // uniqued section specifically for it.
1291  bool EmitUniquedSection;
1292  if (Kind.isText())
1293  EmitUniquedSection = TM.getFunctionSections();
1294  else
1295  EmitUniquedSection = TM.getDataSections();
1296 
1297  if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1299 
1300  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1301 
1302  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1303  int Selection = getSelectionForCOFF(GO);
1304  if (!Selection)
1306  const GlobalValue *ComdatGV;
1307  if (GO->hasComdat())
1308  ComdatGV = getComdatGVForCOFF(GO);
1309  else
1310  ComdatGV = GO;
1311 
1312  unsigned UniqueID = MCContext::GenericSectionID;
1313  if (EmitUniquedSection)
1314  UniqueID = NextUniqueID++;
1315 
1316  if (!ComdatGV->hasPrivateLinkage()) {
1317  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1318  StringRef COMDATSymName = Sym->getName();
1319 
1320  // Append "$symbol" to the section name when targetting mingw. The ld.bfd
1321  // COFF linker will not properly handle comdats otherwise.
1322  if (getTargetTriple().isWindowsGNUEnvironment())
1323  raw_svector_ostream(Name) << '$' << COMDATSymName;
1324 
1325  return getContext().getCOFFSection(Name, Characteristics, Kind,
1326  COMDATSymName, Selection, UniqueID);
1327  } else {
1328  SmallString<256> TmpData;
1329  getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1330  return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1331  Selection, UniqueID);
1332  }
1333  }
1334 
1335  if (Kind.isText())
1336  return TextSection;
1337 
1338  if (Kind.isThreadLocal())
1339  return TLSDataSection;
1340 
1341  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1342  return ReadOnlySection;
1343 
1344  // Note: we claim that common symbols are put in BSSSection, but they are
1345  // really emitted with the magic .comm directive, which creates a symbol table
1346  // entry but not a section.
1347  if (Kind.isBSS() || Kind.isCommon())
1348  return BSSSection;
1349 
1350  return DataSection;
1351 }
1352 
1354  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1355  const TargetMachine &TM) const {
1356  bool CannotUsePrivateLabel = false;
1357  if (GV->hasPrivateLinkage() &&
1358  ((isa<Function>(GV) && TM.getFunctionSections()) ||
1359  (isa<GlobalVariable>(GV) && TM.getDataSections())))
1360  CannotUsePrivateLabel = true;
1361 
1362  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1363 }
1364 
1366  const Function &F, const TargetMachine &TM) const {
1367  // If the function can be removed, produce a unique section so that
1368  // the table doesn't prevent the removal.
1369  const Comdat *C = F.getComdat();
1370  bool EmitUniqueSection = TM.getFunctionSections() || C;
1371  if (!EmitUniqueSection)
1372  return ReadOnlySection;
1373 
1374  // FIXME: we should produce a symbol for F instead.
1375  if (F.hasPrivateLinkage())
1376  return ReadOnlySection;
1377 
1378  MCSymbol *Sym = TM.getSymbol(&F);
1379  StringRef COMDATSymName = Sym->getName();
1380 
1383  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1384  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1385  unsigned UniqueID = NextUniqueID++;
1386 
1387  return getContext().getCOFFSection(
1388  SecName, Characteristics, Kind, COMDATSymName,
1390 }
1391 
1393  Module &M) const {
1394  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1395  // Emit the linker options to the linker .drectve section. According to the
1396  // spec, this section is a space-separated string containing flags for
1397  // linker.
1398  MCSection *Sec = getDrectveSection();
1399  Streamer.SwitchSection(Sec);
1400  for (const auto &Option : LinkerOptions->operands()) {
1401  for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1402  // Lead with a space for consistency with our dllexport implementation.
1403  std::string Directive(" ");
1404  Directive.append(cast<MDString>(Piece)->getString());
1405  Streamer.EmitBytes(Directive);
1406  }
1407  }
1408  }
1409 
1410  unsigned Version = 0;
1411  unsigned Flags = 0;
1413 
1414  GetObjCImageInfo(M, Version, Flags, Section);
1415  if (Section.empty())
1416  return;
1417 
1418  auto &C = getContext();
1419  auto *S = C.getCOFFSection(
1422  Streamer.SwitchSection(S);
1423  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1424  Streamer.EmitIntValue(Version, 4);
1425  Streamer.EmitIntValue(Flags, 4);
1426  Streamer.AddBlankLine();
1427 }
1428 
1430  const TargetMachine &TM) {
1432  const Triple &T = TM.getTargetTriple();
1442  } else {
1451  }
1452 }
1453 
1455  const Triple &T, bool IsCtor,
1456  unsigned Priority,
1457  const MCSymbol *KeySym,
1460  // If the priority is the default, use .CRT$XCU, possibly associative.
1461  if (Priority == 65535)
1462  return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1463 
1464  // Otherwise, we need to compute a new section name. Low priorities should
1465  // run earlier. The linker will sort sections ASCII-betically, and we need a
1466  // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1467  // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1468  // low priorities need to sort before 'L', since the CRT uses that
1469  // internally, so we use ".CRT$XCA00001" for them.
1471  raw_svector_ostream OS(Name);
1472  OS << ".CRT$XC" << (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1473  MCSectionCOFF *Sec = Ctx.getCOFFSection(
1476  return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1477  }
1478 
1479  std::string Name = IsCtor ? ".ctors" : ".dtors";
1480  if (Priority != 65535)
1481  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1482 
1483  return Ctx.getAssociativeCOFFSection(
1488  KeySym, 0);
1489 }
1490 
1492  unsigned Priority, const MCSymbol *KeySym) const {
1494  Priority, KeySym,
1495  cast<MCSectionCOFF>(StaticCtorSection));
1496 }
1497 
1499  unsigned Priority, const MCSymbol *KeySym) const {
1501  Priority, KeySym,
1502  cast<MCSectionCOFF>(StaticDtorSection));
1503 }
1504 
1506  raw_ostream &OS, const GlobalValue *GV) const {
1508 }
1509 
1511  raw_ostream &OS, const GlobalValue *GV) const {
1513 }
1514 
1516  const GlobalValue *LHS, const GlobalValue *RHS,
1517  const TargetMachine &TM) const {
1518  const Triple &T = TM.getTargetTriple();
1519  if (!T.isKnownWindowsMSVCEnvironment() &&
1522  return nullptr;
1523 
1524  // Our symbols should exist in address space zero, cowardly no-op if
1525  // otherwise.
1526  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1527  RHS->getType()->getPointerAddressSpace() != 0)
1528  return nullptr;
1529 
1530  // Both ptrtoint instructions must wrap global objects:
1531  // - Only global variables are eligible for image relative relocations.
1532  // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1533  // We expect __ImageBase to be a global variable without a section, externally
1534  // defined.
1535  //
1536  // It should look something like this: @__ImageBase = external constant i8
1537  if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1538  LHS->isThreadLocal() || RHS->isThreadLocal() ||
1539  RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1540  cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1541  return nullptr;
1542 
1543  return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1545  getContext());
1546 }
1547 
1548 static std::string APIntToHexString(const APInt &AI) {
1549  unsigned Width = (AI.getBitWidth() / 8) * 2;
1550  std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1551  unsigned Size = HexString.size();
1552  assert(Width >= Size && "hex string is too large!");
1553  HexString.insert(HexString.begin(), Width - Size, '0');
1554 
1555  return HexString;
1556 }
1557 
1558 static std::string scalarConstantToHexString(const Constant *C) {
1559  Type *Ty = C->getType();
1560  if (isa<UndefValue>(C)) {
1562  } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1563  return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1564  } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1565  return APIntToHexString(CI->getValue());
1566  } else {
1567  unsigned NumElements;
1568  if (isa<VectorType>(Ty))
1569  NumElements = Ty->getVectorNumElements();
1570  else
1571  NumElements = Ty->getArrayNumElements();
1572  std::string HexString;
1573  for (int I = NumElements - 1, E = -1; I != E; --I)
1575  return HexString;
1576  }
1577 }
1578 
1580  const DataLayout &DL, SectionKind Kind, const Constant *C,
1581  unsigned &Align) const {
1582  if (Kind.isMergeableConst() && C &&
1584  // This creates comdat sections with the given symbol name, but unless
1585  // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1586  // will be created with a null storage class, which makes GNU binutils
1587  // error out.
1591  std::string COMDATSymName;
1592  if (Kind.isMergeableConst4()) {
1593  if (Align <= 4) {
1594  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1595  Align = 4;
1596  }
1597  } else if (Kind.isMergeableConst8()) {
1598  if (Align <= 8) {
1599  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1600  Align = 8;
1601  }
1602  } else if (Kind.isMergeableConst16()) {
1603  // FIXME: These may not be appropriate for non-x86 architectures.
1604  if (Align <= 16) {
1605  COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1606  Align = 16;
1607  }
1608  } else if (Kind.isMergeableConst32()) {
1609  if (Align <= 32) {
1610  COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1611  Align = 32;
1612  }
1613  }
1614 
1615  if (!COMDATSymName.empty())
1616  return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1617  COMDATSymName,
1619  }
1620 
1621  return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1622 }
1623 
1624 
1625 //===----------------------------------------------------------------------===//
1626 // Wasm
1627 //===----------------------------------------------------------------------===//
1628 
1629 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1630  const Comdat *C = GV->getComdat();
1631  if (!C)
1632  return nullptr;
1633 
1634  if (C->getSelectionKind() != Comdat::Any)
1635  report_fatal_error("WebAssembly COMDATs only support "
1636  "SelectionKind::Any, '" + C->getName() + "' cannot be "
1637  "lowered.");
1638 
1639  return C;
1640 }
1641 
1643  // If we're told we have function data, then use that.
1644  if (K.isText())
1645  return SectionKind::getText();
1646 
1647  // Otherwise, ignore whatever section type the generic impl detected and use
1648  // a plain data section.
1649  return SectionKind::getData();
1650 }
1651 
1653  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1654  // We don't support explict section names for functions in the wasm object
1655  // format. Each function has to be in its own unique section.
1656  if (isa<Function>(GO)) {
1657  return SelectSectionForGlobal(GO, Kind, TM);
1658  }
1659 
1660  StringRef Name = GO->getSection();
1661 
1662  Kind = getWasmKindForNamedSection(Name, Kind);
1663 
1664  StringRef Group = "";
1665  if (const Comdat *C = getWasmComdat(GO)) {
1666  Group = C->getName();
1667  }
1668 
1669  return getContext().getWasmSection(Name, Kind, Group,
1671 }
1672 
1674  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1675  const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1676  StringRef Group = "";
1677  if (const Comdat *C = getWasmComdat(GO)) {
1678  Group = C->getName();
1679  }
1680 
1681  bool UniqueSectionNames = TM.getUniqueSectionNames();
1683 
1684  if (const auto *F = dyn_cast<Function>(GO)) {
1685  const auto &OptionalPrefix = F->getSectionPrefix();
1686  if (OptionalPrefix)
1687  Name += *OptionalPrefix;
1688  }
1689 
1690  if (EmitUniqueSection && UniqueSectionNames) {
1691  Name.push_back('.');
1692  TM.getNameWithPrefix(Name, GO, Mang, true);
1693  }
1694  unsigned UniqueID = MCContext::GenericSectionID;
1695  if (EmitUniqueSection && !UniqueSectionNames) {
1696  UniqueID = *NextUniqueID;
1697  (*NextUniqueID)++;
1698  }
1699  return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1700 }
1701 
1703  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1704 
1705  if (Kind.isCommon())
1706  report_fatal_error("mergable sections not supported yet on wasm");
1707 
1708  // If we have -ffunction-section or -fdata-section then we should emit the
1709  // global value to a uniqued section specifically for it.
1710  bool EmitUniqueSection = false;
1711  if (Kind.isText())
1712  EmitUniqueSection = TM.getFunctionSections();
1713  else
1714  EmitUniqueSection = TM.getDataSections();
1715  EmitUniqueSection |= GO->hasComdat();
1716 
1717  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1718  EmitUniqueSection, &NextUniqueID);
1719 }
1720 
1722  bool UsesLabelDifference, const Function &F) const {
1723  // We can always create relative relocations, so use another section
1724  // that can be marked non-executable.
1725  return false;
1726 }
1727 
1729  const GlobalValue *LHS, const GlobalValue *RHS,
1730  const TargetMachine &TM) const {
1731  // We may only use a PLT-relative relocation to refer to unnamed_addr
1732  // functions.
1733  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1734  return nullptr;
1735 
1736  // Basic sanity checks.
1737  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1738  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1739  RHS->isThreadLocal())
1740  return nullptr;
1741 
1742  return MCBinaryExpr::createSub(
1744  getContext()),
1746 }
1747 
1750  getContext().getWasmSection(".init_array", SectionKind::getData());
1751 }
1752 
1754  unsigned Priority, const MCSymbol *KeySym) const {
1755  return Priority == UINT16_MAX ?
1757  getContext().getWasmSection(".init_array." + utostr(Priority),
1759 }
1760 
1762  unsigned Priority, const MCSymbol *KeySym) const {
1763  llvm_unreachable("@llvm.global_dtors should have been lowered already");
1764  return nullptr;
1765 }
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:293
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:218
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:711
static SectionKind getData()
Definition: SectionKind.h:202
static MCSectionCOFF * getCOFFStaticStructorSection(MCContext &Ctx, const Triple &T, bool IsCtor, unsigned Priority, const MCSymbol *KeySym, MCSectionCOFF *Default)
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:436
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
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:322
bool hasPrivateLinkage() const
Definition: GlobalValue.h:435
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:139
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:147
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
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const override
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:294
static std::string scalarConstantToHexString(const Constant *C)
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:64
#define LLVM_FALLTHROUGH
Definition: Compiler.h:86
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:327
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.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
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:977
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit the module flags that specify the garbage collection information.
static void checkMachOComdat(const GlobalValue *GV)
This file contains the declarations for metadata subclasses.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K)
Definition: MCContext.h:454
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
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:321
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:39
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:510
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:864
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
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.
setjmp/longjmp based exceptions
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1069
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:611
static bool isThumb(const MCSubtargetInfo &STI)
unsigned getTypeAndAttributes() const
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1503
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:422
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:470
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:128
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
This represents a section on Windows.
Definition: MCSectionCOFF.h:27
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)
bool hasSection() const
Definition: GlobalValue.h:270
int64_t getConstant() const
Definition: MCValue.h:47
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:49
A tuple of MDNodes.
Definition: Metadata.h:1326
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:364
uint64_t getArrayNumElements() const
Definition: DerivedTypes.h:388
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:531
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:1444
The linker may choose any COMDAT.
Definition: Comdat.h:35
bool hasCOFFComdatConstants() const
Definition: MCAsmInfo.h:476
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:63
bool hasExternalLinkage() const
Definition: GlobalValue.h:422
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
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
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:545
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:273
op_range operands() const
Definition: Metadata.h:1067
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:286
static std::string APIntToHexString(const APInt &AI)
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:245
MCSection * ConstDataCoalSection
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:113
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.
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:339
static SectionKind getThreadData()
Definition: SectionKind.h:197
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
bool isWindowsItaniumEnvironment() const
Definition: Triple.h:539
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
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:112
bool isWindowsCoreCLREnvironment() const
Definition: Triple.h:535
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
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:284
bool isReadOnlyWithRel() const
Definition: SectionKind.h:168
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:338
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:370
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 getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:285
static const Comdat * getWasmComdat(const GlobalValue *GV)
No other Module may specify this COMDAT.
Definition: Comdat.h:38
Streaming machine code generation interface.
Definition: MCStreamer.h:183
StringRef getName() const
Definition: Comdat.cpp:27
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.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const override
Given a mergeable constant with the specified size and relocation information, return a section that ...
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:629
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
Definition: MCStreamer.cpp:999
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)
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const
Given a constant with the SectionKind, return a section that it should be placed in.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
MCSymbol * getSymbol(const GlobalValue *GV) const
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
virtual bool isSectionAtomizableBySymbols(const MCSection &Section) const
True if the section is atomized using the symbols in it.
Definition: MCAsmInfo.cpp:74
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:987
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:185
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
const Triple & getTargetTriple() const
void emitLinkerFlagsForUsed(raw_ostream &OS, const GlobalValue *GV) const override
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:36
StubValueTy & getGVStubEntry(MCSymbol *Sym)
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)
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Definition: MachO.h:190
static SectionKind getThreadBSS()
Definition: SectionKind.h:196
BlockVerifier::State From
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
const MCSymbol & getSymbol() const
Definition: MCExpr.h:335
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:847
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:37
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:200
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:224
bool isOSFreeBSD() const
Definition: Triple.h:487
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:810
This file contains constants used for implementing Dwarf debug support.
const Comdat * getComdat() const
Definition: Globals.cpp:171
Class for arbitrary precision integers.
Definition: APInt.h:70
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:372
CodeModel::Model getCodeModel() const
Returns the code model.
static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K)
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:215
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:443
bool getUniqueSectionNames() const
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:195
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:482
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:224
static int getSelectionForCOFF(const GlobalValue *GV)
#define I(x, y, z)
Definition: MD5.cpp:58
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:323
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
Definition: MCStreamer.cpp:968
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:276
uint32_t Size
Definition: Profile.cpp:47
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:216
const Module * getModule() const
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets...
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:261
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:203
const unsigned Kind
static unsigned getEntrySizeForKind(SectionKind Kind)
MCSection * TLSBSSSection
Section directive for Thread Local uninitialized data.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:483
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:389
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
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:566
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:328
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:570
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:331
Metadata * get() const
Definition: Metadata.h:722
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:46
virtual void emitCGProfileEntry(const MCSymbolRefExpr *From, const MCSymbolRefExpr *To, uint64_t Count)
Definition: MCStreamer.cpp:670
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:59
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:112
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:247
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...
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:569
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:140
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
static SectionKind getReadOnly()
Definition: SectionKind.h:182
const uint64_t Version
Definition: InstrProf.h:895
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:164
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:274
This class contains meta information specific to a module.
std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:125
SelectionKind getSelectionKind() const
Definition: Comdat.h:45
static SectionKind getText()
Definition: SectionKind.h:180
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override