LCOV - code coverage report
Current view: top level - lib/Object - IRSymtab.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 170 173 98.3 %
Date: 2017-09-14 15:23:50 Functions: 14 14 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/Analysis/ObjectUtils.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       72330 :   if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
      56             :     return OverrideName;
      57             :   return DefaultName;
      58             : }
      59             : 
      60       72330 : const char *kExpectedProducerName = getExpectedProducerName();
      61             : 
      62             : /// Stores the temporary state that is required to build an IR symbol table.
      63       32436 : 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        3604 :   Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
      72             :           BumpPtrAllocator &Alloc)
      73       39644 :       : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
      74             : 
      75             :   DenseMap<const Comdat *, unsigned> 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       62216 :     S.Offset = StrtabBuilder.add(Value);
      89       62216 :     S.Size = Value.size();
      90             :   }
      91             : 
      92             :   template <typename T>
      93        6764 :   void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
      94       20292 :     R.Offset = Symtab.size();
      95       20292 :     R.Size = Objs.size();
      96       27056 :     Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
      97       13528 :                   reinterpret_cast<const char *>(Objs.data() + Objs.size()));
      98        6764 :   }
      99             : 
     100             :   Error addModule(Module *M);
     101             :   Error addSymbol(const ModuleSymbolTable &Msymtab,
     102             :                   const SmallPtrSet<GlobalValue *, 8> &Used,
     103             :                   ModuleSymbolTable::Symbol Sym);
     104             : 
     105             :   Error build(ArrayRef<Module *> Mods);
     106             : };
     107             : 
     108        3615 : Error Builder::addModule(Module *M) {
     109        3615 :   if (M->getDataLayoutStr().empty())
     110             :     return make_error<StringError>("input module has no datalayout",
     111        3802 :                                    inconvertibleErrorCode());
     112             : 
     113        1714 :   SmallPtrSet<GlobalValue *, 8> Used;
     114        1714 :   collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
     115             : 
     116        3428 :   ModuleSymbolTable Msymtab;
     117        1714 :   Msymtab.addModule(M);
     118             : 
     119             :   storage::Module Mod;
     120        5142 :   Mod.Begin = Syms.size();
     121        5142 :   Mod.End = Syms.size() + Msymtab.symbols().size();
     122        5142 :   Mod.UncBegin = Uncommons.size();
     123        1714 :   Mods.push_back(Mod);
     124             : 
     125        3428 :   if (TT.isOSBinFormatCOFF()) {
     126         219 :     if (auto E = M->materializeMetadata())
     127           0 :       return E;
     128          73 :     if (NamedMDNode *LinkerOptions =
     129          73 :             M->getNamedMetadata("llvm.linker.options")) {
     130           6 :       for (MDNode *MDOptions : LinkerOptions->operands())
     131           9 :         for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
     132           6 :           COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
     133             :     }
     134             :   }
     135             : 
     136       11760 :   for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
     137       25020 :     if (Error Err = addSymbol(Msymtab, Used, Msym))
     138          24 :       return Err;
     139             : 
     140        5106 :   return Error::success();
     141             : }
     142             : 
     143        8344 : Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
     144             :                          const SmallPtrSet<GlobalValue *, 8> &Used,
     145             :                          ModuleSymbolTable::Symbol Msym) {
     146        8344 :   Syms.emplace_back();
     147       16688 :   storage::Symbol &Sym = Syms.back();
     148        8344 :   Sym = {};
     149             : 
     150        8344 :   storage::Uncommon *Unc = nullptr;
     151         623 :   auto Uncommon = [&]() -> storage::Uncommon & {
     152        2204 :     if (Unc)
     153             :       return *Unc;
     154        1054 :     Sym.Flags |= 1 << storage::Symbol::FB_has_uncommon;
     155        1581 :     Uncommons.emplace_back();
     156        1054 :     Unc = &Uncommons.back();
     157         527 :     *Unc = {};
     158        1054 :     setStr(Unc->COFFWeakExternFallbackName, "");
     159        1581 :     setStr(Unc->SectionName, "");
     160         527 :     return *Unc;
     161        8344 :   };
     162             : 
     163       16688 :   SmallString<64> Name;
     164             :   {
     165       16688 :     raw_svector_ostream OS(Name);
     166        8344 :     Msymtab.printSymbolName(OS, Msym);
     167             :   }
     168       25032 :   setStr(Sym.Name, Saver.save(StringRef(Name)));
     169             : 
     170        8344 :   auto Flags = Msymtab.getSymbolFlags(Msym);
     171        8344 :   if (Flags & object::BasicSymbolRef::SF_Undefined)
     172        1876 :     Sym.Flags |= 1 << storage::Symbol::FB_undefined;
     173        8344 :   if (Flags & object::BasicSymbolRef::SF_Weak)
     174         824 :     Sym.Flags |= 1 << storage::Symbol::FB_weak;
     175        8344 :   if (Flags & object::BasicSymbolRef::SF_Common)
     176          96 :     Sym.Flags |= 1 << storage::Symbol::FB_common;
     177        8344 :   if (Flags & object::BasicSymbolRef::SF_Indirect)
     178         256 :     Sym.Flags |= 1 << storage::Symbol::FB_indirect;
     179        8344 :   if (Flags & object::BasicSymbolRef::SF_Global)
     180        5831 :     Sym.Flags |= 1 << storage::Symbol::FB_global;
     181        8344 :   if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
     182        1243 :     Sym.Flags |= 1 << storage::Symbol::FB_format_specific;
     183        8344 :   if (Flags & object::BasicSymbolRef::SF_Executable)
     184        5172 :     Sym.Flags |= 1 << storage::Symbol::FB_executable;
     185             : 
     186       16688 :   Sym.ComdatIndex = -1;
     187        8152 :   auto *GV = Msym.dyn_cast<GlobalValue *>();
     188        8152 :   if (!GV) {
     189             :     // Undefined module asm symbols act as GC roots and are implicitly used.
     190         192 :     if (Flags & object::BasicSymbolRef::SF_Undefined)
     191          61 :       Sym.Flags |= 1 << storage::Symbol::FB_used;
     192         384 :     setStr(Sym.IRName, "");
     193         576 :     return Error::success();
     194             :   }
     195             : 
     196       16304 :   setStr(Sym.IRName, GV->getName());
     197             : 
     198        8152 :   if (Used.count(GV))
     199          19 :     Sym.Flags |= 1 << storage::Symbol::FB_used;
     200        8152 :   if (GV->isThreadLocal())
     201           7 :     Sym.Flags |= 1 << storage::Symbol::FB_tls;
     202        8152 :   if (GV->hasGlobalUnnamedAddr())
     203        1315 :     Sym.Flags |= 1 << storage::Symbol::FB_unnamed_addr;
     204         177 :   if (canBeOmittedFromSymbolTable(GV))
     205         205 :     Sym.Flags |= 1 << storage::Symbol::FB_may_omit;
     206       16304 :   Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
     207             : 
     208        8152 :   if (Flags & object::BasicSymbolRef::SF_Common) {
     209         288 :     Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
     210             :         GV->getType()->getElementType());
     211          96 :     Uncommon().CommonAlign = GV->getAlignment();
     212             :   }
     213             : 
     214        8152 :   const GlobalObject *Base = GV->getBaseObject();
     215        8152 :   if (!Base)
     216             :     return make_error<StringError>("Unable to determine comdat of alias!",
     217          20 :                                    inconvertibleErrorCode());
     218        8142 :   if (const Comdat *C = Base->getComdat()) {
     219        3880 :     auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
     220        1552 :     Sym.ComdatIndex = P.first->second;
     221             : 
     222         776 :     if (P.second) {
     223             :       storage::Comdat Comdat;
     224         864 :       setStr(Comdat.Name, C->getName());
     225         432 :       Comdats.push_back(Comdat);
     226             :     }
     227             :   }
     228             : 
     229       16284 :   if (TT.isOSBinFormatCOFF()) {
     230         166 :     emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
     231             : 
     232         166 :     if ((Flags & object::BasicSymbolRef::SF_Weak) &&
     233             :         (Flags & object::BasicSymbolRef::SF_Indirect)) {
     234          12 :       auto *Fallback = dyn_cast<GlobalValue>(
     235           2 :           cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
     236             :       if (!Fallback)
     237             :         return make_error<StringError>("Invalid weak external",
     238           4 :                                        inconvertibleErrorCode());
     239           4 :       std::string FallbackName;
     240           4 :       raw_string_ostream OS(FallbackName);
     241           2 :       Msymtab.printSymbolName(OS, Fallback);
     242           2 :       OS.flush();
     243           6 :       setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
     244             :     }
     245             :   }
     246             : 
     247        8140 :   if (!Base->getSection().empty())
     248         858 :     setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
     249             : 
     250       24420 :   return Error::success();
     251             : }
     252             : 
     253        3604 : Error Builder::build(ArrayRef<Module *> IRMods) {
     254             :   storage::Header Hdr;
     255             : 
     256             :   assert(!IRMods.empty());
     257        3604 :   Hdr.Version = storage::Header::kCurrentVersion;
     258       10812 :   setStr(Hdr.Producer, kExpectedProducerName);
     259       14416 :   setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
     260       14416 :   setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
     261       18020 :   TT = Triple(IRMods[0]->getTargetTriple());
     262             : 
     263        8910 :   for (auto *M : IRMods)
     264        8932 :     if (Error Err = addModule(M))
     265        3826 :       return Err;
     266             : 
     267        3382 :   COFFLinkerOptsOS.flush();
     268        5073 :   setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
     269             : 
     270             :   // We are about to fill in the header's range fields, so reserve space for it
     271             :   // and copy it in afterwards.
     272        1691 :   Symtab.resize(sizeof(storage::Header));
     273        1691 :   writeRange(Hdr.Modules, Mods);
     274        1691 :   writeRange(Hdr.Comdats, Comdats);
     275        1691 :   writeRange(Hdr.Symbols, Syms);
     276        1691 :   writeRange(Hdr.Uncommons, Uncommons);
     277             : 
     278        3382 :   *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
     279        5073 :   return Error::success();
     280             : }
     281             : 
     282             : } // end anonymous namespace
     283             : 
     284        3604 : Error irsymtab::build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
     285             :                       StringTableBuilder &StrtabBuilder,
     286             :                       BumpPtrAllocator &Alloc) {
     287        3604 :   return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
     288             : }
     289             : 
     290             : // Upgrade a vector of bitcode modules created by an old version of LLVM by
     291             : // creating an irsymtab for them in the current format.
     292          20 : static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
     293          40 :   FileContents FC;
     294             : 
     295          40 :   LLVMContext Ctx;
     296          40 :   std::vector<Module *> Mods;
     297          40 :   std::vector<std::unique_ptr<Module>> OwnedMods;
     298          62 :   for (auto BM : BMs) {
     299             :     Expected<std::unique_ptr<Module>> MOrErr =
     300             :         BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
     301          44 :                          /*IsImporting*/ false);
     302          22 :     if (!MOrErr)
     303           0 :       return MOrErr.takeError();
     304             : 
     305          66 :     Mods.push_back(MOrErr->get());
     306          44 :     OwnedMods.push_back(std::move(*MOrErr));
     307             :   }
     308             : 
     309          40 :   StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
     310          40 :   BumpPtrAllocator Alloc;
     311          56 :   if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
     312          16 :     return std::move(E);
     313             : 
     314          16 :   StrtabBuilder.finalizeInOrder();
     315          16 :   FC.Strtab.resize(StrtabBuilder.getSize());
     316          32 :   StrtabBuilder.write((uint8_t *)FC.Strtab.data());
     317             : 
     318          96 :   FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
     319          32 :                   {FC.Strtab.data(), FC.Strtab.size()}};
     320          16 :   return std::move(FC);
     321             : }
     322             : 
     323         669 : Expected<FileContents> irsymtab::readBitcode(const BitcodeFileContents &BFC) {
     324        1338 :   if (BFC.Mods.empty())
     325           2 :     return make_error<StringError>("Bitcode file does not contain any modules",
     326           3 :                                    inconvertibleErrorCode());
     327             : 
     328        1985 :   if (BFC.StrtabForSymtab.empty() ||
     329        1298 :       BFC.Symtab.size() < sizeof(storage::Header))
     330          38 :     return upgrade(BFC.Mods);
     331             : 
     332             :   // We cannot use the regular reader to read the version and producer, because
     333             :   // it will expect the header to be in the current format. The only thing we
     334             :   // can rely on is that the version and producer will be present as the first
     335             :   // struct elements.
     336        1298 :   auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
     337        1298 :   unsigned Version = Hdr->Version;
     338        1298 :   StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
     339         649 :   if (Version != storage::Header::kCurrentVersion ||
     340        1298 :       Producer != kExpectedProducerName)
     341           2 :     return upgrade(BFC.Mods);
     342             : 
     343        1296 :   FileContents FC;
     344        1944 :   FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
     345             :                   {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
     346             : 
     347             :   // Finally, make sure that the number of modules in the symbol table matches
     348             :   // the number of modules in the bitcode file. If they differ, it may mean that
     349             :   // the bitcode file was created by binary concatenation, so we need to create
     350             :   // a new symbol table from scratch.
     351        1296 :   if (FC.TheReader.getNumModules() != BFC.Mods.size())
     352           0 :     return upgrade(std::move(BFC.Mods));
     353             : 
     354         648 :   return std::move(FC);
     355      144660 : }

Generated by: LCOV version 1.13