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/Module.h"
00026 #include "llvm/MC/MCContext.h"
00027 #include "llvm/MC/MCExpr.h"
00028 #include "llvm/MC/MCSectionCOFF.h"
00029 #include "llvm/MC/MCSectionELF.h"
00030 #include "llvm/MC/MCSectionMachO.h"
00031 #include "llvm/MC/MCStreamer.h"
00032 #include "llvm/MC/MCSymbol.h"
00033 #include "llvm/Support/Dwarf.h"
00034 #include "llvm/Support/ELF.h"
00035 #include "llvm/Support/ErrorHandling.h"
00036 #include "llvm/Support/raw_ostream.h"
00037 #include "llvm/Target/Mangler.h"
00038 #include "llvm/Target/TargetMachine.h"
00039 using namespace llvm;
00040 using namespace dwarf;
00041 
00042 //===----------------------------------------------------------------------===//
00043 //                                  ELF
00044 //===----------------------------------------------------------------------===//
00045 
00046 MCSymbol *
00047 TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV,
00048                                                      Mangler *Mang,
00049                                                 MachineModuleInfo *MMI) const {
00050   unsigned Encoding = getPersonalityEncoding();
00051   switch (Encoding & 0x70) {
00052   default:
00053     report_fatal_error("We do not support this DWARF encoding yet!");
00054   case dwarf::DW_EH_PE_absptr:
00055     return  Mang->getSymbol(GV);
00056   case dwarf::DW_EH_PE_pcrel: {
00057     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
00058                                           Mang->getSymbol(GV)->getName());
00059   }
00060   }
00061 }
00062 
00063 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
00064                                                        const TargetMachine &TM,
00065                                                        const MCSymbol *Sym) const {
00066   SmallString<64> NameData("DW.ref.");
00067   NameData += Sym->getName();
00068   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
00069   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
00070   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
00071   StringRef Prefix = ".data.";
00072   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
00073   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
00074   const MCSection *Sec = getContext().getELFSection(NameData,
00075                                                     ELF::SHT_PROGBITS,
00076                                                     Flags,
00077                                                     SectionKind::getDataRel(),
00078                                                     0, Label->getName());
00079   unsigned Size = TM.getDataLayout()->getPointerSize();
00080   Streamer.SwitchSection(Sec);
00081   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
00082   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
00083   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
00084   Streamer.EmitELFSize(Label, E);
00085   Streamer.EmitLabel(Label);
00086 
00087   Streamer.EmitSymbolValue(Sym, Size);
00088 }
00089 
00090 const MCExpr *TargetLoweringObjectFileELF::
00091 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang,
00092                         MachineModuleInfo *MMI, unsigned Encoding,
00093                         MCStreamer &Streamer) const {
00094 
00095   if (Encoding & dwarf::DW_EH_PE_indirect) {
00096     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
00097 
00098     SmallString<128> Name;
00099     Mang->getNameWithPrefix(Name, GV, true);
00100     Name += ".DW.stub";
00101 
00102     // Add information about the stub reference to ELFMMI so that the stub
00103     // gets emitted by the asmprinter.
00104     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
00105     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
00106     if (StubSym.getPointer() == 0) {
00107       MCSymbol *Sym = Mang->getSymbol(GV);
00108       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00109     }
00110 
00111     return TargetLoweringObjectFile::
00112       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00113                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00114   }
00115 
00116   return TargetLoweringObjectFile::
00117     getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
00118 }
00119 
00120 static SectionKind
00121 getELFKindForNamedSection(StringRef Name, SectionKind K) {
00122   // N.B.: The defaults used in here are no the same ones used in MC.
00123   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
00124   // both gas and MC will produce a section with no flags. Given
00125   // section(".eh_frame") gcc will produce:
00126   //
00127   //   .section   .eh_frame,"a",@progbits
00128   if (Name.empty() || Name[0] != '.') return K;
00129 
00130   // Some lame default implementation based on some magic section names.
00131   if (Name == ".bss" ||
00132       Name.startswith(".bss.") ||
00133       Name.startswith(".gnu.linkonce.b.") ||
00134       Name.startswith(".llvm.linkonce.b.") ||
00135       Name == ".sbss" ||
00136       Name.startswith(".sbss.") ||
00137       Name.startswith(".gnu.linkonce.sb.") ||
00138       Name.startswith(".llvm.linkonce.sb."))
00139     return SectionKind::getBSS();
00140 
00141   if (Name == ".tdata" ||
00142       Name.startswith(".tdata.") ||
00143       Name.startswith(".gnu.linkonce.td.") ||
00144       Name.startswith(".llvm.linkonce.td."))
00145     return SectionKind::getThreadData();
00146 
00147   if (Name == ".tbss" ||
00148       Name.startswith(".tbss.") ||
00149       Name.startswith(".gnu.linkonce.tb.") ||
00150       Name.startswith(".llvm.linkonce.tb."))
00151     return SectionKind::getThreadBSS();
00152 
00153   return K;
00154 }
00155 
00156 
00157 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
00158 
00159   if (Name == ".init_array")
00160     return ELF::SHT_INIT_ARRAY;
00161 
00162   if (Name == ".fini_array")
00163     return ELF::SHT_FINI_ARRAY;
00164 
00165   if (Name == ".preinit_array")
00166     return ELF::SHT_PREINIT_ARRAY;
00167 
00168   if (K.isBSS() || K.isThreadBSS())
00169     return ELF::SHT_NOBITS;
00170 
00171   return ELF::SHT_PROGBITS;
00172 }
00173 
00174 
00175 static unsigned
00176 getELFSectionFlags(SectionKind K) {
00177   unsigned Flags = 0;
00178 
00179   if (!K.isMetadata())
00180     Flags |= ELF::SHF_ALLOC;
00181 
00182   if (K.isText())
00183     Flags |= ELF::SHF_EXECINSTR;
00184 
00185   if (K.isWriteable())
00186     Flags |= ELF::SHF_WRITE;
00187 
00188   if (K.isThreadLocal())
00189     Flags |= ELF::SHF_TLS;
00190 
00191   // K.isMergeableConst() is left out to honour PR4650
00192   if (K.isMergeableCString() || K.isMergeableConst4() ||
00193       K.isMergeableConst8() || K.isMergeableConst16())
00194     Flags |= ELF::SHF_MERGE;
00195 
00196   if (K.isMergeableCString())
00197     Flags |= ELF::SHF_STRINGS;
00198 
00199   return Flags;
00200 }
00201 
00202 
00203 const MCSection *TargetLoweringObjectFileELF::
00204 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
00205                          Mangler *Mang, const TargetMachine &TM) const {
00206   StringRef SectionName = GV->getSection();
00207 
00208   // Infer section flags from the section name if we can.
00209   Kind = getELFKindForNamedSection(SectionName, Kind);
00210 
00211   return getContext().getELFSection(SectionName,
00212                                     getELFSectionType(SectionName, Kind),
00213                                     getELFSectionFlags(Kind), Kind);
00214 }
00215 
00216 /// getSectionPrefixForGlobal - Return the section prefix name used by options
00217 /// FunctionsSections and DataSections.
00218 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
00219   if (Kind.isText())                 return ".text.";
00220   if (Kind.isReadOnly())             return ".rodata.";
00221   if (Kind.isBSS())                  return ".bss.";
00222 
00223   if (Kind.isThreadData())           return ".tdata.";
00224   if (Kind.isThreadBSS())            return ".tbss.";
00225 
00226   if (Kind.isDataNoRel())            return ".data.";
00227   if (Kind.isDataRelLocal())         return ".data.rel.local.";
00228   if (Kind.isDataRel())              return ".data.rel.";
00229   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
00230 
00231   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00232   return ".data.rel.ro.";
00233 }
00234 
00235 
00236 const MCSection *TargetLoweringObjectFileELF::
00237 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00238                        Mangler *Mang, const TargetMachine &TM) const {
00239   // If we have -ffunction-section or -fdata-section then we should emit the
00240   // global value to a uniqued section specifically for it.
00241   bool EmitUniquedSection;
00242   if (Kind.isText())
00243     EmitUniquedSection = TM.getFunctionSections();
00244   else
00245     EmitUniquedSection = TM.getDataSections();
00246 
00247   // If this global is linkonce/weak and the target handles this by emitting it
00248   // into a 'uniqued' section name, create and return the section now.
00249   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
00250       !Kind.isCommon()) {
00251     const char *Prefix;
00252     Prefix = getSectionPrefixForGlobal(Kind);
00253 
00254     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
00255     MCSymbol *Sym = Mang->getSymbol(GV);
00256     Name.append(Sym->getName().begin(), Sym->getName().end());
00257     StringRef Group = "";
00258     unsigned Flags = getELFSectionFlags(Kind);
00259     if (GV->isWeakForLinker()) {
00260       Group = Sym->getName();
00261       Flags |= ELF::SHF_GROUP;
00262     }
00263 
00264     return getContext().getELFSection(Name.str(),
00265                                       getELFSectionType(Name.str(), Kind),
00266                                       Flags, Kind, 0, Group);
00267   }
00268 
00269   if (Kind.isText()) return TextSection;
00270 
00271   if (Kind.isMergeable1ByteCString() ||
00272       Kind.isMergeable2ByteCString() ||
00273       Kind.isMergeable4ByteCString()) {
00274 
00275     // We also need alignment here.
00276     // FIXME: this is getting the alignment of the character, not the
00277     // alignment of the global!
00278     unsigned Align =
00279       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
00280 
00281     const char *SizeSpec = ".rodata.str1.";
00282     if (Kind.isMergeable2ByteCString())
00283       SizeSpec = ".rodata.str2.";
00284     else if (Kind.isMergeable4ByteCString())
00285       SizeSpec = ".rodata.str4.";
00286     else
00287       assert(Kind.isMergeable1ByteCString() && "unknown string width");
00288 
00289 
00290     std::string Name = SizeSpec + utostr(Align);
00291     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00292                                       ELF::SHF_ALLOC |
00293                                       ELF::SHF_MERGE |
00294                                       ELF::SHF_STRINGS,
00295                                       Kind);
00296   }
00297 
00298   if (Kind.isMergeableConst()) {
00299     if (Kind.isMergeableConst4() && MergeableConst4Section)
00300       return MergeableConst4Section;
00301     if (Kind.isMergeableConst8() && MergeableConst8Section)
00302       return MergeableConst8Section;
00303     if (Kind.isMergeableConst16() && MergeableConst16Section)
00304       return MergeableConst16Section;
00305     return ReadOnlySection;  // .const
00306   }
00307 
00308   if (Kind.isReadOnly())             return ReadOnlySection;
00309 
00310   if (Kind.isThreadData())           return TLSDataSection;
00311   if (Kind.isThreadBSS())            return TLSBSSSection;
00312 
00313   // Note: we claim that common symbols are put in BSSSection, but they are
00314   // really emitted with the magic .comm directive, which creates a symbol table
00315   // entry but not a section.
00316   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
00317 
00318   if (Kind.isDataNoRel())            return DataSection;
00319   if (Kind.isDataRelLocal())         return DataRelLocalSection;
00320   if (Kind.isDataRel())              return DataRelSection;
00321   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00322 
00323   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00324   return DataRelROSection;
00325 }
00326 
00327 /// getSectionForConstant - Given a mergeable constant with the
00328 /// specified size and relocation information, return a section that it
00329 /// should be placed in.
00330 const MCSection *TargetLoweringObjectFileELF::
00331 getSectionForConstant(SectionKind Kind) const {
00332   if (Kind.isMergeableConst4() && MergeableConst4Section)
00333     return MergeableConst4Section;
00334   if (Kind.isMergeableConst8() && MergeableConst8Section)
00335     return MergeableConst8Section;
00336   if (Kind.isMergeableConst16() && MergeableConst16Section)
00337     return MergeableConst16Section;
00338   if (Kind.isReadOnly())
00339     return ReadOnlySection;
00340 
00341   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00342   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00343   return DataRelROSection;
00344 }
00345 
00346 const MCSection *
00347 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
00348   // The default scheme is .ctor / .dtor, so we have to invert the priority
00349   // numbering.
00350   if (Priority == 65535)
00351     return StaticCtorSection;
00352 
00353   if (UseInitArray) {
00354     std::string Name = std::string(".init_array.") + utostr(Priority);
00355     return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
00356                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00357                                       SectionKind::getDataRel());
00358   } else {
00359     std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
00360     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00361                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00362                                       SectionKind::getDataRel());
00363   }
00364 }
00365 
00366 const MCSection *
00367 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
00368   // The default scheme is .ctor / .dtor, so we have to invert the priority
00369   // numbering.
00370   if (Priority == 65535)
00371     return StaticDtorSection;
00372 
00373   if (UseInitArray) {
00374     std::string Name = std::string(".fini_array.") + utostr(Priority);
00375     return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
00376                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00377                                       SectionKind::getDataRel());
00378   } else {
00379     std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
00380     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00381                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00382                                       SectionKind::getDataRel());
00383   }
00384 }
00385 
00386 void
00387 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00388   UseInitArray = UseInitArray_;
00389   if (!UseInitArray)
00390     return;
00391 
00392   StaticCtorSection =
00393     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
00394                                ELF::SHF_WRITE |
00395                                ELF::SHF_ALLOC,
00396                                SectionKind::getDataRel());
00397   StaticDtorSection =
00398     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
00399                                ELF::SHF_WRITE |
00400                                ELF::SHF_ALLOC,
00401                                SectionKind::getDataRel());
00402 }
00403 
00404 //===----------------------------------------------------------------------===//
00405 //                                 MachO
00406 //===----------------------------------------------------------------------===//
00407 
00408 /// emitModuleFlags - Perform code emission for module flags.
00409 void TargetLoweringObjectFileMachO::
00410 emitModuleFlags(MCStreamer &Streamer,
00411                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00412                 Mangler *Mang, const TargetMachine &TM) const {
00413   unsigned VersionVal = 0;
00414   unsigned ImageInfoFlags = 0;
00415   MDNode *LinkerOptions = 0;
00416   StringRef SectionVal;
00417 
00418   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00419          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00420     const Module::ModuleFlagEntry &MFE = *i;
00421 
00422     // Ignore flags with 'Require' behavior.
00423     if (MFE.Behavior == Module::Require)
00424       continue;
00425 
00426     StringRef Key = MFE.Key->getString();
00427     Value *Val = MFE.Val;
00428 
00429     if (Key == "Objective-C Image Info Version") {
00430       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
00431     } else if (Key == "Objective-C Garbage Collection" ||
00432                Key == "Objective-C GC Only" ||
00433                Key == "Objective-C Is Simulated") {
00434       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
00435     } else if (Key == "Objective-C Image Info Section") {
00436       SectionVal = cast<MDString>(Val)->getString();
00437     } else if (Key == "Linker Options") {
00438       LinkerOptions = cast<MDNode>(Val);
00439     }
00440   }
00441 
00442   // Emit the linker options if present.
00443   if (LinkerOptions) {
00444     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00445       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00446       SmallVector<std::string, 4> StrOptions;
00447 
00448       // Convert to strings.
00449       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00450         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00451         StrOptions.push_back(MDOption->getString());
00452       }
00453 
00454       Streamer.EmitLinkerOptions(StrOptions);
00455     }
00456   }
00457 
00458   // The section is mandatory. If we don't have it, then we don't have GC info.
00459   if (SectionVal.empty()) return;
00460 
00461   StringRef Segment, Section;
00462   unsigned TAA = 0, StubSize = 0;
00463   bool TAAParsed;
00464   std::string ErrorCode =
00465     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00466                                           TAA, TAAParsed, StubSize);
00467   if (!ErrorCode.empty())
00468     // If invalid, report the error with report_fatal_error.
00469     report_fatal_error("Invalid section specifier '" + Section + "': " +
00470                        ErrorCode + ".");
00471 
00472   // Get the section.
00473   const MCSectionMachO *S =
00474     getContext().getMachOSection(Segment, Section, TAA, StubSize,
00475                                  SectionKind::getDataNoRel());
00476   Streamer.SwitchSection(S);
00477   Streamer.EmitLabel(getContext().
00478                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00479   Streamer.EmitIntValue(VersionVal, 4);
00480   Streamer.EmitIntValue(ImageInfoFlags, 4);
00481   Streamer.AddBlankLine();
00482 }
00483 
00484 const MCSection *TargetLoweringObjectFileMachO::
00485 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
00486                          Mangler *Mang, const TargetMachine &TM) const {
00487   // Parse the section specifier and create it if valid.
00488   StringRef Segment, Section;
00489   unsigned TAA = 0, StubSize = 0;
00490   bool TAAParsed;
00491   std::string ErrorCode =
00492     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00493                                           TAA, TAAParsed, StubSize);
00494   if (!ErrorCode.empty()) {
00495     // If invalid, report the error with report_fatal_error.
00496     report_fatal_error("Global variable '" + GV->getName() +
00497                        "' has an invalid section specifier '" +
00498                        GV->getSection() + "': " + ErrorCode + ".");
00499   }
00500 
00501   // Get the section.
00502   const MCSectionMachO *S =
00503     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00504 
00505   // If TAA wasn't set by ParseSectionSpecifier() above,
00506   // use the value returned by getMachOSection() as a default.
00507   if (!TAAParsed)
00508     TAA = S->getTypeAndAttributes();
00509 
00510   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00511   // If the user declared multiple globals with different section flags, we need
00512   // to reject it here.
00513   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00514     // If invalid, report the error with report_fatal_error.
00515     report_fatal_error("Global variable '" + GV->getName() +
00516                        "' section type or attributes does not match previous"
00517                        " section specifier");
00518   }
00519 
00520   return S;
00521 }
00522 
00523 const MCSection *TargetLoweringObjectFileMachO::
00524 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00525                        Mangler *Mang, const TargetMachine &TM) const {
00526   if (Kind.isText())
00527     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00528 
00529   // If this is weak/linkonce, put this in a coalescable section, either in text
00530   // or data depending on if it is writable.
00531   if (GV->isWeakForLinker()) {
00532     if (Kind.isReadOnly())
00533       return ConstTextCoalSection;
00534     return DataCoalSection;
00535   }
00536 
00537   // FIXME: Alignment check should be handled by section classifier.
00538   if (Kind.isMergeable1ByteCString() &&
00539       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00540     return CStringSection;
00541 
00542   // Do not put 16-bit arrays in the UString section if they have an
00543   // externally visible label, this runs into issues with certain linker
00544   // versions.
00545   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00546       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00547     return UStringSection;
00548 
00549   if (Kind.isMergeableConst()) {
00550     if (Kind.isMergeableConst4())
00551       return FourByteConstantSection;
00552     if (Kind.isMergeableConst8())
00553       return EightByteConstantSection;
00554     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
00555       return SixteenByteConstantSection;
00556   }
00557 
00558   // Otherwise, if it is readonly, but not something we can specially optimize,
00559   // just drop it in .const.
00560   if (Kind.isReadOnly())
00561     return ReadOnlySection;
00562 
00563   // If this is marked const, put it into a const section.  But if the dynamic
00564   // linker needs to write to it, put it in the data segment.
00565   if (Kind.isReadOnlyWithRel())
00566     return ConstDataSection;
00567 
00568   // Put zero initialized globals with strong external linkage in the
00569   // DATA, __common section with the .zerofill directive.
00570   if (Kind.isBSSExtern())
00571     return DataCommonSection;
00572 
00573   // Put zero initialized globals with local linkage in __DATA,__bss directive
00574   // with the .zerofill directive (aka .lcomm).
00575   if (Kind.isBSSLocal())
00576     return DataBSSSection;
00577 
00578   // Handle thread local data.
00579   if (Kind.isThreadBSS()) return TLSBSSSection;
00580   if (Kind.isThreadData()) return TLSDataSection;
00581 
00582   // Otherwise, just drop the variable in the normal data section.
00583   return DataSection;
00584 }
00585 
00586 const MCSection *
00587 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
00588   // If this constant requires a relocation, we have to put it in the data
00589   // segment, not in the text segment.
00590   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00591     return ConstDataSection;
00592 
00593   if (Kind.isMergeableConst4())
00594     return FourByteConstantSection;
00595   if (Kind.isMergeableConst8())
00596     return EightByteConstantSection;
00597   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
00598     return SixteenByteConstantSection;
00599   return ReadOnlySection;  // .const
00600 }
00601 
00602 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
00603 /// not to emit the UsedDirective for some symbols in llvm.used.
00604 // FIXME: REMOVE this (rdar://7071300)
00605 bool TargetLoweringObjectFileMachO::
00606 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
00607   /// On Darwin, internally linked data beginning with "L" or "l" does not have
00608   /// the directive emitted (this occurs in ObjC metadata).
00609   if (!GV) return false;
00610 
00611   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
00612   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
00613     // FIXME: ObjC metadata is currently emitted as internal symbols that have
00614     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
00615     // this horrible hack can go away.
00616     MCSymbol *Sym = Mang->getSymbol(GV);
00617     if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
00618       return false;
00619   }
00620 
00621   return true;
00622 }
00623 
00624 const MCExpr *TargetLoweringObjectFileMachO::
00625 getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang,
00626                         MachineModuleInfo *MMI, unsigned Encoding,
00627                         MCStreamer &Streamer) const {
00628   // The mach-o version of this method defaults to returning a stub reference.
00629 
00630   if (Encoding & DW_EH_PE_indirect) {
00631     MachineModuleInfoMachO &MachOMMI =
00632       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00633 
00634     SmallString<128> Name;
00635     Mang->getNameWithPrefix(Name, GV, true);
00636     Name += "$non_lazy_ptr";
00637 
00638     // Add information about the stub reference to MachOMMI so that the stub
00639     // gets emitted by the asmprinter.
00640     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
00641     MachineModuleInfoImpl::StubValueTy &StubSym =
00642       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00643                                   MachOMMI.getGVStubEntry(SSym);
00644     if (StubSym.getPointer() == 0) {
00645       MCSymbol *Sym = Mang->getSymbol(GV);
00646       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00647     }
00648 
00649     return TargetLoweringObjectFile::
00650       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00651                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00652   }
00653 
00654   return TargetLoweringObjectFile::
00655     getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
00656 }
00657 
00658 MCSymbol *TargetLoweringObjectFileMachO::
00659 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
00660                         MachineModuleInfo *MMI) const {
00661   // The mach-o version of this method defaults to returning a stub reference.
00662   MachineModuleInfoMachO &MachOMMI =
00663     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00664 
00665   SmallString<128> Name;
00666   Mang->getNameWithPrefix(Name, GV, true);
00667   Name += "$non_lazy_ptr";
00668 
00669   // Add information about the stub reference to MachOMMI so that the stub
00670   // gets emitted by the asmprinter.
00671   MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
00672   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00673   if (StubSym.getPointer() == 0) {
00674     MCSymbol *Sym = Mang->getSymbol(GV);
00675     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00676   }
00677 
00678   return SSym;
00679 }
00680 
00681 //===----------------------------------------------------------------------===//
00682 //                                  COFF
00683 //===----------------------------------------------------------------------===//
00684 
00685 static unsigned
00686 getCOFFSectionFlags(SectionKind K) {
00687   unsigned Flags = 0;
00688 
00689   if (K.isMetadata())
00690     Flags |=
00691       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00692   else if (K.isText())
00693     Flags |=
00694       COFF::IMAGE_SCN_MEM_EXECUTE |
00695       COFF::IMAGE_SCN_MEM_READ |
00696       COFF::IMAGE_SCN_CNT_CODE;
00697   else if (K.isBSS ())
00698     Flags |=
00699       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00700       COFF::IMAGE_SCN_MEM_READ |
00701       COFF::IMAGE_SCN_MEM_WRITE;
00702   else if (K.isThreadLocal())
00703     Flags |=
00704       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00705       COFF::IMAGE_SCN_MEM_READ |
00706       COFF::IMAGE_SCN_MEM_WRITE;
00707   else if (K.isReadOnly())
00708     Flags |=
00709       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00710       COFF::IMAGE_SCN_MEM_READ;
00711   else if (K.isWriteable())
00712     Flags |=
00713       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00714       COFF::IMAGE_SCN_MEM_READ |
00715       COFF::IMAGE_SCN_MEM_WRITE;
00716 
00717   return Flags;
00718 }
00719 
00720 const MCSection *TargetLoweringObjectFileCOFF::
00721 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
00722                          Mangler *Mang, const TargetMachine &TM) const {
00723   int Selection = 0;
00724   unsigned Characteristics = getCOFFSectionFlags(Kind);
00725   SmallString<128> Name(GV->getSection().c_str());
00726   if (GV->isWeakForLinker()) {
00727     Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
00728     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00729     MCSymbol *Sym = Mang->getSymbol(GV);
00730     Name.append("$");
00731     Name.append(Sym->getName().begin() + 1, Sym->getName().end());
00732   }
00733   return getContext().getCOFFSection(Name,
00734                                      Characteristics,
00735                                      Selection,
00736                                      Kind);
00737 }
00738 
00739 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
00740   if (Kind.isText())
00741     return ".text$";
00742   if (Kind.isBSS ())
00743     return ".bss$";
00744   if (Kind.isThreadLocal()) {
00745     // 'LLVM' is just an arbitary string to ensure that the section name gets
00746     // sorted in between '.tls$AAA' and '.tls$ZZZ' by the linker.
00747     return ".tls$LLVM";
00748   }
00749   if (Kind.isWriteable())
00750     return ".data$";
00751   return ".rdata$";
00752 }
00753 
00754 
00755 const MCSection *TargetLoweringObjectFileCOFF::
00756 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00757                        Mangler *Mang, const TargetMachine &TM) const {
00758 
00759   // If this global is linkonce/weak and the target handles this by emitting it
00760   // into a 'uniqued' section name, create and return the section now.
00761   if (GV->isWeakForLinker()) {
00762     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
00763     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
00764     MCSymbol *Sym = Mang->getSymbol(GV);
00765     Name.append(Sym->getName().begin() + 1, Sym->getName().end());
00766 
00767     unsigned Characteristics = getCOFFSectionFlags(Kind);
00768 
00769     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00770 
00771     return getContext().getCOFFSection(Name.str(), Characteristics,
00772                           COFF::IMAGE_COMDAT_SELECT_ANY, Kind);
00773   }
00774 
00775   if (Kind.isText())
00776     return getTextSection();
00777 
00778   if (Kind.isThreadLocal())
00779     return getTLSDataSection();
00780 
00781   return getDataSection();
00782 }
00783 
00784 void TargetLoweringObjectFileCOFF::
00785 emitModuleFlags(MCStreamer &Streamer,
00786                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00787                 Mangler *Mang, const TargetMachine &TM) const {
00788   MDNode *LinkerOptions = 0;
00789 
00790   // Look for the "Linker Options" flag, since it's the only one we support.
00791   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00792        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00793     const Module::ModuleFlagEntry &MFE = *i;
00794     StringRef Key = MFE.Key->getString();
00795     Value *Val = MFE.Val;
00796     if (Key == "Linker Options") {
00797       LinkerOptions = cast<MDNode>(Val);
00798       break;
00799     }
00800   }
00801   if (!LinkerOptions)
00802     return;
00803 
00804   // Emit the linker options to the linker .drectve section.  According to the
00805   // spec, this section is a space-separated string containing flags for linker.
00806   const MCSection *Sec = getDrectveSection();
00807   Streamer.SwitchSection(Sec);
00808   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00809     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00810     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00811       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00812       StringRef Op = MDOption->getString();
00813       // Lead with a space for consistency with our dllexport implementation.
00814       std::string Escaped(" ");
00815       if (Op.find(" ") != StringRef::npos) {
00816         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
00817         // how to escape quotes, but it probably uses this algorithm:
00818         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
00819         // FIXME: Reuse escaping code from Support/Windows/Program.inc
00820         Escaped.push_back('\"');
00821         Escaped.append(Op);
00822         Escaped.push_back('\"');
00823       } else {
00824         Escaped.append(Op);
00825       }
00826       Streamer.EmitBytes(Escaped);
00827     }
00828   }
00829 }