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

Generated by: LCOV version 1.13