LLVM API Documentation

TargetLoweringObjectFile.cpp

Go to the documentation of this file.
00001 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Function.h"
00019 #include "llvm/GlobalVariable.h"
00020 #include "llvm/MC/MCContext.h"
00021 #include "llvm/MC/MCSectionMachO.h"
00022 #include "llvm/MC/MCSectionELF.h"
00023 #include "llvm/Target/TargetData.h"
00024 #include "llvm/Target/TargetMachine.h"
00025 #include "llvm/Target/TargetOptions.h"
00026 #include "llvm/Support/Mangler.h"
00027 #include "llvm/ADT/SmallString.h"
00028 #include "llvm/ADT/StringExtras.h"
00029 using namespace llvm;
00030 
00031 //===----------------------------------------------------------------------===//
00032 //                              Generic Code
00033 //===----------------------------------------------------------------------===//
00034 
00035 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
00036   TextSection = 0;
00037   DataSection = 0;
00038   BSSSection = 0;
00039   ReadOnlySection = 0;
00040   StaticCtorSection = 0;
00041   StaticDtorSection = 0;
00042   LSDASection = 0;
00043   EHFrameSection = 0;
00044 
00045   DwarfAbbrevSection = 0;
00046   DwarfInfoSection = 0;
00047   DwarfLineSection = 0;
00048   DwarfFrameSection = 0;
00049   DwarfPubNamesSection = 0;
00050   DwarfPubTypesSection = 0;
00051   DwarfDebugInlineSection = 0;
00052   DwarfStrSection = 0;
00053   DwarfLocSection = 0;
00054   DwarfARangesSection = 0;
00055   DwarfRangesSection = 0;
00056   DwarfMacroInfoSection = 0;
00057 }
00058 
00059 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
00060 }
00061 
00062 static bool isSuitableForBSS(const GlobalVariable *GV) {
00063   Constant *C = GV->getInitializer();
00064   
00065   // Must have zero initializer.
00066   if (!C->isNullValue())
00067     return false;
00068   
00069   // Leave constant zeros in readonly constant sections, so they can be shared.
00070   if (GV->isConstant())
00071     return false;
00072   
00073   // If the global has an explicit section specified, don't put it in BSS.
00074   if (!GV->getSection().empty())
00075     return false;
00076   
00077   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
00078   if (NoZerosInBSS)
00079     return false;
00080   
00081   // Otherwise, put it in BSS!
00082   return true;
00083 }
00084 
00085 /// IsNullTerminatedString - Return true if the specified constant (which is
00086 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
00087 /// nul value and contains no other nuls in it.
00088 static bool IsNullTerminatedString(const Constant *C) {
00089   const ArrayType *ATy = cast<ArrayType>(C->getType());
00090   
00091   // First check: is we have constant array of i8 terminated with zero
00092   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
00093     if (ATy->getNumElements() == 0) return false;
00094 
00095     ConstantInt *Null =
00096       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
00097     if (Null == 0 || Null->getZExtValue() != 0)
00098       return false; // Not null terminated.
00099     
00100     // Verify that the null doesn't occur anywhere else in the string.
00101     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
00102       // Reject constantexpr elements etc.
00103       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
00104           CVA->getOperand(i) == Null)
00105         return false;
00106     return true;
00107   }
00108 
00109   // Another possibility: [1 x i8] zeroinitializer
00110   if (isa<ConstantAggregateZero>(C))
00111     return ATy->getNumElements() == 1;
00112 
00113   return false;
00114 }
00115 
00116 /// getKindForGlobal - This is a top-level target-independent classifier for
00117 /// a global variable.  Given an global variable and information from TM, it
00118 /// classifies the global in a variety of ways that make various target
00119 /// implementations simpler.  The target implementation is free to ignore this
00120 /// extra info of course.
00121 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
00122                                                        const TargetMachine &TM){
00123   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
00124          "Can only be used for global definitions");
00125   
00126   Reloc::Model ReloModel = TM.getRelocationModel();
00127   
00128   // Early exit - functions should be always in text sections.
00129   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00130   if (GVar == 0)
00131     return SectionKind::getText();
00132   
00133   // Handle thread-local data first.
00134   if (GVar->isThreadLocal()) {
00135     if (isSuitableForBSS(GVar))
00136       return SectionKind::getThreadBSS();
00137     return SectionKind::getThreadData();
00138   }
00139 
00140   // Variable can be easily put to BSS section.
00141   if (isSuitableForBSS(GVar))
00142     return SectionKind::getBSS();
00143 
00144   Constant *C = GVar->getInitializer();
00145   
00146   // If the global is marked constant, we can put it into a mergable section,
00147   // a mergable string section, or general .data if it contains relocations.
00148   if (GVar->isConstant()) {
00149     // If the initializer for the global contains something that requires a
00150     // relocation, then we may have to drop this into a wriable data section
00151     // even though it is marked const.
00152     switch (C->getRelocationInfo()) {
00153     default: llvm_unreachable("unknown relocation info kind");
00154     case Constant::NoRelocation:
00155       // If initializer is a null-terminated string, put it in a "cstring"
00156       // section of the right width.
00157       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
00158         if (const IntegerType *ITy = 
00159               dyn_cast<IntegerType>(ATy->getElementType())) {
00160           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
00161                ITy->getBitWidth() == 32) &&
00162               IsNullTerminatedString(C)) {
00163             if (ITy->getBitWidth() == 8)
00164               return SectionKind::getMergeable1ByteCString();
00165             if (ITy->getBitWidth() == 16)
00166               return SectionKind::getMergeable2ByteCString();
00167                                          
00168             assert(ITy->getBitWidth() == 32 && "Unknown width");
00169             return SectionKind::getMergeable4ByteCString();
00170           }
00171         }
00172       }
00173         
00174       // Otherwise, just drop it into a mergable constant section.  If we have
00175       // a section for this size, use it, otherwise use the arbitrary sized
00176       // mergable section.
00177       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
00178       case 4:  return SectionKind::getMergeableConst4();
00179       case 8:  return SectionKind::getMergeableConst8();
00180       case 16: return SectionKind::getMergeableConst16();
00181       default: return SectionKind::getMergeableConst();
00182       }
00183       
00184     case Constant::LocalRelocation:
00185       // In static relocation model, the linker will resolve all addresses, so
00186       // the relocation entries will actually be constants by the time the app
00187       // starts up.  However, we can't put this into a mergable section, because
00188       // the linker doesn't take relocations into consideration when it tries to
00189       // merge entries in the section.
00190       if (ReloModel == Reloc::Static)
00191         return SectionKind::getReadOnly();
00192               
00193       // Otherwise, the dynamic linker needs to fix it up, put it in the
00194       // writable data.rel.local section.
00195       return SectionKind::getReadOnlyWithRelLocal();
00196               
00197     case Constant::GlobalRelocations:
00198       // In static relocation model, the linker will resolve all addresses, so
00199       // the relocation entries will actually be constants by the time the app
00200       // starts up.  However, we can't put this into a mergable section, because
00201       // the linker doesn't take relocations into consideration when it tries to
00202       // merge entries in the section.
00203       if (ReloModel == Reloc::Static)
00204         return SectionKind::getReadOnly();
00205       
00206       // Otherwise, the dynamic linker needs to fix it up, put it in the
00207       // writable data.rel section.
00208       return SectionKind::getReadOnlyWithRel();
00209     }
00210   }
00211 
00212   // Okay, this isn't a constant.  If the initializer for the global is going
00213   // to require a runtime relocation by the dynamic linker, put it into a more
00214   // specific section to improve startup time of the app.  This coalesces these
00215   // globals together onto fewer pages, improving the locality of the dynamic
00216   // linker.
00217   if (ReloModel == Reloc::Static)
00218     return SectionKind::getDataNoRel();
00219 
00220   switch (C->getRelocationInfo()) {
00221   default: llvm_unreachable("unknown relocation info kind");
00222   case Constant::NoRelocation:
00223     return SectionKind::getDataNoRel();
00224   case Constant::LocalRelocation:
00225     return SectionKind::getDataRelLocal();
00226   case Constant::GlobalRelocations:
00227     return SectionKind::getDataRel();
00228   }
00229 }
00230 
00231 /// SectionForGlobal - This method computes the appropriate section to emit
00232 /// the specified global variable or function definition.  This should not
00233 /// be passed external (or available externally) globals.
00234 const MCSection *TargetLoweringObjectFile::
00235 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
00236                  const TargetMachine &TM) const {
00237   // Select section name.
00238   if (GV->hasSection())
00239     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
00240   
00241   
00242   // Use default section depending on the 'type' of global
00243   return SelectSectionForGlobal(GV, Kind, Mang, TM);
00244 }
00245 
00246 
00247 // Lame default implementation. Calculate the section name for global.
00248 const MCSection *
00249 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
00250                                                  SectionKind Kind,
00251                                                  Mangler *Mang,
00252                                                  const TargetMachine &TM) const{
00253   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
00254   
00255   if (Kind.isText())
00256     return getTextSection();
00257   
00258   if (Kind.isBSS() && BSSSection != 0)
00259     return BSSSection;
00260   
00261   if (Kind.isReadOnly() && ReadOnlySection != 0)
00262     return ReadOnlySection;
00263 
00264   return getDataSection();
00265 }
00266 
00267 /// getSectionForConstant - Given a mergable constant with the
00268 /// specified size and relocation information, return a section that it
00269 /// should be placed in.
00270 const MCSection *
00271 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
00272   if (Kind.isReadOnly() && ReadOnlySection != 0)
00273     return ReadOnlySection;
00274   
00275   return DataSection;
00276 }
00277 
00278 
00279 
00280 //===----------------------------------------------------------------------===//
00281 //                                  ELF
00282 //===----------------------------------------------------------------------===//
00283 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
00284 
00285 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
00286   // If we have the section uniquing map, free it.
00287   delete (ELFUniqueMapTy*)UniquingMap;
00288 }
00289 
00290 const MCSection *TargetLoweringObjectFileELF::
00291 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
00292               SectionKind Kind, bool IsExplicit) const {
00293   if (UniquingMap == 0)
00294     UniquingMap = new ELFUniqueMapTy();
00295   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
00296   
00297   // Do the lookup, if we have a hit, return it.
00298   const MCSectionELF *&Entry = Map[Section];
00299   if (Entry) return Entry;
00300   
00301   return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
00302                                       getContext());
00303 }
00304 
00305 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
00306                                              const TargetMachine &TM) {
00307   if (UniquingMap != 0)
00308     ((ELFUniqueMapTy*)UniquingMap)->clear();
00309   TargetLoweringObjectFile::Initialize(Ctx, TM);
00310 
00311   BSSSection = 
00312     getELFSection(".bss", MCSectionELF::SHT_NOBITS,
00313                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
00314                   SectionKind::getBSS());
00315     
00316   TextSection = 
00317     getELFSection(".text", MCSectionELF::SHT_PROGBITS,
00318                   MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
00319                   SectionKind::getText());
00320 
00321   DataSection = 
00322     getELFSection(".data", MCSectionELF::SHT_PROGBITS,
00323                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
00324                   SectionKind::getDataRel());
00325 
00326   ReadOnlySection = 
00327     getELFSection(".rodata", MCSectionELF::SHT_PROGBITS, 
00328                   MCSectionELF::SHF_ALLOC, 
00329                   SectionKind::getReadOnly());
00330 
00331   TLSDataSection = 
00332     getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
00333                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS | 
00334                   MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
00335   
00336   TLSBSSSection = 
00337     getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
00338                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
00339                   MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
00340 
00341   DataRelSection = 
00342     getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
00343                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00344                   SectionKind::getDataRel());
00345 
00346   DataRelLocalSection = 
00347     getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
00348                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00349                   SectionKind::getDataRelLocal());
00350 
00351   DataRelROSection = 
00352     getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
00353                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00354                   SectionKind::getReadOnlyWithRel());
00355 
00356   DataRelROLocalSection = 
00357     getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
00358                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00359                   SectionKind::getReadOnlyWithRelLocal());
00360     
00361   MergeableConst4Section = 
00362     getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
00363                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
00364                   SectionKind::getMergeableConst4());
00365 
00366   MergeableConst8Section = 
00367     getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
00368                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
00369                   SectionKind::getMergeableConst8());
00370 
00371   MergeableConst16Section = 
00372     getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
00373                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
00374                   SectionKind::getMergeableConst16());
00375 
00376   StaticCtorSection =
00377     getELFSection(".ctors", MCSectionELF::SHT_PROGBITS, 
00378                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00379                   SectionKind::getDataRel());
00380 
00381   StaticDtorSection =
00382     getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
00383                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00384                   SectionKind::getDataRel());
00385   
00386   // Exception Handling Sections.
00387   
00388   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
00389   // it contains relocatable pointers.  In PIC mode, this is probably a big
00390   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
00391   // adjusted or this should be a data section.
00392   LSDASection =
00393     getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
00394                   MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
00395   EHFrameSection =
00396     getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS, 
00397                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
00398                   SectionKind::getDataRel());
00399   
00400   // Debug Info Sections.
00401   DwarfAbbrevSection = 
00402     getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0, 
00403                   SectionKind::getMetadata());
00404   DwarfInfoSection = 
00405     getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0, 
00406                   SectionKind::getMetadata());
00407   DwarfLineSection = 
00408     getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0, 
00409                   SectionKind::getMetadata());
00410   DwarfFrameSection = 
00411     getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0, 
00412                   SectionKind::getMetadata());
00413   DwarfPubNamesSection = 
00414     getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0, 
00415                   SectionKind::getMetadata());
00416   DwarfPubTypesSection = 
00417     getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0, 
00418                   SectionKind::getMetadata());
00419   DwarfStrSection = 
00420     getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
00421                   SectionKind::getMetadata());
00422   DwarfLocSection = 
00423     getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0, 
00424                   SectionKind::getMetadata());
00425   DwarfARangesSection = 
00426     getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0, 
00427                   SectionKind::getMetadata());
00428   DwarfRangesSection = 
00429     getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0, 
00430                   SectionKind::getMetadata());
00431   DwarfMacroInfoSection = 
00432     getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0, 
00433                   SectionKind::getMetadata());
00434 }
00435 
00436 
00437 static SectionKind 
00438 getELFKindForNamedSection(const char *Name, SectionKind K) {
00439   if (Name[0] != '.') return K;
00440   
00441   // Some lame default implementation based on some magic section names.
00442   if (strcmp(Name, ".bss") == 0 ||
00443       strncmp(Name, ".bss.", 5) == 0 ||
00444       strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
00445       strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
00446       strcmp(Name, ".sbss") == 0 ||
00447       strncmp(Name, ".sbss.", 6) == 0 ||
00448       strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
00449       strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
00450     return SectionKind::getBSS();
00451   
00452   if (strcmp(Name, ".tdata") == 0 ||
00453       strncmp(Name, ".tdata.", 7) == 0 ||
00454       strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
00455       strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
00456     return SectionKind::getThreadData();
00457   
00458   if (strcmp(Name, ".tbss") == 0 ||
00459       strncmp(Name, ".tbss.", 6) == 0 ||
00460       strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
00461       strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
00462     return SectionKind::getThreadBSS();
00463   
00464   return K;
00465 }
00466 
00467 
00468 static unsigned
00469 getELFSectionType(const char *Name, SectionKind K) {
00470 
00471   if (strcmp(Name, ".init_array") == 0)
00472     return MCSectionELF::SHT_INIT_ARRAY;
00473 
00474   if (strcmp(Name, ".fini_array") == 0)
00475     return MCSectionELF::SHT_FINI_ARRAY;
00476 
00477   if (strcmp(Name, ".preinit_array") == 0)
00478     return MCSectionELF::SHT_PREINIT_ARRAY;
00479 
00480   if (K.isBSS() || K.isThreadBSS())
00481     return MCSectionELF::SHT_NOBITS;
00482 
00483   return MCSectionELF::SHT_PROGBITS;
00484 }
00485 
00486 
00487 static unsigned
00488 getELFSectionFlags(SectionKind K) {
00489   unsigned Flags = 0;
00490 
00491   if (!K.isMetadata())
00492     Flags |= MCSectionELF::SHF_ALLOC;
00493   
00494   if (K.isText())
00495     Flags |= MCSectionELF::SHF_EXECINSTR;
00496   
00497   if (K.isWriteable())
00498     Flags |= MCSectionELF::SHF_WRITE;
00499   
00500   if (K.isThreadLocal())
00501     Flags |= MCSectionELF::SHF_TLS;
00502   
00503   // K.isMergeableConst() is left out to honour PR4650
00504   if (K.isMergeableCString() || K.isMergeableConst4() ||
00505       K.isMergeableConst8() || K.isMergeableConst16())
00506     Flags |= MCSectionELF::SHF_MERGE;
00507 
00508   if (K.isMergeableCString())
00509     Flags |= MCSectionELF::SHF_STRINGS;
00510 
00511   return Flags;
00512 }
00513 
00514 
00515 const MCSection *TargetLoweringObjectFileELF::
00516 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
00517                          Mangler *Mang, const TargetMachine &TM) const {
00518   const char *SectionName = GV->getSection().c_str();
00519 
00520   // Infer section flags from the section name if we can.
00521   Kind = getELFKindForNamedSection(SectionName, Kind);
00522   
00523   return getELFSection(SectionName, 
00524                        getELFSectionType(SectionName, Kind), 
00525                        getELFSectionFlags(Kind), Kind, true);
00526 }
00527 
00528 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
00529   if (Kind.isText())                 return ".gnu.linkonce.t.";
00530   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
00531   
00532   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
00533   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
00534   
00535   if (Kind.isBSS())                  return ".gnu.linkonce.b.";
00536   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
00537   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
00538   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
00539   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
00540   
00541   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00542   return ".gnu.linkonce.d.rel.ro.";
00543 }
00544 
00545 const MCSection *TargetLoweringObjectFileELF::
00546 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00547                        Mangler *Mang, const TargetMachine &TM) const {
00548   
00549   // If this global is linkonce/weak and the target handles this by emitting it
00550   // into a 'uniqued' section name, create and return the section now.
00551   if (GV->isWeakForLinker()) {
00552     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
00553     std::string Name = Mang->makeNameProper(GV->getNameStr());
00554 
00555     return getELFSection((Prefix+Name).c_str(), 
00556                          getELFSectionType((Prefix+Name).c_str(), Kind), 
00557                          getELFSectionFlags(Kind), 
00558                          Kind);
00559   }
00560   
00561   if (Kind.isText()) return TextSection;
00562   
00563   if (Kind.isMergeable1ByteCString() ||
00564       Kind.isMergeable2ByteCString() ||
00565       Kind.isMergeable4ByteCString()) {
00566     
00567     // We also need alignment here.
00568     // FIXME: this is getting the alignment of the character, not the
00569     // alignment of the global!
00570     unsigned Align = 
00571       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
00572     
00573     const char *SizeSpec = ".rodata.str1.";
00574     if (Kind.isMergeable2ByteCString())
00575       SizeSpec = ".rodata.str2.";
00576     else if (Kind.isMergeable4ByteCString())
00577       SizeSpec = ".rodata.str4.";
00578     else
00579       assert(Kind.isMergeable1ByteCString() && "unknown string width");
00580     
00581     
00582     std::string Name = SizeSpec + utostr(Align);
00583     return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS, 
00584                          MCSectionELF::SHF_ALLOC | 
00585                          MCSectionELF::SHF_MERGE | 
00586                          MCSectionELF::SHF_STRINGS, 
00587                          Kind);
00588   }
00589   
00590   if (Kind.isMergeableConst()) {
00591     if (Kind.isMergeableConst4() && MergeableConst4Section)
00592       return MergeableConst4Section;
00593     if (Kind.isMergeableConst8() && MergeableConst8Section)
00594       return MergeableConst8Section;
00595     if (Kind.isMergeableConst16() && MergeableConst16Section)
00596       return MergeableConst16Section;
00597     return ReadOnlySection;  // .const
00598   }
00599   
00600   if (Kind.isReadOnly())             return ReadOnlySection;
00601   
00602   if (Kind.isThreadData())           return TLSDataSection;
00603   if (Kind.isThreadBSS())            return TLSBSSSection;
00604   
00605   if (Kind.isBSS())                  return BSSSection;
00606   
00607   if (Kind.isDataNoRel())            return DataSection;
00608   if (Kind.isDataRelLocal())         return DataRelLocalSection;
00609   if (Kind.isDataRel())              return DataRelSection;
00610   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00611   
00612   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00613   return DataRelROSection;
00614 }
00615 
00616 /// getSectionForConstant - Given a mergeable constant with the
00617 /// specified size and relocation information, return a section that it
00618 /// should be placed in.
00619 const MCSection *TargetLoweringObjectFileELF::
00620 getSectionForConstant(SectionKind Kind) const {
00621   if (Kind.isMergeableConst4() && MergeableConst4Section)
00622     return MergeableConst4Section;
00623   if (Kind.isMergeableConst8() && MergeableConst8Section)
00624     return MergeableConst8Section;
00625   if (Kind.isMergeableConst16() && MergeableConst16Section)
00626     return MergeableConst16Section;
00627   if (Kind.isReadOnly())
00628     return ReadOnlySection;
00629   
00630   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00631   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00632   return DataRelROSection;
00633 }
00634 
00635 //===----------------------------------------------------------------------===//
00636 //                                 MachO
00637 //===----------------------------------------------------------------------===//
00638 
00639 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
00640 
00641 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
00642   // If we have the MachO uniquing map, free it.
00643   delete (MachOUniqueMapTy*)UniquingMap;
00644 }
00645 
00646 
00647 const MCSectionMachO *TargetLoweringObjectFileMachO::
00648 getMachOSection(const StringRef &Segment, const StringRef &Section,
00649                 unsigned TypeAndAttributes,
00650                 unsigned Reserved2, SectionKind Kind) const {
00651   // We unique sections by their segment/section pair.  The returned section
00652   // may not have the same flags as the requested section, if so this should be
00653   // diagnosed by the client as an error.
00654   
00655   // Create the map if it doesn't already exist.
00656   if (UniquingMap == 0)
00657     UniquingMap = new MachOUniqueMapTy();
00658   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
00659   
00660   // Form the name to look up.
00661   SmallString<64> Name;
00662   Name.append(Segment.begin(), Segment.end());
00663   Name.push_back(',');
00664   Name.append(Section.begin(), Section.end());
00665   
00666   // Do the lookup, if we have a hit, return it.
00667   const MCSectionMachO *&Entry = Map[StringRef(Name.data(), Name.size())];
00668   if (Entry) return Entry;
00669 
00670   // Otherwise, return a new section.
00671   return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
00672                                         Reserved2, Kind, getContext());
00673 }
00674 
00675 
00676 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
00677                                                const TargetMachine &TM) {
00678   if (UniquingMap != 0)
00679     ((MachOUniqueMapTy*)UniquingMap)->clear();
00680   TargetLoweringObjectFile::Initialize(Ctx, TM);
00681   
00682   TextSection // .text
00683     = getMachOSection("__TEXT", "__text",
00684                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
00685                       SectionKind::getText());
00686   DataSection // .data
00687     = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
00688   
00689   CStringSection // .cstring
00690     = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
00691                       SectionKind::getMergeable1ByteCString());
00692   UStringSection
00693     = getMachOSection("__TEXT","__ustring", 0,
00694                       SectionKind::getMergeable2ByteCString());
00695   FourByteConstantSection // .literal4
00696     = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
00697                       SectionKind::getMergeableConst4());
00698   EightByteConstantSection // .literal8
00699     = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
00700                       SectionKind::getMergeableConst8());
00701   
00702   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
00703   // to using it in -static mode.
00704   SixteenByteConstantSection = 0;
00705   if (TM.getRelocationModel() != Reloc::Static &&
00706       TM.getTargetData()->getPointerSize() == 32)
00707     SixteenByteConstantSection =   // .literal16
00708       getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
00709                       SectionKind::getMergeableConst16());
00710   
00711   ReadOnlySection  // .const
00712     = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
00713   
00714   TextCoalSection
00715     = getMachOSection("__TEXT", "__textcoal_nt",
00716                       MCSectionMachO::S_COALESCED |
00717                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
00718                       SectionKind::getText());
00719   ConstTextCoalSection
00720     = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
00721                       SectionKind::getText());
00722   ConstDataCoalSection
00723     = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
00724                       SectionKind::getText());
00725   ConstDataSection  // .const_data
00726     = getMachOSection("__DATA", "__const", 0,
00727                       SectionKind::getReadOnlyWithRel());
00728   DataCoalSection
00729     = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
00730                       SectionKind::getDataRel());
00731 
00732   
00733   LazySymbolPointerSection
00734     = getMachOSection("__DATA", "__la_symbol_ptr",
00735                       MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
00736                       SectionKind::getMetadata());
00737   NonLazySymbolPointerSection
00738     = getMachOSection("__DATA", "__nl_symbol_ptr",
00739                       MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
00740                       SectionKind::getMetadata());
00741   
00742   if (TM.getRelocationModel() == Reloc::Static) {
00743     StaticCtorSection
00744       = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
00745     StaticDtorSection
00746       = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
00747   } else {
00748     StaticCtorSection
00749       = getMachOSection("__DATA", "__mod_init_func",
00750                         MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
00751                         SectionKind::getDataRel());
00752     StaticDtorSection
00753       = getMachOSection("__DATA", "__mod_term_func", 
00754                         MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
00755                         SectionKind::getDataRel());
00756   }
00757   
00758   // Exception Handling.
00759   LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
00760                                 SectionKind::getDataRel());
00761   EHFrameSection =
00762     getMachOSection("__TEXT", "__eh_frame",
00763                     MCSectionMachO::S_COALESCED |
00764                     MCSectionMachO::S_ATTR_NO_TOC |
00765                     MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
00766                     MCSectionMachO::S_ATTR_LIVE_SUPPORT,
00767                     SectionKind::getReadOnly());
00768 
00769   // Debug Information.
00770   DwarfAbbrevSection = 
00771     getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
00772                     SectionKind::getMetadata());
00773   DwarfInfoSection =  
00774     getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
00775                     SectionKind::getMetadata());
00776   DwarfLineSection =  
00777     getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
00778                     SectionKind::getMetadata());
00779   DwarfFrameSection =  
00780     getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
00781                     SectionKind::getMetadata());
00782   DwarfPubNamesSection =  
00783     getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
00784                     SectionKind::getMetadata());
00785   DwarfPubTypesSection =  
00786     getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
00787                     SectionKind::getMetadata());
00788   DwarfStrSection =  
00789     getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
00790                     SectionKind::getMetadata());
00791   DwarfLocSection =  
00792     getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
00793                     SectionKind::getMetadata());
00794   DwarfARangesSection =  
00795     getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
00796                     SectionKind::getMetadata());
00797   DwarfRangesSection =  
00798     getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
00799                     SectionKind::getMetadata());
00800   DwarfMacroInfoSection =  
00801     getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
00802                     SectionKind::getMetadata());
00803   DwarfDebugInlineSection = 
00804     getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
00805                     SectionKind::getMetadata());
00806 }
00807 
00808 const MCSection *TargetLoweringObjectFileMachO::
00809 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
00810                          Mangler *Mang, const TargetMachine &TM) const {
00811   // Parse the section specifier and create it if valid.
00812   StringRef Segment, Section;
00813   unsigned TAA, StubSize;
00814   std::string ErrorCode =
00815     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00816                                           TAA, StubSize);
00817   if (!ErrorCode.empty()) {
00818     // If invalid, report the error with llvm_report_error.
00819     llvm_report_error("Global variable '" + GV->getNameStr() +
00820                       "' has an invalid section specifier '" + GV->getSection()+
00821                       "': " + ErrorCode + ".");
00822     // Fall back to dropping it into the data section.
00823     return DataSection;
00824   }
00825   
00826   // Get the section.
00827   const MCSectionMachO *S =
00828     getMachOSection(Segment, Section, TAA, StubSize, Kind);
00829   
00830   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00831   // If the user declared multiple globals with different section flags, we need
00832   // to reject it here.
00833   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00834     // If invalid, report the error with llvm_report_error.
00835     llvm_report_error("Global variable '" + GV->getNameStr() +
00836                       "' section type or attributes does not match previous"
00837                       " section specifier");
00838   }
00839   
00840   return S;
00841 }
00842 
00843 const MCSection *TargetLoweringObjectFileMachO::
00844 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00845                        Mangler *Mang, const TargetMachine &TM) const {
00846   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
00847   
00848   if (Kind.isText())
00849     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00850   
00851   // If this is weak/linkonce, put this in a coalescable section, either in text
00852   // or data depending on if it is writable.
00853   if (GV->isWeakForLinker()) {
00854     if (Kind.isReadOnly())
00855       return ConstTextCoalSection;
00856     return DataCoalSection;
00857   }
00858   
00859   // FIXME: Alignment check should be handled by section classifier.
00860   if (Kind.isMergeable1ByteCString() ||
00861       Kind.isMergeable2ByteCString()) {
00862     if (TM.getTargetData()->getPreferredAlignment(
00863                                               cast<GlobalVariable>(GV)) < 32) {
00864       if (Kind.isMergeable1ByteCString())
00865         return CStringSection;
00866       assert(Kind.isMergeable2ByteCString());
00867       return UStringSection;
00868     }
00869   }
00870   
00871   if (Kind.isMergeableConst()) {
00872     if (Kind.isMergeableConst4())
00873       return FourByteConstantSection;
00874     if (Kind.isMergeableConst8())
00875       return EightByteConstantSection;
00876     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
00877       return SixteenByteConstantSection;
00878   }
00879 
00880   // Otherwise, if it is readonly, but not something we can specially optimize,
00881   // just drop it in .const.
00882   if (Kind.isReadOnly())
00883     return ReadOnlySection;
00884 
00885   // If this is marked const, put it into a const section.  But if the dynamic
00886   // linker needs to write to it, put it in the data segment.
00887   if (Kind.isReadOnlyWithRel())
00888     return ConstDataSection;
00889   
00890   // Otherwise, just drop the variable in the normal data section.
00891   return DataSection;
00892 }
00893 
00894 const MCSection *
00895 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
00896   // If this constant requires a relocation, we have to put it in the data
00897   // segment, not in the text segment.
00898   if (Kind.isDataRel())
00899     return ConstDataSection;
00900   
00901   if (Kind.isMergeableConst4())
00902     return FourByteConstantSection;
00903   if (Kind.isMergeableConst8())
00904     return EightByteConstantSection;
00905   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
00906     return SixteenByteConstantSection;
00907   return ReadOnlySection;  // .const
00908 }
00909 
00910 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
00911 /// not to emit the UsedDirective for some symbols in llvm.used.
00912 // FIXME: REMOVE this (rdar://7071300)
00913 bool TargetLoweringObjectFileMachO::
00914 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
00915   /// On Darwin, internally linked data beginning with "L" or "l" does not have
00916   /// the directive emitted (this occurs in ObjC metadata).
00917   if (!GV) return false;
00918     
00919   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
00920   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
00921     // FIXME: ObjC metadata is currently emitted as internal symbols that have
00922     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
00923     // this horrible hack can go away.
00924     const std::string &Name = Mang->getMangledName(GV);
00925     if (Name[0] == 'L' || Name[0] == 'l')
00926       return false;
00927   }
00928   
00929   return true;
00930 }
00931 
00932 
00933 //===----------------------------------------------------------------------===//
00934 //                                  COFF
00935 //===----------------------------------------------------------------------===//
00936 
00937 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
00938 
00939 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
00940   delete (COFFUniqueMapTy*)UniquingMap;
00941 }
00942 
00943 
00944 const MCSection *TargetLoweringObjectFileCOFF::
00945 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
00946   // Create the map if it doesn't already exist.
00947   if (UniquingMap == 0)
00948     UniquingMap = new MachOUniqueMapTy();
00949   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
00950   
00951   // Do the lookup, if we have a hit, return it.
00952   const MCSectionCOFF *&Entry = Map[Name];
00953   if (Entry) return Entry;
00954   
00955   return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
00956 }
00957 
00958 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
00959                                               const TargetMachine &TM) {
00960   if (UniquingMap != 0)
00961     ((COFFUniqueMapTy*)UniquingMap)->clear();
00962   TargetLoweringObjectFile::Initialize(Ctx, TM);
00963   TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
00964   DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
00965   StaticCtorSection =
00966     getCOFFSection(".ctors", false, SectionKind::getDataRel());
00967   StaticDtorSection =
00968     getCOFFSection(".dtors", false, SectionKind::getDataRel());
00969   
00970   // FIXME: We're emitting LSDA info into a readonly section on COFF, even
00971   // though it contains relocatable pointers.  In PIC mode, this is probably a
00972   // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
00973   // adjusted or this should be a data section.
00974   LSDASection =
00975     getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
00976   EHFrameSection =
00977     getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
00978   
00979   // Debug info.
00980   // FIXME: Don't use 'directive' mode here.
00981   DwarfAbbrevSection =  
00982     getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
00983                    true, SectionKind::getMetadata());
00984   DwarfInfoSection =    
00985     getCOFFSection("\t.section\t.debug_info,\"dr\"",
00986                    true, SectionKind::getMetadata());
00987   DwarfLineSection =    
00988     getCOFFSection("\t.section\t.debug_line,\"dr\"",
00989                    true, SectionKind::getMetadata());
00990   DwarfFrameSection =   
00991     getCOFFSection("\t.section\t.debug_frame,\"dr\"",
00992                    true, SectionKind::getMetadata());
00993   DwarfPubNamesSection =
00994     getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
00995                    true, SectionKind::getMetadata());
00996   DwarfPubTypesSection =
00997     getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
00998                    true, SectionKind::getMetadata());
00999   DwarfStrSection =     
01000     getCOFFSection("\t.section\t.debug_str,\"dr\"",
01001                    true, SectionKind::getMetadata());
01002   DwarfLocSection =     
01003     getCOFFSection("\t.section\t.debug_loc,\"dr\"",
01004                    true, SectionKind::getMetadata());
01005   DwarfARangesSection = 
01006     getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
01007                    true, SectionKind::getMetadata());
01008   DwarfRangesSection =  
01009     getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
01010                    true, SectionKind::getMetadata());
01011   DwarfMacroInfoSection = 
01012     getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
01013                    true, SectionKind::getMetadata());
01014 }
01015 
01016 const MCSection *TargetLoweringObjectFileCOFF::
01017 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
01018                          Mangler *Mang, const TargetMachine &TM) const {
01019   return getCOFFSection(GV->getSection().c_str(), false, Kind);
01020 }
01021 
01022 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
01023   if (Kind.isText())
01024     return ".text$linkonce";
01025   if (Kind.isWriteable())
01026     return ".data$linkonce";
01027   return ".rdata$linkonce";
01028 }
01029 
01030 
01031 const MCSection *TargetLoweringObjectFileCOFF::
01032 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
01033                        Mangler *Mang, const TargetMachine &TM) const {
01034   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
01035   
01036   // If this global is linkonce/weak and the target handles this by emitting it
01037   // into a 'uniqued' section name, create and return the section now.
01038   if (GV->isWeakForLinker()) {
01039     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
01040     std::string Name = Mang->makeNameProper(GV->getNameStr());
01041     return getCOFFSection((Prefix+Name).c_str(), false, Kind);
01042   }
01043   
01044   if (Kind.isText())
01045     return getTextSection();
01046   
01047   return getDataSection();
01048 }
01049