LLVM  6.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"
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 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  if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
56  return OverrideName;
57  return DefaultName;
58 }
59 
60 const char *kExpectedProducerName = getExpectedProducerName();
61 
62 /// Stores the temporary state that is required to build an IR symbol table.
63 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  Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
72  BumpPtrAllocator &Alloc)
73  : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
74 
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  S.Offset = StrtabBuilder.add(Value);
89  S.Size = Value.size();
90  }
91 
92  template <typename T>
93  void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
94  R.Offset = Symtab.size();
95  R.Size = Objs.size();
96  Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
97  reinterpret_cast<const char *>(Objs.data() + Objs.size()));
98  }
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,
106 
108 };
109 
110 Error Builder::addModule(Module *M) {
111  if (M->getDataLayoutStr().empty())
112  return make_error<StringError>("input module has no datalayout",
114 
116  collectUsedGlobalVariables(*M, Used, /*CompilerUsed*/ false);
117 
118  ModuleSymbolTable Msymtab;
119  Msymtab.addModule(M);
120 
121  storage::Module Mod;
122  Mod.Begin = Syms.size();
123  Mod.End = Syms.size() + Msymtab.symbols().size();
124  Mod.UncBegin = Uncommons.size();
125  Mods.push_back(Mod);
126 
127  if (TT.isOSBinFormatCOFF()) {
128  if (auto E = M->materializeMetadata())
129  return E;
130  if (NamedMDNode *LinkerOptions =
131  M->getNamedMetadata("llvm.linker.options")) {
132  for (MDNode *MDOptions : LinkerOptions->operands())
133  for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
134  COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
135  }
136  }
137 
138  for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
139  if (Error Err = addSymbol(Msymtab, Used, Msym))
140  return Err;
141 
142  return Error::success();
143 }
144 
145 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
146  auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
147  if (P.second) {
148  std::string Name;
149  if (TT.isOSBinFormatCOFF()) {
150  const GlobalValue *GV = M->getNamedValue(C->getName());
151  if (!GV)
152  return make_error<StringError>("Could not find leader",
154  // Internal leaders do not affect symbol resolution, therefore they do not
155  // appear in the symbol table.
156  if (GV->hasLocalLinkage()) {
157  P.first->second = -1;
158  return -1;
159  }
160  llvm::raw_string_ostream OS(Name);
161  Mang.getNameWithPrefix(OS, GV, false);
162  } else {
163  Name = C->getName();
164  }
165 
167  setStr(Comdat.Name, Saver.save(Name));
168  Comdats.push_back(Comdat);
169  }
170 
171  return P.first->second;
172 }
173 
174 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
175  const SmallPtrSet<GlobalValue *, 8> &Used,
177  Syms.emplace_back();
178  storage::Symbol &Sym = Syms.back();
179  Sym = {};
180 
181  storage::Uncommon *Unc = nullptr;
182  auto Uncommon = [&]() -> storage::Uncommon & {
183  if (Unc)
184  return *Unc;
186  Uncommons.emplace_back();
187  Unc = &Uncommons.back();
188  *Unc = {};
189  setStr(Unc->COFFWeakExternFallbackName, "");
190  setStr(Unc->SectionName, "");
191  return *Unc;
192  };
193 
195  {
196  raw_svector_ostream OS(Name);
197  Msymtab.printSymbolName(OS, Msym);
198  }
199  setStr(Sym.Name, Saver.save(StringRef(Name)));
200 
201  auto Flags = Msymtab.getSymbolFlags(Msym);
205  Sym.Flags |= 1 << storage::Symbol::FB_weak;
207  Sym.Flags |= 1 << storage::Symbol::FB_common;
211  Sym.Flags |= 1 << storage::Symbol::FB_global;
216 
217  Sym.ComdatIndex = -1;
218  auto *GV = Msym.dyn_cast<GlobalValue *>();
219  if (!GV) {
220  // Undefined module asm symbols act as GC roots and are implicitly used.
221  if (Flags & object::BasicSymbolRef::SF_Undefined)
222  Sym.Flags |= 1 << storage::Symbol::FB_used;
223  setStr(Sym.IRName, "");
224  return Error::success();
225  }
226 
227  setStr(Sym.IRName, GV->getName());
228 
229  if (Used.count(GV))
230  Sym.Flags |= 1 << storage::Symbol::FB_used;
231  if (GV->isThreadLocal())
232  Sym.Flags |= 1 << storage::Symbol::FB_tls;
233  if (GV->hasGlobalUnnamedAddr())
237  Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
238 
239  if (Flags & object::BasicSymbolRef::SF_Common) {
240  Uncommon().CommonSize = GV->getParent()->getDataLayout().getTypeAllocSize(
241  GV->getType()->getElementType());
242  Uncommon().CommonAlign = GV->getAlignment();
243  }
244 
245  const GlobalObject *Base = GV->getBaseObject();
246  if (!Base)
247  return make_error<StringError>("Unable to determine comdat of alias!",
249  if (const Comdat *C = Base->getComdat()) {
250  Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
251  if (!ComdatIndexOrErr)
252  return ComdatIndexOrErr.takeError();
253  Sym.ComdatIndex = *ComdatIndexOrErr;
254  }
255 
256  if (TT.isOSBinFormatCOFF()) {
257  emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
258 
259  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",
266  std::string FallbackName;
267  raw_string_ostream OS(FallbackName);
268  Msymtab.printSymbolName(OS, Fallback);
269  OS.flush();
270  setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
271  }
272  }
273 
274  if (!Base->getSection().empty())
275  setStr(Uncommon().SectionName, Saver.save(Base->getSection()));
276 
277  return Error::success();
278 }
279 
281  storage::Header Hdr;
282 
283  assert(!IRMods.empty());
285  setStr(Hdr.Producer, kExpectedProducerName);
286  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
287  setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
288  TT = Triple(IRMods[0]->getTargetTriple());
289 
290  for (auto *M : IRMods)
291  if (Error Err = addModule(M))
292  return Err;
293 
294  COFFLinkerOptsOS.flush();
295  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  Symtab.resize(sizeof(storage::Header));
300  writeRange(Hdr.Modules, Mods);
301  writeRange(Hdr.Comdats, Comdats);
302  writeRange(Hdr.Symbols, Syms);
303  writeRange(Hdr.Uncommons, Uncommons);
304 
305  *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
306  return Error::success();
307 }
308 
309 } // end anonymous namespace
310 
312  StringTableBuilder &StrtabBuilder,
313  BumpPtrAllocator &Alloc) {
314  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.
321 
322  LLVMContext Ctx;
323  std::vector<Module *> Mods;
324  std::vector<std::unique_ptr<Module>> OwnedMods;
325  for (auto BM : BMs) {
327  BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
328  /*IsImporting*/ false);
329  if (!MOrErr)
330  return MOrErr.takeError();
331 
332  Mods.push_back(MOrErr->get());
333  OwnedMods.push_back(std::move(*MOrErr));
334  }
335 
337  BumpPtrAllocator Alloc;
338  if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
339  return std::move(E);
340 
341  StrtabBuilder.finalizeInOrder();
342  FC.Strtab.resize(StrtabBuilder.getSize());
343  StrtabBuilder.write((uint8_t *)FC.Strtab.data());
344 
345  FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
346  {FC.Strtab.data(), FC.Strtab.size()}};
347  return std::move(FC);
348 }
349 
351  if (BFC.Mods.empty())
352  return make_error<StringError>("Bitcode file does not contain any modules",
354 
355  if (BFC.StrtabForSymtab.empty() ||
356  BFC.Symtab.size() < sizeof(storage::Header))
357  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  StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
366  if (Version != storage::Header::kCurrentVersion ||
367  Producer != kExpectedProducerName)
368  return upgrade(BFC.Mods);
369 
371  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  if (FC.TheReader.getNumModules() != BFC.Mods.size())
379  return upgrade(std::move(BFC.Mods));
380 
381  return std::move(FC);
382 }
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:427
uint32_t getSymbolFlags(Symbol S) const
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition: IRSymtab.cpp:319
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_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
bool canBeOmittedFromSymbolTable(const GlobalValue *GV)
True if GV can be left out of the object symbol table.
Definition: ObjectUtils.h:22
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.
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:489
const std::string & getDataLayoutStr() const
Get the data layout string for the module&#39;s target platform.
Definition: Module.h:224
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:537
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.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:191
A tuple of MDNodes.
Definition: Metadata.h:1323
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
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:242
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
unsigned getAlignment() const
Definition: Globals.cpp:97
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
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:311
#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:24
Word Version
Version number of the symtab format.
Definition: IRSymtab.h:133
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:225
void finalizeInOrder()
Finalize the string table without reording it.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition: Triple.h:593
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:138
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:177
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
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
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:513
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:517
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:192
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition: IRSymtab.cpp:350
StringRef save(const char *S)
Definition: StringSaver.h:26
void printSymbolName(raw_ostream &OS, Symbol S) const
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:482
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
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:403
Saves strings in the inheritor&#39;s stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:120
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:143
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:220
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
const GlobalObject * getBaseObject() const
Definition: Globals.cpp:256
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:462
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:556
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:156
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:109
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:238
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
StringRef get(StringRef Strtab) const
Definition: IRSymtab.h:57
Word UncBegin
The index of the first Uncommon for this Module.
Definition: IRSymtab.h:77
const uint64_t Version
Definition: InstrProf.h:867
llvm::Error materializeMetadata()
Definition: Module.cpp:400
Type * getElementType() const
Definition: DerivedTypes.h:486
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:265
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:73
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87
void resize(size_type N)
Definition: SmallVector.h:355
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition: IRSymtab.h:123