LCOV - code coverage report
Current view: top level - lib/CodeGen - TargetLoweringObjectFileImpl.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 576 642 89.7 %
Date: 2017-09-14 15:23:50 Functions: 46 53 86.8 %
Legend: Lines: hit not hit

          Line data    Source code
       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             : 
      15             : #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
      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"
      22             : #include "llvm/BinaryFormat/Dwarf.h"
      23             : #include "llvm/BinaryFormat/ELF.h"
      24             : #include "llvm/BinaryFormat/MachO.h"
      25             : #include "llvm/CodeGen/MachineModuleInfo.h"
      26             : #include "llvm/CodeGen/MachineModuleInfoImpls.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"
      52             : #include "llvm/ProfileData/InstrProf.h"
      53             : #include "llvm/Support/Casting.h"
      54             : #include "llvm/Support/CodeGen.h"
      55             : #include "llvm/Support/ErrorHandling.h"
      56             : #include "llvm/Support/raw_ostream.h"
      57             : #include "llvm/Target/TargetMachine.h"
      58             : #include <cassert>
      59             : #include <string>
      60             : 
      61             : using namespace llvm;
      62             : using namespace dwarf;
      63             : 
      64       16535 : static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
      65             :                              StringRef &Section) {
      66       33071 :   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
      67       16535 :   M.getModuleFlagsMetadata(ModuleFlags);
      68             : 
      69       52212 :   for (const auto &MFE: ModuleFlags) {
      70             :     // Ignore flags with 'Require' behaviour.
      71        2604 :     if (MFE.Behavior == Module::Require)
      72           0 :       continue;
      73             : 
      74        2604 :     StringRef Key = MFE.Key->getString();
      75        2671 :     if (Key == "Objective-C Image Info Version") {
      76         201 :       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
      77        2537 :     } else if (Key == "Objective-C Garbage Collection" ||
      78        2470 :                Key == "Objective-C GC Only" ||
      79        2470 :                Key == "Objective-C Is Simulated" ||
      80        2470 :                Key == "Objective-C Class Properties" ||
      81        2403 :                Key == "Objective-C Image Swift Version") {
      82         402 :       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
      83        2470 :     } else if (Key == "Objective-C Image Info Section") {
      84         134 :       Section = cast<MDString>(MFE.Val)->getString();
      85             :     }
      86             :   }
      87       16536 : }
      88             : 
      89             : //===----------------------------------------------------------------------===//
      90             : //                                  ELF
      91             : //===----------------------------------------------------------------------===//
      92             : 
      93       13519 : void TargetLoweringObjectFileELF::emitModuleMetadata(
      94             :     MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
      95       13519 :   unsigned Version = 0;
      96       13519 :   unsigned Flags = 0;
      97       13519 :   StringRef Section;
      98             : 
      99       13519 :   GetObjCImageInfo(M, Version, Flags, Section);
     100       13520 :   if (Section.empty())
     101       13481 :     return;
     102             : 
     103          39 :   auto &C = getContext();
     104          78 :   auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
     105          39 :   Streamer.SwitchSection(S);
     106         117 :   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
     107          39 :   Streamer.EmitIntValue(Version, 4);
     108          39 :   Streamer.EmitIntValue(Flags, 4);
     109          39 :   Streamer.AddBlankLine();
     110             : }
     111             : 
     112        2353 : MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
     113             :     const GlobalValue *GV, const TargetMachine &TM,
     114             :     MachineModuleInfo *MMI) const {
     115        2353 :   unsigned Encoding = getPersonalityEncoding();
     116        2353 :   if ((Encoding & 0x80) == DW_EH_PE_indirect)
     117       10740 :     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
     118       15036 :                                           TM.getSymbol(GV)->getName());
     119         205 :   if ((Encoding & 0x70) == DW_EH_PE_absptr)
     120         205 :     return TM.getSymbol(GV);
     121           0 :   report_fatal_error("We do not support this DWARF encoding yet!");
     122             : }
     123             : 
     124          84 : void TargetLoweringObjectFileELF::emitPersonalityValue(
     125             :     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
     126         252 :   SmallString<64> NameData("DW.ref.");
     127         168 :   NameData += Sym->getName();
     128             :   MCSymbolELF *Label =
     129         252 :       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
     130          84 :   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
     131          84 :   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
     132          84 :   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
     133         420 :   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
     134          84 :                                                    ELF::SHT_PROGBITS, Flags, 0);
     135          84 :   unsigned Size = DL.getPointerSize();
     136          84 :   Streamer.SwitchSection(Sec);
     137          84 :   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
     138          84 :   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
     139          84 :   const MCExpr *E = MCConstantExpr::create(Size, getContext());
     140          84 :   Streamer.emitELFSize(Label, E);
     141          84 :   Streamer.EmitLabel(Label);
     142             : 
     143          84 :   Streamer.EmitSymbolValue(Sym, Size);
     144          84 : }
     145             : 
     146          74 : const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
     147             :     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
     148             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     149          74 :   if (Encoding & DW_EH_PE_indirect) {
     150          53 :     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
     151             : 
     152         106 :     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
     153             : 
     154             :     // Add information about the stub reference to ELFMMI so that the stub
     155             :     // gets emitted by the asmprinter.
     156          53 :     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
     157          53 :     if (!StubSym.getPointer()) {
     158          27 :       MCSymbol *Sym = TM.getSymbol(GV);
     159          54 :       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     160             :     }
     161             : 
     162             :     return TargetLoweringObjectFile::
     163         106 :       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
     164          53 :                         Encoding & ~DW_EH_PE_indirect, Streamer);
     165             :   }
     166             : 
     167          21 :   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
     168          21 :                                                            MMI, Streamer);
     169             : }
     170             : 
     171             : static SectionKind
     172         351 : getELFKindForNamedSection(StringRef Name, SectionKind K) {
     173             :   // N.B.: The defaults used in here are no the same ones used in MC.
     174             :   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
     175             :   // both gas and MC will produce a section with no flags. Given
     176             :   // section(".eh_frame") gcc will produce:
     177             :   //
     178             :   //   .section   .eh_frame,"a",@progbits
     179             : 
     180        1404 :   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
     181             :                                       /*AddSegmentInfo=*/false))
     182             :     return SectionKind::getMetadata();
     183             : 
     184         700 :   if (Name.empty() || Name[0] != '.') return K;
     185             : 
     186             :   // Some lame default implementation based on some magic section names.
     187         173 :   if (Name == ".bss" ||
     188         172 :       Name.startswith(".bss.") ||
     189         171 :       Name.startswith(".gnu.linkonce.b.") ||
     190         171 :       Name.startswith(".llvm.linkonce.b.") ||
     191         171 :       Name == ".sbss" ||
     192         170 :       Name.startswith(".sbss.") ||
     193         170 :       Name.startswith(".gnu.linkonce.sb.") ||
     194         170 :       Name.startswith(".llvm.linkonce.sb."))
     195             :     return SectionKind::getBSS();
     196             : 
     197         170 :   if (Name == ".tdata" ||
     198         170 :       Name.startswith(".tdata.") ||
     199         170 :       Name.startswith(".gnu.linkonce.td.") ||
     200         170 :       Name.startswith(".llvm.linkonce.td."))
     201             :     return SectionKind::getThreadData();
     202             : 
     203         170 :   if (Name == ".tbss" ||
     204         170 :       Name.startswith(".tbss.") ||
     205         170 :       Name.startswith(".gnu.linkonce.tb.") ||
     206         170 :       Name.startswith(".llvm.linkonce.tb."))
     207             :     return SectionKind::getThreadBSS();
     208             : 
     209         170 :   return K;
     210             : }
     211             : 
     212      183926 : static unsigned getELFSectionType(StringRef Name, SectionKind K) {
     213             :   // Use SHT_NOTE for section whose name starts with ".note" to allow
     214             :   // emitting ELF notes from C variable declaration.
     215             :   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
     216      183926 :   if (Name.startswith(".note"))
     217             :     return ELF::SHT_NOTE;
     218             : 
     219      183925 :   if (Name == ".init_array")
     220             :     return ELF::SHT_INIT_ARRAY;
     221             : 
     222      183924 :   if (Name == ".fini_array")
     223             :     return ELF::SHT_FINI_ARRAY;
     224             : 
     225      183923 :   if (Name == ".preinit_array")
     226             :     return ELF::SHT_PREINIT_ARRAY;
     227             : 
     228      183922 :   if (K.isBSS() || K.isThreadBSS())
     229             :     return ELF::SHT_NOBITS;
     230             : 
     231             :   return ELF::SHT_PROGBITS;
     232             : }
     233             : 
     234      183903 : static unsigned getELFSectionFlags(SectionKind K) {
     235      183903 :   unsigned Flags = 0;
     236             : 
     237      183903 :   if (!K.isMetadata())
     238      183902 :     Flags |= ELF::SHF_ALLOC;
     239             : 
     240      183903 :   if (K.isText())
     241      122742 :     Flags |= ELF::SHF_EXECINSTR;
     242             : 
     243      183903 :   if (K.isExecuteOnly())
     244          78 :     Flags |= ELF::SHF_ARM_PURECODE;
     245             : 
     246             :   if (K.isWriteable())
     247       33869 :     Flags |= ELF::SHF_WRITE;
     248             : 
     249      183903 :   if (K.isThreadLocal())
     250         162 :     Flags |= ELF::SHF_TLS;
     251             : 
     252      341209 :   if (K.isMergeableCString() || K.isMergeableConst())
     253       26718 :     Flags |= ELF::SHF_MERGE;
     254             : 
     255      183903 :   if (K.isMergeableCString())
     256       26597 :     Flags |= ELF::SHF_STRINGS;
     257             : 
     258      183903 :   return Flags;
     259             : }
     260             : 
     261      183926 : static const Comdat *getELFComdat(const GlobalValue *GV) {
     262      183926 :   const Comdat *C = GV->getComdat();
     263      183926 :   if (!C)
     264             :     return nullptr;
     265             : 
     266        4374 :   if (C->getSelectionKind() != Comdat::Any)
     267           0 :     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
     268           0 :                        C->getName() + "' cannot be lowered.");
     269             : 
     270             :   return C;
     271             : }
     272             : 
     273      183903 : static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
     274             :                                               const TargetMachine &TM) {
     275      183903 :   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
     276      183903 :   if (!MD)
     277             :     return nullptr;
     278             : 
     279          22 :   const MDOperand &Op = MD->getOperand(0);
     280          22 :   if (!Op.get())
     281             :     return nullptr;
     282             : 
     283          20 :   auto *VM = dyn_cast<ValueAsMetadata>(Op);
     284             :   if (!VM)
     285           0 :     report_fatal_error("MD_associated operand is not ValueAsMetadata");
     286             : 
     287          38 :   GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
     288          18 :   return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
     289             : }
     290             : 
     291         351 : MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
     292             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     293         351 :   StringRef SectionName = GO->getSection();
     294             : 
     295             :   // Check if '#pragma clang section' name is applicable.
     296             :   // Note that pragma directive overrides -ffunction-section, -fdata-section
     297             :   // and so section name is exactly as user specified and not uniqued.
     298         151 :   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
     299         151 :   if (GV && GV->hasImplicitSection()) {
     300          13 :     auto Attrs = GV->getAttributes();
     301          33 :     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
     302           7 :       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
     303          12 :     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
     304           3 :       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
     305           6 :     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
     306           3 :       SectionName = Attrs.getAttribute("data-section").getValueAsString();
     307             :     }
     308             :   }
     309         200 :   const Function *F = dyn_cast<Function>(GO);
     310         400 :   if (F && F->hasFnAttribute("implicit-section-name")) {
     311           4 :     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
     312             :   }
     313             : 
     314             :   // Infer section flags from the section name if we can.
     315         351 :   Kind = getELFKindForNamedSection(SectionName, Kind);
     316             : 
     317         351 :   StringRef Group = "";
     318         351 :   unsigned Flags = getELFSectionFlags(Kind);
     319         351 :   if (const Comdat *C = getELFComdat(GO)) {
     320           3 :     Group = C->getName();
     321           3 :     Flags |= ELF::SHF_GROUP;
     322             :   }
     323             : 
     324             :   // A section can have at most one associated section. Put each global with
     325             :   // MD_associated in a unique section.
     326         351 :   unsigned UniqueID = MCContext::GenericSectionID;
     327         351 :   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
     328         351 :   if (AssociatedSymbol) {
     329           6 :     UniqueID = NextUniqueID++;
     330           6 :     Flags |= ELF::SHF_LINK_ORDER;
     331             :   }
     332             : 
     333        1404 :   MCSectionELF *Section = getContext().getELFSection(
     334             :       SectionName, getELFSectionType(SectionName, Kind), Flags,
     335         351 :       /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
     336             :   // Make sure that we did not get some other section with incompatible sh_link.
     337             :   // This should not be possible due to UniqueID code above.
     338             :   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
     339         351 :   return Section;
     340             : }
     341             : 
     342             : /// Return the section prefix name used by options FunctionsSections and
     343             : /// DataSections.
     344      156857 : static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
     345      156857 :   if (Kind.isText())
     346      122542 :     return ".text";
     347       33746 :   if (Kind.isReadOnly())
     348         569 :     return ".rodata";
     349       33746 :   if (Kind.isBSS())
     350       24018 :     return ".bss";
     351        9728 :   if (Kind.isThreadData())
     352          76 :     return ".tdata";
     353        9652 :   if (Kind.isThreadBSS())
     354          86 :     return ".tbss";
     355        9566 :   if (Kind.isData())
     356        6114 :     return ".data";
     357             :   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
     358        3452 :   return ".data.rel.ro";
     359             : }
     360             : 
     361      183575 : static MCSectionELF *selectELFSectionForGlobal(
     362             :     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
     363             :     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
     364             :     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
     365      183575 :   unsigned EntrySize = 0;
     366      183575 :   if (Kind.isMergeableCString()) {
     367       26597 :     if (Kind.isMergeable2ByteCString()) {
     368             :       EntrySize = 2;
     369       26589 :     } else if (Kind.isMergeable4ByteCString()) {
     370             :       EntrySize = 4;
     371             :     } else {
     372       26580 :       EntrySize = 1;
     373             :       assert(Kind.isMergeable1ByteCString() && "unknown string width");
     374             :     }
     375      156978 :   } else if (Kind.isMergeableConst()) {
     376         121 :     if (Kind.isMergeableConst4()) {
     377             :       EntrySize = 4;
     378          80 :     } else if (Kind.isMergeableConst8()) {
     379             :       EntrySize = 8;
     380          30 :     } else if (Kind.isMergeableConst16()) {
     381             :       EntrySize = 16;
     382             :     } else {
     383             :       assert(Kind.isMergeableConst32() && "unknown data width");
     384          10 :       EntrySize = 32;
     385             :     }
     386             :   }
     387             : 
     388      183575 :   StringRef Group = "";
     389      183575 :   if (const Comdat *C = getELFComdat(GO)) {
     390        4371 :     Flags |= ELF::SHF_GROUP;
     391        4371 :     Group = C->getName();
     392             :   }
     393             : 
     394      183575 :   bool UniqueSectionNames = TM.getUniqueSectionNames();
     395      367150 :   SmallString<128> Name;
     396      183575 :   if (Kind.isMergeableCString()) {
     397             :     // We also need alignment here.
     398             :     // FIXME: this is getting the alignment of the character, not the
     399             :     // alignment of the global!
     400       53194 :     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
     401       26597 :         cast<GlobalVariable>(GO));
     402             : 
     403      106388 :     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
     404      132985 :     Name = SizeSpec + utostr(Align);
     405      156978 :   } else if (Kind.isMergeableConst()) {
     406         242 :     Name = ".rodata.cst";
     407         484 :     Name += utostr(EntrySize);
     408             :   } else {
     409      156857 :     Name = getSectionPrefixForGlobal(Kind);
     410             :   }
     411             : 
     412      122565 :   if (const auto *F = dyn_cast<Function>(GO)) {
     413      122565 :     const auto &OptionalPrefix = F->getSectionPrefix();
     414      122565 :     if (OptionalPrefix)
     415           8 :       Name += *OptionalPrefix;
     416             :   }
     417             : 
     418      183575 :   if (EmitUniqueSection && UniqueSectionNames) {
     419       33277 :     Name.push_back('.');
     420       33277 :     TM.getNameWithPrefix(Name, GO, Mang, true);
     421             :   }
     422      183575 :   unsigned UniqueID = MCContext::GenericSectionID;
     423      183575 :   if (EmitUniqueSection && !UniqueSectionNames) {
     424           7 :     UniqueID = *NextUniqueID;
     425           7 :     (*NextUniqueID)++;
     426             :   }
     427             :   // Use 0 as the unique ID for execute-only text
     428      183575 :   if (Kind.isExecuteOnly())
     429          75 :     UniqueID = 0;
     430      734300 :   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
     431      367150 :                            EntrySize, Group, UniqueID, AssociatedSymbol);
     432             : }
     433             : 
     434      183552 : MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
     435             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     436      183552 :   unsigned Flags = getELFSectionFlags(Kind);
     437             : 
     438             :   // If we have -ffunction-section or -fdata-section then we should emit the
     439             :   // global value to a uniqued section specifically for it.
     440      183552 :   bool EmitUniqueSection = false;
     441      183552 :   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
     442      156834 :     if (Kind.isText())
     443      122542 :       EmitUniqueSection = TM.getFunctionSections();
     444             :     else
     445       34292 :       EmitUniqueSection = TM.getDataSections();
     446             :   }
     447      183552 :   EmitUniqueSection |= GO->hasComdat();
     448             : 
     449      183552 :   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
     450      183552 :   if (AssociatedSymbol) {
     451          12 :     EmitUniqueSection = true;
     452          12 :     Flags |= ELF::SHF_LINK_ORDER;
     453             :   }
     454             : 
     455      183552 :   MCSectionELF *Section = selectELFSectionForGlobal(
     456             :       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
     457      183552 :       &NextUniqueID, AssociatedSymbol);
     458             :   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
     459      183552 :   return Section;
     460             : }
     461             : 
     462         111 : MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
     463             :     const Function &F, const TargetMachine &TM) const {
     464             :   // If the function can be removed, produce a unique section so that
     465             :   // the table doesn't prevent the removal.
     466         111 :   const Comdat *C = F.getComdat();
     467         111 :   bool EmitUniqueSection = TM.getFunctionSections() || C;
     468             :   if (!EmitUniqueSection)
     469          88 :     return ReadOnlySection;
     470             : 
     471          46 :   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
     472             :                                    getMangler(), TM, EmitUniqueSection,
     473             :                                    ELF::SHF_ALLOC, &NextUniqueID,
     474          23 :                                    /* AssociatedSymbol */ nullptr);
     475             : }
     476             : 
     477         108 : bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
     478             :     bool UsesLabelDifference, const Function &F) const {
     479             :   // We can always create relative relocations, so use another section
     480             :   // that can be marked non-executable.
     481         108 :   return false;
     482             : }
     483             : 
     484             : /// Given a mergeable constant with the specified size and relocation
     485             : /// information, return a section that it should be placed in.
     486       15524 : MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
     487             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
     488             :     unsigned &Align) const {
     489       15524 :   if (Kind.isMergeableConst4() && MergeableConst4Section)
     490             :     return MergeableConst4Section;
     491       13997 :   if (Kind.isMergeableConst8() && MergeableConst8Section)
     492             :     return MergeableConst8Section;
     493       12973 :   if (Kind.isMergeableConst16() && MergeableConst16Section)
     494             :     return MergeableConst16Section;
     495        3987 :   if (Kind.isMergeableConst32() && MergeableConst32Section)
     496             :     return MergeableConst32Section;
     497          17 :   if (Kind.isReadOnly())
     498        1188 :     return ReadOnlySection;
     499             : 
     500             :   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
     501          17 :   return DataRelROSection;
     502             : }
     503             : 
     504         177 : static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
     505             :                                               bool IsCtor, unsigned Priority,
     506             :                                               const MCSymbol *KeySym) {
     507         354 :   std::string Name;
     508             :   unsigned Type;
     509         177 :   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
     510         190 :   StringRef COMDAT = KeySym ? KeySym->getName() : "";
     511             : 
     512         177 :   if (KeySym)
     513          13 :     Flags |= ELF::SHF_GROUP;
     514             : 
     515         177 :   if (UseInitArray) {
     516         149 :     if (IsCtor) {
     517         147 :       Type = ELF::SHT_INIT_ARRAY;
     518             :       Name = ".init_array";
     519             :     } else {
     520           2 :       Type = ELF::SHT_FINI_ARRAY;
     521             :       Name = ".fini_array";
     522             :     }
     523         149 :     if (Priority != 65535) {
     524          70 :       Name += '.';
     525         210 :       Name += utostr(Priority);
     526             :     }
     527             :   } else {
     528             :     // The default scheme is .ctor / .dtor, so we have to invert the priority
     529             :     // numbering.
     530          28 :     if (IsCtor)
     531             :       Name = ".ctors";
     532             :     else
     533             :       Name = ".dtors";
     534          28 :     if (Priority != 65535) {
     535          14 :       Name += '.';
     536          42 :       Name += utostr(65535 - Priority);
     537             :     }
     538             :     Type = ELF::SHT_PROGBITS;
     539             :   }
     540             : 
     541         708 :   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
     542             : }
     543             : 
     544         169 : MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
     545             :     unsigned Priority, const MCSymbol *KeySym) const {
     546         169 :   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
     547         169 :                                   KeySym);
     548             : }
     549             : 
     550           8 : MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
     551             :     unsigned Priority, const MCSymbol *KeySym) const {
     552           8 :   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
     553           8 :                                   KeySym);
     554             : }
     555             : 
     556          11 : const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
     557             :     const GlobalValue *LHS, const GlobalValue *RHS,
     558             :     const TargetMachine &TM) const {
     559             :   // We may only use a PLT-relative relocation to refer to unnamed_addr
     560             :   // functions.
     561          18 :   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
     562             :     return nullptr;
     563             : 
     564             :   // Basic sanity checks.
     565          18 :   if (LHS->getType()->getPointerAddressSpace() != 0 ||
     566          30 :       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
     567           6 :       RHS->isThreadLocal())
     568             :     return nullptr;
     569             : 
     570           6 :   return MCBinaryExpr::createSub(
     571          12 :       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
     572           6 :                               getContext()),
     573          18 :       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
     574             : }
     575             : 
     576             : void
     577        8290 : TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
     578        8290 :   UseInitArray = UseInitArray_;
     579        8290 :   MCContext &Ctx = getContext();
     580        8290 :   if (!UseInitArray) {
     581         758 :     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
     582             :                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
     583             : 
     584         758 :     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
     585             :                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
     586         379 :     return;
     587             :   }
     588             : 
     589       15822 :   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
     590             :                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
     591       15822 :   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
     592             :                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
     593             : }
     594             : 
     595             : //===----------------------------------------------------------------------===//
     596             : //                                 MachO
     597             : //===----------------------------------------------------------------------===//
     598             : 
     599        4562 : TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
     600        9124 :   : TargetLoweringObjectFile() {
     601        4562 :   SupportIndirectSymViaGOTPCRel = true;
     602        4562 : }
     603             : 
     604        2441 : void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
     605             :                                                const TargetMachine &TM) {
     606        2441 :   TargetLoweringObjectFile::Initialize(Ctx, TM);
     607        2441 :   if (TM.getRelocationModel() == Reloc::Static) {
     608          98 :     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
     609             :                                             SectionKind::getData());
     610          98 :     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
     611             :                                             SectionKind::getData());
     612             :   } else {
     613        4784 :     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
     614             :                                             MachO::S_MOD_INIT_FUNC_POINTERS,
     615             :                                             SectionKind::getData());
     616        4784 :     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
     617             :                                             MachO::S_MOD_TERM_FUNC_POINTERS,
     618             :                                             SectionKind::getData());
     619             :   }
     620        2441 : }
     621             : 
     622        2426 : void TargetLoweringObjectFileMachO::emitModuleMetadata(
     623             :     MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
     624             :   // Emit the linker options if present.
     625        2426 :   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
     626          11 :     for (const auto &Option : LinkerOptions->operands()) {
     627          12 :       SmallVector<std::string, 4> StrOptions;
     628          26 :       for (const auto &Piece : cast<MDNode>(Option)->operands())
     629          24 :         StrOptions.push_back(cast<MDString>(Piece)->getString());
     630          12 :       Streamer.EmitLinkerOptions(StrOptions);
     631             :     }
     632             :   }
     633             : 
     634        2426 :   unsigned VersionVal = 0;
     635        2426 :   unsigned ImageInfoFlags = 0;
     636        2426 :   StringRef SectionVal;
     637             : 
     638        2426 :   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
     639             : 
     640             :   // The section is mandatory. If we don't have it, then we don't have GC info.
     641        2426 :   if (SectionVal.empty())
     642        2401 :     return;
     643             : 
     644          25 :   StringRef Segment, Section;
     645          25 :   unsigned TAA = 0, StubSize = 0;
     646             :   bool TAAParsed;
     647             :   std::string ErrorCode =
     648             :     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
     649          50 :                                           TAA, TAAParsed, StubSize);
     650          25 :   if (!ErrorCode.empty())
     651             :     // If invalid, report the error with report_fatal_error.
     652           0 :     report_fatal_error("Invalid section specifier '" + Section + "': " +
     653           0 :                        ErrorCode + ".");
     654             : 
     655             :   // Get the section.
     656          50 :   MCSectionMachO *S = getContext().getMachOSection(
     657          25 :       Segment, Section, TAA, StubSize, SectionKind::getData());
     658          25 :   Streamer.SwitchSection(S);
     659          75 :   Streamer.EmitLabel(getContext().
     660          75 :                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
     661          25 :   Streamer.EmitIntValue(VersionVal, 4);
     662          25 :   Streamer.EmitIntValue(ImageInfoFlags, 4);
     663          25 :   Streamer.AddBlankLine();
     664             : }
     665             : 
     666       18272 : static void checkMachOComdat(const GlobalValue *GV) {
     667       18272 :   const Comdat *C = GV->getComdat();
     668       18272 :   if (!C)
     669       18271 :     return;
     670             : 
     671           3 :   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
     672           1 :                      "' cannot be lowered.");
     673             : }
     674             : 
     675         813 : MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
     676             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     677             :   // Parse the section specifier and create it if valid.
     678         813 :   StringRef Segment, Section;
     679         813 :   unsigned TAA = 0, StubSize = 0;
     680             :   bool TAAParsed;
     681             : 
     682         813 :   checkMachOComdat(GO);
     683             : 
     684             :   std::string ErrorCode =
     685             :     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
     686        1626 :                                           TAA, TAAParsed, StubSize);
     687         813 :   if (!ErrorCode.empty()) {
     688             :     // If invalid, report the error with report_fatal_error.
     689           0 :     report_fatal_error("Global variable '" + GO->getName() +
     690           0 :                        "' has an invalid section specifier '" +
     691           0 :                        GO->getSection() + "': " + ErrorCode + ".");
     692             :   }
     693             : 
     694             :   // Get the section.
     695             :   MCSectionMachO *S =
     696         813 :       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
     697             : 
     698             :   // If TAA wasn't set by ParseSectionSpecifier() above,
     699             :   // use the value returned by getMachOSection() as a default.
     700         813 :   if (!TAAParsed)
     701         189 :     TAA = S->getTypeAndAttributes();
     702             : 
     703             :   // Okay, now that we got the section, verify that the TAA & StubSize agree.
     704             :   // If the user declared multiple globals with different section flags, we need
     705             :   // to reject it here.
     706         813 :   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
     707             :     // If invalid, report the error with report_fatal_error.
     708           0 :     report_fatal_error("Global variable '" + GO->getName() +
     709             :                        "' section type or attributes does not match previous"
     710           0 :                        " section specifier");
     711             :   }
     712             : 
     713        1626 :   return S;
     714             : }
     715             : 
     716       17459 : MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
     717             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     718       17459 :   checkMachOComdat(GO);
     719             : 
     720             :   // Handle thread local data.
     721       17458 :   if (Kind.isThreadBSS()) return TLSBSSSection;
     722       17386 :   if (Kind.isThreadData()) return TLSDataSection;
     723             : 
     724       17378 :   if (Kind.isText())
     725       32108 :     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
     726             : 
     727             :   // If this is weak/linkonce, put this in a coalescable section, either in text
     728             :   // or data depending on if it is writable.
     729        2475 :   if (GO->isWeakForLinker()) {
     730          57 :     if (Kind.isReadOnly())
     731          36 :       return ConstTextCoalSection;
     732          57 :     return DataCoalSection;
     733             :   }
     734             : 
     735             :   // FIXME: Alignment check should be handled by section classifier.
     736        1591 :   if (Kind.isMergeable1ByteCString() &&
     737         800 :       GO->getParent()->getDataLayout().getPreferredAlignment(
     738             :           cast<GlobalVariable>(GO)) < 32)
     739         400 :     return CStringSection;
     740             : 
     741             :   // Do not put 16-bit arrays in the UString section if they have an
     742             :   // externally visible label, this runs into issues with certain linker
     743             :   // versions.
     744         809 :   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
     745           8 :       GO->getParent()->getDataLayout().getPreferredAlignment(
     746             :           cast<GlobalVariable>(GO)) < 32)
     747           4 :     return UStringSection;
     748             : 
     749             :   // With MachO only variables whose corresponding symbol starts with 'l' or
     750             :   // 'L' can be merged, so we only try merging GVs with private linkage.
     751        1803 :   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
     752          35 :     if (Kind.isMergeableConst4())
     753           3 :       return FourByteConstantSection;
     754          32 :     if (Kind.isMergeableConst8())
     755           6 :       return EightByteConstantSection;
     756          26 :     if (Kind.isMergeableConst16())
     757          23 :       return SixteenByteConstantSection;
     758             :   }
     759             : 
     760             :   // Otherwise, if it is readonly, but not something we can specially optimize,
     761             :   // just drop it in .const.
     762         529 :   if (Kind.isReadOnly())
     763         226 :     return ReadOnlySection;
     764             : 
     765             :   // If this is marked const, put it into a const section.  But if the dynamic
     766             :   // linker needs to write to it, put it in the data segment.
     767         529 :   if (Kind.isReadOnlyWithRel())
     768          83 :     return ConstDataSection;
     769             : 
     770             :   // Put zero initialized globals with strong external linkage in the
     771             :   // DATA, __common section with the .zerofill directive.
     772         446 :   if (Kind.isBSSExtern())
     773         166 :     return DataCommonSection;
     774             : 
     775             :   // Put zero initialized globals with local linkage in __DATA,__bss directive
     776             :   // with the .zerofill directive (aka .lcomm).
     777         280 :   if (Kind.isBSSLocal())
     778         140 :     return DataBSSSection;
     779             : 
     780             :   // Otherwise, just drop the variable in the normal data section.
     781         140 :   return DataSection;
     782             : }
     783             : 
     784         869 : MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
     785             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
     786             :     unsigned &Align) const {
     787             :   // If this constant requires a relocation, we have to put it in the data
     788             :   // segment, not in the text segment.
     789         869 :   if (Kind.isData() || Kind.isReadOnlyWithRel())
     790           0 :     return ConstDataSection;
     791             : 
     792         869 :   if (Kind.isMergeableConst4())
     793         247 :     return FourByteConstantSection;
     794         622 :   if (Kind.isMergeableConst8())
     795         106 :     return EightByteConstantSection;
     796         516 :   if (Kind.isMergeableConst16())
     797         321 :     return SixteenByteConstantSection;
     798         195 :   return ReadOnlySection;  // .const
     799             : }
     800             : 
     801           8 : const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
     802             :     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
     803             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     804             :   // The mach-o version of this method defaults to returning a stub reference.
     805             : 
     806           8 :   if (Encoding & DW_EH_PE_indirect) {
     807             :     MachineModuleInfoMachO &MachOMMI =
     808           8 :       MMI->getObjFileInfo<MachineModuleInfoMachO>();
     809             : 
     810          16 :     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
     811             : 
     812             :     // Add information about the stub reference to MachOMMI so that the stub
     813             :     // gets emitted by the asmprinter.
     814           8 :     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
     815           8 :     if (!StubSym.getPointer()) {
     816           7 :       MCSymbol *Sym = TM.getSymbol(GV);
     817          14 :       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     818             :     }
     819             : 
     820             :     return TargetLoweringObjectFile::
     821          16 :       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
     822           8 :                         Encoding & ~DW_EH_PE_indirect, Streamer);
     823             :   }
     824             : 
     825           0 :   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
     826           0 :                                                            MMI, Streamer);
     827             : }
     828             : 
     829          24 : MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
     830             :     const GlobalValue *GV, const TargetMachine &TM,
     831             :     MachineModuleInfo *MMI) const {
     832             :   // The mach-o version of this method defaults to returning a stub reference.
     833             :   MachineModuleInfoMachO &MachOMMI =
     834          24 :     MMI->getObjFileInfo<MachineModuleInfoMachO>();
     835             : 
     836          48 :   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
     837             : 
     838             :   // Add information about the stub reference to MachOMMI so that the stub
     839             :   // gets emitted by the asmprinter.
     840          24 :   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
     841          24 :   if (!StubSym.getPointer()) {
     842          15 :     MCSymbol *Sym = TM.getSymbol(GV);
     843          30 :     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     844             :   }
     845             : 
     846          24 :   return SSym;
     847             : }
     848             : 
     849          10 : const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
     850             :     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
     851             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     852             :   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
     853             :   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
     854             :   // through a non_lazy_ptr stub instead. One advantage is that it allows the
     855             :   // computation of deltas to final external symbols. Example:
     856             :   //
     857             :   //    _extgotequiv:
     858             :   //       .long   _extfoo
     859             :   //
     860             :   //    _delta:
     861             :   //       .long   _extgotequiv-_delta
     862             :   //
     863             :   // is transformed to:
     864             :   //
     865             :   //    _delta:
     866             :   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
     867             :   //
     868             :   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
     869             :   //    L_extfoo$non_lazy_ptr:
     870             :   //       .indirect_symbol        _extfoo
     871             :   //       .long   0
     872             :   //
     873             :   MachineModuleInfoMachO &MachOMMI =
     874          10 :     MMI->getObjFileInfo<MachineModuleInfoMachO>();
     875          10 :   MCContext &Ctx = getContext();
     876             : 
     877             :   // The offset must consider the original displacement from the base symbol
     878             :   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
     879          10 :   Offset = -MV.getConstant();
     880          10 :   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
     881             : 
     882             :   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
     883             :   // non_lazy_ptr stubs.
     884          20 :   SmallString<128> Name;
     885          10 :   StringRef Suffix = "$non_lazy_ptr";
     886          20 :   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
     887          20 :   Name += Sym->getName();
     888          10 :   Name += Suffix;
     889          10 :   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
     890             : 
     891          10 :   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
     892          10 :   if (!StubSym.getPointer())
     893           4 :     StubSym = MachineModuleInfoImpl::
     894           4 :       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
     895             : 
     896             :   const MCExpr *BSymExpr =
     897          10 :     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
     898             :   const MCExpr *LHS =
     899          10 :     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
     900             : 
     901          10 :   if (!Offset)
     902           2 :     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
     903             : 
     904             :   const MCExpr *RHS =
     905          16 :     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
     906           8 :   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
     907             : }
     908             : 
     909             : static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
     910             :                                const MCSection &Section) {
     911        1055 :   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
     912             :     return true;
     913             : 
     914             :   // If it is not dead stripped, it is safe to use private labels.
     915         373 :   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
     916         746 :   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
     917             :     return true;
     918             : 
     919             :   return false;
     920             : }
     921             : 
     922        1055 : void TargetLoweringObjectFileMachO::getNameWithPrefix(
     923             :     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
     924             :     const TargetMachine &TM) const {
     925        1055 :   bool CannotUsePrivateLabel = true;
     926        1055 :   if (auto *GO = GV->getBaseObject()) {
     927        1055 :     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
     928        1055 :     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
     929        1055 :     CannotUsePrivateLabel =
     930        2110 :         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
     931             :   }
     932        1055 :   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
     933        1055 : }
     934             : 
     935             : //===----------------------------------------------------------------------===//
     936             : //                                  COFF
     937             : //===----------------------------------------------------------------------===//
     938             : 
     939             : static unsigned
     940         173 : getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
     941         173 :   unsigned Flags = 0;
     942         173 :   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
     943             : 
     944         173 :   if (K.isMetadata())
     945             :     Flags |=
     946             :       COFF::IMAGE_SCN_MEM_DISCARDABLE;
     947         173 :   else if (K.isText())
     948             :     Flags |=
     949             :       COFF::IMAGE_SCN_MEM_EXECUTE |
     950             :       COFF::IMAGE_SCN_MEM_READ |
     951          47 :       COFF::IMAGE_SCN_CNT_CODE |
     952             :       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
     953         126 :   else if (K.isBSS())
     954             :     Flags |=
     955             :       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
     956             :       COFF::IMAGE_SCN_MEM_READ |
     957             :       COFF::IMAGE_SCN_MEM_WRITE;
     958         111 :   else if (K.isThreadLocal())
     959             :     Flags |=
     960             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     961             :       COFF::IMAGE_SCN_MEM_READ |
     962             :       COFF::IMAGE_SCN_MEM_WRITE;
     963          80 :   else if (K.isReadOnly() || K.isReadOnlyWithRel())
     964             :     Flags |=
     965             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     966             :       COFF::IMAGE_SCN_MEM_READ;
     967          33 :   else if (K.isWriteable())
     968             :     Flags |=
     969             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     970             :       COFF::IMAGE_SCN_MEM_READ |
     971             :       COFF::IMAGE_SCN_MEM_WRITE;
     972             : 
     973         173 :   return Flags;
     974             : }
     975             : 
     976         249 : static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
     977         249 :   const Comdat *C = GV->getComdat();
     978             :   assert(C && "expected GV to have a Comdat!");
     979             : 
     980         249 :   StringRef ComdatGVName = C->getName();
     981         249 :   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
     982         249 :   if (!ComdatGV)
     983           2 :     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
     984           1 :                        "' does not exist.");
     985             : 
     986         248 :   if (ComdatGV->getComdat() != C)
     987           2 :     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
     988           1 :                        "' is not a key for its COMDAT.");
     989             : 
     990         247 :   return ComdatGV;
     991             : }
     992             : 
     993         151 : static int getSelectionForCOFF(const GlobalValue *GV) {
     994         151 :   if (const Comdat *C = GV->getComdat()) {
     995         127 :     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
     996          10 :     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
     997          10 :       ComdatKey = GA->getBaseObject();
     998         125 :     if (ComdatKey == GV) {
     999         116 :       switch (C->getSelectionKind()) {
    1000             :       case Comdat::Any:
    1001             :         return COFF::IMAGE_COMDAT_SELECT_ANY;
    1002           1 :       case Comdat::ExactMatch:
    1003           1 :         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
    1004          11 :       case Comdat::Largest:
    1005          11 :         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
    1006           1 :       case Comdat::NoDuplicates:
    1007           1 :         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
    1008           2 :       case Comdat::SameSize:
    1009           2 :         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
    1010             :       }
    1011             :     } else {
    1012             :       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
    1013             :     }
    1014             :   }
    1015             :   return 0;
    1016             : }
    1017             : 
    1018          21 : MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
    1019             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1020          21 :   int Selection = 0;
    1021          21 :   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1022          21 :   StringRef Name = GO->getSection();
    1023          21 :   StringRef COMDATSymName = "";
    1024          21 :   if (GO->hasComdat()) {
    1025           3 :     Selection = getSelectionForCOFF(GO);
    1026             :     const GlobalValue *ComdatGV;
    1027           3 :     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
    1028           0 :       ComdatGV = getComdatGVForCOFF(GO);
    1029             :     else
    1030             :       ComdatGV = GO;
    1031             : 
    1032           3 :     if (!ComdatGV->hasPrivateLinkage()) {
    1033           3 :       MCSymbol *Sym = TM.getSymbol(ComdatGV);
    1034           3 :       COMDATSymName = Sym->getName();
    1035           3 :       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1036             :     } else {
    1037             :       Selection = 0;
    1038             :     }
    1039             :   }
    1040             : 
    1041          21 :   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
    1042          21 :                                      Selection);
    1043             : }
    1044             : 
    1045         152 : static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
    1046         152 :   if (Kind.isText())
    1047             :     return ".text";
    1048         107 :   if (Kind.isBSS())
    1049             :     return ".bss";
    1050          92 :   if (Kind.isThreadLocal())
    1051             :     return ".tls$";
    1052          66 :   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
    1053             :     return ".rdata";
    1054             :   return ".data";
    1055             : }
    1056             : 
    1057        2516 : MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
    1058             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1059             :   // If we have -ffunction-sections then we should emit the global value to a
    1060             :   // uniqued section specifically for it.
    1061             :   bool EmitUniquedSection;
    1062        2516 :   if (Kind.isText())
    1063        2153 :     EmitUniquedSection = TM.getFunctionSections();
    1064             :   else
    1065         363 :     EmitUniquedSection = TM.getDataSections();
    1066             : 
    1067        5008 :   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
    1068         148 :     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
    1069         148 :     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1070             : 
    1071         148 :     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1072         148 :     int Selection = getSelectionForCOFF(GO);
    1073         146 :     if (!Selection)
    1074          24 :       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
    1075             :     const GlobalValue *ComdatGV;
    1076         146 :     if (GO->hasComdat())
    1077         122 :       ComdatGV = getComdatGVForCOFF(GO);
    1078             :     else
    1079             :       ComdatGV = GO;
    1080             : 
    1081         146 :     unsigned UniqueID = MCContext::GenericSectionID;
    1082         146 :     if (EmitUniquedSection)
    1083          24 :       UniqueID = NextUniqueID++;
    1084             : 
    1085         146 :     if (!ComdatGV->hasPrivateLinkage()) {
    1086         144 :       MCSymbol *Sym = TM.getSymbol(ComdatGV);
    1087         144 :       StringRef COMDATSymName = Sym->getName();
    1088         432 :       return getContext().getCOFFSection(Name, Characteristics, Kind,
    1089         144 :                                          COMDATSymName, Selection, UniqueID);
    1090             :     } else {
    1091           4 :       SmallString<256> TmpData;
    1092           2 :       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
    1093           8 :       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
    1094           2 :                                          Selection, UniqueID);
    1095             :     }
    1096             :   }
    1097             : 
    1098        2368 :   if (Kind.isText())
    1099        2108 :     return TextSection;
    1100             : 
    1101         260 :   if (Kind.isThreadLocal())
    1102          34 :     return TLSDataSection;
    1103             : 
    1104         123 :   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
    1105         106 :     return ReadOnlySection;
    1106             : 
    1107             :   // Note: we claim that common symbols are put in BSSSection, but they are
    1108             :   // really emitted with the magic .comm directive, which creates a symbol table
    1109             :   // entry but not a section.
    1110         157 :   if (Kind.isBSS() || Kind.isCommon())
    1111          83 :     return BSSSection;
    1112             : 
    1113          37 :   return DataSection;
    1114             : }
    1115             : 
    1116         205 : void TargetLoweringObjectFileCOFF::getNameWithPrefix(
    1117             :     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
    1118             :     const TargetMachine &TM) const {
    1119         205 :   bool CannotUsePrivateLabel = false;
    1120         615 :   if (GV->hasPrivateLinkage() &&
    1121         414 :       ((isa<Function>(GV) && TM.getFunctionSections()) ||
    1122         406 :        (isa<GlobalVariable>(GV) && TM.getDataSections())))
    1123             :     CannotUsePrivateLabel = true;
    1124             : 
    1125         205 :   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
    1126         205 : }
    1127             : 
    1128           7 : MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
    1129             :     const Function &F, const TargetMachine &TM) const {
    1130             :   // If the function can be removed, produce a unique section so that
    1131             :   // the table doesn't prevent the removal.
    1132           7 :   const Comdat *C = F.getComdat();
    1133           7 :   bool EmitUniqueSection = TM.getFunctionSections() || C;
    1134             :   if (!EmitUniqueSection)
    1135           3 :     return ReadOnlySection;
    1136             : 
    1137             :   // FIXME: we should produce a symbol for F instead.
    1138           8 :   if (F.hasPrivateLinkage())
    1139           0 :     return ReadOnlySection;
    1140             : 
    1141           4 :   MCSymbol *Sym = TM.getSymbol(&F);
    1142           4 :   StringRef COMDATSymName = Sym->getName();
    1143             : 
    1144           4 :   SectionKind Kind = SectionKind::getReadOnly();
    1145           4 :   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
    1146           4 :   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1147           4 :   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1148           4 :   unsigned UniqueID = NextUniqueID++;
    1149             : 
    1150          12 :   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
    1151           4 :                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
    1152             : }
    1153             : 
    1154         590 : void TargetLoweringObjectFileCOFF::emitModuleMetadata(
    1155             :     MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
    1156         590 :   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
    1157             :     // Emit the linker options to the linker .drectve section.  According to the
    1158             :     // spec, this section is a space-separated string containing flags for
    1159             :     // linker.
    1160           7 :     MCSection *Sec = getDrectveSection();
    1161           7 :     Streamer.SwitchSection(Sec);
    1162          16 :     for (const auto &Option : LinkerOptions->operands()) {
    1163          37 :       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
    1164             :         // Lead with a space for consistency with our dllexport implementation.
    1165          40 :         std::string Directive(" ");
    1166          40 :         Directive.append(cast<MDString>(Piece)->getString());
    1167          20 :         Streamer.EmitBytes(Directive);
    1168             :       }
    1169             :     }
    1170             :   }
    1171             : 
    1172         590 :   unsigned Version = 0;
    1173         590 :   unsigned Flags = 0;
    1174         590 :   StringRef Section;
    1175             : 
    1176         590 :   GetObjCImageInfo(M, Version, Flags, Section);
    1177         590 :   if (Section.empty())
    1178         587 :     return;
    1179             : 
    1180           3 :   auto &C = getContext();
    1181             :   auto *S = C.getCOFFSection(
    1182             :       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
    1183           3 :       SectionKind::getReadOnly());
    1184           3 :   Streamer.SwitchSection(S);
    1185           9 :   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
    1186           3 :   Streamer.EmitIntValue(Version, 4);
    1187           3 :   Streamer.EmitIntValue(Flags, 4);
    1188           3 :   Streamer.AddBlankLine();
    1189             : }
    1190             : 
    1191         593 : void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
    1192             :                                               const TargetMachine &TM) {
    1193         593 :   TargetLoweringObjectFile::Initialize(Ctx, TM);
    1194         593 :   const Triple &T = TM.getTargetTriple();
    1195             :   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
    1196         497 :     StaticCtorSection =
    1197        1491 :         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1198             :                                            COFF::IMAGE_SCN_MEM_READ,
    1199             :                            SectionKind::getReadOnly());
    1200         497 :     StaticDtorSection =
    1201        1491 :         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1202             :                                            COFF::IMAGE_SCN_MEM_READ,
    1203             :                            SectionKind::getReadOnly());
    1204             :   } else {
    1205         192 :     StaticCtorSection = Ctx.getCOFFSection(
    1206             :         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1207             :                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
    1208             :         SectionKind::getData());
    1209         192 :     StaticDtorSection = Ctx.getCOFFSection(
    1210             :         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1211             :                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
    1212             :         SectionKind::getData());
    1213             :   }
    1214         593 : }
    1215             : 
    1216          15 : MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
    1217             :     unsigned Priority, const MCSymbol *KeySym) const {
    1218          30 :   return getContext().getAssociativeCOFFSection(
    1219          30 :       cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
    1220             : }
    1221             : 
    1222           5 : MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
    1223             :     unsigned Priority, const MCSymbol *KeySym) const {
    1224          10 :   return getContext().getAssociativeCOFFSection(
    1225          10 :       cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
    1226             : }
    1227             : 
    1228        4379 : void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
    1229             :     raw_ostream &OS, const GlobalValue *GV) const {
    1230        8758 :   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
    1231        4379 : }
    1232             : 
    1233             : //===----------------------------------------------------------------------===//
    1234             : //                                  Wasm
    1235             : //===----------------------------------------------------------------------===//
    1236             : 
    1237           0 : static const Comdat *getWasmComdat(const GlobalValue *GV) {
    1238           0 :   const Comdat *C = GV->getComdat();
    1239           0 :   if (!C)
    1240             :     return nullptr;
    1241             : 
    1242           0 :   if (C->getSelectionKind() != Comdat::Any)
    1243           0 :     report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
    1244           0 :                        C->getName() + "' cannot be lowered.");
    1245             : 
    1246             :   return C;
    1247             : }
    1248             : 
    1249           0 : MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
    1250             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1251           0 :   llvm_unreachable("getExplicitSectionGlobal not yet implemented");
    1252             :   return nullptr;
    1253             : }
    1254             : 
    1255           0 : static MCSectionWasm *selectWasmSectionForGlobal(
    1256             :     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
    1257             :     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
    1258           0 :   StringRef Group = "";
    1259           0 :   if (getWasmComdat(GO))
    1260           0 :     llvm_unreachable("comdat not yet supported for wasm");
    1261             : 
    1262           0 :   bool UniqueSectionNames = TM.getUniqueSectionNames();
    1263           0 :   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
    1264             : 
    1265           0 :   if (const auto *F = dyn_cast<Function>(GO)) {
    1266           0 :     const auto &OptionalPrefix = F->getSectionPrefix();
    1267           0 :     if (OptionalPrefix)
    1268           0 :       Name += *OptionalPrefix;
    1269             :   }
    1270             : 
    1271           0 :   if (EmitUniqueSection && UniqueSectionNames) {
    1272           0 :     Name.push_back('.');
    1273           0 :     TM.getNameWithPrefix(Name, GO, Mang, true);
    1274             :   }
    1275           0 :   unsigned UniqueID = MCContext::GenericSectionID;
    1276           0 :   if (EmitUniqueSection && !UniqueSectionNames) {
    1277           0 :     UniqueID = *NextUniqueID;
    1278           0 :     (*NextUniqueID)++;
    1279             :   }
    1280           0 :   return Ctx.getWasmSection(Name, /*Type=*/0, Group, UniqueID);
    1281             : }
    1282             : 
    1283           0 : MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
    1284             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1285             : 
    1286           0 :   if (Kind.isCommon())
    1287           0 :     report_fatal_error("mergable sections not supported yet on wasm");
    1288             : 
    1289             :   // If we have -ffunction-section or -fdata-section then we should emit the
    1290             :   // global value to a uniqued section specifically for it.
    1291           0 :   bool EmitUniqueSection = false;
    1292           0 :   if (Kind.isText())
    1293           0 :     EmitUniqueSection = TM.getFunctionSections();
    1294             :   else
    1295           0 :     EmitUniqueSection = TM.getDataSections();
    1296           0 :   EmitUniqueSection |= GO->hasComdat();
    1297             : 
    1298           0 :   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
    1299           0 :                                     EmitUniqueSection, &NextUniqueID);
    1300             : }
    1301             : 
    1302           0 : bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
    1303             :     bool UsesLabelDifference, const Function &F) const {
    1304             :   // We can always create relative relocations, so use another section
    1305             :   // that can be marked non-executable.
    1306           0 :   return false;
    1307             : }
    1308             : 
    1309           0 : const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
    1310             :     const GlobalValue *LHS, const GlobalValue *RHS,
    1311             :     const TargetMachine &TM) const {
    1312             :   // We may only use a PLT-relative relocation to refer to unnamed_addr
    1313             :   // functions.
    1314           0 :   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
    1315             :     return nullptr;
    1316             : 
    1317             :   // Basic sanity checks.
    1318           0 :   if (LHS->getType()->getPointerAddressSpace() != 0 ||
    1319           0 :       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
    1320           0 :       RHS->isThreadLocal())
    1321             :     return nullptr;
    1322             : 
    1323           0 :   return MCBinaryExpr::createSub(
    1324           0 :       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
    1325           0 :                               getContext()),
    1326           0 :       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
    1327             : }
    1328             : 
    1329             : void
    1330           0 : TargetLoweringObjectFileWasm::InitializeWasm() {
    1331             :   // TODO: Initialize StaticCtorSection and StaticDtorSection.
    1332           0 : }

Generated by: LCOV version 1.13