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