LLVM API Documentation

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/Support/Dwarf.h"
00035 #include "llvm/Support/ELF.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include "llvm/Target/TargetLowering.h"
00039 #include "llvm/Target/TargetMachine.h"
00040 #include "llvm/Target/TargetSubtargetInfo.h"
00041 using namespace llvm;
00042 using namespace dwarf;
00043 
00044 //===----------------------------------------------------------------------===//
00045 //                                  ELF
00046 //===----------------------------------------------------------------------===//
00047 
00048 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
00049     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00050     MachineModuleInfo *MMI) const {
00051   unsigned Encoding = getPersonalityEncoding();
00052   if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
00053     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
00054                                           TM.getSymbol(GV, Mang)->getName());
00055   if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
00056     return TM.getSymbol(GV, Mang);
00057   report_fatal_error("We do not support this DWARF encoding yet!");
00058 }
00059 
00060 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
00061                                                        const TargetMachine &TM,
00062                                                        const MCSymbol *Sym) const {
00063   SmallString<64> NameData("DW.ref.");
00064   NameData += Sym->getName();
00065   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
00066   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
00067   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
00068   StringRef Prefix = ".data.";
00069   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
00070   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
00071   const MCSection *Sec = getContext().getELFSection(NameData,
00072                                                     ELF::SHT_PROGBITS,
00073                                                     Flags,
00074                                                     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 
00168 static unsigned
00169 getELFSectionFlags(SectionKind K) {
00170   unsigned Flags = 0;
00171 
00172   if (!K.isMetadata())
00173     Flags |= ELF::SHF_ALLOC;
00174 
00175   if (K.isText())
00176     Flags |= ELF::SHF_EXECINSTR;
00177 
00178   if (K.isWriteable())
00179     Flags |= ELF::SHF_WRITE;
00180 
00181   if (K.isThreadLocal())
00182     Flags |= ELF::SHF_TLS;
00183 
00184   if (K.isMergeableCString() || K.isMergeableConst())
00185     Flags |= ELF::SHF_MERGE;
00186 
00187   if (K.isMergeableCString())
00188     Flags |= ELF::SHF_STRINGS;
00189 
00190   return Flags;
00191 }
00192 
00193 static const Comdat *getELFComdat(const GlobalValue *GV) {
00194   const Comdat *C = GV->getComdat();
00195   if (!C)
00196     return nullptr;
00197 
00198   if (C->getSelectionKind() != Comdat::Any)
00199     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
00200                        C->getName() + "' cannot be lowered.");
00201 
00202   return C;
00203 }
00204 
00205 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
00206     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00207     const TargetMachine &TM) const {
00208   StringRef SectionName = GV->getSection();
00209 
00210   // Infer section flags from the section name if we can.
00211   Kind = getELFKindForNamedSection(SectionName, Kind);
00212 
00213   StringRef Group = "";
00214   unsigned Flags = getELFSectionFlags(Kind);
00215   if (const Comdat *C = getELFComdat(GV)) {
00216     Group = C->getName();
00217     Flags |= ELF::SHF_GROUP;
00218   }
00219   return getContext().getELFSection(SectionName,
00220                                     getELFSectionType(SectionName, Kind), Flags,
00221                                     /*EntrySize=*/0, Group);
00222 }
00223 
00224 /// getSectionPrefixForGlobal - Return the section prefix name used by options
00225 /// FunctionsSections and DataSections.
00226 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
00227   if (Kind.isText())                 return ".text.";
00228   if (Kind.isReadOnly())             return ".rodata.";
00229   if (Kind.isBSS())                  return ".bss.";
00230 
00231   if (Kind.isThreadData())           return ".tdata.";
00232   if (Kind.isThreadBSS())            return ".tbss.";
00233 
00234   if (Kind.isDataNoRel())            return ".data.";
00235   if (Kind.isDataRelLocal())         return ".data.rel.local.";
00236   if (Kind.isDataRel())              return ".data.rel.";
00237   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
00238 
00239   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00240   return ".data.rel.ro.";
00241 }
00242 
00243 const MCSection *TargetLoweringObjectFileELF::
00244 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00245                        Mangler &Mang, const TargetMachine &TM) const {
00246   unsigned Flags = getELFSectionFlags(Kind);
00247 
00248   // If we have -ffunction-section or -fdata-section then we should emit the
00249   // global value to a uniqued section specifically for it.
00250   bool EmitUniquedSection = false;
00251   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
00252     if (Kind.isText())
00253       EmitUniquedSection = TM.getFunctionSections();
00254     else
00255       EmitUniquedSection = TM.getDataSections();
00256   }
00257 
00258   if (EmitUniquedSection || GV->hasComdat()) {
00259     StringRef Prefix = getSectionPrefixForGlobal(Kind);
00260 
00261     SmallString<128> Name(Prefix);
00262     TM.getNameWithPrefix(Name, GV, Mang, true);
00263 
00264     StringRef Group = "";
00265     if (const Comdat *C = getELFComdat(GV)) {
00266       Flags |= ELF::SHF_GROUP;
00267       Group = C->getName();
00268     }
00269 
00270     return getContext().getELFSection(
00271         Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
00272   }
00273 
00274   if (Kind.isText()) return TextSection;
00275 
00276   if (Kind.isMergeableCString()) {
00277 
00278     // We also need alignment here.
00279     // FIXME: this is getting the alignment of the character, not the
00280     // alignment of the global!
00281     unsigned Align =
00282         TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
00283 
00284     unsigned EntrySize = 1;
00285     if (Kind.isMergeable2ByteCString())
00286       EntrySize = 2;
00287     else if (Kind.isMergeable4ByteCString())
00288       EntrySize = 4;
00289     else
00290       assert(Kind.isMergeable1ByteCString() && "unknown string width");
00291 
00292     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
00293     std::string Name = SizeSpec + utostr(Align);
00294     return getContext().getELFSection(
00295         Name, ELF::SHT_PROGBITS,
00296         ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
00297   }
00298 
00299   if (Kind.isMergeableConst()) {
00300     if (Kind.isMergeableConst4() && MergeableConst4Section)
00301       return MergeableConst4Section;
00302     if (Kind.isMergeableConst8() && MergeableConst8Section)
00303       return MergeableConst8Section;
00304     if (Kind.isMergeableConst16() && MergeableConst16Section)
00305       return MergeableConst16Section;
00306     return ReadOnlySection;  // .const
00307   }
00308 
00309   if (Kind.isReadOnly())             return ReadOnlySection;
00310 
00311   if (Kind.isThreadData())           return TLSDataSection;
00312   if (Kind.isThreadBSS())            return TLSBSSSection;
00313 
00314   // Note: we claim that common symbols are put in BSSSection, but they are
00315   // really emitted with the magic .comm directive, which creates a symbol table
00316   // entry but not a section.
00317   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
00318 
00319   if (Kind.isDataNoRel())            return DataSection;
00320   if (Kind.isDataRelLocal())         return DataRelLocalSection;
00321   if (Kind.isDataRel())              return DataRelSection;
00322   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00323 
00324   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00325   return DataRelROSection;
00326 }
00327 
00328 /// getSectionForConstant - Given a mergeable constant with the
00329 /// specified size and relocation information, return a section that it
00330 /// should be placed in.
00331 const MCSection *
00332 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
00333                                                    const Constant *C) const {
00334   if (Kind.isMergeableConst4() && MergeableConst4Section)
00335     return MergeableConst4Section;
00336   if (Kind.isMergeableConst8() && MergeableConst8Section)
00337     return MergeableConst8Section;
00338   if (Kind.isMergeableConst16() && MergeableConst16Section)
00339     return MergeableConst16Section;
00340   if (Kind.isReadOnly())
00341     return ReadOnlySection;
00342 
00343   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00344   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00345   return DataRelROSection;
00346 }
00347 
00348 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
00349                                                     bool UseInitArray,
00350                                                     bool IsCtor,
00351                                                     unsigned Priority,
00352                                                     const MCSymbol *KeySym) {
00353   std::string Name;
00354   unsigned Type;
00355   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
00356   StringRef COMDAT = KeySym ? KeySym->getName() : "";
00357 
00358   if (KeySym)
00359     Flags |= ELF::SHF_GROUP;
00360 
00361   if (UseInitArray) {
00362     if (IsCtor) {
00363       Type = ELF::SHT_INIT_ARRAY;
00364       Name = ".init_array";
00365     } else {
00366       Type = ELF::SHT_FINI_ARRAY;
00367       Name = ".fini_array";
00368     }
00369     if (Priority != 65535) {
00370       Name += '.';
00371       Name += utostr(Priority);
00372     }
00373   } else {
00374     // The default scheme is .ctor / .dtor, so we have to invert the priority
00375     // numbering.
00376     if (IsCtor)
00377       Name = ".ctors";
00378     else
00379       Name = ".dtors";
00380     if (Priority != 65535) {
00381       Name += '.';
00382       Name += utostr(65535 - Priority);
00383     }
00384     Type = ELF::SHT_PROGBITS;
00385   }
00386 
00387   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
00388 }
00389 
00390 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
00391     unsigned Priority, const MCSymbol *KeySym) const {
00392   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
00393                                   KeySym);
00394 }
00395 
00396 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
00397     unsigned Priority, const MCSymbol *KeySym) const {
00398   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
00399                                   KeySym);
00400 }
00401 
00402 void
00403 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00404   UseInitArray = UseInitArray_;
00405   if (!UseInitArray)
00406     return;
00407 
00408   StaticCtorSection = getContext().getELFSection(
00409       ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
00410   StaticDtorSection = getContext().getELFSection(
00411       ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
00412 }
00413 
00414 //===----------------------------------------------------------------------===//
00415 //                                 MachO
00416 //===----------------------------------------------------------------------===//
00417 
00418 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
00419 /// option string. Returns StringRef() if the option does not specify a library.
00420 StringRef TargetLoweringObjectFileMachO::
00421 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00422   const char *LibCmd = "-l";
00423   if (LinkerOption.startswith(LibCmd))
00424     return LinkerOption.substr(strlen(LibCmd));
00425   return StringRef();
00426 }
00427 
00428 /// emitModuleFlags - Perform code emission for module flags.
00429 void TargetLoweringObjectFileMachO::
00430 emitModuleFlags(MCStreamer &Streamer,
00431                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00432                 Mangler &Mang, const TargetMachine &TM) const {
00433   unsigned VersionVal = 0;
00434   unsigned ImageInfoFlags = 0;
00435   MDNode *LinkerOptions = nullptr;
00436   StringRef SectionVal;
00437 
00438   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00439          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00440     const Module::ModuleFlagEntry &MFE = *i;
00441 
00442     // Ignore flags with 'Require' behavior.
00443     if (MFE.Behavior == Module::Require)
00444       continue;
00445 
00446     StringRef Key = MFE.Key->getString();
00447     Metadata *Val = MFE.Val;
00448 
00449     if (Key == "Objective-C Image Info Version") {
00450       VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
00451     } else if (Key == "Objective-C Garbage Collection" ||
00452                Key == "Objective-C GC Only" ||
00453                Key == "Objective-C Is Simulated" ||
00454                Key == "Objective-C Image Swift Version") {
00455       ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
00456     } else if (Key == "Objective-C Image Info Section") {
00457       SectionVal = cast<MDString>(Val)->getString();
00458     } else if (Key == "Linker Options") {
00459       LinkerOptions = cast<MDNode>(Val);
00460     }
00461   }
00462 
00463   // Emit the linker options if present.
00464   if (LinkerOptions) {
00465     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00466       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00467       SmallVector<std::string, 4> StrOptions;
00468 
00469       // Convert to strings.
00470       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00471         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00472         StrOptions.push_back(MDOption->getString());
00473       }
00474 
00475       Streamer.EmitLinkerOptions(StrOptions);
00476     }
00477   }
00478 
00479   // The section is mandatory. If we don't have it, then we don't have GC info.
00480   if (SectionVal.empty()) return;
00481 
00482   StringRef Segment, Section;
00483   unsigned TAA = 0, StubSize = 0;
00484   bool TAAParsed;
00485   std::string ErrorCode =
00486     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00487                                           TAA, TAAParsed, StubSize);
00488   if (!ErrorCode.empty())
00489     // If invalid, report the error with report_fatal_error.
00490     report_fatal_error("Invalid section specifier '" + Section + "': " +
00491                        ErrorCode + ".");
00492 
00493   // Get the section.
00494   const MCSectionMachO *S =
00495     getContext().getMachOSection(Segment, Section, TAA, StubSize,
00496                                  SectionKind::getDataNoRel());
00497   Streamer.SwitchSection(S);
00498   Streamer.EmitLabel(getContext().
00499                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00500   Streamer.EmitIntValue(VersionVal, 4);
00501   Streamer.EmitIntValue(ImageInfoFlags, 4);
00502   Streamer.AddBlankLine();
00503 }
00504 
00505 static void checkMachOComdat(const GlobalValue *GV) {
00506   const Comdat *C = GV->getComdat();
00507   if (!C)
00508     return;
00509 
00510   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
00511                      "' cannot be lowered.");
00512 }
00513 
00514 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
00515     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00516     const TargetMachine &TM) const {
00517   // Parse the section specifier and create it if valid.
00518   StringRef Segment, Section;
00519   unsigned TAA = 0, StubSize = 0;
00520   bool TAAParsed;
00521 
00522   checkMachOComdat(GV);
00523 
00524   std::string ErrorCode =
00525     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00526                                           TAA, TAAParsed, StubSize);
00527   if (!ErrorCode.empty()) {
00528     // If invalid, report the error with report_fatal_error.
00529     report_fatal_error("Global variable '" + GV->getName() +
00530                        "' has an invalid section specifier '" +
00531                        GV->getSection() + "': " + ErrorCode + ".");
00532   }
00533 
00534   // Get the section.
00535   const MCSectionMachO *S =
00536     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00537 
00538   // If TAA wasn't set by ParseSectionSpecifier() above,
00539   // use the value returned by getMachOSection() as a default.
00540   if (!TAAParsed)
00541     TAA = S->getTypeAndAttributes();
00542 
00543   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00544   // If the user declared multiple globals with different section flags, we need
00545   // to reject it here.
00546   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00547     // If invalid, report the error with report_fatal_error.
00548     report_fatal_error("Global variable '" + GV->getName() +
00549                        "' section type or attributes does not match previous"
00550                        " section specifier");
00551   }
00552 
00553   return S;
00554 }
00555 
00556 const MCSection *TargetLoweringObjectFileMachO::
00557 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00558                        Mangler &Mang, const TargetMachine &TM) const {
00559   checkMachOComdat(GV);
00560 
00561   // Handle thread local data.
00562   if (Kind.isThreadBSS()) return TLSBSSSection;
00563   if (Kind.isThreadData()) return TLSDataSection;
00564 
00565   if (Kind.isText())
00566     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00567 
00568   // If this is weak/linkonce, put this in a coalescable section, either in text
00569   // or data depending on if it is writable.
00570   if (GV->isWeakForLinker()) {
00571     if (Kind.isReadOnly())
00572       return ConstTextCoalSection;
00573     return DataCoalSection;
00574   }
00575 
00576   // FIXME: Alignment check should be handled by section classifier.
00577   if (Kind.isMergeable1ByteCString() &&
00578       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00579     return CStringSection;
00580 
00581   // Do not put 16-bit arrays in the UString section if they have an
00582   // externally visible label, this runs into issues with certain linker
00583   // versions.
00584   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00585       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00586     return UStringSection;
00587 
00588   // With MachO only variables whose corresponding symbol starts with 'l' or
00589   // 'L' can be merged, so we only try merging GVs with private linkage.
00590   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
00591     if (Kind.isMergeableConst4())
00592       return FourByteConstantSection;
00593     if (Kind.isMergeableConst8())
00594       return EightByteConstantSection;
00595     if (Kind.isMergeableConst16())
00596       return SixteenByteConstantSection;
00597   }
00598 
00599   // Otherwise, if it is readonly, but not something we can specially optimize,
00600   // just drop it in .const.
00601   if (Kind.isReadOnly())
00602     return ReadOnlySection;
00603 
00604   // If this is marked const, put it into a const section.  But if the dynamic
00605   // linker needs to write to it, put it in the data segment.
00606   if (Kind.isReadOnlyWithRel())
00607     return ConstDataSection;
00608 
00609   // Put zero initialized globals with strong external linkage in the
00610   // DATA, __common section with the .zerofill directive.
00611   if (Kind.isBSSExtern())
00612     return DataCommonSection;
00613 
00614   // Put zero initialized globals with local linkage in __DATA,__bss directive
00615   // with the .zerofill directive (aka .lcomm).
00616   if (Kind.isBSSLocal())
00617     return DataBSSSection;
00618 
00619   // Otherwise, just drop the variable in the normal data section.
00620   return DataSection;
00621 }
00622 
00623 const MCSection *
00624 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
00625                                                      const Constant *C) const {
00626   // If this constant requires a relocation, we have to put it in the data
00627   // segment, not in the text segment.
00628   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00629     return ConstDataSection;
00630 
00631   if (Kind.isMergeableConst4())
00632     return FourByteConstantSection;
00633   if (Kind.isMergeableConst8())
00634     return EightByteConstantSection;
00635   if (Kind.isMergeableConst16())
00636     return SixteenByteConstantSection;
00637   return ReadOnlySection;  // .const
00638 }
00639 
00640 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
00641     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00642     const TargetMachine &TM, MachineModuleInfo *MMI,
00643     MCStreamer &Streamer) const {
00644   // The mach-o version of this method defaults to returning a stub reference.
00645 
00646   if (Encoding & DW_EH_PE_indirect) {
00647     MachineModuleInfoMachO &MachOMMI =
00648       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00649 
00650     MCSymbol *SSym =
00651         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00652 
00653     // Add information about the stub reference to MachOMMI so that the stub
00654     // gets emitted by the asmprinter.
00655     MachineModuleInfoImpl::StubValueTy &StubSym =
00656       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00657                                   MachOMMI.getGVStubEntry(SSym);
00658     if (!StubSym.getPointer()) {
00659       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00660       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00661     }
00662 
00663     return TargetLoweringObjectFile::
00664       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00665                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00666   }
00667 
00668   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
00669                                                            TM, MMI, Streamer);
00670 }
00671 
00672 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
00673     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00674     MachineModuleInfo *MMI) const {
00675   // The mach-o version of this method defaults to returning a stub reference.
00676   MachineModuleInfoMachO &MachOMMI =
00677     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00678 
00679   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00680 
00681   // Add information about the stub reference to MachOMMI so that the stub
00682   // gets emitted by the asmprinter.
00683   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00684   if (!StubSym.getPointer()) {
00685     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00686     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00687   }
00688 
00689   return SSym;
00690 }
00691 
00692 //===----------------------------------------------------------------------===//
00693 //                                  COFF
00694 //===----------------------------------------------------------------------===//
00695 
00696 static unsigned
00697 getCOFFSectionFlags(SectionKind K) {
00698   unsigned Flags = 0;
00699 
00700   if (K.isMetadata())
00701     Flags |=
00702       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00703   else if (K.isText())
00704     Flags |=
00705       COFF::IMAGE_SCN_MEM_EXECUTE |
00706       COFF::IMAGE_SCN_MEM_READ |
00707       COFF::IMAGE_SCN_CNT_CODE;
00708   else if (K.isBSS())
00709     Flags |=
00710       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00711       COFF::IMAGE_SCN_MEM_READ |
00712       COFF::IMAGE_SCN_MEM_WRITE;
00713   else if (K.isThreadLocal())
00714     Flags |=
00715       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00716       COFF::IMAGE_SCN_MEM_READ |
00717       COFF::IMAGE_SCN_MEM_WRITE;
00718   else if (K.isReadOnly() || K.isReadOnlyWithRel())
00719     Flags |=
00720       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00721       COFF::IMAGE_SCN_MEM_READ;
00722   else if (K.isWriteable())
00723     Flags |=
00724       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00725       COFF::IMAGE_SCN_MEM_READ |
00726       COFF::IMAGE_SCN_MEM_WRITE;
00727 
00728   return Flags;
00729 }
00730 
00731 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
00732   const Comdat *C = GV->getComdat();
00733   assert(C && "expected GV to have a Comdat!");
00734 
00735   StringRef ComdatGVName = C->getName();
00736   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
00737   if (!ComdatGV)
00738     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00739                        "' does not exist.");
00740 
00741   if (ComdatGV->getComdat() != C)
00742     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00743                        "' is not a key for its COMDAT.");
00744 
00745   return ComdatGV;
00746 }
00747 
00748 static int getSelectionForCOFF(const GlobalValue *GV) {
00749   if (const Comdat *C = GV->getComdat()) {
00750     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
00751     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
00752       ComdatKey = GA->getBaseObject();
00753     if (ComdatKey == GV) {
00754       switch (C->getSelectionKind()) {
00755       case Comdat::Any:
00756         return COFF::IMAGE_COMDAT_SELECT_ANY;
00757       case Comdat::ExactMatch:
00758         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
00759       case Comdat::Largest:
00760         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
00761       case Comdat::NoDuplicates:
00762         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00763       case Comdat::SameSize:
00764         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
00765       }
00766     } else {
00767       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
00768     }
00769   } else if (GV->isWeakForLinker()) {
00770     return COFF::IMAGE_COMDAT_SELECT_ANY;
00771   }
00772   return 0;
00773 }
00774 
00775 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
00776     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00777     const TargetMachine &TM) const {
00778   int Selection = 0;
00779   unsigned Characteristics = getCOFFSectionFlags(Kind);
00780   StringRef Name = GV->getSection();
00781   StringRef COMDATSymName = "";
00782   if (GV->hasComdat()) {
00783     Selection = getSelectionForCOFF(GV);
00784     const GlobalValue *ComdatGV;
00785     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
00786       ComdatGV = getComdatGVForCOFF(GV);
00787     else
00788       ComdatGV = GV;
00789 
00790     if (!ComdatGV->hasPrivateLinkage()) {
00791       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00792       COMDATSymName = Sym->getName();
00793       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00794     } else {
00795       Selection = 0;
00796     }
00797   }
00798   return getContext().getCOFFSection(Name,
00799                                      Characteristics,
00800                                      Kind,
00801                                      COMDATSymName,
00802                                      Selection);
00803 }
00804 
00805 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
00806   if (Kind.isText())
00807     return ".text";
00808   if (Kind.isBSS())
00809     return ".bss";
00810   if (Kind.isThreadLocal())
00811     return ".tls$";
00812   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
00813     return ".rdata";
00814   return ".data";
00815 }
00816 
00817 
00818 const MCSection *TargetLoweringObjectFileCOFF::
00819 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00820                        Mangler &Mang, const TargetMachine &TM) const {
00821   // If we have -ffunction-sections then we should emit the global value to a
00822   // uniqued section specifically for it.
00823   bool EmitUniquedSection;
00824   if (Kind.isText())
00825     EmitUniquedSection = TM.getFunctionSections();
00826   else
00827     EmitUniquedSection = TM.getDataSections();
00828 
00829   if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
00830     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00831     unsigned Characteristics = getCOFFSectionFlags(Kind);
00832 
00833     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00834     int Selection = getSelectionForCOFF(GV);
00835     if (!Selection)
00836       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00837     const GlobalValue *ComdatGV;
00838     if (GV->hasComdat())
00839       ComdatGV = getComdatGVForCOFF(GV);
00840     else
00841       ComdatGV = GV;
00842 
00843     if (!ComdatGV->hasPrivateLinkage()) {
00844       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00845       StringRef COMDATSymName = Sym->getName();
00846       return getContext().getCOFFSection(Name, Characteristics, Kind,
00847                                          COMDATSymName, Selection);
00848     }
00849   }
00850 
00851   if (Kind.isText())
00852     return TextSection;
00853 
00854   if (Kind.isThreadLocal())
00855     return TLSDataSection;
00856 
00857   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
00858     return ReadOnlySection;
00859 
00860   // Note: we claim that common symbols are put in BSSSection, but they are
00861   // really emitted with the magic .comm directive, which creates a symbol table
00862   // entry but not a section.
00863   if (Kind.isBSS() || Kind.isCommon())
00864     return BSSSection;
00865 
00866   return DataSection;
00867 }
00868 
00869 StringRef TargetLoweringObjectFileCOFF::
00870 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00871   const char *LibCmd = "/DEFAULTLIB:";
00872   if (LinkerOption.startswith(LibCmd))
00873     return LinkerOption.substr(strlen(LibCmd));
00874   return StringRef();
00875 }
00876 
00877 void TargetLoweringObjectFileCOFF::
00878 emitModuleFlags(MCStreamer &Streamer,
00879                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00880                 Mangler &Mang, const TargetMachine &TM) const {
00881   MDNode *LinkerOptions = nullptr;
00882 
00883   // Look for the "Linker Options" flag, since it's the only one we support.
00884   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00885        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00886     const Module::ModuleFlagEntry &MFE = *i;
00887     StringRef Key = MFE.Key->getString();
00888     Metadata *Val = MFE.Val;
00889     if (Key == "Linker Options") {
00890       LinkerOptions = cast<MDNode>(Val);
00891       break;
00892     }
00893   }
00894   if (!LinkerOptions)
00895     return;
00896 
00897   // Emit the linker options to the linker .drectve section.  According to the
00898   // spec, this section is a space-separated string containing flags for linker.
00899   const MCSection *Sec = getDrectveSection();
00900   Streamer.SwitchSection(Sec);
00901   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00902     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00903     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00904       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00905       StringRef Op = MDOption->getString();
00906       // Lead with a space for consistency with our dllexport implementation.
00907       std::string Escaped(" ");
00908       if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
00909         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
00910         // how to escape quotes, but it probably uses this algorithm:
00911         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
00912         // FIXME: Reuse escaping code from Support/Windows/Program.inc
00913         Escaped.push_back('\"');
00914         Escaped.append(Op);
00915         Escaped.push_back('\"');
00916       } else {
00917         Escaped.append(Op);
00918       }
00919       Streamer.EmitBytes(Escaped);
00920     }
00921   }
00922 }
00923 
00924 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
00925     unsigned Priority, const MCSymbol *KeySym) const {
00926   return getContext().getAssociativeCOFFSection(
00927       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
00928 }
00929 
00930 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
00931     unsigned Priority, const MCSymbol *KeySym) const {
00932   return getContext().getAssociativeCOFFSection(
00933       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
00934 }