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