LLVM  7.0.0
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 
101  Module &M) const {
102  auto &C = getContext();
103 
104  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
105  auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
107 
108  Streamer.SwitchSection(S);
109 
110  for (const auto &Operand : LinkerOptions->operands()) {
111  if (cast<MDNode>(Operand)->getNumOperands() != 2)
112  report_fatal_error("invalid llvm.linker.options");
113  for (const auto &Option : cast<MDNode>(Operand)->operands()) {
114  Streamer.EmitBytes(cast<MDString>(Option)->getString());
115  Streamer.EmitIntValue(0, 1);
116  }
117  }
118  }
119 
120  unsigned Version = 0;
121  unsigned Flags = 0;
123 
124  GetObjCImageInfo(M, Version, Flags, Section);
125  if (!Section.empty()) {
126  auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
127  Streamer.SwitchSection(S);
128  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
129  Streamer.EmitIntValue(Version, 4);
130  Streamer.EmitIntValue(Flags, 4);
131  Streamer.AddBlankLine();
132  }
133 
135  M.getModuleFlagsMetadata(ModuleFlags);
136 
137  MDNode *CFGProfile = nullptr;
138 
139  for (const auto &MFE : ModuleFlags) {
140  StringRef Key = MFE.Key->getString();
141  if (Key == "CG Profile") {
142  CFGProfile = cast<MDNode>(MFE.Val);
143  break;
144  }
145  }
146 
147  if (!CFGProfile)
148  return;
149 
150  auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
151  if (!MDO)
152  return nullptr;
153  auto V = cast<ValueAsMetadata>(MDO);
154  const Function *F = cast<Function>(V->getValue());
155  return TM->getSymbol(F);
156  };
157 
158  for (const auto &Edge : CFGProfile->operands()) {
159  MDNode *E = cast<MDNode>(Edge);
160  const MCSymbol *From = GetSym(E->getOperand(0));
161  const MCSymbol *To = GetSym(E->getOperand(1));
162  // Skip null functions. This can happen if functions are dead stripped after
163  // the CGProfile pass has been run.
164  if (!From || !To)
165  continue;
166  uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
167  ->getValue()
168  ->getUniqueInteger()
169  .getZExtValue();
170  Streamer.emitCGProfileEntry(
173  }
174 }
175 
177  const GlobalValue *GV, const TargetMachine &TM,
178  MachineModuleInfo *MMI) const {
179  unsigned Encoding = getPersonalityEncoding();
180  if ((Encoding & 0x80) == DW_EH_PE_indirect)
181  return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
182  TM.getSymbol(GV)->getName());
183  if ((Encoding & 0x70) == DW_EH_PE_absptr)
184  return TM.getSymbol(GV);
185  report_fatal_error("We do not support this DWARF encoding yet!");
186 }
187 
189  MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
190  SmallString<64> NameData("DW.ref.");
191  NameData += Sym->getName();
192  MCSymbolELF *Label =
193  cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
194  Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
195  Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
196  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
197  MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
198  ELF::SHT_PROGBITS, Flags, 0);
199  unsigned Size = DL.getPointerSize();
200  Streamer.SwitchSection(Sec);
202  Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
203  const MCExpr *E = MCConstantExpr::create(Size, getContext());
204  Streamer.emitELFSize(Label, E);
205  Streamer.EmitLabel(Label);
206 
207  Streamer.EmitSymbolValue(Sym, Size);
208 }
209 
211  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
212  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
213  if (Encoding & DW_EH_PE_indirect) {
215 
216  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
217 
218  // Add information about the stub reference to ELFMMI so that the stub
219  // gets emitted by the asmprinter.
220  MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
221  if (!StubSym.getPointer()) {
222  MCSymbol *Sym = TM.getSymbol(GV);
224  }
225 
227  getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
228  Encoding & ~DW_EH_PE_indirect, Streamer);
229  }
230 
232  MMI, Streamer);
233 }
234 
236  // N.B.: The defaults used in here are not the same ones used in MC.
237  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
238  // both gas and MC will produce a section with no flags. Given
239  // section(".eh_frame") gcc will produce:
240  //
241  // .section .eh_frame,"a",@progbits
242 
243  if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
244  /*AddSegmentInfo=*/false))
245  return SectionKind::getMetadata();
246 
247  if (Name.empty() || Name[0] != '.') return K;
248 
249  // Default implementation based on some magic section names.
250  if (Name == ".bss" ||
251  Name.startswith(".bss.") ||
252  Name.startswith(".gnu.linkonce.b.") ||
253  Name.startswith(".llvm.linkonce.b.") ||
254  Name == ".sbss" ||
255  Name.startswith(".sbss.") ||
256  Name.startswith(".gnu.linkonce.sb.") ||
257  Name.startswith(".llvm.linkonce.sb."))
258  return SectionKind::getBSS();
259 
260  if (Name == ".tdata" ||
261  Name.startswith(".tdata.") ||
262  Name.startswith(".gnu.linkonce.td.") ||
263  Name.startswith(".llvm.linkonce.td."))
265 
266  if (Name == ".tbss" ||
267  Name.startswith(".tbss.") ||
268  Name.startswith(".gnu.linkonce.tb.") ||
269  Name.startswith(".llvm.linkonce.tb."))
270  return SectionKind::getThreadBSS();
271 
272  return K;
273 }
274 
276  // Use SHT_NOTE for section whose name starts with ".note" to allow
277  // emitting ELF notes from C variable declaration.
278  // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
279  if (Name.startswith(".note"))
280  return ELF::SHT_NOTE;
281 
282  if (Name == ".init_array")
283  return ELF::SHT_INIT_ARRAY;
284 
285  if (Name == ".fini_array")
286  return ELF::SHT_FINI_ARRAY;
287 
288  if (Name == ".preinit_array")
289  return ELF::SHT_PREINIT_ARRAY;
290 
291  if (K.isBSS() || K.isThreadBSS())
292  return ELF::SHT_NOBITS;
293 
294  return ELF::SHT_PROGBITS;
295 }
296 
297 static unsigned getELFSectionFlags(SectionKind K) {
298  unsigned Flags = 0;
299 
300  if (!K.isMetadata())
301  Flags |= ELF::SHF_ALLOC;
302 
303  if (K.isText())
304  Flags |= ELF::SHF_EXECINSTR;
305 
306  if (K.isExecuteOnly())
307  Flags |= ELF::SHF_ARM_PURECODE;
308 
309  if (K.isWriteable())
310  Flags |= ELF::SHF_WRITE;
311 
312  if (K.isThreadLocal())
313  Flags |= ELF::SHF_TLS;
314 
315  if (K.isMergeableCString() || K.isMergeableConst())
316  Flags |= ELF::SHF_MERGE;
317 
318  if (K.isMergeableCString())
319  Flags |= ELF::SHF_STRINGS;
320 
321  return Flags;
322 }
323 
324 static const Comdat *getELFComdat(const GlobalValue *GV) {
325  const Comdat *C = GV->getComdat();
326  if (!C)
327  return nullptr;
328 
329  if (C->getSelectionKind() != Comdat::Any)
330  report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
331  C->getName() + "' cannot be lowered.");
332 
333  return C;
334 }
335 
337  const TargetMachine &TM) {
339  if (!MD)
340  return nullptr;
341 
342  const MDOperand &Op = MD->getOperand(0);
343  if (!Op.get())
344  return nullptr;
345 
346  auto *VM = dyn_cast<ValueAsMetadata>(Op);
347  if (!VM)
348  report_fatal_error("MD_associated operand is not ValueAsMetadata");
349 
350  GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
351  return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
352 }
353 
355  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
357 
358  // Check if '#pragma clang section' name is applicable.
359  // Note that pragma directive overrides -ffunction-section, -fdata-section
360  // and so section name is exactly as user specified and not uniqued.
361  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
362  if (GV && GV->hasImplicitSection()) {
363  auto Attrs = GV->getAttributes();
364  if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
365  SectionName = Attrs.getAttribute("bss-section").getValueAsString();
366  } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
367  SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
368  } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
369  SectionName = Attrs.getAttribute("data-section").getValueAsString();
370  }
371  }
372  const Function *F = dyn_cast<Function>(GO);
373  if (F && F->hasFnAttribute("implicit-section-name")) {
374  SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
375  }
376 
377  // Infer section flags from the section name if we can.
378  Kind = getELFKindForNamedSection(SectionName, Kind);
379 
380  StringRef Group = "";
381  unsigned Flags = getELFSectionFlags(Kind);
382  if (const Comdat *C = getELFComdat(GO)) {
383  Group = C->getName();
384  Flags |= ELF::SHF_GROUP;
385  }
386 
387  // A section can have at most one associated section. Put each global with
388  // MD_associated in a unique section.
389  unsigned UniqueID = MCContext::GenericSectionID;
390  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
391  if (AssociatedSymbol) {
392  UniqueID = NextUniqueID++;
393  Flags |= ELF::SHF_LINK_ORDER;
394  }
395 
396  MCSectionELF *Section = getContext().getELFSection(
397  SectionName, getELFSectionType(SectionName, Kind), Flags,
398  /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
399  // Make sure that we did not get some other section with incompatible sh_link.
400  // This should not be possible due to UniqueID code above.
401  assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
402  "Associated symbol mismatch between sections");
403  return Section;
404 }
405 
406 /// Return the section prefix name used by options FunctionsSections and
407 /// DataSections.
409  if (Kind.isText())
410  return ".text";
411  if (Kind.isReadOnly())
412  return ".rodata";
413  if (Kind.isBSS())
414  return ".bss";
415  if (Kind.isThreadData())
416  return ".tdata";
417  if (Kind.isThreadBSS())
418  return ".tbss";
419  if (Kind.isData())
420  return ".data";
421  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
422  return ".data.rel.ro";
423 }
424 
426  if (Kind.isMergeable1ByteCString())
427  return 1;
428  else if (Kind.isMergeable2ByteCString())
429  return 2;
430  else if (Kind.isMergeable4ByteCString())
431  return 4;
432  else if (Kind.isMergeableConst4())
433  return 4;
434  else if (Kind.isMergeableConst8())
435  return 8;
436  else if (Kind.isMergeableConst16())
437  return 16;
438  else if (Kind.isMergeableConst32())
439  return 32;
440  else {
441  // We shouldn't have mergeable C strings or mergeable constants that we
442  // didn't handle above.
443  assert(!Kind.isMergeableCString() && "unknown string width");
444  assert(!Kind.isMergeableConst() && "unknown data width");
445  return 0;
446  }
447 }
448 
450  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
451  const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
452  unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
453 
454  StringRef Group = "";
455  if (const Comdat *C = getELFComdat(GO)) {
456  Flags |= ELF::SHF_GROUP;
457  Group = C->getName();
458  }
459 
460  // Get the section entry size based on the kind.
461  unsigned EntrySize = getEntrySizeForKind(Kind);
462 
464  if (Kind.isMergeableCString()) {
465  // We also need alignment here.
466  // FIXME: this is getting the alignment of the character, not the
467  // alignment of the global!
469  cast<GlobalVariable>(GO));
470 
471  std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
472  Name = SizeSpec + utostr(Align);
473  } else if (Kind.isMergeableConst()) {
474  Name = ".rodata.cst";
475  Name += utostr(EntrySize);
476  } else {
477  Name = getSectionPrefixForGlobal(Kind);
478  }
479 
480  if (const auto *F = dyn_cast<Function>(GO)) {
481  const auto &OptionalPrefix = F->getSectionPrefix();
482  if (OptionalPrefix)
483  Name += *OptionalPrefix;
484  }
485 
486  unsigned UniqueID = MCContext::GenericSectionID;
487  if (EmitUniqueSection) {
488  if (TM.getUniqueSectionNames()) {
489  Name.push_back('.');
490  TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
491  } else {
492  UniqueID = *NextUniqueID;
493  (*NextUniqueID)++;
494  }
495  }
496  // Use 0 as the unique ID for execute-only text.
497  if (Kind.isExecuteOnly())
498  UniqueID = 0;
499  return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
500  EntrySize, Group, UniqueID, AssociatedSymbol);
501 }
502 
504  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
505  unsigned Flags = getELFSectionFlags(Kind);
506 
507  // If we have -ffunction-section or -fdata-section then we should emit the
508  // global value to a uniqued section specifically for it.
509  bool EmitUniqueSection = false;
510  if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
511  if (Kind.isText())
512  EmitUniqueSection = TM.getFunctionSections();
513  else
514  EmitUniqueSection = TM.getDataSections();
515  }
516  EmitUniqueSection |= GO->hasComdat();
517 
518  const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
519  if (AssociatedSymbol) {
520  EmitUniqueSection = true;
521  Flags |= ELF::SHF_LINK_ORDER;
522  }
523 
525  getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
526  &NextUniqueID, AssociatedSymbol);
527  assert(Section->getAssociatedSymbol() == AssociatedSymbol);
528  return Section;
529 }
530 
532  const Function &F, const TargetMachine &TM) const {
533  // If the function can be removed, produce a unique section so that
534  // the table doesn't prevent the removal.
535  const Comdat *C = F.getComdat();
536  bool EmitUniqueSection = TM.getFunctionSections() || C;
537  if (!EmitUniqueSection)
538  return ReadOnlySection;
539 
540  return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
541  getMangler(), TM, EmitUniqueSection,
542  ELF::SHF_ALLOC, &NextUniqueID,
543  /* AssociatedSymbol */ nullptr);
544 }
545 
547  bool UsesLabelDifference, const Function &F) const {
548  // We can always create relative relocations, so use another section
549  // that can be marked non-executable.
550  return false;
551 }
552 
553 /// Given a mergeable constant with the specified size and relocation
554 /// information, return a section that it should be placed in.
556  const DataLayout &DL, SectionKind Kind, const Constant *C,
557  unsigned &Align) const {
558  if (Kind.isMergeableConst4() && MergeableConst4Section)
559  return MergeableConst4Section;
560  if (Kind.isMergeableConst8() && MergeableConst8Section)
561  return MergeableConst8Section;
562  if (Kind.isMergeableConst16() && MergeableConst16Section)
563  return MergeableConst16Section;
564  if (Kind.isMergeableConst32() && MergeableConst32Section)
565  return MergeableConst32Section;
566  if (Kind.isReadOnly())
567  return ReadOnlySection;
568 
569  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
570  return DataRelROSection;
571 }
572 
573 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
574  bool IsCtor, unsigned Priority,
575  const MCSymbol *KeySym) {
576  std::string Name;
577  unsigned Type;
578  unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
579  StringRef COMDAT = KeySym ? KeySym->getName() : "";
580 
581  if (KeySym)
582  Flags |= ELF::SHF_GROUP;
583 
584  if (UseInitArray) {
585  if (IsCtor) {
586  Type = ELF::SHT_INIT_ARRAY;
587  Name = ".init_array";
588  } else {
589  Type = ELF::SHT_FINI_ARRAY;
590  Name = ".fini_array";
591  }
592  if (Priority != 65535) {
593  Name += '.';
594  Name += utostr(Priority);
595  }
596  } else {
597  // The default scheme is .ctor / .dtor, so we have to invert the priority
598  // numbering.
599  if (IsCtor)
600  Name = ".ctors";
601  else
602  Name = ".dtors";
603  if (Priority != 65535)
604  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
605  Type = ELF::SHT_PROGBITS;
606  }
607 
608  return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
609 }
610 
612  unsigned Priority, const MCSymbol *KeySym) const {
613  return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
614  KeySym);
615 }
616 
618  unsigned Priority, const MCSymbol *KeySym) const {
619  return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
620  KeySym);
621 }
622 
624  const GlobalValue *LHS, const GlobalValue *RHS,
625  const TargetMachine &TM) const {
626  // We may only use a PLT-relative relocation to refer to unnamed_addr
627  // functions.
628  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
629  return nullptr;
630 
631  // Basic sanity checks.
632  if (LHS->getType()->getPointerAddressSpace() != 0 ||
633  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
634  RHS->isThreadLocal())
635  return nullptr;
636 
638  MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
639  getContext()),
640  MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
641 }
642 
643 void
645  UseInitArray = UseInitArray_;
646  MCContext &Ctx = getContext();
647  if (!UseInitArray) {
648  StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
650 
651  StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
653  return;
654  }
655 
656  StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
658  StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
660 }
661 
662 //===----------------------------------------------------------------------===//
663 // MachO
664 //===----------------------------------------------------------------------===//
665 
669 }
670 
672  const TargetMachine &TM) {
674  if (TM.getRelocationModel() == Reloc::Static) {
675  StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
677  StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
679  } else {
680  StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
683  StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
686  }
687 }
688 
690  Module &M) const {
691  // Emit the linker options if present.
692  if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
693  for (const auto &Option : LinkerOptions->operands()) {
694  SmallVector<std::string, 4> StrOptions;
695  for (const auto &Piece : cast<MDNode>(Option)->operands())
696  StrOptions.push_back(cast<MDString>(Piece)->getString());
697  Streamer.EmitLinkerOptions(StrOptions);
698  }
699  }
700 
701  unsigned VersionVal = 0;
702  unsigned ImageInfoFlags = 0;
703  StringRef SectionVal;
704 
705  GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
706 
707  // The section is mandatory. If we don't have it, then we don't have GC info.
708  if (SectionVal.empty())
709  return;
710 
711  StringRef Segment, Section;
712  unsigned TAA = 0, StubSize = 0;
713  bool TAAParsed;
714  std::string ErrorCode =
715  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
716  TAA, TAAParsed, StubSize);
717  if (!ErrorCode.empty())
718  // If invalid, report the error with report_fatal_error.
719  report_fatal_error("Invalid section specifier '" + Section + "': " +
720  ErrorCode + ".");
721 
722  // Get the section.
724  Segment, Section, TAA, StubSize, SectionKind::getData());
725  Streamer.SwitchSection(S);
726  Streamer.EmitLabel(getContext().
727  getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
728  Streamer.EmitIntValue(VersionVal, 4);
729  Streamer.EmitIntValue(ImageInfoFlags, 4);
730  Streamer.AddBlankLine();
731 }
732 
733 static void checkMachOComdat(const GlobalValue *GV) {
734  const Comdat *C = GV->getComdat();
735  if (!C)
736  return;
737 
738  report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
739  "' cannot be lowered.");
740 }
741 
743  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
744  // Parse the section specifier and create it if valid.
745  StringRef Segment, Section;
746  unsigned TAA = 0, StubSize = 0;
747  bool TAAParsed;
748 
749  checkMachOComdat(GO);
750 
751  std::string ErrorCode =
753  TAA, TAAParsed, StubSize);
754  if (!ErrorCode.empty()) {
755  // If invalid, report the error with report_fatal_error.
756  report_fatal_error("Global variable '" + GO->getName() +
757  "' has an invalid section specifier '" +
758  GO->getSection() + "': " + ErrorCode + ".");
759  }
760 
761  // Get the section.
762  MCSectionMachO *S =
763  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
764 
765  // If TAA wasn't set by ParseSectionSpecifier() above,
766  // use the value returned by getMachOSection() as a default.
767  if (!TAAParsed)
768  TAA = S->getTypeAndAttributes();
769 
770  // Okay, now that we got the section, verify that the TAA & StubSize agree.
771  // If the user declared multiple globals with different section flags, we need
772  // to reject it here.
773  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
774  // If invalid, report the error with report_fatal_error.
775  report_fatal_error("Global variable '" + GO->getName() +
776  "' section type or attributes does not match previous"
777  " section specifier");
778  }
779 
780  return S;
781 }
782 
784  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
785  checkMachOComdat(GO);
786 
787  // Handle thread local data.
788  if (Kind.isThreadBSS()) return TLSBSSSection;
789  if (Kind.isThreadData()) return TLSDataSection;
790 
791  if (Kind.isText())
793 
794  // If this is weak/linkonce, put this in a coalescable section, either in text
795  // or data depending on if it is writable.
796  if (GO->isWeakForLinker()) {
797  if (Kind.isReadOnly())
798  return ConstTextCoalSection;
799  if (Kind.isReadOnlyWithRel())
800  return ConstDataCoalSection;
801  return DataCoalSection;
802  }
803 
804  // FIXME: Alignment check should be handled by section classifier.
805  if (Kind.isMergeable1ByteCString() &&
807  cast<GlobalVariable>(GO)) < 32)
808  return CStringSection;
809 
810  // Do not put 16-bit arrays in the UString section if they have an
811  // externally visible label, this runs into issues with certain linker
812  // versions.
813  if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
815  cast<GlobalVariable>(GO)) < 32)
816  return UStringSection;
817 
818  // With MachO only variables whose corresponding symbol starts with 'l' or
819  // 'L' can be merged, so we only try merging GVs with private linkage.
820  if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
821  if (Kind.isMergeableConst4())
823  if (Kind.isMergeableConst8())
825  if (Kind.isMergeableConst16())
827  }
828 
829  // Otherwise, if it is readonly, but not something we can specially optimize,
830  // just drop it in .const.
831  if (Kind.isReadOnly())
832  return ReadOnlySection;
833 
834  // If this is marked const, put it into a const section. But if the dynamic
835  // linker needs to write to it, put it in the data segment.
836  if (Kind.isReadOnlyWithRel())
837  return ConstDataSection;
838 
839  // Put zero initialized globals with strong external linkage in the
840  // DATA, __common section with the .zerofill directive.
841  if (Kind.isBSSExtern())
842  return DataCommonSection;
843 
844  // Put zero initialized globals with local linkage in __DATA,__bss directive
845  // with the .zerofill directive (aka .lcomm).
846  if (Kind.isBSSLocal())
847  return DataBSSSection;
848 
849  // Otherwise, just drop the variable in the normal data section.
850  return DataSection;
851 }
852 
854  const DataLayout &DL, SectionKind Kind, const Constant *C,
855  unsigned &Align) const {
856  // If this constant requires a relocation, we have to put it in the data
857  // segment, not in the text segment.
858  if (Kind.isData() || Kind.isReadOnlyWithRel())
859  return ConstDataSection;
860 
861  if (Kind.isMergeableConst4())
863  if (Kind.isMergeableConst8())
865  if (Kind.isMergeableConst16())
867  return ReadOnlySection; // .const
868 }
869 
871  const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
872  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
873  // The mach-o version of this method defaults to returning a stub reference.
874 
875  if (Encoding & DW_EH_PE_indirect) {
876  MachineModuleInfoMachO &MachOMMI =
878 
879  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
880 
881  // Add information about the stub reference to MachOMMI so that the stub
882  // gets emitted by the asmprinter.
883  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
884  if (!StubSym.getPointer()) {
885  MCSymbol *Sym = TM.getSymbol(GV);
887  }
888 
891  Encoding & ~DW_EH_PE_indirect, Streamer);
892  }
893 
895  MMI, Streamer);
896 }
897 
899  const GlobalValue *GV, const TargetMachine &TM,
900  MachineModuleInfo *MMI) const {
901  // The mach-o version of this method defaults to returning a stub reference.
902  MachineModuleInfoMachO &MachOMMI =
904 
905  MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
906 
907  // Add information about the stub reference to MachOMMI so that the stub
908  // gets emitted by the asmprinter.
909  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
910  if (!StubSym.getPointer()) {
911  MCSymbol *Sym = TM.getSymbol(GV);
913  }
914 
915  return SSym;
916 }
917 
919  const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
920  MachineModuleInfo *MMI, MCStreamer &Streamer) const {
921  // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
922  // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
923  // through a non_lazy_ptr stub instead. One advantage is that it allows the
924  // computation of deltas to final external symbols. Example:
925  //
926  // _extgotequiv:
927  // .long _extfoo
928  //
929  // _delta:
930  // .long _extgotequiv-_delta
931  //
932  // is transformed to:
933  //
934  // _delta:
935  // .long L_extfoo$non_lazy_ptr-(_delta+0)
936  //
937  // .section __IMPORT,__pointers,non_lazy_symbol_pointers
938  // L_extfoo$non_lazy_ptr:
939  // .indirect_symbol _extfoo
940  // .long 0
941  //
942  MachineModuleInfoMachO &MachOMMI =
944  MCContext &Ctx = getContext();
945 
946  // The offset must consider the original displacement from the base symbol
947  // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
948  Offset = -MV.getConstant();
949  const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
950 
951  // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
952  // non_lazy_ptr stubs.
954  StringRef Suffix = "$non_lazy_ptr";
955  Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
956  Name += Sym->getName();
957  Name += Suffix;
958  MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
959 
960  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
961  if (!StubSym.getPointer())
962  StubSym = MachineModuleInfoImpl::
963  StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
964 
965  const MCExpr *BSymExpr =
967  const MCExpr *LHS =
969 
970  if (!Offset)
971  return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
972 
973  const MCExpr *RHS =
974  MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
975  return MCBinaryExpr::createSub(LHS, RHS, Ctx);
976 }
977 
978 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
979  const MCSection &Section) {
980  if (!AsmInfo.isSectionAtomizableBySymbols(Section))
981  return true;
982 
983  // If it is not dead stripped, it is safe to use private labels.
984  const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
986  return true;
987 
988  return false;
989 }
990 
992  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
993  const TargetMachine &TM) const {
994  bool CannotUsePrivateLabel = true;
995  if (auto *GO = GV->getBaseObject()) {
997  const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
998  CannotUsePrivateLabel =
999  !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1000  }
1001  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1002 }
1003 
1004 //===----------------------------------------------------------------------===//
1005 // COFF
1006 //===----------------------------------------------------------------------===//
1007 
1008 static unsigned
1010  unsigned Flags = 0;
1011  bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1012 
1013  if (K.isMetadata())
1014  Flags |=
1016  else if (K.isText())
1017  Flags |=
1022  else if (K.isBSS())
1023  Flags |=
1027  else if (K.isThreadLocal())
1028  Flags |=
1032  else if (K.isReadOnly() || K.isReadOnlyWithRel())
1033  Flags |=
1036  else if (K.isWriteable())
1037  Flags |=
1041 
1042  return Flags;
1043 }
1044 
1045 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1046  const Comdat *C = GV->getComdat();
1047  assert(C && "expected GV to have a Comdat!");
1048 
1049  StringRef ComdatGVName = C->getName();
1050  const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1051  if (!ComdatGV)
1052  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1053  "' does not exist.");
1054 
1055  if (ComdatGV->getComdat() != C)
1056  report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1057  "' is not a key for its COMDAT.");
1058 
1059  return ComdatGV;
1060 }
1061 
1062 static int getSelectionForCOFF(const GlobalValue *GV) {
1063  if (const Comdat *C = GV->getComdat()) {
1064  const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1065  if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1066  ComdatKey = GA->getBaseObject();
1067  if (ComdatKey == GV) {
1068  switch (C->getSelectionKind()) {
1069  case Comdat::Any:
1071  case Comdat::ExactMatch:
1073  case Comdat::Largest:
1075  case Comdat::NoDuplicates:
1077  case Comdat::SameSize:
1079  }
1080  } else {
1082  }
1083  }
1084  return 0;
1085 }
1086 
1088  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1089  int Selection = 0;
1090  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1091  StringRef Name = GO->getSection();
1092  StringRef COMDATSymName = "";
1093  if (GO->hasComdat()) {
1094  Selection = getSelectionForCOFF(GO);
1095  const GlobalValue *ComdatGV;
1096  if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1097  ComdatGV = getComdatGVForCOFF(GO);
1098  else
1099  ComdatGV = GO;
1100 
1101  if (!ComdatGV->hasPrivateLinkage()) {
1102  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1103  COMDATSymName = Sym->getName();
1104  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1105  } else {
1106  Selection = 0;
1107  }
1108  }
1109 
1110  return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1111  Selection);
1112 }
1113 
1115  if (Kind.isText())
1116  return ".text";
1117  if (Kind.isBSS())
1118  return ".bss";
1119  if (Kind.isThreadLocal())
1120  return ".tls$";
1121  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1122  return ".rdata";
1123  return ".data";
1124 }
1125 
1127  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1128  // If we have -ffunction-sections then we should emit the global value to a
1129  // uniqued section specifically for it.
1130  bool EmitUniquedSection;
1131  if (Kind.isText())
1132  EmitUniquedSection = TM.getFunctionSections();
1133  else
1134  EmitUniquedSection = TM.getDataSections();
1135 
1136  if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1138 
1139  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1140 
1141  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1142  int Selection = getSelectionForCOFF(GO);
1143  if (!Selection)
1145  const GlobalValue *ComdatGV;
1146  if (GO->hasComdat())
1147  ComdatGV = getComdatGVForCOFF(GO);
1148  else
1149  ComdatGV = GO;
1150 
1151  unsigned UniqueID = MCContext::GenericSectionID;
1152  if (EmitUniquedSection)
1153  UniqueID = NextUniqueID++;
1154 
1155  if (!ComdatGV->hasPrivateLinkage()) {
1156  MCSymbol *Sym = TM.getSymbol(ComdatGV);
1157  StringRef COMDATSymName = Sym->getName();
1158 
1159  // Append "$symbol" to the section name when targetting mingw. The ld.bfd
1160  // COFF linker will not properly handle comdats otherwise.
1161  if (getTargetTriple().isWindowsGNUEnvironment())
1162  raw_svector_ostream(Name) << '$' << COMDATSymName;
1163 
1164  return getContext().getCOFFSection(Name, Characteristics, Kind,
1165  COMDATSymName, Selection, UniqueID);
1166  } else {
1167  SmallString<256> TmpData;
1168  getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1169  return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1170  Selection, UniqueID);
1171  }
1172  }
1173 
1174  if (Kind.isText())
1175  return TextSection;
1176 
1177  if (Kind.isThreadLocal())
1178  return TLSDataSection;
1179 
1180  if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1181  return ReadOnlySection;
1182 
1183  // Note: we claim that common symbols are put in BSSSection, but they are
1184  // really emitted with the magic .comm directive, which creates a symbol table
1185  // entry but not a section.
1186  if (Kind.isBSS() || Kind.isCommon())
1187  return BSSSection;
1188 
1189  return DataSection;
1190 }
1191 
1193  SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1194  const TargetMachine &TM) const {
1195  bool CannotUsePrivateLabel = false;
1196  if (GV->hasPrivateLinkage() &&
1197  ((isa<Function>(GV) && TM.getFunctionSections()) ||
1198  (isa<GlobalVariable>(GV) && TM.getDataSections())))
1199  CannotUsePrivateLabel = true;
1200 
1201  getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1202 }
1203 
1205  const Function &F, const TargetMachine &TM) const {
1206  // If the function can be removed, produce a unique section so that
1207  // the table doesn't prevent the removal.
1208  const Comdat *C = F.getComdat();
1209  bool EmitUniqueSection = TM.getFunctionSections() || C;
1210  if (!EmitUniqueSection)
1211  return ReadOnlySection;
1212 
1213  // FIXME: we should produce a symbol for F instead.
1214  if (F.hasPrivateLinkage())
1215  return ReadOnlySection;
1216 
1217  MCSymbol *Sym = TM.getSymbol(&F);
1218  StringRef COMDATSymName = Sym->getName();
1219 
1222  unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1223  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1224  unsigned UniqueID = NextUniqueID++;
1225 
1226  return getContext().getCOFFSection(
1227  SecName, Characteristics, Kind, COMDATSymName,
1229 }
1230 
1232  Module &M) const {
1233  if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1234  // Emit the linker options to the linker .drectve section. According to the
1235  // spec, this section is a space-separated string containing flags for
1236  // linker.
1237  MCSection *Sec = getDrectveSection();
1238  Streamer.SwitchSection(Sec);
1239  for (const auto &Option : LinkerOptions->operands()) {
1240  for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1241  // Lead with a space for consistency with our dllexport implementation.
1242  std::string Directive(" ");
1243  Directive.append(cast<MDString>(Piece)->getString());
1244  Streamer.EmitBytes(Directive);
1245  }
1246  }
1247  }
1248 
1249  unsigned Version = 0;
1250  unsigned Flags = 0;
1252 
1253  GetObjCImageInfo(M, Version, Flags, Section);
1254  if (Section.empty())
1255  return;
1256 
1257  auto &C = getContext();
1258  auto *S = C.getCOFFSection(
1261  Streamer.SwitchSection(S);
1262  Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1263  Streamer.EmitIntValue(Version, 4);
1264  Streamer.EmitIntValue(Flags, 4);
1265  Streamer.AddBlankLine();
1266 }
1267 
1269  const TargetMachine &TM) {
1271  const Triple &T = TM.getTargetTriple();
1281  } else {
1290  }
1291 }
1292 
1294  const Triple &T, bool IsCtor,
1295  unsigned Priority,
1296  const MCSymbol *KeySym,
1299  return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1300 
1301  std::string Name = IsCtor ? ".ctors" : ".dtors";
1302  if (Priority != 65535)
1303  raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1304 
1305  return Ctx.getAssociativeCOFFSection(
1310  KeySym, 0);
1311 }
1312 
1314  unsigned Priority, const MCSymbol *KeySym) const {
1316  Priority, KeySym,
1317  cast<MCSectionCOFF>(StaticCtorSection));
1318 }
1319 
1321  unsigned Priority, const MCSymbol *KeySym) const {
1323  Priority, KeySym,
1324  cast<MCSectionCOFF>(StaticDtorSection));
1325 }
1326 
1328  raw_ostream &OS, const GlobalValue *GV) const {
1330 }
1331 
1333  raw_ostream &OS, const GlobalValue *GV) const {
1335 }
1336 
1338  const GlobalValue *LHS, const GlobalValue *RHS,
1339  const TargetMachine &TM) const {
1340  const Triple &T = TM.getTargetTriple();
1341  if (!T.isKnownWindowsMSVCEnvironment() &&
1344  return nullptr;
1345 
1346  // Our symbols should exist in address space zero, cowardly no-op if
1347  // otherwise.
1348  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1349  RHS->getType()->getPointerAddressSpace() != 0)
1350  return nullptr;
1351 
1352  // Both ptrtoint instructions must wrap global objects:
1353  // - Only global variables are eligible for image relative relocations.
1354  // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1355  // We expect __ImageBase to be a global variable without a section, externally
1356  // defined.
1357  //
1358  // It should look something like this: @__ImageBase = external constant i8
1359  if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1360  LHS->isThreadLocal() || RHS->isThreadLocal() ||
1361  RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1362  cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1363  return nullptr;
1364 
1365  return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1367  getContext());
1368 }
1369 
1370 static std::string APIntToHexString(const APInt &AI) {
1371  unsigned Width = (AI.getBitWidth() / 8) * 2;
1372  std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1373  unsigned Size = HexString.size();
1374  assert(Width >= Size && "hex string is too large!");
1375  HexString.insert(HexString.begin(), Width - Size, '0');
1376 
1377  return HexString;
1378 }
1379 
1380 static std::string scalarConstantToHexString(const Constant *C) {
1381  Type *Ty = C->getType();
1382  if (isa<UndefValue>(C)) {
1384  } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1385  return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1386  } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1387  return APIntToHexString(CI->getValue());
1388  } else {
1389  unsigned NumElements;
1390  if (isa<VectorType>(Ty))
1391  NumElements = Ty->getVectorNumElements();
1392  else
1393  NumElements = Ty->getArrayNumElements();
1394  std::string HexString;
1395  for (int I = NumElements - 1, E = -1; I != E; --I)
1397  return HexString;
1398  }
1399 }
1400 
1402  const DataLayout &DL, SectionKind Kind, const Constant *C,
1403  unsigned &Align) const {
1404  if (Kind.isMergeableConst() && C &&
1406  // This creates comdat sections with the given symbol name, but unless
1407  // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1408  // will be created with a null storage class, which makes GNU binutils
1409  // error out.
1413  std::string COMDATSymName;
1414  if (Kind.isMergeableConst4()) {
1415  if (Align <= 4) {
1416  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1417  Align = 4;
1418  }
1419  } else if (Kind.isMergeableConst8()) {
1420  if (Align <= 8) {
1421  COMDATSymName = "__real@" + scalarConstantToHexString(C);
1422  Align = 8;
1423  }
1424  } else if (Kind.isMergeableConst16()) {
1425  // FIXME: These may not be appropriate for non-x86 architectures.
1426  if (Align <= 16) {
1427  COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1428  Align = 16;
1429  }
1430  } else if (Kind.isMergeableConst32()) {
1431  if (Align <= 32) {
1432  COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1433  Align = 32;
1434  }
1435  }
1436 
1437  if (!COMDATSymName.empty())
1438  return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1439  COMDATSymName,
1441  }
1442 
1443  return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1444 }
1445 
1446 
1447 //===----------------------------------------------------------------------===//
1448 // Wasm
1449 //===----------------------------------------------------------------------===//
1450 
1451 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1452  const Comdat *C = GV->getComdat();
1453  if (!C)
1454  return nullptr;
1455 
1456  if (C->getSelectionKind() != Comdat::Any)
1457  report_fatal_error("WebAssembly COMDATs only support "
1458  "SelectionKind::Any, '" + C->getName() + "' cannot be "
1459  "lowered.");
1460 
1461  return C;
1462 }
1463 
1465  // If we're told we have function data, then use that.
1466  if (K.isText())
1467  return SectionKind::getText();
1468 
1469  // Otherwise, ignore whatever section type the generic impl detected and use
1470  // a plain data section.
1471  return SectionKind::getData();
1472 }
1473 
1475  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1476  // We don't support explict section names for functions in the wasm object
1477  // format. Each function has to be in its own unique section.
1478  if (isa<Function>(GO)) {
1479  return SelectSectionForGlobal(GO, Kind, TM);
1480  }
1481 
1482  StringRef Name = GO->getSection();
1483 
1484  Kind = getWasmKindForNamedSection(Name, Kind);
1485 
1486  StringRef Group = "";
1487  if (const Comdat *C = getWasmComdat(GO)) {
1488  Group = C->getName();
1489  }
1490 
1491  return getContext().getWasmSection(Name, Kind, Group,
1493 }
1494 
1496  MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1497  const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1498  StringRef Group = "";
1499  if (const Comdat *C = getWasmComdat(GO)) {
1500  Group = C->getName();
1501  }
1502 
1503  bool UniqueSectionNames = TM.getUniqueSectionNames();
1505 
1506  if (const auto *F = dyn_cast<Function>(GO)) {
1507  const auto &OptionalPrefix = F->getSectionPrefix();
1508  if (OptionalPrefix)
1509  Name += *OptionalPrefix;
1510  }
1511 
1512  if (EmitUniqueSection && UniqueSectionNames) {
1513  Name.push_back('.');
1514  TM.getNameWithPrefix(Name, GO, Mang, true);
1515  }
1516  unsigned UniqueID = MCContext::GenericSectionID;
1517  if (EmitUniqueSection && !UniqueSectionNames) {
1518  UniqueID = *NextUniqueID;
1519  (*NextUniqueID)++;
1520  }
1521  return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1522 }
1523 
1525  const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1526 
1527  if (Kind.isCommon())
1528  report_fatal_error("mergable sections not supported yet on wasm");
1529 
1530  // If we have -ffunction-section or -fdata-section then we should emit the
1531  // global value to a uniqued section specifically for it.
1532  bool EmitUniqueSection = false;
1533  if (Kind.isText())
1534  EmitUniqueSection = TM.getFunctionSections();
1535  else
1536  EmitUniqueSection = TM.getDataSections();
1537  EmitUniqueSection |= GO->hasComdat();
1538 
1539  return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1540  EmitUniqueSection, &NextUniqueID);
1541 }
1542 
1544  bool UsesLabelDifference, const Function &F) const {
1545  // We can always create relative relocations, so use another section
1546  // that can be marked non-executable.
1547  return false;
1548 }
1549 
1551  const GlobalValue *LHS, const GlobalValue *RHS,
1552  const TargetMachine &TM) const {
1553  // We may only use a PLT-relative relocation to refer to unnamed_addr
1554  // functions.
1555  if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1556  return nullptr;
1557 
1558  // Basic sanity checks.
1559  if (LHS->getType()->getPointerAddressSpace() != 0 ||
1560  RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1561  RHS->isThreadLocal())
1562  return nullptr;
1563 
1564  return MCBinaryExpr::createSub(
1566  getContext()),
1568 }
1569 
1572  getContext().getWasmSection(".init_array", SectionKind::getData());
1573 }
1574 
1576  unsigned Priority, const MCSymbol *KeySym) const {
1577  return Priority == UINT16_MAX ?
1579  getContext().getWasmSection(".init_array." + utostr(Priority),
1581 }
1582 
1584  unsigned Priority, const MCSymbol *KeySym) const {
1585  llvm_unreachable("@llvm.global_dtors should have been lowered already");
1586  return nullptr;
1587 }
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:709
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: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:321
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:119
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:63
void emitLinkerFlagsForGlobal(raw_ostream &OS, const GlobalValue *GV) const override
virtual void AddBlankLine()
AddBlankLine - Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:324
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:971
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:458
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:307
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:504
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
bool isMergeableCString() const
Definition: SectionKind.h:128
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
Metadata node.
Definition: Metadata.h:862
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:165
F(f)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, unsigned &Align) const override
Given a constant with the SectionKind, return a section that it should be placed in.
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
const MCExpr * getIndirectSymViaGOTPCRel(const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Get MachO PC relative GOT entry relocation.
unsigned getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
Definition: DataLayout.cpp:611
static bool isThumb(const MCSubtargetInfo &STI)
unsigned getTypeAndAttributes() const
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1502
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:127
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:269
int64_t getConstant() const
Definition: MCValue.h:47
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:49
A tuple of MDNodes.
Definition: Metadata.h:1323
static SectionKind getBSS()
Definition: SectionKind.h:198
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
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:530
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp: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:421
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:544
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:1065
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:285
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:242
MCSection * ConstDataCoalSection
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:112
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
bool isBSSLocal() const
Definition: SectionKind.h:161
bool isMergeableConst32() const
Definition: SectionKind.h:143
bool hasImplicitSection() const
Check if section name is present.
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:337
static SectionKind getThreadData()
Definition: SectionKind.h:197
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:459
bool isWindowsItaniumEnvironment() const
Definition: Triple.h:538
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:376
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:534
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:369
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:282
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:993
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:981
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
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
const MCSymbol & getSymbol() const
Definition: MCExpr.h:334
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:199
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
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:166
Class for arbitrary precision integers.
Definition: APInt.h:69
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:440
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: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: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:962
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:275
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:256
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:477
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:393
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:565
bool isData() const
Definition: SectionKind.h:166
bool isThreadLocal() const
Definition: SectionKind.h:149
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
bool isMergeable1ByteCString() const
Definition: SectionKind.h:132
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:322
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:317
Metadata * get() const
Definition: Metadata.h:720
bool isExecuteOnly() const
Definition: SectionKind.h:121
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
virtual void emitCGProfileEntry(const MCSymbolRefExpr *From, const MCSymbolRefExpr *To, uint64_t Count)
Definition: MCStreamer.cpp:664
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:246
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:568
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:273
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