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