LLVM  8.0.0svn
IRSymtab.cpp
Go to the documentation of this file.
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"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/Error.h"
35 #include "llvm/Support/VCSRevision.h"
37 #include <cassert>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace irsymtab;
44 
45 static const char *LibcallRoutineNames[] = {
46 #define HANDLE_LIBCALL(code, name) name,
47 #include "llvm/IR/RuntimeLibcalls.def"
48 #undef HANDLE_LIBCALL
49 };
50 
51 namespace {
52 
53 const char *getExpectedProducerName() {
54  static char DefaultName[] = LLVM_VERSION_STRING
55 #ifdef LLVM_REVISION
56  " " LLVM_REVISION
57 #endif
58  ;
59  // Allows for testing of the irsymtab writer and upgrade mechanism. This
60  // environment variable should not be set by users.
61  if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
62  return OverrideName;
63  return DefaultName;
64 }
65 
66 const char *kExpectedProducerName = getExpectedProducerName();
67 
68 /// Stores the temporary state that is required to build an IR symbol table.
69 struct Builder {
70  SmallVector<char, 0> &Symtab;
71  StringTableBuilder &StrtabBuilder;
72  StringSaver Saver;
73 
74  // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
75  // The StringTableBuilder does not create a copy of any strings added to it,
76  // so this provides somewhere to store any strings that we create.
77  Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
78  BumpPtrAllocator &Alloc)
79  : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
80 
82  Mangler Mang;
83  Triple TT;
84 
85  std::vector<storage::Comdat> Comdats;
86  std::vector<storage::Module> Mods;
87  std::vector<storage::Symbol> Syms;
88  std::vector<storage::Uncommon> Uncommons;
89 
90  std::string COFFLinkerOpts;
91  raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
92 
93  void setStr(storage::Str &S, StringRef Value) {
94  S.Offset = StrtabBuilder.add(Value);
95  S.Size = Value.size();
96  }
97 
98  template <typename T>
99  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
100  R.Offset = Symtab.size();
101  R.Size = Objs.size();
102  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
103  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
104  }
105 
106  Expected<int> getComdatIndex(const Comdat *C, const Module *M);
107 
108  Error addModule(Module *M);
109  Error addSymbol(const ModuleSymbolTable &Msymtab,
110  const SmallPtrSet<GlobalValue *, 8> &Used,
112 
114 };
115 
116 Error Builder::addModule(Module *M) {
117  if (M->getDataLayoutStr().empty())
118  return make_error<StringError>("input module has no datalayout",
120 
122  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
123 
124  ModuleSymbolTable Msymtab;
125  Msymtab.addModule(M);
126 
128  Mod.Begin = Syms.size();
129  Mod.End = Syms.size() + Msymtab.symbols().size();
130  Mod.UncBegin = Uncommons.size();
131  Mods.push_back(Mod);
132 
133  if (TT.isOSBinFormatCOFF()) {
134  if (auto E = M->materializeMetadata())
135  return E;
136  if (NamedMDNode *LinkerOptions =
137  M->getNamedMetadata("llvm.linker.options")) {
138  for (MDNode *MDOptions : LinkerOptions->operands())
139  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
140  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
141  }
142  }
143 
144  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
145  if (Error Err = addSymbol(Msymtab, Used, Msym))
146  return Err;
147 
148  return Error::success();
149 }
150 
151 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
152  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
153  if (P.second) {
154  std::string Name;
155  if (TT.isOSBinFormatCOFF()) {
156  const GlobalValue *GV = M->getNamedValue(C->getName());
157  if (!GV)
158  return make_error<StringError>("Could not find leader",
160  // Internal leaders do not affect symbol resolution, therefore they do not
161  // appear in the symbol table.
162  if (GV->hasLocalLinkage()) {
163  P.first->second = -1;
164  return -1;
165  }
166  llvm::raw_string_ostream OS(Name);
167  Mang.getNameWithPrefix(OS, GV, false);
168  } else {
169  Name = C->getName();
170  }
171 
173  setStr(Comdat.Name, Saver.save(Name));
174  Comdats.push_back(Comdat);
175  }
176 
177  return P.first->second;
178 }
179 
180 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
181  const SmallPtrSet<GlobalValue *, 8> &Used,
183  Syms.emplace_back();
184  storage::Symbol &Sym = Syms.back();
185  Sym = {};
186 
187  storage::Uncommon *Unc = nullptr;
188  auto Uncommon = [&]() -> storage::Uncommon & {
189  if (Unc)
190  return *Unc;
192  Uncommons.emplace_back();
193  Unc = &Uncommons.back();
194  *Unc = {};
195  setStr(Unc->COFFWeakExternFallbackName, "");
196  setStr(Unc->SectionName, "");
197  return *Unc;
198  };
199 
201  {
202  raw_svector_ostream OS(Name);
203  Msymtab.printSymbolName(OS, Msym);
204  }
205  setStr(Sym.Name, Saver.save(StringRef(Name)));
206 
207  auto Flags = Msymtab.getSymbolFlags(Msym);
211  Sym.Flags |= 1 << storage::Symbol::FB_weak;
213  Sym.Flags |= 1 << storage::Symbol::FB_common;
217  Sym.Flags |= 1 << storage::Symbol::FB_global;
222 
223  Sym.ComdatIndex = -1;
224  auto *GV = Msym.dyn_cast<GlobalValue *>();
225  if (!GV) {
226  // Undefined module asm symbols act as GC roots and are implicitly used.
227  if (Flags & object::BasicSymbolRef::SF_Undefined)
228  Sym.Flags |= 1 << storage::Symbol::FB_used;
229  setStr(Sym.IRName, "");
230  return Error::success();
231  }
232 
233  setStr(Sym.IRName, GV->getName());
234 
235  bool IsBuiltinFunc = false;
236 
237  for (const char *LibcallName : LibcallRoutineNames)
238  if (GV->getName() == LibcallName)
239  IsBuiltinFunc = true;
240 
241  if (Used.count(GV) || IsBuiltinFunc)
242  Sym.Flags |= 1 << storage::Symbol::FB_used;
243  if (GV->isThreadLocal())
244  Sym.Flags |= 1 << storage::Symbol::FB_tls;
245  if (GV->hasGlobalUnnamedAddr())
247  if (GV->canBeOmittedFromSymbolTable())
249  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
250 
251  if (Flags & object::BasicSymbolRef::SF_Common) {
252  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
253  GV->getType()->getElementType());
254  Uncommon().CommonAlign = GV->getAlignment();
255  }
256 
257  const GlobalObject *Base = GV->getBaseObject();
258  if (!Base)
259  return make_error<StringError>("Unable to determine comdat of alias!",
261  if (const Comdat *C = Base->getComdat()) {
262  Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
263  if (!ComdatIndexOrErr)
264  return ComdatIndexOrErr.takeError();
265  Sym.ComdatIndex = *ComdatIndexOrErr;
266  }
267 
268  if (TT.isOSBinFormatCOFF()) {
269  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
270 
271  if ((Flags & object::BasicSymbolRef::SF_Weak) &&
272  (Flags & object::BasicSymbolRef::SF_Indirect)) {
273  auto *Fallback = dyn_cast<GlobalValue>(
274  cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
275  if (!Fallback)
276  return make_error<StringError>("Invalid weak external",
278  std::string FallbackName;
279  raw_string_ostream OS(FallbackName);
280  Msymtab.printSymbolName(OS, Fallback);
281  OS.flush();
282  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
283  }
284  }
285 
286  if (!Base->getSection().empty())
287  setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
288 
289  return Error::success();
290 }
291 
293  storage::Header Hdr;
294 
295  assert(!IRMods.empty());
297  setStr(Hdr.Producer, kExpectedProducerName);
298  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
299  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
300  TT = Triple(IRMods[0]->getTargetTriple());
301 
302  for (auto *M : IRMods)
303  if (Error Err = addModule(M))
304  return Err;
305 
306  COFFLinkerOptsOS.flush();
307  setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
308 
309  // We are about to fill in the header's range fields, so reserve space for it
310  // and copy it in afterwards.
311  Symtab.resize(sizeof(storage::Header));
312  writeRange(Hdr.Modules, Mods);
313  writeRange(Hdr.Comdats, Comdats);
314  writeRange(Hdr.Symbols, Syms);
315  writeRange(Hdr.Uncommons, Uncommons);
316 
317  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
318  return Error::success();
319 }
320 
321 } // end anonymous namespace
322 
324  StringTableBuilder &StrtabBuilder,
325  BumpPtrAllocator &Alloc) {
326  return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
327 }
328 
329 // Upgrade a vector of bitcode modules created by an old version of LLVM by
330 // creating an irsymtab for them in the current format.
333 
334  LLVMContext Ctx;
335  std::vector<Module *> Mods;
336  std::vector<std::unique_ptr<Module>> OwnedMods;
337  for (auto BM : BMs) {
339  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
340  /*IsImporting*/ false);
341  if (!MOrErr)
342  return MOrErr.takeError();
343 
344  Mods.push_back(MOrErr->get());
345  OwnedMods.push_back(std::move(*MOrErr));
346  }
347 
349  BumpPtrAllocator Alloc;
350  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
351  return std::move(E);
352 
353  StrtabBuilder.finalizeInOrder();
354  FC.Strtab.resize(StrtabBuilder.getSize());
355  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
356 
357  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
358  {FC.Strtab.data(), FC.Strtab.size()}};
359  return std::move(FC);
360 }
361 
363  if (BFC.Mods.empty())
364  return make_error<StringError>("Bitcode file does not contain any modules",
366 
367  if (BFC.StrtabForSymtab.empty() ||
368  BFC.Symtab.size() < sizeof(storage::Header))
369  return upgrade(BFC.Mods);
370 
371  // We cannot use the regular reader to read the version and producer, because
372  // it will expect the header to be in the current format. The only thing we
373  // can rely on is that the version and producer will be present as the first
374  // struct elements.
375  auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
376  unsigned Version = Hdr->Version;
377  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
378  if (Version != storage::Header::kCurrentVersion ||
379  Producer != kExpectedProducerName)
380  return upgrade(BFC.Mods);
381 
383  FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
384  {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
385 
386  // Finally, make sure that the number of modules in the symbol table matches
387  // the number of modules in the bitcode file. If they differ, it may mean that
388  // the bitcode file was created by binary concatenation, so we need to create
389  // a new symbol table from scratch.
390  if (FC.TheReader.getNumModules() != BFC.Mods.size())
391  return upgrade(std::move(BFC.Mods));
392 
393  return std::move(FC);
394 }
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:90
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:709
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
uint32_t getSymbolFlags(Symbol S) const
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:331
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
Definition: IRSymtab.h:87
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
This file contains the declarations for metadata subclasses.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Word ComdatIndex
The index into Header::Comdats, or -1 if not a comdat member.
Definition: IRSymtab.h:96
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:510
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:229
Metadata node.
Definition: Metadata.h:862
Str SectionName
Specified section name, if any.
Definition: IRSymtab.h:126
Error takeError()
Take ownership of the stored error.
Definition: Error.h:553
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Definition: IRSymtab.h:93
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
A reference to a range of objects in the symbol table.
Definition: IRSymtab.h:63
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
A tuple of MDNodes.
Definition: Metadata.h:1324
size_t getNumModules() const
Definition: IRSymtab.h:264
The contents of the irsymtab in a bitcode file.
Definition: IRSymtab.h:347
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
void write(raw_ostream &OS) const
Utility for building string tables with deduplicated suffixes.
op_range operands() const
Definition: Metadata.h:1065
size_t add(CachedHashStringRef S)
Add a string to the builder.
SmallVector< char, 0 > Symtab
Definition: IRSymtab.h:348
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:244
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:112
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
A reference to a string in the string table.
Definition: IRSymtab.h:54
Error build(ArrayRef< Module *> Mods, SmallVector< char, 0 > &Symtab, StringTableBuilder &StrtabBuilder, BumpPtrAllocator &Alloc)
Fills in Symtab and StrtabBuilder with a valid symbol and string table for Mods.
Definition: IRSymtab.cpp:323
#define P(N)
Describes the range of a particular module&#39;s symbols within the symbol table.
Definition: IRSymtab.h:73
StringRef getName() const
Definition: Comdat.cpp:27
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:133
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void finalizeInOrder()
Finalize the string table without reording it.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:141
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition: IRSymtab.h:150
Str Name
The mangled symbol name.
Definition: IRSymtab.h:89
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:185
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol...
Definition: IRSymtab.h:118
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
Definition: PointerUnion.h:142
SmallVector< char, 0 > Strtab
Definition: IRSymtab.h:348
size_t size() const
Definition: SmallVector.h:53
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static ErrorSuccess success()
Create a success value.
Definition: Error.h:327
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallPtrSetImpl< GlobalValue *> &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:531
Range< Uncommon > Uncommons
Definition: IRSymtab.h:145
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
Module.h This file contains the declarations for the Module class.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:533
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:362
The access may modify the value stored in memory.
void printSymbolName(raw_ostream &OS, Symbol S) const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:478
Str Producer
The producer&#39;s version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition: IRSymtab.h:140
const Comdat * getComdat() const
Definition: GlobalObject.h:101
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
Definition: StringSaver.h:22
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:149
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:483
LLVM Value Representation.
Definition: Value.h:73
This is equivalent to an IR comdat.
Definition: IRSymtab.h:81
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Word UncBegin
The index of the first Uncommon for this Module.
Definition: IRSymtab.h:77
const uint64_t Version
Definition: InstrProf.h:895
llvm::Error materializeMetadata()
Definition: Module.cpp:402
std::vector< BitcodeModule > Mods
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87
static const char * LibcallRoutineNames[]
Definition: IRSymtab.cpp:45
void resize(size_type N)
Definition: SmallVector.h:351
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:123