LLVM  9.0.0svn
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/ELF.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Mangler.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSectionCOFF.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/MC/MCSectionWasm.h"
46 #include "llvm/MC/MCStreamer.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/MC/MCSymbolELF.h"
49 #include "llvm/MC/MCValue.h"
50 #include "llvm/MC/SectionKind.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CodeGen.h"
54 #include "llvm/Support/Format.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  const TargetMachine &TgtM) {
96  TM = &TgtM;
97 
98  CodeModel::Model CM = TgtM.getCodeModel();
99 
100  switch (TgtM.getTargetTriple().getArch()) {
101  case Triple::arm:
102  case Triple::armeb:
103  case Triple::thumb:
104  case Triple::thumbeb:
106  break;
107  // Fallthrough if not using EHABI
109  case Triple::ppc:
110  case Triple::x86:
111  PersonalityEncoding = isPositionIndependent()
116  LSDAEncoding = isPositionIndependent()
119  TTypeEncoding = isPositionIndependent()
123  break;
124  case Triple::x86_64:
125  if (isPositionIndependent()) {
126  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
127  ((CM == CodeModel::Small || CM == CodeModel::Medium)
129  LSDAEncoding = dwarf::DW_EH_PE_pcrel |
130  (CM == CodeModel::Small
133  ((CM == CodeModel::Small || CM == CodeModel::Medium)
134  ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
135  } else {
136  PersonalityEncoding =
137  (CM == CodeModel::Small || CM == CodeModel::Medium)
139  LSDAEncoding = (CM == CodeModel::Small)
141  TTypeEncoding = (CM == CodeModel::Small)
143  }
144  break;
145  case Triple::hexagon:
146  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
147  LSDAEncoding = dwarf::DW_EH_PE_absptr;
148  TTypeEncoding = dwarf::DW_EH_PE_absptr;
149  if (isPositionIndependent()) {
150  PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
151  LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
153  }
154  break;
155  case Triple::aarch64:
156  case Triple::aarch64_be:
157  // The small model guarantees static code/data size < 4GB, but not where it
158  // will be in memory. Most of these could end up >2GB away so even a signed
159  // pc-relative 32-bit address is insufficient, theoretically.
160  if (isPositionIndependent()) {
161  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
166  } else {
167  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
168  LSDAEncoding = dwarf::DW_EH_PE_absptr;
169  TTypeEncoding = dwarf::DW_EH_PE_absptr;
170  }
171  break;
172  case Triple::lanai:
173  LSDAEncoding = dwarf::DW_EH_PE_absptr;
174  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
175  TTypeEncoding = dwarf::DW_EH_PE_absptr;
176  break;
177  case Triple::mips:
178  case Triple::mipsel:
179  case Triple::mips64:
180  case Triple::mips64el:
181  // MIPS uses indirect pointer to refer personality functions and types, so
182  // that the eh_frame section can be read-only. DW.ref.personality will be
183  // generated for relocation.
184  PersonalityEncoding = dwarf::DW_EH_PE_indirect;
185  // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
186  // identify N64 from just a triple.
189  // We don't support PC-relative LSDA references in GAS so we use the default
190  // DW_EH_PE_absptr for those.
191 
192  // FreeBSD must be explicit about the data size and using pcrel since it's
193  // assembler/linker won't do the automatic conversion that the Linux tools
194  // do.
195  if (TgtM.getTargetTriple().isOSFreeBSD()) {
196  PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
198  }
199  break;
200  case Triple::ppc64:
201  case Triple::ppc64le:
202  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
207  break;
208  case Triple::sparcel:
209  case Triple::sparc:
210  if (isPositionIndependent()) {
212  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
216  } else {
217  LSDAEncoding = dwarf::DW_EH_PE_absptr;
218  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
219  TTypeEncoding = dwarf::DW_EH_PE_absptr;
220  }
221  break;
222  case Triple::sparcv9:
224  if (isPositionIndependent()) {
225  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
229  } else {
230  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
231  TTypeEncoding = dwarf::DW_EH_PE_absptr;
232  }
233  break;
234  case Triple::systemz:
235  // All currently-defined code models guarantee that 4-byte PC-relative
236  // values will be in range.
237  if (isPositionIndependent()) {
238  PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
243  } else {
244  PersonalityEncoding = dwarf::DW_EH_PE_absptr;
245  LSDAEncoding = dwarf::DW_EH_PE_absptr;
246  TTypeEncoding = dwarf::DW_EH_PE_absptr;
247  }
248  break;
249  default:
250  break;
251  }
252 }
253 
255  Module &M) const {
256  auto &C = getContext();
257 
258  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
259  auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
261 
262  Streamer.SwitchSection(S);
263 
264  for (const auto &Operand : LinkerOptions->operands()) {
265  if (cast<MDNode>(Operand)->getNumOperands() != 2)
266  report_fatal_error("invalid llvm.linker.options");
267  for (const auto &Option : cast<MDNode>(Operand)->operands()) {
268  Streamer.EmitBytes(cast<MDString>(Option)->getString());
269  Streamer.EmitIntValue(0, 1);
270  }
271  }
272  }
273 
274  unsigned Version = 0;
275  unsigned Flags = 0;
277 
278  GetObjCImageInfo(M, Version, Flags, Section);
279  if (!Section.empty()) {
280  auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
281  Streamer.SwitchSection(S);
282  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
283  Streamer.EmitIntValue(Version, 4);
284  Streamer.EmitIntValue(Flags, 4);
285  Streamer.AddBlankLine();
286  }
287 
289  M.getModuleFlagsMetadata(ModuleFlags);
290 
291  MDNode *CFGProfile = nullptr;
292 
293  for (const auto &MFE : ModuleFlags) {
294  StringRef Key = MFE.Key->getString();
295  if (Key == "CG Profile") {
296  CFGProfile = cast<MDNode>(MFE.Val);
297  break;
298  }
299  }
300 
301  if (!CFGProfile)
302  return;
303 
304  auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
305  if (!MDO)
306  return nullptr;
307  auto V = cast<ValueAsMetadata>(MDO);
308  const Function *F = cast<Function>(V->getValue());
309  return TM->getSymbol(F);
310  };
311 
312  for (const auto &Edge : CFGProfile->operands()) {
313  MDNode *E = cast<MDNode>(Edge);
314  const MCSymbol *From = GetSym(E->getOperand(0));
315  const MCSymbol *To = GetSym(E->getOperand(1));
316  // Skip null functions. This can happen if functions are dead stripped after
317  // the CGProfile pass has been run.
318  if (!From || !To)
319  continue;
320  uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
321  ->getValue()
322  ->getUniqueInteger()
323  .getZExtValue();
324  Streamer.emitCGProfileEntry(
327  }
328 }
329 
331  const GlobalValue *GV, const TargetMachine &TM,
332  MachineModuleInfo *MMI) const {
333  unsigned Encoding = getPersonalityEncoding();
334  if ((Encoding & 0x80) == DW_EH_PE_indirect)
335  return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
336  TM.getSymbol(GV)->getName());
337  if ((Encoding & 0x70) == DW_EH_PE_absptr)
338  return TM.getSymbol(GV);
339  report_fatal_error("We do not support this DWARF encoding yet!");
340 }
341 
343  MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
344  SmallString<64> NameData("DW.ref.");
345  NameData += Sym->getName();
346  MCSymbolELF *Label =
347  cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
348  Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
349  Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
350  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
351  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
352  ELF::SHT_PROGBITS, Flags, 0);
353  unsigned Size = DL.getPointerSize();
354  Streamer.SwitchSection(Sec);
356  Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
357  const MCExpr *E = MCConstantExpr::create(Size, getContext());
358  Streamer.emitELFSize(Label, E);
359  Streamer.EmitLabel(Label);
360 
361  Streamer.EmitSymbolValue(Sym, Size);
362 }
363 
365  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
366  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
367  if (Encoding & DW_EH_PE_indirect) {
369 
370  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
371 
372  // Add information about the stub reference to ELFMMI so that the stub
373  // gets emitted by the asmprinter.
374  MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
375  if (!StubSym.getPointer()) {
376  MCSymbol *Sym = TM.getSymbol(GV);
378  }
379 
381  getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
382  Encoding & ~DW_EH_PE_indirect, Streamer);
383  }
384 
386  MMI, Streamer);
387 }
388 
390  // N.B.: The defaults used in here are not the same ones used in MC.
391  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
392  // both gas and MC will produce a section with no flags. Given
393  // section(".eh_frame") gcc will produce:
394  //
395  // .section .eh_frame,"a",@progbits
396 
397  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
398  /*AddSegmentInfo=*/false))
399  return SectionKind::getMetadata();
400 
401  if (Name.empty() || Name[0] != '.') return K;
402 
403  // Default implementation based on some magic section names.
404  if (Name == ".bss" ||
405  Name.startswith(".bss.") ||
406  Name.startswith(".gnu.linkonce.b.") ||
407  Name.startswith(".llvm.linkonce.b.") ||
408  Name == ".sbss" ||
409  Name.startswith(".sbss.") ||
410  Name.startswith(".gnu.linkonce.sb.") ||
411  Name.startswith(".llvm.linkonce.sb."))
412  return SectionKind::getBSS();
413 
414  if (Name == ".tdata" ||
415  Name.startswith(".tdata.") ||
416  Name.startswith(".gnu.linkonce.td.") ||
417  Name.startswith(".llvm.linkonce.td."))
419 
420  if (Name == ".tbss" ||
421  Name.startswith(".tbss.") ||
422  Name.startswith(".gnu.linkonce.tb.") ||
423  Name.startswith(".llvm.linkonce.tb."))
424  return SectionKind::getThreadBSS();
425 
426  return K;
427 }
428 
430  // Use SHT_NOTE for section whose name starts with ".note" to allow
431  // emitting ELF notes from C variable declaration.
432  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
433  if (Name.startswith(".note"))
434  return ELF::SHT_NOTE;
435 
436  if (Name == ".init_array")
437  return ELF::SHT_INIT_ARRAY;
438 
439  if (Name == ".fini_array")
440  return ELF::SHT_FINI_ARRAY;
441 
442  if (Name == ".preinit_array")
443  return ELF::SHT_PREINIT_ARRAY;
444 
445  if (K.isBSS() || K.isThreadBSS())
446  return ELF::SHT_NOBITS;
447 
448  return ELF::SHT_PROGBITS;
449 }
450 
451 static unsigned getELFSectionFlags(SectionKind K) {
452  unsigned Flags = 0;
453 
454  if (!K.isMetadata())
455  Flags |= ELF::SHF_ALLOC;
456 
457  if (K.isText())
458  Flags |= ELF::SHF_EXECINSTR;
459 
460  if (K.isExecuteOnly())
461  Flags |= ELF::SHF_ARM_PURECODE;
462 
463  if (K.isWriteable())
464  Flags |= ELF::SHF_WRITE;
465 
466  if (K.isThreadLocal())
467  Flags |= ELF::SHF_TLS;
468 
469  if (K.isMergeableCString() || K.isMergeableConst())
470  Flags |= ELF::SHF_MERGE;
471 
472  if (K.isMergeableCString())
473  Flags |= ELF::SHF_STRINGS;
474 
475  return Flags;
476 }
477 
478 static const Comdat *getELFComdat(const GlobalValue *GV) {
479  const Comdat *C = GV->getComdat();
480  if (!C)
481  return nullptr;
482 
483  if (C->getSelectionKind() != Comdat::Any)
484  report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
485  C->getName() + "' cannot be lowered.");
486 
487  return C;
488 }
489 
491  const TargetMachine &TM) {
493  if (!MD)
494  return nullptr;
495 
496  const MDOperand &Op = MD->getOperand(0);
497  if (!Op.get())
498  return nullptr;
499 
500  auto *VM = dyn_cast<ValueAsMetadata>(Op);
501  if (!VM)
502  report_fatal_error("MD_associated operand is not ValueAsMetadata");
503 
504  GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
505  return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
506 }
507 
509  if (Kind.isMergeable1ByteCString())
510  return 1;
511  else if (Kind.isMergeable2ByteCString())
512  return 2;
513  else if (Kind.isMergeable4ByteCString())
514  return 4;
515  else if (Kind.isMergeableConst4())
516  return 4;
517  else if (Kind.isMergeableConst8())
518  return 8;
519  else if (Kind.isMergeableConst16())
520  return 16;
521  else if (Kind.isMergeableConst32())
522  return 32;
523  else {
524  // We shouldn't have mergeable C strings or mergeable constants that we
525  // didn't handle above.
526  assert(!Kind.isMergeableCString() && "unknown string width");
527  assert(!Kind.isMergeableConst() && "unknown data width");
528  return 0;
529  }
530 }
531 
533  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
535 
536  // Check if '#pragma clang section' name is applicable.
537  // Note that pragma directive overrides -ffunction-section, -fdata-section
538  // and so section name is exactly as user specified and not uniqued.
539  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
540  if (GV && GV->hasImplicitSection()) {
541  auto Attrs = GV->getAttributes();
542  if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
543  SectionName = Attrs.getAttribute("bss-section").getValueAsString();
544  } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
545  SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
546  } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
547  SectionName = Attrs.getAttribute("data-section").getValueAsString();
548  }
549  }
550  const Function *F = dyn_cast<Function>(GO);
551  if (F && F->hasFnAttribute("implicit-section-name")) {
552  SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
553  }
554 
555  // Infer section flags from the section name if we can.
556  Kind = getELFKindForNamedSection(SectionName, Kind);
557 
558  StringRef Group = "";
559  unsigned Flags = getELFSectionFlags(Kind);
560  if (const Comdat *C = getELFComdat(GO)) {
561  Group = C->getName();
562  Flags |= ELF::SHF_GROUP;
563  }
564 
565  // A section can have at most one associated section. Put each global with
566  // MD_associated in a unique section.
567  unsigned UniqueID = MCContext::GenericSectionID;
568  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
569  if (AssociatedSymbol) {
570  UniqueID = NextUniqueID++;
571  Flags |= ELF::SHF_LINK_ORDER;
572  }
573 
574  MCSectionELF *Section = getContext().getELFSection(
575  SectionName, getELFSectionType(SectionName, Kind), Flags,
576  getEntrySizeForKind(Kind), Group, UniqueID, AssociatedSymbol);
577  // Make sure that we did not get some other section with incompatible sh_link.
578  // This should not be possible due to UniqueID code above.
579  assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
580  "Associated symbol mismatch between sections");
581  return Section;
582 }
583 
584 /// Return the section prefix name used by options FunctionsSections and
585 /// DataSections.
587  if (Kind.isText())
588  return ".text";
589  if (Kind.isReadOnly())
590  return ".rodata";
591  if (Kind.isBSS())
592  return ".bss";
593  if (Kind.isThreadData())
594  return ".tdata";
595  if (Kind.isThreadBSS())
596  return ".tbss";
597  if (Kind.isData())
598  return ".data";
599  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
600  return ".data.rel.ro";
601 }
602 
604  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
605  const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
606  unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
607 
608  StringRef Group = "";
609  if (const Comdat *C = getELFComdat(GO)) {
610  Flags |= ELF::SHF_GROUP;
611  Group = C->getName();
612  }
613 
614  // Get the section entry size based on the kind.
615  unsigned EntrySize = getEntrySizeForKind(Kind);
616 
618  if (Kind.isMergeableCString()) {
619  // We also need alignment here.
620  // FIXME: this is getting the alignment of the character, not the
621  // alignment of the global!
623  cast<GlobalVariable>(GO));
624 
625  std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
626  Name = SizeSpec + utostr(Align);
627  } else if (Kind.isMergeableConst()) {
628  Name = ".rodata.cst";
629  Name += utostr(EntrySize);
630  } else {
631  Name = getSectionPrefixForGlobal(Kind);
632  }
633 
634  if (const auto *F = dyn_cast<Function>(GO)) {
635  const auto &OptionalPrefix = F->getSectionPrefix();
636  if (OptionalPrefix)
637  Name += *OptionalPrefix;
638  }
639 
640  unsigned UniqueID = MCContext::GenericSectionID;
641  if (EmitUniqueSection) {
642  if (TM.getUniqueSectionNames()) {
643  Name.push_back('.');
644  TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
645  } else {
646  UniqueID = *NextUniqueID;
647  (*NextUniqueID)++;
648  }
649  }
650  // Use 0 as the unique ID for execute-only text.
651  if (Kind.isExecuteOnly())
652  UniqueID = 0;
653  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
654  EntrySize, Group, UniqueID, AssociatedSymbol);
655 }
656 
658  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
659  unsigned Flags = getELFSectionFlags(Kind);
660 
661  // If we have -ffunction-section or -fdata-section then we should emit the
662  // global value to a uniqued section specifically for it.
663  bool EmitUniqueSection = false;
664  if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
665  if (Kind.isText())
666  EmitUniqueSection = TM.getFunctionSections();
667  else
668  EmitUniqueSection = TM.getDataSections();
669  }
670  EmitUniqueSection |= GO->hasComdat();
671 
672  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
673  if (AssociatedSymbol) {
674  EmitUniqueSection = true;
675  Flags |= ELF::SHF_LINK_ORDER;
676  }
677 
679  getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
680  &NextUniqueID, AssociatedSymbol);
681  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
682  return Section;
683 }
684 
686  const Function &F, const TargetMachine &TM) const {
687  // If the function can be removed, produce a unique section so that
688  // the table doesn't prevent the removal.
689  const Comdat *C = F.getComdat();
690  bool EmitUniqueSection = TM.getFunctionSections() || C;
691  if (!EmitUniqueSection)
692  return ReadOnlySection;
693 
694  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
695  getMangler(), TM, EmitUniqueSection,
696  ELF::SHF_ALLOC, &NextUniqueID,
697  /* AssociatedSymbol */ nullptr);
698 }
699 
701  bool UsesLabelDifference, const Function &F) const {
702  // We can always create relative relocations, so use another section
703  // that can be marked non-executable.
704  return false;
705 }
706 
707 /// Given a mergeable constant with the specified size and relocation
708 /// information, return a section that it should be placed in.
710  const DataLayout &DL, SectionKind Kind, const Constant *C,
711  unsigned &Align) const {
712  if (Kind.isMergeableConst4() && MergeableConst4Section)
713  return MergeableConst4Section;
714  if (Kind.isMergeableConst8() && MergeableConst8Section)
715  return MergeableConst8Section;
716  if (Kind.isMergeableConst16() && MergeableConst16Section)
717  return MergeableConst16Section;
718  if (Kind.isMergeableConst32() && MergeableConst32Section)
719  return MergeableConst32Section;
720  if (Kind.isReadOnly())
721  return ReadOnlySection;
722 
723  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
724  return DataRelROSection;
725 }
726 
727 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
728  bool IsCtor, unsigned Priority,
729  const MCSymbol *KeySym) {
730  std::string Name;
731  unsigned Type;
732  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
733  StringRef COMDAT = KeySym ? KeySym->getName() : "";
734 
735  if (KeySym)
736  Flags |= ELF::SHF_GROUP;
737 
738  if (UseInitArray) {
739  if (IsCtor) {
740  Type = ELF::SHT_INIT_ARRAY;
741  Name = ".init_array";
742  } else {
743  Type = ELF::SHT_FINI_ARRAY;
744  Name = ".fini_array";
745  }
746  if (Priority != 65535) {
747  Name += '.';
748  Name += utostr(Priority);
749  }
750  } else {
751  // The default scheme is .ctor / .dtor, so we have to invert the priority
752  // numbering.
753  if (IsCtor)
754  Name = ".ctors";
755  else
756  Name = ".dtors";
757  if (Priority != 65535)
758  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
759  Type = ELF::SHT_PROGBITS;
760  }
761 
762  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
763 }
764 
766  unsigned Priority, const MCSymbol *KeySym) const {
767  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
768  KeySym);
769 }
770 
772  unsigned Priority, const MCSymbol *KeySym) const {
773  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
774  KeySym);
775 }
776 
778  const GlobalValue *LHS, const GlobalValue *RHS,
779  const TargetMachine &TM) const {
780  // We may only use a PLT-relative relocation to refer to unnamed_addr
781  // functions.
782  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
783  return nullptr;
784 
785  // Basic sanity checks.
786  if (LHS->getType()->getPointerAddressSpace() != 0 ||
787  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
788  RHS->isThreadLocal())
789  return nullptr;
790 
792  MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
793  getContext()),
794  MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
795 }
796 
798  // Use ".GCC.command.line" since this feature is to support clang's
799  // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
800  // same name.
801  return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
803 }
804 
805 void
807  UseInitArray = UseInitArray_;
808  MCContext &Ctx = getContext();
809  if (!UseInitArray) {
810  StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
812 
813  StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
815  return;
816  }
817 
818  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
820  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
822 }
823 
824 //===----------------------------------------------------------------------===//
825 // MachO
826 //===----------------------------------------------------------------------===//
827 
831 }
832 
834  const TargetMachine &TM) {
836  if (TM.getRelocationModel() == Reloc::Static) {
837  StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
839  StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
841  } else {
842  StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
845  StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
848  }
849 
853  TTypeEncoding =
855 }
856 
858  Module &M) const {
859  // Emit the linker options if present.
860  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
861  for (const auto &Option : LinkerOptions->operands()) {
862  SmallVector<std::string, 4> StrOptions;
863  for (const auto &Piece : cast<MDNode>(Option)->operands())
864  StrOptions.push_back(cast<MDString>(Piece)->getString());
865  Streamer.EmitLinkerOptions(StrOptions);
866  }
867  }
868 
869  unsigned VersionVal = 0;
870  unsigned ImageInfoFlags = 0;
871  StringRef SectionVal;
872 
873  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
874 
875  // The section is mandatory. If we don't have it, then we don't have GC info.
876  if (SectionVal.empty())
877  return;
878 
879  StringRef Segment, Section;
880  unsigned TAA = 0, StubSize = 0;
881  bool TAAParsed;
882  std::string ErrorCode =
883  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
884  TAA, TAAParsed, StubSize);
885  if (!ErrorCode.empty())
886  // If invalid, report the error with report_fatal_error.
887  report_fatal_error("Invalid section specifier '" + Section + "': " +
888  ErrorCode + ".");
889 
890  // Get the section.
892  Segment, Section, TAA, StubSize, SectionKind::getData());
893  Streamer.SwitchSection(S);
894  Streamer.EmitLabel(getContext().
895  getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
896  Streamer.EmitIntValue(VersionVal, 4);
897  Streamer.EmitIntValue(ImageInfoFlags, 4);
898  Streamer.AddBlankLine();
899 }
900 
901 static void checkMachOComdat(const GlobalValue *GV) {
902  const Comdat *C = GV->getComdat();
903  if (!C)
904  return;
905 
906  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
907  "' cannot be lowered.");
908 }
909 
911  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
912  // Parse the section specifier and create it if valid.
913  StringRef Segment, Section;
914  unsigned TAA = 0, StubSize = 0;
915  bool TAAParsed;
916 
917  checkMachOComdat(GO);
918 
919  std::string ErrorCode =
921  TAA, TAAParsed, StubSize);
922  if (!ErrorCode.empty()) {
923  // If invalid, report the error with report_fatal_error.
924  report_fatal_error("Global variable '" + GO->getName() +
925  "' has an invalid section specifier '" +
926  GO->getSection() + "': " + ErrorCode + ".");
927  }
928 
929  // Get the section.
930  MCSectionMachO *S =
931  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
932 
933  // If TAA wasn't set by ParseSectionSpecifier() above,
934  // use the value returned by getMachOSection() as a default.
935  if (!TAAParsed)
936  TAA = S->getTypeAndAttributes();
937 
938  // Okay, now that we got the section, verify that the TAA & StubSize agree.
939  // If the user declared multiple globals with different section flags, we need
940  // to reject it here.
941  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
942  // If invalid, report the error with report_fatal_error.
943  report_fatal_error("Global variable '" + GO->getName() +
944  "' section type or attributes does not match previous"
945  " section specifier");
946  }
947 
948  return S;
949 }
950 
952  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
953  checkMachOComdat(GO);
954 
955  // Handle thread local data.
956  if (Kind.isThreadBSS()) return TLSBSSSection;
957  if (Kind.isThreadData()) return TLSDataSection;
958 
959  if (Kind.isText())
961 
962  // If this is weak/linkonce, put this in a coalescable section, either in text
963  // or data depending on if it is writable.
964  if (GO->isWeakForLinker()) {
965  if (Kind.isReadOnly())
966  return ConstTextCoalSection;
967  if (Kind.isReadOnlyWithRel())
968  return ConstDataCoalSection;
969  return DataCoalSection;
970  }
971 
972  // FIXME: Alignment check should be handled by section classifier.
973  if (Kind.isMergeable1ByteCString() &&
975  cast<GlobalVariable>(GO)) < 32)
976  return CStringSection;
977 
978  // Do not put 16-bit arrays in the UString section if they have an
979  // externally visible label, this runs into issues with certain linker
980  // versions.
981  if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
983  cast<GlobalVariable>(GO)) < 32)
984  return UStringSection;
985 
986  // With MachO only variables whose corresponding symbol starts with 'l' or
987  // 'L' can be merged, so we only try merging GVs with private linkage.
988  if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
989  if (Kind.isMergeableConst4())
991  if (Kind.isMergeableConst8())
993  if (Kind.isMergeableConst16())
995  }
996 
997  // Otherwise, if it is readonly, but not something we can specially optimize,
998  // just drop it in .const.
999  if (Kind.isReadOnly())
1000  return ReadOnlySection;
1001 
1002  // If this is marked const, put it into a const section. But if the dynamic
1003  // linker needs to write to it, put it in the data segment.
1004  if (Kind.isReadOnlyWithRel())
1005  return ConstDataSection;
1006 
1007  // Put zero initialized globals with strong external linkage in the
1008  // DATA, __common section with the .zerofill directive.
1009  if (Kind.isBSSExtern())
1010  return DataCommonSection;
1011 
1012  // Put zero initialized globals with local linkage in __DATA,__bss directive
1013  // with the .zerofill directive (aka .lcomm).
1014  if (Kind.isBSSLocal())
1015  return DataBSSSection;
1016 
1017  // Otherwise, just drop the variable in the normal data section.
1018  return DataSection;
1019 }
1020 
1022  const DataLayout &DL, SectionKind Kind, const Constant *C,
1023  unsigned &Align) const {
1024  // If this constant requires a relocation, we have to put it in the data
1025  // segment, not in the text segment.
1026  if (Kind.isData() || Kind.isReadOnlyWithRel())
1027  return ConstDataSection;
1028 
1029  if (Kind.isMergeableConst4())
1030  return FourByteConstantSection;
1031  if (Kind.isMergeableConst8())
1032  return EightByteConstantSection;
1033  if (Kind.isMergeableConst16())
1035  return ReadOnlySection; // .const
1036 }
1037 
1039  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1040  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1041  // The mach-o version of this method defaults to returning a stub reference.
1042 
1043  if (Encoding & DW_EH_PE_indirect) {
1044  MachineModuleInfoMachO &MachOMMI =
1046 
1047  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1048 
1049  // Add information about the stub reference to MachOMMI so that the stub
1050  // gets emitted by the asmprinter.
1051  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1052  if (!StubSym.getPointer()) {
1053  MCSymbol *Sym = TM.getSymbol(GV);
1054  StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1055  }
1056 
1059  Encoding & ~DW_EH_PE_indirect, Streamer);
1060  }
1061 
1062  return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1063  MMI, Streamer);
1064 }
1065 
1067  const GlobalValue *GV, const TargetMachine &TM,
1068  MachineModuleInfo *MMI) const {
1069  // The mach-o version of this method defaults to returning a stub reference.
1070  MachineModuleInfoMachO &MachOMMI =
1072 
1073  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1074 
1075  // Add information about the stub reference to MachOMMI so that the stub
1076  // gets emitted by the asmprinter.
1077  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1078  if (!StubSym.getPointer()) {
1079  MCSymbol *Sym = TM.getSymbol(GV);
1080  StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1081  }
1082 
1083  return SSym;
1084 }
1085 
1087  const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
1088  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1089  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1090  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1091  // through a non_lazy_ptr stub instead. One advantage is that it allows the
1092  // computation of deltas to final external symbols. Example:
1093  //
1094  // _extgotequiv:
1095  // .long _extfoo
1096  //
1097  // _delta:
1098  // .long _extgotequiv-_delta
1099  //
1100  // is transformed to:
1101  //
1102  // _delta:
1103  // .long L_extfoo$non_lazy_ptr-(_delta+0)
1104  //
1105  // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1106  // L_extfoo$non_lazy_ptr:
1107  // .indirect_symbol _extfoo
1108  // .long 0
1109  //
1110  // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1111  // may point to both local (same translation unit) and global (other
1112  // translation units) symbols. Example:
1113  //
1114  // .section __DATA,__pointers,non_lazy_symbol_pointers
1115  // L1:
1116  // .indirect_symbol _myGlobal
1117  // .long 0
1118  // L2:
1119  // .indirect_symbol _myLocal
1120  // .long _myLocal
1121  //
1122  // If the symbol is local, instead of the symbol's index, the assembler
1123  // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1124  // Then the linker will notice the constant in the table and will look at the
1125  // content of the symbol.
1126  MachineModuleInfoMachO &MachOMMI =
1128  MCContext &Ctx = getContext();
1129 
1130  // The offset must consider the original displacement from the base symbol
1131  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1132  Offset = -MV.getConstant();
1133  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1134 
1135  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1136  // non_lazy_ptr stubs.
1138  StringRef Suffix = "$non_lazy_ptr";
1139  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1140  Name += Sym->getName();
1141  Name += Suffix;
1142  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1143 
1144  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1145  if (!StubSym.getPointer()) {
1146  bool IsIndirectLocal = Sym->isDefined() && !Sym->isExternal();
1147  // With the assumption that IsIndirectLocal == GV->hasLocalLinkage().
1148  StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1149  !IsIndirectLocal);
1150  }
1151 
1152  const MCExpr *BSymExpr =
1154  const MCExpr *LHS =
1156 
1157  if (!Offset)
1158  return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1159 
1160  const MCExpr *RHS =
1161  MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1162  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1163 }
1164 
1165 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1166  const MCSection &Section) {
1167  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1168  return true;
1169 
1170  // If it is not dead stripped, it is safe to use private labels.
1171  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1173  return true;
1174 
1175  return false;
1176 }
1177 
1179  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1180  const TargetMachine &TM) const {
1181  bool CannotUsePrivateLabel = true;
1182  if (auto *GO = GV->getBaseObject()) {
1184  const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1185  CannotUsePrivateLabel =
1186  !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1187  }
1188  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1189 }
1190 
1191 //===----------------------------------------------------------------------===//
1192 // COFF
1193 //===----------------------------------------------------------------------===//
1194 
1195 static unsigned
1197  unsigned Flags = 0;
1198  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1199 
1200  if (K.isMetadata())
1201  Flags |=
1203  else if (K.isText())
1204  Flags |=
1209  else if (K.isBSS())
1210  Flags |=
1214  else if (K.isThreadLocal())
1215  Flags |=
1219  else if (K.isReadOnly() || K.isReadOnlyWithRel())
1220  Flags |=
1223  else if (K.isWriteable())
1224  Flags |=
1228 
1229  return Flags;
1230 }
1231 
1232 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1233  const Comdat *C = GV->getComdat();
1234  assert(C && "expected GV to have a Comdat!");
1235 
1236  StringRef ComdatGVName = C->getName();
1237  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1238  if (!ComdatGV)
1239  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1240  "' does not exist.");
1241 
1242  if (ComdatGV->getComdat() != C)
1243  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1244  "' is not a key for its COMDAT.");
1245 
1246  return ComdatGV;
1247 }
1248 
1249 static int getSelectionForCOFF(const GlobalValue *GV) {
1250  if (const Comdat *C = GV->getComdat()) {
1251  const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1252  if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1253  ComdatKey = GA->getBaseObject();
1254  if (ComdatKey == GV) {
1255  switch (C->getSelectionKind()) {
1256  case Comdat::Any:
1258  case Comdat::ExactMatch:
1260  case Comdat::Largest:
1262  case Comdat::NoDuplicates:
1264  case Comdat::SameSize:
1266  }
1267  } else {
1269  }
1270  }
1271  return 0;
1272 }
1273 
1275  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1276  int Selection = 0;
1277  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1278  StringRef Name = GO->getSection();
1279  StringRef COMDATSymName = "";
1280  if (GO->hasComdat()) {
1281  Selection = getSelectionForCOFF(GO);
1282  const GlobalValue *ComdatGV;
1283  if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1284  ComdatGV = getComdatGVForCOFF(GO);
1285  else
1286  ComdatGV = GO;
1287 
1288  if (!ComdatGV->hasPrivateLinkage()) {
1289  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1290  COMDATSymName = Sym->getName();
1291  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1292  } else {
1293  Selection = 0;
1294  }
1295  }
1296 
1297  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1298  Selection);
1299 }
1300 
1302  if (Kind.isText())
1303  return ".text";
1304  if (Kind.isBSS())
1305  return ".bss";
1306  if (Kind.isThreadLocal())
1307  return ".tls$";
1308  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1309  return ".rdata";
1310  return ".data";
1311 }
1312 
1314  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1315  // If we have -ffunction-sections then we should emit the global value to a
1316  // uniqued section specifically for it.
1317  bool EmitUniquedSection;
1318  if (Kind.isText())
1319  EmitUniquedSection = TM.getFunctionSections();
1320  else
1321  EmitUniquedSection = TM.getDataSections();
1322 
1323  if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1325 
1326  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1327 
1328  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1329  int Selection = getSelectionForCOFF(GO);
1330  if (!Selection)
1332  const GlobalValue *ComdatGV;
1333  if (GO->hasComdat())
1334  ComdatGV = getComdatGVForCOFF(GO);
1335  else
1336  ComdatGV = GO;
1337 
1338  unsigned UniqueID = MCContext::GenericSectionID;
1339  if (EmitUniquedSection)
1340  UniqueID = NextUniqueID++;
1341 
1342  if (!ComdatGV->hasPrivateLinkage()) {
1343  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1344  StringRef COMDATSymName = Sym->getName();
1345 
1346  // Append "$symbol" to the section name *before* IR-level mangling is
1347  // applied when targetting mingw. This is what GCC does, and the ld.bfd
1348  // COFF linker will not properly handle comdats otherwise.
1349  if (getTargetTriple().isWindowsGNUEnvironment())
1350  raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1351 
1352  return getContext().getCOFFSection(Name, Characteristics, Kind,
1353  COMDATSymName, Selection, UniqueID);
1354  } else {
1355  SmallString<256> TmpData;
1356  getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1357  return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1358  Selection, UniqueID);
1359  }
1360  }
1361 
1362  if (Kind.isText())
1363  return TextSection;
1364 
1365  if (Kind.isThreadLocal())
1366  return TLSDataSection;
1367 
1368  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1369  return ReadOnlySection;
1370 
1371  // Note: we claim that common symbols are put in BSSSection, but they are
1372  // really emitted with the magic .comm directive, which creates a symbol table
1373  // entry but not a section.
1374  if (Kind.isBSS() || Kind.isCommon())
1375  return BSSSection;
1376 
1377  return DataSection;
1378 }
1379 
1381  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1382  const TargetMachine &TM) const {
1383  bool CannotUsePrivateLabel = false;
1384  if (GV->hasPrivateLinkage() &&
1385  ((isa<Function>(GV) && TM.getFunctionSections()) ||
1386  (isa<GlobalVariable>(GV) && TM.getDataSections())))
1387  CannotUsePrivateLabel = true;
1388 
1389  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1390 }
1391 
1393  const Function &F, const TargetMachine &TM) const {
1394  // If the function can be removed, produce a unique section so that
1395  // the table doesn't prevent the removal.
1396  const Comdat *C = F.getComdat();
1397  bool EmitUniqueSection = TM.getFunctionSections() || C;
1398  if (!EmitUniqueSection)
1399  return ReadOnlySection;
1400 
1401  // FIXME: we should produce a symbol for F instead.
1402  if (F.hasPrivateLinkage())
1403  return ReadOnlySection;
1404 
1405  MCSymbol *Sym = TM.getSymbol(&F);
1406  StringRef COMDATSymName = Sym->getName();
1407 
1410  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1411  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1412  unsigned UniqueID = NextUniqueID++;
1413 
1414  return getContext().getCOFFSection(
1415  SecName, Characteristics, Kind, COMDATSymName,
1417 }
1418 
1420  Module &M) const {
1421  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1422  // Emit the linker options to the linker .drectve section. According to the
1423  // spec, this section is a space-separated string containing flags for
1424  // linker.
1425  MCSection *Sec = getDrectveSection();
1426  Streamer.SwitchSection(Sec);
1427  for (const auto &Option : LinkerOptions->operands()) {
1428  for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1429  // Lead with a space for consistency with our dllexport implementation.
1430  std::string Directive(" ");
1431  Directive.append(cast<MDString>(Piece)->getString());
1432  Streamer.EmitBytes(Directive);
1433  }
1434  }
1435  }
1436 
1437  unsigned Version = 0;
1438  unsigned Flags = 0;
1440 
1441  GetObjCImageInfo(M, Version, Flags, Section);
1442  if (Section.empty())
1443  return;
1444 
1445  auto &C = getContext();
1446  auto *S = C.getCOFFSection(
1449  Streamer.SwitchSection(S);
1450  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1451  Streamer.EmitIntValue(Version, 4);
1452  Streamer.EmitIntValue(Flags, 4);
1453  Streamer.AddBlankLine();
1454 }
1455 
1457  const TargetMachine &TM) {
1459  const Triple &T = TM.getTargetTriple();
1469  } else {
1478  }
1479 }
1480 
1482  const Triple &T, bool IsCtor,
1483  unsigned Priority,
1484  const MCSymbol *KeySym,
1487  // If the priority is the default, use .CRT$XCU, possibly associative.
1488  if (Priority == 65535)
1489  return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1490 
1491  // Otherwise, we need to compute a new section name. Low priorities should
1492  // run earlier. The linker will sort sections ASCII-betically, and we need a
1493  // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1494  // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1495  // low priorities need to sort before 'L', since the CRT uses that
1496  // internally, so we use ".CRT$XCA00001" for them.
1498  raw_svector_ostream OS(Name);
1499  OS << ".CRT$XC" << (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1500  MCSectionCOFF *Sec = Ctx.getCOFFSection(
1503  return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1504  }
1505 
1506  std::string Name = IsCtor ? ".ctors" : ".dtors";
1507  if (Priority != 65535)
1508  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1509 
1510  return Ctx.getAssociativeCOFFSection(
1515  KeySym, 0);
1516 }
1517 
1519  unsigned Priority, const MCSymbol *KeySym) const {
1521  Priority, KeySym,
1522  cast<MCSectionCOFF>(StaticCtorSection));
1523 }
1524 
1526  unsigned Priority, const MCSymbol *KeySym) const {
1528  Priority, KeySym,
1529  cast<MCSectionCOFF>(StaticDtorSection));
1530 }
1531 
1533  raw_ostream &OS, const GlobalValue *GV) const {
1535 }
1536 
1538  raw_ostream &OS, const GlobalValue *GV) const {
1540 }
1541 
1543  const GlobalValue *LHS, const GlobalValue *RHS,
1544  const TargetMachine &TM) const {
1545  const Triple &T = TM.getTargetTriple();
1546  if (!T.isKnownWindowsMSVCEnvironment() &&
1549  return nullptr;
1550 
1551  // Our symbols should exist in address space zero, cowardly no-op if
1552  // otherwise.
1553  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1554  RHS->getType()->getPointerAddressSpace() != 0)
1555  return nullptr;
1556 
1557  // Both ptrtoint instructions must wrap global objects:
1558  // - Only global variables are eligible for image relative relocations.
1559  // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1560  // We expect __ImageBase to be a global variable without a section, externally
1561  // defined.
1562  //
1563  // It should look something like this: @__ImageBase = external constant i8
1564  if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1565  LHS->isThreadLocal() || RHS->isThreadLocal() ||
1566  RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1567  cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1568  return nullptr;
1569 
1570  return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1572  getContext());
1573 }
1574 
1575 static std::string APIntToHexString(const APInt &AI) {
1576  unsigned Width = (AI.getBitWidth() / 8) * 2;
1577  std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1578  unsigned Size = HexString.size();
1579  assert(Width >= Size && "hex string is too large!");
1580  HexString.insert(HexString.begin(), Width - Size, '0');
1581 
1582  return HexString;
1583 }
1584 
1585 static std::string scalarConstantToHexString(const Constant *C) {
1586  Type *Ty = C->getType();
1587  if (isa<UndefValue>(C)) {
1589  } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1590  return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1591  } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1592  return APIntToHexString(CI->getValue());
1593  } else {
1594  unsigned NumElements;
1595  if (isa<VectorType>(Ty))
1596  NumElements = Ty->getVectorNumElements();
1597  else
1598  NumElements = Ty->getArrayNumElements();
1599  std::string HexString;
1600  for (int I = NumElements - 1, E = -1; I != E; --I)
1602  return HexString;
1603  }
1604 }
1605 
1607  const DataLayout &DL, SectionKind Kind, const Constant *C,
1608  unsigned &Align) const {
1609  if (Kind.isMergeableConst() && C &&
1611  // This creates comdat sections with the given symbol name, but unless
1612  // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1613  // will be created with a null storage class, which makes GNU binutils
1614  // error out.
1618  std::string COMDATSymName;
1619  if (Kind.isMergeableConst4()) {
1620  if (Align <= 4) {
1621  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1622  Align = 4;
1623  }
1624  } else if (Kind.isMergeableConst8()) {
1625  if (Align <= 8) {
1626  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1627  Align = 8;
1628  }
1629  } else if (Kind.isMergeableConst16()) {
1630  // FIXME: These may not be appropriate for non-x86 architectures.
1631  if (Align <= 16) {
1632  COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1633  Align = 16;
1634  }
1635  } else if (Kind.isMergeableConst32()) {
1636  if (Align <= 32) {
1637  COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1638  Align = 32;
1639  }
1640  }
1641 
1642  if (!COMDATSymName.empty())
1643  return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1644  COMDATSymName,
1646  }
1647 
1648  return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1649 }
1650 
1651 
1652 //===----------------------------------------------------------------------===//
1653 // Wasm
1654 //===----------------------------------------------------------------------===//
1655 
1656 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1657  const Comdat *C = GV->getComdat();
1658  if (!C)
1659  return nullptr;
1660 
1661  if (C->getSelectionKind() != Comdat::Any)
1662  report_fatal_error("WebAssembly COMDATs only support "
1663  "SelectionKind::Any, '" + C->getName() + "' cannot be "
1664  "lowered.");
1665 
1666  return C;
1667 }
1668 
1670  // If we're told we have function data, then use that.
1671  if (K.isText())
1672  return SectionKind::getText();
1673 
1674  // Otherwise, ignore whatever section type the generic impl detected and use
1675  // a plain data section.
1676  return SectionKind::getData();
1677 }
1678 
1680  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1681  // We don't support explict section names for functions in the wasm object
1682  // format. Each function has to be in its own unique section.
1683  if (isa<Function>(GO)) {
1684  return SelectSectionForGlobal(GO, Kind, TM);
1685  }
1686 
1687  StringRef Name = GO->getSection();
1688 
1689  Kind = getWasmKindForNamedSection(Name, Kind);
1690 
1691  StringRef Group = "";
1692  if (const Comdat *C = getWasmComdat(GO)) {
1693  Group = C->getName();
1694  }
1695 
1696  return getContext().getWasmSection(Name, Kind, Group,
1698 }
1699 
1701  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1702  const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1703  StringRef Group = "";
1704  if (const Comdat *C = getWasmComdat(GO)) {
1705  Group = C->getName();
1706  }
1707 
1708  bool UniqueSectionNames = TM.getUniqueSectionNames();
1710 
1711  if (const auto *F = dyn_cast<Function>(GO)) {
1712  const auto &OptionalPrefix = F->getSectionPrefix();
1713  if (OptionalPrefix)
1714  Name += *OptionalPrefix;
1715  }
1716 
1717  if (EmitUniqueSection && UniqueSectionNames) {
1718  Name.push_back('.');
1719  TM.getNameWithPrefix(Name, GO, Mang, true);
1720  }
1721  unsigned UniqueID = MCContext::GenericSectionID;
1722  if (EmitUniqueSection && !UniqueSectionNames) {
1723  UniqueID = *NextUniqueID;
1724  (*NextUniqueID)++;
1725  }
1726  return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1727 }
1728 
1730  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1731 
1732  if (Kind.isCommon())
1733  report_fatal_error("mergable sections not supported yet on wasm");
1734 
1735  // If we have -ffunction-section or -fdata-section then we should emit the
1736  // global value to a uniqued section specifically for it.
1737  bool EmitUniqueSection = false;
1738  if (Kind.isText())
1739  EmitUniqueSection = TM.getFunctionSections();
1740  else
1741  EmitUniqueSection = TM.getDataSections();
1742  EmitUniqueSection |= GO->hasComdat();
1743 
1744  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1745  EmitUniqueSection, &NextUniqueID);
1746 }
1747 
1749  bool UsesLabelDifference, const Function &F) const {
1750  // We can always create relative relocations, so use another section
1751  // that can be marked non-executable.
1752  return false;
1753 }
1754 
1756  const GlobalValue *LHS, const GlobalValue *RHS,
1757  const TargetMachine &TM) const {
1758  // We may only use a PLT-relative relocation to refer to unnamed_addr
1759  // functions.
1760  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1761  return nullptr;
1762 
1763  // Basic sanity checks.
1764  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1765  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1766  RHS->isThreadLocal())
1767  return nullptr;
1768 
1769  return MCBinaryExpr::createSub(
1771  getContext()),
1773 }
1774 
1777  getContext().getWasmSection(".init_array", SectionKind::getData());
1778 
1779  // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
1780  // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
1782 }
1783 
1785  unsigned Priority, const MCSymbol *KeySym) const {
1786  return Priority == UINT16_MAX ?
1788  getContext().getWasmSection(".init_array." + utostr(Priority),
1790 }
1791 
1793  unsigned Priority, const MCSymbol *KeySym) const {
1794  llvm_unreachable("@llvm.global_dtors should have been lowered already");
1795  return nullptr;
1796 }
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:292
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:161
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:89
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
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:110
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:710
static SectionKind getData()
Definition: SectionKind.h:201
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:153
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
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:434
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
This class represents lattice values for constants.
Definition: AllocatorList.h:23
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:158
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:24
This represents an "assembler immediate".
Definition: MCValue.h:39
bool isWriteable() const
Definition: SectionKind.h:144
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const override
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:293
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:41
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
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:332
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
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
void push_back(const T &Elt)
Definition: SmallVector.h:211
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.
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:123
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K)
Definition: MCContext.h:453
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
bool isMergeableConst8() const
Definition: SectionKind.h:140
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:320
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:38
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
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:127
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
Metadata node.
Definition: Metadata.h:863
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:164
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:1068
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:502
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Definition: MachO.h:189
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:610
static bool isThumb(const MCSubtargetInfo &STI)
unsigned getTypeAndAttributes() const
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Definition: MCContext.cpp:421
bool isMergeable2ByteCString() const
Definition: SectionKind.h:132
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:469
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:26
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:269
int64_t getConstant() const
Definition: MCValue.h:46
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:48
A tuple of MDNodes.
Definition: Metadata.h:1325
amdgpu Simplify well known AMD library false Value Value const Twine & Name
static SectionKind getBSS()
Definition: SectionKind.h:197
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:370
uint64_t getArrayNumElements() const
Definition: DerivedTypes.h:387
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:534
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1443
The linker may choose any COMDAT.
Definition: Comdat.h:34
bool hasCOFFComdatConstants() const
Definition: MCAsmInfo.h:475
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
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for termination.
Definition: MachO.h:142
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:62
bool hasExternalLinkage() const
Definition: GlobalValue.h:421
Key
PAL metadata keys.
bool isText() const
Definition: SectionKind.h:118
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
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:272
op_range operands() const
Definition: Metadata.h:1066
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:289
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
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:251
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:160
bool isMergeableConst32() const
Definition: SectionKind.h:142
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:338
static SectionKind getThreadData()
Definition: SectionKind.h:196
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
bool isWindowsItaniumEnvironment() const
Definition: Triple.h:542
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:123
bool isWindowsCoreCLREnvironment() const
Definition: Triple.h:538
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:283
bool isReadOnlyWithRel() const
Definition: SectionKind.h:167
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:334
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:369
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:55
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
.hidden (ELF)
Definition: MCDirectives.h:30
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:291
static const Comdat * getWasmComdat(const GlobalValue *GV)
No other Module may specify this COMDAT.
Definition: Comdat.h:37
Streaming machine code generation interface.
Definition: MCStreamer.h:188
StringRef getName() const
Definition: Comdat.cpp:26
static std::string ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
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:45
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:41
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:628
virtual void SwitchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
This represents a section on wasm.
Definition: MCSectionWasm.h:27
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:73
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.
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:184
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
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...
bool isMergeableConst16() const
Definition: SectionKind.h:141
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:35
StubValueTy & getGVStubEntry(MCSymbol *Sym)
bool isExternal() const
Definition: MCSymbol.h:392
StubValueTy & getGVStubEntry(MCSymbol *Sym)
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool isThreadBSS() const
Definition: SectionKind.h:152
#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:43
MCSection * getDrectveSection() const
bool isBSS() const
Definition: SectionKind.h:159
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:139
static const MCSymbolELF * getAssociatedSymbol(const GlobalObject *GO, const TargetMachine &TM)
static SectionKind getThreadBSS()
Definition: SectionKind.h:195
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:133
bool isCommon() const
Definition: SectionKind.h:163
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
Module.h This file contains the declarations for the Module class.
static SectionKind getMetadata()
Definition: SectionKind.h:178
bool isMetadata() const
Definition: SectionKind.h:116
const Triple & getTargetTriple() const
static const Comdat * getELFComdat(const GlobalValue *GV)
The linker will choose the largest COMDAT.
Definition: Comdat.h:36
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:199
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
bool isOSFreeBSD() const
Definition: Triple.h:490
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:461
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:817
This file contains constants used for implementing Dwarf debug support.
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:247
const Comdat * getComdat() const
Definition: Globals.cpp:170
Class for arbitrary precision integers.
Definition: APInt.h:69
CodeModel::Model getCodeModel() const
Returns the code model.
static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K)
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
static StringRef getSectionPrefixForGlobal(SectionKind Kind)
Return the section prefix name used by options FunctionsSections and DataSections.
MCSection * FourByteConstantSection
bool hasComdat() const
Definition: GlobalObject.h:99
bool isReadOnly() const
Definition: SectionKind.h:122
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
const Comdat * getComdat() const
Definition: GlobalObject.h:100
bool isMergeableConst() const
Definition: SectionKind.h:135
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:214
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:448
bool getUniqueSectionNames() const
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:194
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:481
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:213
static int getSelectionForCOFF(const GlobalValue *GV)
#define I(x, y, z)
Definition: MD5.cpp:58
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:322
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
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:27
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:322
Type * getValueType() const
Definition: GlobalValue.h:275
uint32_t Size
Definition: Profile.cpp:46
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:215
const Module * getModule() const
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets...
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:260
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:202
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:482
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:388
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
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:565
bool isData() const
Definition: SectionKind.h:165
bool isThreadLocal() const
Definition: SectionKind.h:148
bool isMergeable1ByteCString() const
Definition: SectionKind.h:131
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
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:346
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:569
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:330
Metadata * get() const
Definition: Metadata.h:721
bool isExecuteOnly() const
Definition: SectionKind.h:120
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
virtual void emitCGProfileEntry(const MCSymbolRefExpr *From, const MCSymbolRefExpr *To, uint64_t Count)
Definition: MCStreamer.cpp:708
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:58
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:111
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:246
const MCSymbol * getAssociatedSymbol() const
Definition: MCSectionELF.h:89
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
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:568
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:139
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:181
const uint64_t Version
Definition: InstrProf.h:894
static unsigned getELFSectionType(StringRef Name, SectionKind K)
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:163
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
This class contains meta information specific to a module.
std::string utohexstr(uint64_t X, bool LowerCase=false)
Definition: StringExtras.h:124
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:371
SelectionKind getSelectionKind() const
Definition: Comdat.h:44
static SectionKind getText()
Definition: SectionKind.h:179
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override