LLVM  mainline
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements classes used to handle lowerings specific to common
00011 // object file formats.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/ADT/Triple.h"
00019 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/Function.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/Mangler.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/MC/MCContext.h"
00028 #include "llvm/MC/MCExpr.h"
00029 #include "llvm/MC/MCSectionCOFF.h"
00030 #include "llvm/MC/MCSectionELF.h"
00031 #include "llvm/MC/MCSectionMachO.h"
00032 #include "llvm/MC/MCStreamer.h"
00033 #include "llvm/MC/MCSymbol.h"
00034 #include "llvm/MC/MCValue.h"
00035 #include "llvm/Support/Dwarf.h"
00036 #include "llvm/Support/ELF.h"
00037 #include "llvm/Support/ErrorHandling.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include "llvm/Target/TargetLowering.h"
00040 #include "llvm/Target/TargetMachine.h"
00041 #include "llvm/Target/TargetSubtargetInfo.h"
00042 using namespace llvm;
00043 using namespace dwarf;
00044 
00045 //===----------------------------------------------------------------------===//
00046 //                                  ELF
00047 //===----------------------------------------------------------------------===//
00048 
00049 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
00050     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00051     MachineModuleInfo *MMI) const {
00052   unsigned Encoding = getPersonalityEncoding();
00053   if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
00054     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
00055                                           TM.getSymbol(GV, Mang)->getName());
00056   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
00057     return TM.getSymbol(GV, Mang);
00058   report_fatal_error("We do not support this DWARF encoding yet!");
00059 }
00060 
00061 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
00062                                                        const TargetMachine &TM,
00063                                                        const MCSymbol *Sym) const {
00064   SmallString<64> NameData("DW.ref.");
00065   NameData += Sym->getName();
00066   MCSymbol *Label = getContext().getOrCreateSymbol(NameData);
00067   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
00068   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
00069   StringRef Prefix = ".data.";
00070   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
00071   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
00072   MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
00073                                               Flags, 0, Label->getName());
00074   unsigned Size = TM.getDataLayout()->getPointerSize();
00075   Streamer.SwitchSection(Sec);
00076   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
00077   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
00078   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
00079   Streamer.EmitELFSize(Label, E);
00080   Streamer.EmitLabel(Label);
00081 
00082   Streamer.EmitSymbolValue(Sym, Size);
00083 }
00084 
00085 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
00086     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00087     const TargetMachine &TM, MachineModuleInfo *MMI,
00088     MCStreamer &Streamer) const {
00089 
00090   if (Encoding & dwarf::DW_EH_PE_indirect) {
00091     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
00092 
00093     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
00094 
00095     // Add information about the stub reference to ELFMMI so that the stub
00096     // gets emitted by the asmprinter.
00097     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
00098     if (!StubSym.getPointer()) {
00099       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00100       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00101     }
00102 
00103     return TargetLoweringObjectFile::
00104       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00105                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00106   }
00107 
00108   return TargetLoweringObjectFile::
00109     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
00110 }
00111 
00112 static SectionKind
00113 getELFKindForNamedSection(StringRef Name, SectionKind K) {
00114   // N.B.: The defaults used in here are no the same ones used in MC.
00115   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
00116   // both gas and MC will produce a section with no flags. Given
00117   // section(".eh_frame") gcc will produce:
00118   //
00119   //   .section   .eh_frame,"a",@progbits
00120   if (Name.empty() || Name[0] != '.') return K;
00121 
00122   // Some lame default implementation based on some magic section names.
00123   if (Name == ".bss" ||
00124       Name.startswith(".bss.") ||
00125       Name.startswith(".gnu.linkonce.b.") ||
00126       Name.startswith(".llvm.linkonce.b.") ||
00127       Name == ".sbss" ||
00128       Name.startswith(".sbss.") ||
00129       Name.startswith(".gnu.linkonce.sb.") ||
00130       Name.startswith(".llvm.linkonce.sb."))
00131     return SectionKind::getBSS();
00132 
00133   if (Name == ".tdata" ||
00134       Name.startswith(".tdata.") ||
00135       Name.startswith(".gnu.linkonce.td.") ||
00136       Name.startswith(".llvm.linkonce.td."))
00137     return SectionKind::getThreadData();
00138 
00139   if (Name == ".tbss" ||
00140       Name.startswith(".tbss.") ||
00141       Name.startswith(".gnu.linkonce.tb.") ||
00142       Name.startswith(".llvm.linkonce.tb."))
00143     return SectionKind::getThreadBSS();
00144 
00145   return K;
00146 }
00147 
00148 
00149 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
00150 
00151   if (Name == ".init_array")
00152     return ELF::SHT_INIT_ARRAY;
00153 
00154   if (Name == ".fini_array")
00155     return ELF::SHT_FINI_ARRAY;
00156 
00157   if (Name == ".preinit_array")
00158     return ELF::SHT_PREINIT_ARRAY;
00159 
00160   if (K.isBSS() || K.isThreadBSS())
00161     return ELF::SHT_NOBITS;
00162 
00163   return ELF::SHT_PROGBITS;
00164 }
00165 
00166 static unsigned getELFSectionFlags(SectionKind K) {
00167   unsigned Flags = 0;
00168 
00169   if (!K.isMetadata())
00170     Flags |= ELF::SHF_ALLOC;
00171 
00172   if (K.isText())
00173     Flags |= ELF::SHF_EXECINSTR;
00174 
00175   if (K.isWriteable())
00176     Flags |= ELF::SHF_WRITE;
00177 
00178   if (K.isThreadLocal())
00179     Flags |= ELF::SHF_TLS;
00180 
00181   if (K.isMergeableCString() || K.isMergeableConst())
00182     Flags |= ELF::SHF_MERGE;
00183 
00184   if (K.isMergeableCString())
00185     Flags |= ELF::SHF_STRINGS;
00186 
00187   return Flags;
00188 }
00189 
00190 static const Comdat *getELFComdat(const GlobalValue *GV) {
00191   const Comdat *C = GV->getComdat();
00192   if (!C)
00193     return nullptr;
00194 
00195   if (C->getSelectionKind() != Comdat::Any)
00196     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
00197                        C->getName() + "' cannot be lowered.");
00198 
00199   return C;
00200 }
00201 
00202 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
00203     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00204     const TargetMachine &TM) const {
00205   StringRef SectionName = GV->getSection();
00206 
00207   // Infer section flags from the section name if we can.
00208   Kind = getELFKindForNamedSection(SectionName, Kind);
00209 
00210   StringRef Group = "";
00211   unsigned Flags = getELFSectionFlags(Kind);
00212   if (const Comdat *C = getELFComdat(GV)) {
00213     Group = C->getName();
00214     Flags |= ELF::SHF_GROUP;
00215   }
00216   return getContext().getELFSection(SectionName,
00217                                     getELFSectionType(SectionName, Kind), Flags,
00218                                     /*EntrySize=*/0, Group);
00219 }
00220 
00221 /// Return the section prefix name used by options FunctionsSections and
00222 /// DataSections.
00223 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
00224   if (Kind.isText())
00225     return ".text";
00226   if (Kind.isReadOnly())
00227     return ".rodata";
00228   if (Kind.isBSS())
00229     return ".bss";
00230   if (Kind.isThreadData())
00231     return ".tdata";
00232   if (Kind.isThreadBSS())
00233     return ".tbss";
00234   if (Kind.isDataNoRel())
00235     return ".data";
00236   if (Kind.isDataRelLocal())
00237     return ".data.rel.local";
00238   if (Kind.isDataRel())
00239     return ".data.rel";
00240   if (Kind.isReadOnlyWithRelLocal())
00241     return ".data.rel.ro.local";
00242   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00243   return ".data.rel.ro";
00244 }
00245 
00246 static MCSectionELF *
00247 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
00248                           SectionKind Kind, Mangler &Mang,
00249                           const TargetMachine &TM, bool EmitUniqueSection,
00250                           unsigned Flags, unsigned *NextUniqueID) {
00251   unsigned EntrySize = 0;
00252   if (Kind.isMergeableCString()) {
00253     if (Kind.isMergeable2ByteCString()) {
00254       EntrySize = 2;
00255     } else if (Kind.isMergeable4ByteCString()) {
00256       EntrySize = 4;
00257     } else {
00258       EntrySize = 1;
00259       assert(Kind.isMergeable1ByteCString() && "unknown string width");
00260     }
00261   } else if (Kind.isMergeableConst()) {
00262     if (Kind.isMergeableConst4()) {
00263       EntrySize = 4;
00264     } else if (Kind.isMergeableConst8()) {
00265       EntrySize = 8;
00266     } else {
00267       assert(Kind.isMergeableConst16() && "unknown data width");
00268       EntrySize = 16;
00269     }
00270   }
00271 
00272   StringRef Group = "";
00273   if (const Comdat *C = getELFComdat(GV)) {
00274     Flags |= ELF::SHF_GROUP;
00275     Group = C->getName();
00276   }
00277 
00278   bool UniqueSectionNames = TM.getUniqueSectionNames();
00279   SmallString<128> Name;
00280   if (Kind.isMergeableCString()) {
00281     // We also need alignment here.
00282     // FIXME: this is getting the alignment of the character, not the
00283     // alignment of the global!
00284     unsigned Align =
00285         TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
00286 
00287     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
00288     Name = SizeSpec + utostr(Align);
00289   } else if (Kind.isMergeableConst()) {
00290     Name = ".rodata.cst";
00291     Name += utostr(EntrySize);
00292   } else {
00293     Name = getSectionPrefixForGlobal(Kind);
00294   }
00295 
00296   if (EmitUniqueSection && UniqueSectionNames) {
00297     Name.push_back('.');
00298     TM.getNameWithPrefix(Name, GV, Mang, true);
00299   }
00300   unsigned UniqueID = ~0;
00301   if (EmitUniqueSection && !UniqueSectionNames) {
00302     UniqueID = *NextUniqueID;
00303     (*NextUniqueID)++;
00304   }
00305   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
00306                            EntrySize, Group, UniqueID);
00307 }
00308 
00309 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
00310     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00311     const TargetMachine &TM) const {
00312   unsigned Flags = getELFSectionFlags(Kind);
00313 
00314   // If we have -ffunction-section or -fdata-section then we should emit the
00315   // global value to a uniqued section specifically for it.
00316   bool EmitUniqueSection = false;
00317   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
00318     if (Kind.isText())
00319       EmitUniqueSection = TM.getFunctionSections();
00320     else
00321       EmitUniqueSection = TM.getDataSections();
00322   }
00323   EmitUniqueSection |= GV->hasComdat();
00324 
00325   return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
00326                                    EmitUniqueSection, Flags, &NextUniqueID);
00327 }
00328 
00329 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
00330     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
00331   // If the function can be removed, produce a unique section so that
00332   // the table doesn't prevent the removal.
00333   const Comdat *C = F.getComdat();
00334   bool EmitUniqueSection = TM.getFunctionSections() || C;
00335   if (!EmitUniqueSection)
00336     return ReadOnlySection;
00337 
00338   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
00339                                    Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
00340                                    &NextUniqueID);
00341 }
00342 
00343 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
00344     bool UsesLabelDifference, const Function &F) const {
00345   // We can always create relative relocations, so use another section
00346   // that can be marked non-executable.
00347   return false;
00348 }
00349 
00350 /// Given a mergeable constant with the specified size and relocation
00351 /// information, return a section that it should be placed in.
00352 MCSection *
00353 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
00354                                                    const Constant *C) const {
00355   if (Kind.isMergeableConst4() && MergeableConst4Section)
00356     return MergeableConst4Section;
00357   if (Kind.isMergeableConst8() && MergeableConst8Section)
00358     return MergeableConst8Section;
00359   if (Kind.isMergeableConst16() && MergeableConst16Section)
00360     return MergeableConst16Section;
00361   if (Kind.isReadOnly())
00362     return ReadOnlySection;
00363 
00364   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00365   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00366   return DataRelROSection;
00367 }
00368 
00369 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
00370                                               bool IsCtor, unsigned Priority,
00371                                               const MCSymbol *KeySym) {
00372   std::string Name;
00373   unsigned Type;
00374   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
00375   StringRef COMDAT = KeySym ? KeySym->getName() : "";
00376 
00377   if (KeySym)
00378     Flags |= ELF::SHF_GROUP;
00379 
00380   if (UseInitArray) {
00381     if (IsCtor) {
00382       Type = ELF::SHT_INIT_ARRAY;
00383       Name = ".init_array";
00384     } else {
00385       Type = ELF::SHT_FINI_ARRAY;
00386       Name = ".fini_array";
00387     }
00388     if (Priority != 65535) {
00389       Name += '.';
00390       Name += utostr(Priority);
00391     }
00392   } else {
00393     // The default scheme is .ctor / .dtor, so we have to invert the priority
00394     // numbering.
00395     if (IsCtor)
00396       Name = ".ctors";
00397     else
00398       Name = ".dtors";
00399     if (Priority != 65535) {
00400       Name += '.';
00401       Name += utostr(65535 - Priority);
00402     }
00403     Type = ELF::SHT_PROGBITS;
00404   }
00405 
00406   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
00407 }
00408 
00409 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
00410     unsigned Priority, const MCSymbol *KeySym) const {
00411   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
00412                                   KeySym);
00413 }
00414 
00415 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
00416     unsigned Priority, const MCSymbol *KeySym) const {
00417   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
00418                                   KeySym);
00419 }
00420 
00421 void
00422 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00423   UseInitArray = UseInitArray_;
00424   if (!UseInitArray)
00425     return;
00426 
00427   StaticCtorSection = getContext().getELFSection(
00428       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
00429   StaticDtorSection = getContext().getELFSection(
00430       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
00431 }
00432 
00433 //===----------------------------------------------------------------------===//
00434 //                                 MachO
00435 //===----------------------------------------------------------------------===//
00436 
00437 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
00438   : TargetLoweringObjectFile() {
00439   SupportIndirectSymViaGOTPCRel = true;
00440 }
00441 
00442 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
00443 /// option string. Returns StringRef() if the option does not specify a library.
00444 StringRef TargetLoweringObjectFileMachO::
00445 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00446   const char *LibCmd = "-l";
00447   if (LinkerOption.startswith(LibCmd))
00448     return LinkerOption.substr(strlen(LibCmd));
00449   return StringRef();
00450 }
00451 
00452 /// emitModuleFlags - Perform code emission for module flags.
00453 void TargetLoweringObjectFileMachO::
00454 emitModuleFlags(MCStreamer &Streamer,
00455                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00456                 Mangler &Mang, const TargetMachine &TM) const {
00457   unsigned VersionVal = 0;
00458   unsigned ImageInfoFlags = 0;
00459   MDNode *LinkerOptions = nullptr;
00460   StringRef SectionVal;
00461 
00462   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00463          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00464     const Module::ModuleFlagEntry &MFE = *i;
00465 
00466     // Ignore flags with 'Require' behavior.
00467     if (MFE.Behavior == Module::Require)
00468       continue;
00469 
00470     StringRef Key = MFE.Key->getString();
00471     Metadata *Val = MFE.Val;
00472 
00473     if (Key == "Objective-C Image Info Version") {
00474       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
00475     } else if (Key == "Objective-C Garbage Collection" ||
00476                Key == "Objective-C GC Only" ||
00477                Key == "Objective-C Is Simulated" ||
00478                Key == "Objective-C Image Swift Version") {
00479       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
00480     } else if (Key == "Objective-C Image Info Section") {
00481       SectionVal = cast<MDString>(Val)->getString();
00482     } else if (Key == "Linker Options") {
00483       LinkerOptions = cast<MDNode>(Val);
00484     }
00485   }
00486 
00487   // Emit the linker options if present.
00488   if (LinkerOptions) {
00489     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00490       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00491       SmallVector<std::string, 4> StrOptions;
00492 
00493       // Convert to strings.
00494       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00495         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00496         StrOptions.push_back(MDOption->getString());
00497       }
00498 
00499       Streamer.EmitLinkerOptions(StrOptions);
00500     }
00501   }
00502 
00503   // The section is mandatory. If we don't have it, then we don't have GC info.
00504   if (SectionVal.empty()) return;
00505 
00506   StringRef Segment, Section;
00507   unsigned TAA = 0, StubSize = 0;
00508   bool TAAParsed;
00509   std::string ErrorCode =
00510     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00511                                           TAA, TAAParsed, StubSize);
00512   if (!ErrorCode.empty())
00513     // If invalid, report the error with report_fatal_error.
00514     report_fatal_error("Invalid section specifier '" + Section + "': " +
00515                        ErrorCode + ".");
00516 
00517   // Get the section.
00518   MCSectionMachO *S = getContext().getMachOSection(
00519       Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
00520   Streamer.SwitchSection(S);
00521   Streamer.EmitLabel(getContext().
00522                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00523   Streamer.EmitIntValue(VersionVal, 4);
00524   Streamer.EmitIntValue(ImageInfoFlags, 4);
00525   Streamer.AddBlankLine();
00526 }
00527 
00528 static void checkMachOComdat(const GlobalValue *GV) {
00529   const Comdat *C = GV->getComdat();
00530   if (!C)
00531     return;
00532 
00533   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
00534                      "' cannot be lowered.");
00535 }
00536 
00537 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
00538     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00539     const TargetMachine &TM) const {
00540   // Parse the section specifier and create it if valid.
00541   StringRef Segment, Section;
00542   unsigned TAA = 0, StubSize = 0;
00543   bool TAAParsed;
00544 
00545   checkMachOComdat(GV);
00546 
00547   std::string ErrorCode =
00548     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00549                                           TAA, TAAParsed, StubSize);
00550   if (!ErrorCode.empty()) {
00551     // If invalid, report the error with report_fatal_error.
00552     report_fatal_error("Global variable '" + GV->getName() +
00553                        "' has an invalid section specifier '" +
00554                        GV->getSection() + "': " + ErrorCode + ".");
00555   }
00556 
00557   // Get the section.
00558   MCSectionMachO *S =
00559       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00560 
00561   // If TAA wasn't set by ParseSectionSpecifier() above,
00562   // use the value returned by getMachOSection() as a default.
00563   if (!TAAParsed)
00564     TAA = S->getTypeAndAttributes();
00565 
00566   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00567   // If the user declared multiple globals with different section flags, we need
00568   // to reject it here.
00569   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00570     // If invalid, report the error with report_fatal_error.
00571     report_fatal_error("Global variable '" + GV->getName() +
00572                        "' section type or attributes does not match previous"
00573                        " section specifier");
00574   }
00575 
00576   return S;
00577 }
00578 
00579 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
00580     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00581     const TargetMachine &TM) const {
00582   checkMachOComdat(GV);
00583 
00584   // Handle thread local data.
00585   if (Kind.isThreadBSS()) return TLSBSSSection;
00586   if (Kind.isThreadData()) return TLSDataSection;
00587 
00588   if (Kind.isText())
00589     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00590 
00591   // If this is weak/linkonce, put this in a coalescable section, either in text
00592   // or data depending on if it is writable.
00593   if (GV->isWeakForLinker()) {
00594     if (Kind.isReadOnly())
00595       return ConstTextCoalSection;
00596     return DataCoalSection;
00597   }
00598 
00599   // FIXME: Alignment check should be handled by section classifier.
00600   if (Kind.isMergeable1ByteCString() &&
00601       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00602     return CStringSection;
00603 
00604   // Do not put 16-bit arrays in the UString section if they have an
00605   // externally visible label, this runs into issues with certain linker
00606   // versions.
00607   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00608       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00609     return UStringSection;
00610 
00611   // With MachO only variables whose corresponding symbol starts with 'l' or
00612   // 'L' can be merged, so we only try merging GVs with private linkage.
00613   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
00614     if (Kind.isMergeableConst4())
00615       return FourByteConstantSection;
00616     if (Kind.isMergeableConst8())
00617       return EightByteConstantSection;
00618     if (Kind.isMergeableConst16())
00619       return SixteenByteConstantSection;
00620   }
00621 
00622   // Otherwise, if it is readonly, but not something we can specially optimize,
00623   // just drop it in .const.
00624   if (Kind.isReadOnly())
00625     return ReadOnlySection;
00626 
00627   // If this is marked const, put it into a const section.  But if the dynamic
00628   // linker needs to write to it, put it in the data segment.
00629   if (Kind.isReadOnlyWithRel())
00630     return ConstDataSection;
00631 
00632   // Put zero initialized globals with strong external linkage in the
00633   // DATA, __common section with the .zerofill directive.
00634   if (Kind.isBSSExtern())
00635     return DataCommonSection;
00636 
00637   // Put zero initialized globals with local linkage in __DATA,__bss directive
00638   // with the .zerofill directive (aka .lcomm).
00639   if (Kind.isBSSLocal())
00640     return DataBSSSection;
00641 
00642   // Otherwise, just drop the variable in the normal data section.
00643   return DataSection;
00644 }
00645 
00646 MCSection *
00647 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
00648                                                      const Constant *C) const {
00649   // If this constant requires a relocation, we have to put it in the data
00650   // segment, not in the text segment.
00651   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00652     return ConstDataSection;
00653 
00654   if (Kind.isMergeableConst4())
00655     return FourByteConstantSection;
00656   if (Kind.isMergeableConst8())
00657     return EightByteConstantSection;
00658   if (Kind.isMergeableConst16())
00659     return SixteenByteConstantSection;
00660   return ReadOnlySection;  // .const
00661 }
00662 
00663 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
00664     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00665     const TargetMachine &TM, MachineModuleInfo *MMI,
00666     MCStreamer &Streamer) const {
00667   // The mach-o version of this method defaults to returning a stub reference.
00668 
00669   if (Encoding & DW_EH_PE_indirect) {
00670     MachineModuleInfoMachO &MachOMMI =
00671       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00672 
00673     MCSymbol *SSym =
00674         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00675 
00676     // Add information about the stub reference to MachOMMI so that the stub
00677     // gets emitted by the asmprinter.
00678     MachineModuleInfoImpl::StubValueTy &StubSym =
00679       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00680                                   MachOMMI.getGVStubEntry(SSym);
00681     if (!StubSym.getPointer()) {
00682       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00683       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00684     }
00685 
00686     return TargetLoweringObjectFile::
00687       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00688                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00689   }
00690 
00691   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
00692                                                            TM, MMI, Streamer);
00693 }
00694 
00695 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
00696     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00697     MachineModuleInfo *MMI) const {
00698   // The mach-o version of this method defaults to returning a stub reference.
00699   MachineModuleInfoMachO &MachOMMI =
00700     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00701 
00702   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00703 
00704   // Add information about the stub reference to MachOMMI so that the stub
00705   // gets emitted by the asmprinter.
00706   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00707   if (!StubSym.getPointer()) {
00708     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00709     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00710   }
00711 
00712   return SSym;
00713 }
00714 
00715 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
00716     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
00717     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
00718   // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
00719   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
00720   // through a non_lazy_ptr stub instead. One advantage is that it allows the
00721   // computation of deltas to final external symbols. Example:
00722   //
00723   //    _extgotequiv:
00724   //       .long   _extfoo
00725   //
00726   //    _delta:
00727   //       .long   _extgotequiv-_delta
00728   //
00729   // is transformed to:
00730   //
00731   //    _delta:
00732   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
00733   //
00734   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
00735   //    L_extfoo$non_lazy_ptr:
00736   //       .indirect_symbol        _extfoo
00737   //       .long   0
00738   //
00739   MachineModuleInfoMachO &MachOMMI =
00740     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00741   MCContext &Ctx = getContext();
00742 
00743   // The offset must consider the original displacement from the base symbol
00744   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
00745   Offset = -MV.getConstant();
00746   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
00747 
00748   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
00749   // non_lazy_ptr stubs.
00750   SmallString<128> Name;
00751   StringRef Suffix = "$non_lazy_ptr";
00752   Name += DL->getPrivateGlobalPrefix();
00753   Name += Sym->getName();
00754   Name += Suffix;
00755   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
00756 
00757   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
00758   if (!StubSym.getPointer())
00759     StubSym = MachineModuleInfoImpl::
00760       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
00761 
00762   const MCExpr *BSymExpr =
00763     MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
00764   const MCExpr *LHS =
00765     MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx);
00766 
00767   if (!Offset)
00768     return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx);
00769 
00770   const MCExpr *RHS =
00771     MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx);
00772   return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
00773 }
00774 
00775 //===----------------------------------------------------------------------===//
00776 //                                  COFF
00777 //===----------------------------------------------------------------------===//
00778 
00779 static unsigned
00780 getCOFFSectionFlags(SectionKind K) {
00781   unsigned Flags = 0;
00782 
00783   if (K.isMetadata())
00784     Flags |=
00785       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00786   else if (K.isText())
00787     Flags |=
00788       COFF::IMAGE_SCN_MEM_EXECUTE |
00789       COFF::IMAGE_SCN_MEM_READ |
00790       COFF::IMAGE_SCN_CNT_CODE;
00791   else if (K.isBSS())
00792     Flags |=
00793       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00794       COFF::IMAGE_SCN_MEM_READ |
00795       COFF::IMAGE_SCN_MEM_WRITE;
00796   else if (K.isThreadLocal())
00797     Flags |=
00798       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00799       COFF::IMAGE_SCN_MEM_READ |
00800       COFF::IMAGE_SCN_MEM_WRITE;
00801   else if (K.isReadOnly() || K.isReadOnlyWithRel())
00802     Flags |=
00803       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00804       COFF::IMAGE_SCN_MEM_READ;
00805   else if (K.isWriteable())
00806     Flags |=
00807       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00808       COFF::IMAGE_SCN_MEM_READ |
00809       COFF::IMAGE_SCN_MEM_WRITE;
00810 
00811   return Flags;
00812 }
00813 
00814 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
00815   const Comdat *C = GV->getComdat();
00816   assert(C && "expected GV to have a Comdat!");
00817 
00818   StringRef ComdatGVName = C->getName();
00819   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
00820   if (!ComdatGV)
00821     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00822                        "' does not exist.");
00823 
00824   if (ComdatGV->getComdat() != C)
00825     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00826                        "' is not a key for its COMDAT.");
00827 
00828   return ComdatGV;
00829 }
00830 
00831 static int getSelectionForCOFF(const GlobalValue *GV) {
00832   if (const Comdat *C = GV->getComdat()) {
00833     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
00834     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
00835       ComdatKey = GA->getBaseObject();
00836     if (ComdatKey == GV) {
00837       switch (C->getSelectionKind()) {
00838       case Comdat::Any:
00839         return COFF::IMAGE_COMDAT_SELECT_ANY;
00840       case Comdat::ExactMatch:
00841         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
00842       case Comdat::Largest:
00843         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
00844       case Comdat::NoDuplicates:
00845         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00846       case Comdat::SameSize:
00847         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
00848       }
00849     } else {
00850       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
00851     }
00852   } else if (GV->isWeakForLinker()) {
00853     return COFF::IMAGE_COMDAT_SELECT_ANY;
00854   }
00855   return 0;
00856 }
00857 
00858 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
00859     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00860     const TargetMachine &TM) const {
00861   int Selection = 0;
00862   unsigned Characteristics = getCOFFSectionFlags(Kind);
00863   StringRef Name = GV->getSection();
00864   StringRef COMDATSymName = "";
00865   if (GV->hasComdat()) {
00866     Selection = getSelectionForCOFF(GV);
00867     const GlobalValue *ComdatGV;
00868     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
00869       ComdatGV = getComdatGVForCOFF(GV);
00870     else
00871       ComdatGV = GV;
00872 
00873     if (!ComdatGV->hasPrivateLinkage()) {
00874       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00875       COMDATSymName = Sym->getName();
00876       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00877     } else {
00878       Selection = 0;
00879     }
00880   }
00881   return getContext().getCOFFSection(Name,
00882                                      Characteristics,
00883                                      Kind,
00884                                      COMDATSymName,
00885                                      Selection);
00886 }
00887 
00888 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
00889   if (Kind.isText())
00890     return ".text";
00891   if (Kind.isBSS())
00892     return ".bss";
00893   if (Kind.isThreadLocal())
00894     return ".tls$";
00895   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
00896     return ".rdata";
00897   return ".data";
00898 }
00899 
00900 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
00901     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00902     const TargetMachine &TM) const {
00903   // If we have -ffunction-sections then we should emit the global value to a
00904   // uniqued section specifically for it.
00905   bool EmitUniquedSection;
00906   if (Kind.isText())
00907     EmitUniquedSection = TM.getFunctionSections();
00908   else
00909     EmitUniquedSection = TM.getDataSections();
00910 
00911   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
00912     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00913     unsigned Characteristics = getCOFFSectionFlags(Kind);
00914 
00915     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00916     int Selection = getSelectionForCOFF(GV);
00917     if (!Selection)
00918       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00919     const GlobalValue *ComdatGV;
00920     if (GV->hasComdat())
00921       ComdatGV = getComdatGVForCOFF(GV);
00922     else
00923       ComdatGV = GV;
00924 
00925     if (!ComdatGV->hasPrivateLinkage()) {
00926       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00927       StringRef COMDATSymName = Sym->getName();
00928       return getContext().getCOFFSection(Name, Characteristics, Kind,
00929                                          COMDATSymName, Selection);
00930     } else {
00931       SmallString<256> TmpData;
00932       getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
00933       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
00934                                          Selection);
00935     }
00936   }
00937 
00938   if (Kind.isText())
00939     return TextSection;
00940 
00941   if (Kind.isThreadLocal())
00942     return TLSDataSection;
00943 
00944   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
00945     return ReadOnlySection;
00946 
00947   // Note: we claim that common symbols are put in BSSSection, but they are
00948   // really emitted with the magic .comm directive, which creates a symbol table
00949   // entry but not a section.
00950   if (Kind.isBSS() || Kind.isCommon())
00951     return BSSSection;
00952 
00953   return DataSection;
00954 }
00955 
00956 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
00957     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
00958     bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
00959   if (GV->hasPrivateLinkage() &&
00960       ((isa<Function>(GV) && TM.getFunctionSections()) ||
00961        (isa<GlobalVariable>(GV) && TM.getDataSections())))
00962     CannotUsePrivateLabel = true;
00963 
00964   Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
00965 }
00966 
00967 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
00968     const Function &F, Mangler &Mang, const TargetMachine &TM) const {
00969   // If the function can be removed, produce a unique section so that
00970   // the table doesn't prevent the removal.
00971   const Comdat *C = F.getComdat();
00972   bool EmitUniqueSection = TM.getFunctionSections() || C;
00973   if (!EmitUniqueSection)
00974     return ReadOnlySection;
00975 
00976   // FIXME: we should produce a symbol for F instead.
00977   if (F.hasPrivateLinkage())
00978     return ReadOnlySection;
00979 
00980   MCSymbol *Sym = TM.getSymbol(&F, Mang);
00981   StringRef COMDATSymName = Sym->getName();
00982 
00983   SectionKind Kind = SectionKind::getReadOnly();
00984   const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00985   unsigned Characteristics = getCOFFSectionFlags(Kind);
00986   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00987 
00988   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
00989                                      COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
00990 }
00991 
00992 StringRef TargetLoweringObjectFileCOFF::
00993 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00994   const char *LibCmd = "/DEFAULTLIB:";
00995   if (LinkerOption.startswith(LibCmd))
00996     return LinkerOption.substr(strlen(LibCmd));
00997   return StringRef();
00998 }
00999 
01000 void TargetLoweringObjectFileCOFF::
01001 emitModuleFlags(MCStreamer &Streamer,
01002                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
01003                 Mangler &Mang, const TargetMachine &TM) const {
01004   MDNode *LinkerOptions = nullptr;
01005 
01006   // Look for the "Linker Options" flag, since it's the only one we support.
01007   for (ArrayRef<Module::ModuleFlagEntry>::iterator
01008        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
01009     const Module::ModuleFlagEntry &MFE = *i;
01010     StringRef Key = MFE.Key->getString();
01011     Metadata *Val = MFE.Val;
01012     if (Key == "Linker Options") {
01013       LinkerOptions = cast<MDNode>(Val);
01014       break;
01015     }
01016   }
01017   if (!LinkerOptions)
01018     return;
01019 
01020   // Emit the linker options to the linker .drectve section.  According to the
01021   // spec, this section is a space-separated string containing flags for linker.
01022   MCSection *Sec = getDrectveSection();
01023   Streamer.SwitchSection(Sec);
01024   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
01025     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
01026     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
01027       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
01028       // Lead with a space for consistency with our dllexport implementation.
01029       std::string Directive(" ");
01030       Directive.append(MDOption->getString());
01031       Streamer.EmitBytes(Directive);
01032     }
01033   }
01034 }
01035 
01036 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
01037     unsigned Priority, const MCSymbol *KeySym) const {
01038   return getContext().getAssociativeCOFFSection(
01039       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
01040 }
01041 
01042 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
01043     unsigned Priority, const MCSymbol *KeySym) const {
01044   return getContext().getAssociativeCOFFSection(
01045       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
01046 }