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 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
00362                                                     bool UseInitArray,
00363                                                     bool IsCtor,
00364                                                     unsigned Priority,
00365                                                     const MCSymbol *KeySym) {
00366   std::string Name;
00367   unsigned Type;
00368   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
00369   SectionKind Kind = SectionKind::getDataRel();
00370   StringRef COMDAT = KeySym ? KeySym->getName() : "";
00371 
00372   if (KeySym)
00373     Flags |= ELF::SHF_GROUP;
00374 
00375   if (UseInitArray) {
00376     if (IsCtor) {
00377       Type = ELF::SHT_INIT_ARRAY;
00378       Name = ".init_array";
00379     } else {
00380       Type = ELF::SHT_FINI_ARRAY;
00381       Name = ".fini_array";
00382     }
00383     if (Priority != 65535) {
00384       Name += '.';
00385       Name += utostr(Priority);
00386     }
00387   } else {
00388     // The default scheme is .ctor / .dtor, so we have to invert the priority
00389     // numbering.
00390     if (IsCtor)
00391       Name = ".ctors";
00392     else
00393       Name = ".dtors";
00394     if (Priority != 65535) {
00395       Name += '.';
00396       Name += utostr(65535 - Priority);
00397     }
00398     Type = ELF::SHT_PROGBITS;
00399   }
00400 
00401   return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
00402 }
00403 
00404 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
00405     unsigned Priority, const MCSymbol *KeySym) const {
00406   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
00407                                   KeySym);
00408 }
00409 
00410 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
00411     unsigned Priority, const MCSymbol *KeySym) const {
00412   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
00413                                   KeySym);
00414 }
00415 
00416 void
00417 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00418   UseInitArray = UseInitArray_;
00419   if (!UseInitArray)
00420     return;
00421 
00422   StaticCtorSection =
00423     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
00424                                ELF::SHF_WRITE |
00425                                ELF::SHF_ALLOC,
00426                                SectionKind::getDataRel());
00427   StaticDtorSection =
00428     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
00429                                ELF::SHF_WRITE |
00430                                ELF::SHF_ALLOC,
00431                                SectionKind::getDataRel());
00432 }
00433 
00434 //===----------------------------------------------------------------------===//
00435 //                                 MachO
00436 //===----------------------------------------------------------------------===//
00437 
00438 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
00439 /// option string. Returns StringRef() if the option does not specify a library.
00440 StringRef TargetLoweringObjectFileMachO::
00441 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00442   const char *LibCmd = "-l";
00443   if (LinkerOption.startswith(LibCmd))
00444     return LinkerOption.substr(strlen(LibCmd));
00445   return StringRef();
00446 }
00447 
00448 /// emitModuleFlags - Perform code emission for module flags.
00449 void TargetLoweringObjectFileMachO::
00450 emitModuleFlags(MCStreamer &Streamer,
00451                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00452                 Mangler &Mang, const TargetMachine &TM) const {
00453   unsigned VersionVal = 0;
00454   unsigned ImageInfoFlags = 0;
00455   MDNode *LinkerOptions = nullptr;
00456   StringRef SectionVal;
00457 
00458   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00459          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00460     const Module::ModuleFlagEntry &MFE = *i;
00461 
00462     // Ignore flags with 'Require' behavior.
00463     if (MFE.Behavior == Module::Require)
00464       continue;
00465 
00466     StringRef Key = MFE.Key->getString();
00467     Value *Val = MFE.Val;
00468 
00469     if (Key == "Objective-C Image Info Version") {
00470       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
00471     } else if (Key == "Objective-C Garbage Collection" ||
00472                Key == "Objective-C GC Only" ||
00473                Key == "Objective-C Is Simulated") {
00474       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
00475     } else if (Key == "Objective-C Image Info Section") {
00476       SectionVal = cast<MDString>(Val)->getString();
00477     } else if (Key == "Linker Options") {
00478       LinkerOptions = cast<MDNode>(Val);
00479     }
00480   }
00481 
00482   // Emit the linker options if present.
00483   if (LinkerOptions) {
00484     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00485       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00486       SmallVector<std::string, 4> StrOptions;
00487 
00488       // Convert to strings.
00489       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00490         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00491         StrOptions.push_back(MDOption->getString());
00492       }
00493 
00494       Streamer.EmitLinkerOptions(StrOptions);
00495     }
00496   }
00497 
00498   // The section is mandatory. If we don't have it, then we don't have GC info.
00499   if (SectionVal.empty()) return;
00500 
00501   StringRef Segment, Section;
00502   unsigned TAA = 0, StubSize = 0;
00503   bool TAAParsed;
00504   std::string ErrorCode =
00505     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00506                                           TAA, TAAParsed, StubSize);
00507   if (!ErrorCode.empty())
00508     // If invalid, report the error with report_fatal_error.
00509     report_fatal_error("Invalid section specifier '" + Section + "': " +
00510                        ErrorCode + ".");
00511 
00512   // Get the section.
00513   const MCSectionMachO *S =
00514     getContext().getMachOSection(Segment, Section, TAA, StubSize,
00515                                  SectionKind::getDataNoRel());
00516   Streamer.SwitchSection(S);
00517   Streamer.EmitLabel(getContext().
00518                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00519   Streamer.EmitIntValue(VersionVal, 4);
00520   Streamer.EmitIntValue(ImageInfoFlags, 4);
00521   Streamer.AddBlankLine();
00522 }
00523 
00524 static void checkMachOComdat(const GlobalValue *GV) {
00525   const Comdat *C = GV->getComdat();
00526   if (!C)
00527     return;
00528 
00529   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
00530                      "' cannot be lowered.");
00531 }
00532 
00533 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
00534     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00535     const TargetMachine &TM) const {
00536   // Parse the section specifier and create it if valid.
00537   StringRef Segment, Section;
00538   unsigned TAA = 0, StubSize = 0;
00539   bool TAAParsed;
00540 
00541   checkMachOComdat(GV);
00542 
00543   std::string ErrorCode =
00544     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00545                                           TAA, TAAParsed, StubSize);
00546   if (!ErrorCode.empty()) {
00547     // If invalid, report the error with report_fatal_error.
00548     report_fatal_error("Global variable '" + GV->getName() +
00549                        "' has an invalid section specifier '" +
00550                        GV->getSection() + "': " + ErrorCode + ".");
00551   }
00552 
00553   // Get the section.
00554   const MCSectionMachO *S =
00555     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00556 
00557   // If TAA wasn't set by ParseSectionSpecifier() above,
00558   // use the value returned by getMachOSection() as a default.
00559   if (!TAAParsed)
00560     TAA = S->getTypeAndAttributes();
00561 
00562   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00563   // If the user declared multiple globals with different section flags, we need
00564   // to reject it here.
00565   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00566     // If invalid, report the error with report_fatal_error.
00567     report_fatal_error("Global variable '" + GV->getName() +
00568                        "' section type or attributes does not match previous"
00569                        " section specifier");
00570   }
00571 
00572   return S;
00573 }
00574 
00575 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
00576     const MCSection &Section) const {
00577     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
00578 
00579     // Sections holding 1 byte strings are atomized based on the data
00580     // they contain.
00581     // Sections holding 2 byte strings require symbols in order to be
00582     // atomized.
00583     // There is no dedicated section for 4 byte strings.
00584     if (SMO.getKind().isMergeable1ByteCString())
00585       return false;
00586 
00587     if (SMO.getSegmentName() == "__DATA" &&
00588         SMO.getSectionName() == "__cfstring")
00589       return false;
00590 
00591     switch (SMO.getType()) {
00592     default:
00593       return true;
00594 
00595       // These sections are atomized at the element boundaries without using
00596       // symbols.
00597     case MachO::S_4BYTE_LITERALS:
00598     case MachO::S_8BYTE_LITERALS:
00599     case MachO::S_16BYTE_LITERALS:
00600     case MachO::S_LITERAL_POINTERS:
00601     case MachO::S_NON_LAZY_SYMBOL_POINTERS:
00602     case MachO::S_LAZY_SYMBOL_POINTERS:
00603     case MachO::S_MOD_INIT_FUNC_POINTERS:
00604     case MachO::S_MOD_TERM_FUNC_POINTERS:
00605     case MachO::S_INTERPOSING:
00606       return false;
00607     }
00608 }
00609 
00610 const MCSection *TargetLoweringObjectFileMachO::
00611 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00612                        Mangler &Mang, const TargetMachine &TM) const {
00613   checkMachOComdat(GV);
00614 
00615   // Handle thread local data.
00616   if (Kind.isThreadBSS()) return TLSBSSSection;
00617   if (Kind.isThreadData()) return TLSDataSection;
00618 
00619   if (Kind.isText())
00620     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00621 
00622   // If this is weak/linkonce, put this in a coalescable section, either in text
00623   // or data depending on if it is writable.
00624   if (GV->isWeakForLinker()) {
00625     if (Kind.isReadOnly())
00626       return ConstTextCoalSection;
00627     return DataCoalSection;
00628   }
00629 
00630   // FIXME: Alignment check should be handled by section classifier.
00631   if (Kind.isMergeable1ByteCString() &&
00632       TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
00633           cast<GlobalVariable>(GV)) < 32)
00634     return CStringSection;
00635 
00636   // Do not put 16-bit arrays in the UString section if they have an
00637   // externally visible label, this runs into issues with certain linker
00638   // versions.
00639   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00640       TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
00641           cast<GlobalVariable>(GV)) < 32)
00642     return UStringSection;
00643 
00644   // With MachO only variables whose corresponding symbol starts with 'l' or
00645   // 'L' can be merged, so we only try merging GVs with private linkage.
00646   if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
00647     if (Kind.isMergeableConst4())
00648       return FourByteConstantSection;
00649     if (Kind.isMergeableConst8())
00650       return EightByteConstantSection;
00651     if (Kind.isMergeableConst16())
00652       return SixteenByteConstantSection;
00653   }
00654 
00655   // Otherwise, if it is readonly, but not something we can specially optimize,
00656   // just drop it in .const.
00657   if (Kind.isReadOnly())
00658     return ReadOnlySection;
00659 
00660   // If this is marked const, put it into a const section.  But if the dynamic
00661   // linker needs to write to it, put it in the data segment.
00662   if (Kind.isReadOnlyWithRel())
00663     return ConstDataSection;
00664 
00665   // Put zero initialized globals with strong external linkage in the
00666   // DATA, __common section with the .zerofill directive.
00667   if (Kind.isBSSExtern())
00668     return DataCommonSection;
00669 
00670   // Put zero initialized globals with local linkage in __DATA,__bss directive
00671   // with the .zerofill directive (aka .lcomm).
00672   if (Kind.isBSSLocal())
00673     return DataBSSSection;
00674 
00675   // Otherwise, just drop the variable in the normal data section.
00676   return DataSection;
00677 }
00678 
00679 const MCSection *
00680 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
00681                                                      const Constant *C) const {
00682   // If this constant requires a relocation, we have to put it in the data
00683   // segment, not in the text segment.
00684   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00685     return ConstDataSection;
00686 
00687   if (Kind.isMergeableConst4())
00688     return FourByteConstantSection;
00689   if (Kind.isMergeableConst8())
00690     return EightByteConstantSection;
00691   if (Kind.isMergeableConst16())
00692     return SixteenByteConstantSection;
00693   return ReadOnlySection;  // .const
00694 }
00695 
00696 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
00697     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00698     const TargetMachine &TM, MachineModuleInfo *MMI,
00699     MCStreamer &Streamer) const {
00700   // The mach-o version of this method defaults to returning a stub reference.
00701 
00702   if (Encoding & DW_EH_PE_indirect) {
00703     MachineModuleInfoMachO &MachOMMI =
00704       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00705 
00706     MCSymbol *SSym =
00707         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00708 
00709     // Add information about the stub reference to MachOMMI so that the stub
00710     // gets emitted by the asmprinter.
00711     MachineModuleInfoImpl::StubValueTy &StubSym =
00712       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00713                                   MachOMMI.getGVStubEntry(SSym);
00714     if (!StubSym.getPointer()) {
00715       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00716       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00717     }
00718 
00719     return TargetLoweringObjectFile::
00720       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00721                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00722   }
00723 
00724   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
00725                                                            TM, MMI, Streamer);
00726 }
00727 
00728 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
00729     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00730     MachineModuleInfo *MMI) const {
00731   // The mach-o version of this method defaults to returning a stub reference.
00732   MachineModuleInfoMachO &MachOMMI =
00733     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00734 
00735   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00736 
00737   // Add information about the stub reference to MachOMMI so that the stub
00738   // gets emitted by the asmprinter.
00739   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00740   if (!StubSym.getPointer()) {
00741     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00742     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00743   }
00744 
00745   return SSym;
00746 }
00747 
00748 //===----------------------------------------------------------------------===//
00749 //                                  COFF
00750 //===----------------------------------------------------------------------===//
00751 
00752 static unsigned
00753 getCOFFSectionFlags(SectionKind K) {
00754   unsigned Flags = 0;
00755 
00756   if (K.isMetadata())
00757     Flags |=
00758       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00759   else if (K.isText())
00760     Flags |=
00761       COFF::IMAGE_SCN_MEM_EXECUTE |
00762       COFF::IMAGE_SCN_MEM_READ |
00763       COFF::IMAGE_SCN_CNT_CODE;
00764   else if (K.isBSS ())
00765     Flags |=
00766       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00767       COFF::IMAGE_SCN_MEM_READ |
00768       COFF::IMAGE_SCN_MEM_WRITE;
00769   else if (K.isThreadLocal())
00770     Flags |=
00771       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00772       COFF::IMAGE_SCN_MEM_READ |
00773       COFF::IMAGE_SCN_MEM_WRITE;
00774   else if (K.isReadOnly())
00775     Flags |=
00776       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00777       COFF::IMAGE_SCN_MEM_READ;
00778   else if (K.isWriteable())
00779     Flags |=
00780       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00781       COFF::IMAGE_SCN_MEM_READ |
00782       COFF::IMAGE_SCN_MEM_WRITE;
00783 
00784   return Flags;
00785 }
00786 
00787 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
00788   const Comdat *C = GV->getComdat();
00789   assert(C && "expected GV to have a Comdat!");
00790 
00791   StringRef ComdatGVName = C->getName();
00792   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
00793   if (!ComdatGV)
00794     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00795                        "' does not exist.");
00796 
00797   if (ComdatGV->getComdat() != C)
00798     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00799                        "' is not a key for it's COMDAT.");
00800 
00801   return ComdatGV;
00802 }
00803 
00804 static int getSelectionForCOFF(const GlobalValue *GV) {
00805   if (const Comdat *C = GV->getComdat()) {
00806     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
00807     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
00808       ComdatKey = GA->getBaseObject();
00809     if (ComdatKey == GV) {
00810       switch (C->getSelectionKind()) {
00811       case Comdat::Any:
00812         return COFF::IMAGE_COMDAT_SELECT_ANY;
00813       case Comdat::ExactMatch:
00814         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
00815       case Comdat::Largest:
00816         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
00817       case Comdat::NoDuplicates:
00818         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00819       case Comdat::SameSize:
00820         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
00821       }
00822     } else {
00823       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
00824     }
00825   } else if (GV->isWeakForLinker()) {
00826     return COFF::IMAGE_COMDAT_SELECT_ANY;
00827   }
00828   return 0;
00829 }
00830 
00831 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
00832     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00833     const TargetMachine &TM) const {
00834   int Selection = 0;
00835   unsigned Characteristics = getCOFFSectionFlags(Kind);
00836   StringRef Name = GV->getSection();
00837   StringRef COMDATSymName = "";
00838   if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
00839     Selection = getSelectionForCOFF(GV);
00840     const GlobalValue *ComdatGV;
00841     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
00842       ComdatGV = getComdatGVForCOFF(GV);
00843     else
00844       ComdatGV = GV;
00845 
00846     if (!ComdatGV->hasPrivateLinkage()) {
00847       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00848       COMDATSymName = Sym->getName();
00849       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00850     } else {
00851       Selection = 0;
00852     }
00853   }
00854   return getContext().getCOFFSection(Name,
00855                                      Characteristics,
00856                                      Kind,
00857                                      COMDATSymName,
00858                                      Selection);
00859 }
00860 
00861 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
00862   if (Kind.isText())
00863     return ".text";
00864   if (Kind.isBSS())
00865     return ".bss";
00866   if (Kind.isThreadLocal())
00867     return ".tls$";
00868   if (Kind.isWriteable())
00869     return ".data";
00870   return ".rdata";
00871 }
00872 
00873 
00874 const MCSection *TargetLoweringObjectFileCOFF::
00875 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00876                        Mangler &Mang, const TargetMachine &TM) const {
00877   // If we have -ffunction-sections then we should emit the global value to a
00878   // uniqued section specifically for it.
00879   bool EmitUniquedSection;
00880   if (Kind.isText())
00881     EmitUniquedSection = TM.getFunctionSections();
00882   else
00883     EmitUniquedSection = TM.getDataSections();
00884 
00885   // If this global is linkonce/weak and the target handles this by emitting it
00886   // into a 'uniqued' section name, create and return the section now.
00887   // Section names depend on the name of the symbol which is not feasible if the
00888   // symbol has private linkage.
00889   if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
00890       !Kind.isCommon()) {
00891     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00892     unsigned Characteristics = getCOFFSectionFlags(Kind);
00893 
00894     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00895     int Selection = getSelectionForCOFF(GV);
00896     if (!Selection)
00897       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00898     const GlobalValue *ComdatGV;
00899     if (GV->hasComdat())
00900       ComdatGV = getComdatGVForCOFF(GV);
00901     else
00902       ComdatGV = GV;
00903 
00904     if (!ComdatGV->hasPrivateLinkage()) {
00905       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00906       StringRef COMDATSymName = Sym->getName();
00907       return getContext().getCOFFSection(Name, Characteristics, Kind,
00908                                          COMDATSymName, Selection);
00909     }
00910   }
00911 
00912   if (Kind.isText())
00913     return TextSection;
00914 
00915   if (Kind.isThreadLocal())
00916     return TLSDataSection;
00917 
00918   if (Kind.isReadOnly())
00919     return ReadOnlySection;
00920 
00921   // Note: we claim that common symbols are put in BSSSection, but they are
00922   // really emitted with the magic .comm directive, which creates a symbol table
00923   // entry but not a section.
00924   if (Kind.isBSS() || Kind.isCommon())
00925     return BSSSection;
00926 
00927   return DataSection;
00928 }
00929 
00930 StringRef TargetLoweringObjectFileCOFF::
00931 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00932   const char *LibCmd = "/DEFAULTLIB:";
00933   if (LinkerOption.startswith(LibCmd))
00934     return LinkerOption.substr(strlen(LibCmd));
00935   return StringRef();
00936 }
00937 
00938 void TargetLoweringObjectFileCOFF::
00939 emitModuleFlags(MCStreamer &Streamer,
00940                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00941                 Mangler &Mang, const TargetMachine &TM) const {
00942   MDNode *LinkerOptions = nullptr;
00943 
00944   // Look for the "Linker Options" flag, since it's the only one we support.
00945   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00946        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00947     const Module::ModuleFlagEntry &MFE = *i;
00948     StringRef Key = MFE.Key->getString();
00949     Value *Val = MFE.Val;
00950     if (Key == "Linker Options") {
00951       LinkerOptions = cast<MDNode>(Val);
00952       break;
00953     }
00954   }
00955   if (!LinkerOptions)
00956     return;
00957 
00958   // Emit the linker options to the linker .drectve section.  According to the
00959   // spec, this section is a space-separated string containing flags for linker.
00960   const MCSection *Sec = getDrectveSection();
00961   Streamer.SwitchSection(Sec);
00962   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00963     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00964     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00965       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00966       StringRef Op = MDOption->getString();
00967       // Lead with a space for consistency with our dllexport implementation.
00968       std::string Escaped(" ");
00969       if (Op.find(" ") != StringRef::npos) {
00970         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
00971         // how to escape quotes, but it probably uses this algorithm:
00972         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
00973         // FIXME: Reuse escaping code from Support/Windows/Program.inc
00974         Escaped.push_back('\"');
00975         Escaped.append(Op);
00976         Escaped.push_back('\"');
00977       } else {
00978         Escaped.append(Op);
00979       }
00980       Streamer.EmitBytes(Escaped);
00981     }
00982   }
00983 }
00984 
00985 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
00986     unsigned Priority, const MCSymbol *KeySym) const {
00987   return getContext().getAssociativeCOFFSection(
00988       cast<MCSectionCOFF>(StaticCtorSection), KeySym);
00989 }
00990 
00991 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
00992     unsigned Priority, const MCSymbol *KeySym) const {
00993   return getContext().getAssociativeCOFFSection(
00994       cast<MCSectionCOFF>(StaticDtorSection), KeySym);
00995 }