LCOV - code coverage report
Current view: top level - lib/Object - IRSymtab.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 140 142 98.6 %
Date: 2018-06-17 00:07:59 Functions: 15 15 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : 
      10             : #include "llvm/Object/IRSymtab.h"
      11             : #include "llvm/ADT/ArrayRef.h"
      12             : #include "llvm/ADT/DenseMap.h"
      13             : #include "llvm/ADT/SmallPtrSet.h"
      14             : #include "llvm/ADT/SmallString.h"
      15             : #include "llvm/ADT/SmallVector.h"
      16             : #include "llvm/ADT/StringRef.h"
      17             : #include "llvm/ADT/Triple.h"
      18             : #include "llvm/Config/llvm-config.h"
      19             : #include "llvm/IR/Comdat.h"
      20             : #include "llvm/IR/DataLayout.h"
      21             : #include "llvm/IR/GlobalAlias.h"
      22             : #include "llvm/IR/GlobalObject.h"
      23             : #include "llvm/IR/Mangler.h"
      24             : #include "llvm/IR/Metadata.h"
      25             : #include "llvm/IR/Module.h"
      26             : #include "llvm/Bitcode/BitcodeReader.h"
      27             : #include "llvm/MC/StringTableBuilder.h"
      28             : #include "llvm/Object/IRObjectFile.h"
      29             : #include "llvm/Object/ModuleSymbolTable.h"
      30             : #include "llvm/Object/SymbolicFile.h"
      31             : #include "llvm/Support/Allocator.h"
      32             : #include "llvm/Support/Casting.h"
      33             : #include "llvm/Support/Error.h"
      34             : #include "llvm/Support/StringSaver.h"
      35             : #include "llvm/Support/VCSRevision.h"
      36             : #include "llvm/Support/raw_ostream.h"
      37             : #include <cassert>
      38             : #include <string>
      39             : #include <utility>
      40             : #include <vector>
      41             : 
      42             : using namespace llvm;
      43             : using namespace irsymtab;
      44             : 
      45             : namespace {
      46             : 
      47             : const char *getExpectedProducerName() {
      48             :   static char DefaultName[] = LLVM_VERSION_STRING
      49             : #ifdef LLVM_REVISION
      50             :       " " LLVM_REVISION
      51             : #endif
      52             :       ;
      53             :   // Allows for testing of the irsymtab writer and upgrade mechanism. This
      54             :   // environment variable should not be set by users.
      55      101193 :   if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
      56             :     return OverrideName;
      57             :   return DefaultName;
      58             : }
      59             : 
      60      101193 : const char *kExpectedProducerName = getExpectedProducerName();
      61             : 
      62             : /// Stores the temporary state that is required to build an IR symbol table.
      63        8898 : struct Builder {
      64             :   SmallVector<char, 0> &Symtab;
      65             :   StringTableBuilder &StrtabBuilder;
      66             :   StringSaver Saver;
      67             : 
      68             :   // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
      69             :   // The StringTableBuilder does not create a copy of any strings added to it,
      70             :   // so this provides somewhere to store any strings that we create.
      71        4449 :   Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
      72             :           BumpPtrAllocator &Alloc)
      73       17796 :       : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
      74             : 
      75             :   DenseMap<const Comdat *, int> ComdatMap;
      76             :   Mangler Mang;
      77             :   Triple TT;
      78             : 
      79             :   std::vector<storage::Comdat> Comdats;
      80             :   std::vector<storage::Module> Mods;
      81             :   std::vector<storage::Symbol> Syms;
      82             :   std::vector<storage::Uncommon> Uncommons;
      83             : 
      84             :   std::string COFFLinkerOpts;
      85             :   raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
      86             : 
      87             :   void setStr(storage::Str &S, StringRef Value) {
      88       56451 :     S.Offset = StrtabBuilder.add(Value);
      89       54337 :     S.Size = Value.size();
      90             :   }
      91             : 
      92             :   template <typename T>
      93        9120 :   void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
      94       18240 :     R.Offset = Symtab.size();
      95       18240 :     R.Size = Objs.size();
      96       18240 :     Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
      97        9120 :                   reinterpret_cast<const char *>(Objs.data() + Objs.size()));
      98        9120 :   }
      99             : 
     100             :   Expected<int> getComdatIndex(const Comdat *C, const Module *M);
     101             : 
     102             :   Error addModule(Module *M);
     103             :   Error addSymbol(const ModuleSymbolTable &Msymtab,
     104             :                   const SmallPtrSet<GlobalValue *, 8> &Used,
     105             :                   ModuleSymbolTable::Symbol Sym);
     106             : 
     107             :   Error build(ArrayRef<Module *> Mods);
     108             : };
     109             : 
     110        4462 : Error Builder::addModule(Module *M) {
     111        4462 :   if (M->getDataLayoutStr().empty())
     112             :     return make_error<StringError>("input module has no datalayout",
     113        4314 :                                    inconvertibleErrorCode());
     114             : 
     115             :   SmallPtrSet<GlobalValue *, 8> Used;
     116        2305 :   collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
     117             : 
     118        4610 :   ModuleSymbolTable Msymtab;
     119        2305 :   Msymtab.addModule(M);
     120             : 
     121             :   storage::Module Mod;
     122        4610 :   Mod.Begin = Syms.size();
     123        2305 :   Mod.End = Syms.size() + Msymtab.symbols().size();
     124        4610 :   Mod.UncBegin = Uncommons.size();
     125        2305 :   Mods.push_back(Mod);
     126             : 
     127        2305 :   if (TT.isOSBinFormatCOFF()) {
     128         182 :     if (auto E = M->materializeMetadata())
     129             :       return E;
     130          91 :     if (NamedMDNode *LinkerOptions =
     131          91 :             M->getNamedMetadata("llvm.linker.options")) {
     132           6 :       for (MDNode *MDOptions : LinkerOptions->operands())
     133           9 :         for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
     134           6 :           COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
     135             :     }
     136             :   }
     137             : 
     138       38319 :   for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
     139       36038 :     if (Error Err = addSymbol(Msymtab, Used, Msym))
     140             :       return Err;
     141             : 
     142             :   return Error::success();
     143             : }
     144             : 
     145        2647 : Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
     146        5294 :   auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
     147        2647 :   if (P.second) {
     148             :     std::string Name;
     149        2011 :     if (TT.isOSBinFormatCOFF()) {
     150          20 :       const GlobalValue *GV = M->getNamedValue(C->getName());
     151          20 :       if (!GV)
     152             :         return make_error<StringError>("Could not find leader",
     153           0 :                                        inconvertibleErrorCode());
     154             :       // Internal leaders do not affect symbol resolution, therefore they do not
     155             :       // appear in the symbol table.
     156             :       if (GV->hasLocalLinkage()) {
     157           3 :         P.first->second = -1;
     158             :         return -1;
     159             :       }
     160          17 :       llvm::raw_string_ostream OS(Name);
     161          17 :       Mang.getNameWithPrefix(OS, GV, false);
     162             :     } else {
     163        5973 :       Name = C->getName();
     164             :     }
     165             : 
     166             :     storage::Comdat Comdat;
     167        4016 :     setStr(Comdat.Name, Saver.save(Name));
     168        2008 :     Comdats.push_back(Comdat);
     169             :   }
     170             : 
     171             :   return P.first->second;
     172             : }
     173             : 
     174       18019 : Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
     175             :                          const SmallPtrSet<GlobalValue *, 8> &Used,
     176             :                          ModuleSymbolTable::Symbol Msym) {
     177       18019 :   Syms.emplace_back();
     178             :   storage::Symbol &Sym = Syms.back();
     179       18019 :   Sym = {};
     180             : 
     181       18019 :   storage::Uncommon *Unc = nullptr;
     182        1058 :   auto Uncommon = [&]() -> storage::Uncommon & {
     183        3935 :     if (Unc)
     184             :       return *Unc;
     185         959 :     Sym.Flags |= 1 << storage::Symbol::FB_has_uncommon;
     186        1918 :     Uncommons.emplace_back();
     187         959 :     Unc = &Uncommons.back();
     188         959 :     *Unc = {};
     189         959 :     setStr(Unc->COFFWeakExternFallbackName, "");
     190         959 :     setStr(Unc->SectionName, "");
     191         959 :     return *Unc;
     192       18019 :   };
     193             : 
     194             :   SmallString<64> Name;
     195             :   {
     196             :     raw_svector_ostream OS(Name);
     197       18019 :     Msymtab.printSymbolName(OS, Msym);
     198             :   }
     199       36038 :   setStr(Sym.Name, Saver.save(StringRef(Name)));
     200             : 
     201       18019 :   auto Flags = Msymtab.getSymbolFlags(Msym);
     202       18019 :   if (Flags & object::BasicSymbolRef::SF_Undefined)
     203             :     Sym.Flags |= 1 << storage::Symbol::FB_undefined;
     204       18019 :   if (Flags & object::BasicSymbolRef::SF_Weak)
     205             :     Sym.Flags |= 1 << storage::Symbol::FB_weak;
     206       18019 :   if (Flags & object::BasicSymbolRef::SF_Common)
     207             :     Sym.Flags |= 1 << storage::Symbol::FB_common;
     208       18019 :   if (Flags & object::BasicSymbolRef::SF_Indirect)
     209             :     Sym.Flags |= 1 << storage::Symbol::FB_indirect;
     210       18019 :   if (Flags & object::BasicSymbolRef::SF_Global)
     211             :     Sym.Flags |= 1 << storage::Symbol::FB_global;
     212       18019 :   if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
     213             :     Sym.Flags |= 1 << storage::Symbol::FB_format_specific;
     214       18019 :   if (Flags & object::BasicSymbolRef::SF_Executable)
     215             :     Sym.Flags |= 1 << storage::Symbol::FB_executable;
     216             : 
     217             :   Sym.ComdatIndex = -1;
     218             :   auto *GV = Msym.dyn_cast<GlobalValue *>();
     219       17823 :   if (!GV) {
     220             :     // Undefined module asm symbols act as GC roots and are implicitly used.
     221         196 :     if (Flags & object::BasicSymbolRef::SF_Undefined)
     222             :       Sym.Flags |= 1 << storage::Symbol::FB_used;
     223         196 :     setStr(Sym.IRName, "");
     224             :     return Error::success();
     225             :   }
     226             : 
     227       17823 :   setStr(Sym.IRName, GV->getName());
     228             : 
     229       17823 :   if (Used.count(GV))
     230             :     Sym.Flags |= 1 << storage::Symbol::FB_used;
     231       17823 :   if (GV->isThreadLocal())
     232             :     Sym.Flags |= 1 << storage::Symbol::FB_tls;
     233       17823 :   if (GV->hasGlobalUnnamedAddr())
     234             :     Sym.Flags |= 1 << storage::Symbol::FB_unnamed_addr;
     235       17823 :   if (GV->canBeOmittedFromSymbolTable())
     236             :     Sym.Flags |= 1 << storage::Symbol::FB_may_omit;
     237             :   Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
     238             : 
     239       17823 :   if (Flags & object::BasicSymbolRef::SF_Common) {
     240         198 :     Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
     241             :         GV->getType()->getElementType());
     242          99 :     Uncommon().CommonAlign = GV->getAlignment();
     243             :   }
     244             : 
     245             :   const GlobalObject *Base = GV->getBaseObject();
     246       17823 :   if (!Base)
     247             :     return make_error<StringError>("Unable to determine comdat of alias!",
     248          20 :                                    inconvertibleErrorCode());
     249       17813 :   if (const Comdat *C = Base->getComdat()) {
     250        2647 :     Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
     251        2647 :     if (!ComdatIndexOrErr)
     252             :       return ComdatIndexOrErr.takeError();
     253        2647 :     Sym.ComdatIndex = *ComdatIndexOrErr;
     254             :   }
     255             : 
     256       17813 :   if (TT.isOSBinFormatCOFF()) {
     257         187 :     emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
     258             : 
     259         187 :     if ((Flags & object::BasicSymbolRef::SF_Weak) &&
     260             :         (Flags & object::BasicSymbolRef::SF_Indirect)) {
     261             :       auto *Fallback = dyn_cast<GlobalValue>(
     262             :           cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
     263             :       if (!Fallback)
     264             :         return make_error<StringError>("Invalid weak external",
     265           4 :                                        inconvertibleErrorCode());
     266             :       std::string FallbackName;
     267           2 :       raw_string_ostream OS(FallbackName);
     268           2 :       Msymtab.printSymbolName(OS, Fallback);
     269             :       OS.flush();
     270           2 :       setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
     271             :     }
     272             :   }
     273             : 
     274       17811 :   if (!Base->getSection().empty())
     275         858 :     setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
     276             : 
     277             :   return Error::success();
     278             : }
     279             : 
     280        4449 : Error Builder::build(ArrayRef<Module *> IRMods) {
     281             :   storage::Header Hdr;
     282             : 
     283             :   assert(!IRMods.empty());
     284             :   Hdr.Version = storage::Header::kCurrentVersion;
     285        8898 :   setStr(Hdr.Producer, kExpectedProducerName);
     286        8898 :   setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
     287        8898 :   setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
     288       13347 :   TT = Triple(IRMods[0]->getTargetTriple());
     289             : 
     290        9035 :   for (auto *M : IRMods)
     291        8924 :     if (Error Err = addModule(M))
     292             :       return Err;
     293             : 
     294        2280 :   COFFLinkerOptsOS.flush();
     295        4560 :   setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
     296             : 
     297             :   // We are about to fill in the header's range fields, so reserve space for it
     298             :   // and copy it in afterwards.
     299        2280 :   Symtab.resize(sizeof(storage::Header));
     300        2280 :   writeRange(Hdr.Modules, Mods);
     301        2280 :   writeRange(Hdr.Comdats, Comdats);
     302        2280 :   writeRange(Hdr.Symbols, Syms);
     303        2280 :   writeRange(Hdr.Uncommons, Uncommons);
     304             : 
     305        2280 :   *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
     306             :   return Error::success();
     307             : }
     308             : 
     309             : } // end anonymous namespace
     310             : 
     311        4449 : Error irsymtab::build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
     312             :                       StringTableBuilder &StrtabBuilder,
     313             :                       BumpPtrAllocator &Alloc) {
     314        4449 :   return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
     315             : }
     316             : 
     317             : // Upgrade a vector of bitcode modules created by an old version of LLVM by
     318             : // creating an irsymtab for them in the current format.
     319          22 : static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
     320          22 :   FileContents FC;
     321             : 
     322          44 :   LLVMContext Ctx;
     323             :   std::vector<Module *> Mods;
     324          22 :   std::vector<std::unique_ptr<Module>> OwnedMods;
     325          70 :   for (auto BM : BMs) {
     326             :     Expected<std::unique_ptr<Module>> MOrErr =
     327             :         BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
     328          48 :                          /*IsImporting*/ false);
     329          24 :     if (!MOrErr)
     330             :       return MOrErr.takeError();
     331             : 
     332          48 :     Mods.push_back(MOrErr->get());
     333             :     OwnedMods.push_back(std::move(*MOrErr));
     334             :   }
     335             : 
     336          44 :   StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
     337          22 :   BumpPtrAllocator Alloc;
     338          44 :   if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
     339             :     return std::move(E);
     340             : 
     341          18 :   StrtabBuilder.finalizeInOrder();
     342          18 :   FC.Strtab.resize(StrtabBuilder.getSize());
     343          18 :   StrtabBuilder.write((uint8_t *)FC.Strtab.data());
     344             : 
     345          36 :   FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
     346          18 :                   {FC.Strtab.data(), FC.Strtab.size()}};
     347             :   return std::move(FC);
     348             : }
     349             : 
     350         840 : Expected<FileContents> irsymtab::readBitcode(const BitcodeFileContents &BFC) {
     351         840 :   if (BFC.Mods.empty())
     352             :     return make_error<StringError>("Bitcode file does not contain any modules",
     353           2 :                                    inconvertibleErrorCode());
     354             : 
     355        1657 :   if (BFC.StrtabForSymtab.empty() ||
     356             :       BFC.Symtab.size() < sizeof(storage::Header))
     357          21 :     return upgrade(BFC.Mods);
     358             : 
     359             :   // We cannot use the regular reader to read the version and producer, because
     360             :   // it will expect the header to be in the current format. The only thing we
     361             :   // can rely on is that the version and producer will be present as the first
     362             :   // struct elements.
     363             :   auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
     364             :   unsigned Version = Hdr->Version;
     365         818 :   StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
     366         818 :   if (Version != storage::Header::kCurrentVersion ||
     367         818 :       Producer != kExpectedProducerName)
     368           1 :     return upgrade(BFC.Mods);
     369             : 
     370         817 :   FileContents FC;
     371         817 :   FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
     372             :                   {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
     373             : 
     374             :   // Finally, make sure that the number of modules in the symbol table matches
     375             :   // the number of modules in the bitcode file. If they differ, it may mean that
     376             :   // the bitcode file was created by binary concatenation, so we need to create
     377             :   // a new symbol table from scratch.
     378        1634 :   if (FC.TheReader.getNumModules() != BFC.Mods.size())
     379           0 :     return upgrade(std::move(BFC.Mods));
     380             : 
     381             :   return std::move(FC);
     382      202386 : }

Generated by: LCOV version 1.13