LLVM 23.0.0git
IRSymtab.cpp
Go to the documentation of this file.
1//===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/StringSet.h"
17#include "llvm/Config/llvm-config.h"
18#include "llvm/IR/Comdat.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/GlobalAlias.h"
22#include "llvm/IR/Mangler.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/IR/Module.h"
31#include "llvm/Support/Error.h"
33#include "llvm/Support/VCSRevision.h"
36#include <cassert>
37#include <string>
38#include <utility>
39#include <vector>
40
41using namespace llvm;
42using namespace irsymtab;
43
45 "disable-bitcode-version-upgrade", cl::Hidden,
46 cl::desc("Disable automatic bitcode upgrade for version mismatch"));
47
48namespace {
49
50const char *getExpectedProducerName() {
51 static char DefaultName[] = LLVM_VERSION_STRING
52#ifdef LLVM_REVISION
53 " " LLVM_REVISION
54#endif
55 ;
56 // Allows for testing of the irsymtab writer and upgrade mechanism. This
57 // environment variable should not be set by users.
58 if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
59 return OverrideName;
60 return DefaultName;
61}
62
63const char *kExpectedProducerName = getExpectedProducerName();
64
65/// Stores the temporary state that is required to build an IR symbol table.
66struct Builder {
67 SmallVector<char, 0> &Symtab;
68 StringTableBuilder &StrtabBuilder;
69 StringSaver Saver;
70
71 // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
72 // The StringTableBuilder does not create a copy of any strings added to it,
73 // so this provides somewhere to store any strings that we create.
74 Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
75 BumpPtrAllocator &Alloc, const Triple &TT)
76 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc), TT(TT) {}
77
78 DenseMap<const Comdat *, int> ComdatMap;
79 Mangler Mang;
80 const Triple &TT;
81
82 std::vector<storage::Comdat> Comdats;
83 std::vector<storage::Module> Mods;
84 std::vector<storage::Symbol> Syms;
85 std::vector<storage::Uncommon> Uncommons;
86
87 std::string COFFLinkerOpts;
88 raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
89
90 std::vector<storage::Str> DependentLibraries;
91
92 void setStr(storage::Str &S, StringRef Value) {
93 S.Offset = StrtabBuilder.add(Value);
94 S.Size = Value.size();
95 }
96
97 template <typename T>
98 void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
99 R.Offset = Symtab.size();
100 R.Size = Objs.size();
101 Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
102 reinterpret_cast<const char *>(Objs.data() + Objs.size()));
103 }
104
105 Expected<int> getComdatIndex(const Comdat *C, const Module *M);
106
107 Error addModule(Module *M);
108 Error addSymbol(const ModuleSymbolTable &Msymtab,
109 const SmallPtrSet<GlobalValue *, 4> &Used,
111
113};
114
115Error Builder::addModule(Module *M) {
116 if (M->getDataLayoutStr().empty())
117 return make_error<StringError>("input module has no datalayout",
119
120 // Symbols in the llvm.used list will get the FB_Used bit and will not be
121 // internalized. We do this for llvm.compiler.used as well:
122 //
123 // IR symbol table tracks module-level asm symbol references but not inline
124 // asm. A symbol only referenced by inline asm is not in the IR symbol table,
125 // so we may not know that the definition (in another translation unit) is
126 // referenced. That definition may have __attribute__((used)) (which lowers to
127 // llvm.compiler.used on ELF targets) to communicate to the compiler that it
128 // may be used by inline asm. The usage is perfectly fine, so we treat
129 // llvm.compiler.used conservatively as llvm.used to work around our own
130 // limitation.
132 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/false);
133 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/true);
134 SmallPtrSet<GlobalValue *, 4> Used(llvm::from_range, UsedV);
135
136 ModuleSymbolTable Msymtab;
137 Msymtab.addModule(M);
138
139 storage::Module Mod;
140 Mod.Begin = Syms.size();
141 Mod.End = Syms.size() + Msymtab.symbols().size();
142 Mod.UncBegin = Uncommons.size();
143 Mods.push_back(Mod);
144
145 if (TT.isOSBinFormatCOFF()) {
146 if (auto E = M->materializeMetadata())
147 return E;
148 if (NamedMDNode *LinkerOptions =
149 M->getNamedMetadata("llvm.linker.options")) {
150 for (MDNode *MDOptions : LinkerOptions->operands())
151 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
152 COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
153 }
154 }
155
156 if (TT.isOSBinFormatELF()) {
157 if (auto E = M->materializeMetadata())
158 return E;
159 if (NamedMDNode *N = M->getNamedMetadata("llvm.dependent-libraries")) {
160 for (MDNode *MDOptions : N->operands()) {
161 const auto OperandStr =
162 cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
163 storage::Str Specifier;
164 setStr(Specifier, OperandStr);
165 DependentLibraries.emplace_back(Specifier);
166 }
167 }
168 }
169
170 for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
171 if (Error Err = addSymbol(Msymtab, Used, Msym))
172 return Err;
173
174 return Error::success();
175}
176
177Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
178 auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
179 if (P.second) {
180 std::string Name;
181 if (TT.isOSBinFormatCOFF()) {
182 const GlobalValue *GV = M->getNamedValue(C->getName());
183 if (!GV)
184 return make_error<StringError>("Could not find leader",
186 // Internal leaders do not affect symbol resolution, therefore they do not
187 // appear in the symbol table.
188 if (GV->hasLocalLinkage()) {
189 P.first->second = -1;
190 return -1;
191 }
192 llvm::raw_string_ostream OS(Name);
193 Mang.getNameWithPrefix(OS, GV, false);
194 } else {
195 Name = std::string(C->getName());
196 }
197
198 storage::Comdat Comdat;
199 setStr(Comdat.Name, Saver.save(Name));
200 Comdat.SelectionKind = C->getSelectionKind();
201 Comdats.push_back(Comdat);
202 }
203
204 return P.first->second;
205}
206
207Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
208 const SmallPtrSet<GlobalValue *, 4> &Used,
210 Syms.emplace_back();
211 storage::Symbol &Sym = Syms.back();
212 Sym = {};
213
214 storage::Uncommon *Unc = nullptr;
215 auto Uncommon = [&]() -> storage::Uncommon & {
216 if (Unc)
217 return *Unc;
219 Uncommons.emplace_back();
220 Unc = &Uncommons.back();
221 *Unc = {};
222 setStr(Unc->COFFWeakExternFallbackName, "");
223 setStr(Unc->SectionName, "");
224 return *Unc;
225 };
226
227 SmallString<64> Name;
228 {
229 raw_svector_ostream OS(Name);
230 Msymtab.printSymbolName(OS, Msym);
231 }
232 setStr(Sym.Name, Saver.save(Name.str()));
233
234 auto Flags = Msymtab.getSymbolFlags(Msym);
249
250 Sym.ComdatIndex = -1;
251 auto *GV = dyn_cast_if_present<GlobalValue *>(Msym);
252 if (!GV) {
253 // Undefined module asm symbols act as GC roots and are implicitly used.
256 setStr(Sym.IRName, "");
257 return Error::success();
258 }
259
260 StringRef GVName = GV->getName();
261 setStr(Sym.IRName, GVName);
262
263 if (Used.count(GV))
265 if (GV->isThreadLocal())
266 Sym.Flags |= 1 << storage::Symbol::FB_tls;
267 if (GV->hasGlobalUnnamedAddr())
271 Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
272
274 auto *GVar = dyn_cast<GlobalVariable>(GV);
275 if (!GVar)
276 return make_error<StringError>("Only variables can have common linkage!",
278 Uncommon().CommonSize = GVar->getGlobalSize(GV->getDataLayout());
279 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
280 }
281
282 const GlobalObject *GO = GV->getAliaseeObject();
283 if (!GO) {
284 if (isa<GlobalIFunc>(GV))
285 GO = cast<GlobalIFunc>(GV)->getResolverFunction();
286 if (!GO)
287 return make_error<StringError>("Unable to determine comdat of alias!",
289 }
290 if (const Comdat *C = GO->getComdat()) {
291 Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
292 if (!ComdatIndexOrErr)
293 return ComdatIndexOrErr.takeError();
294 Sym.ComdatIndex = *ComdatIndexOrErr;
295 }
296
297 if (TT.isOSBinFormatCOFF()) {
298 emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
299
300 if ((Flags & object::BasicSymbolRef::SF_Weak) &&
303 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
304 if (!Fallback)
305 return make_error<StringError>("Invalid weak external",
307 std::string FallbackName;
308 raw_string_ostream OS(FallbackName);
309 Msymtab.printSymbolName(OS, Fallback);
310 setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
311 }
312 }
313
314 if (!GO->getSection().empty())
315 setStr(Uncommon().SectionName, Saver.save(GO->getSection()));
316
317 return Error::success();
318}
319
320Error Builder::build(ArrayRef<Module *> IRMods) {
321 storage::Header Hdr;
322
323 assert(!IRMods.empty());
325 setStr(Hdr.Producer, kExpectedProducerName);
326 setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple().str());
327 setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
328
329 for (auto *M : IRMods)
330 if (Error Err = addModule(M))
331 return Err;
332
333 setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
334
335 // We are about to fill in the header's range fields, so reserve space for it
336 // and copy it in afterwards.
337 Symtab.resize(sizeof(storage::Header));
338 writeRange(Hdr.Modules, Mods);
339 writeRange(Hdr.Comdats, Comdats);
340 writeRange(Hdr.Symbols, Syms);
341 writeRange(Hdr.Uncommons, Uncommons);
342 writeRange(Hdr.DependentLibraries, DependentLibraries);
343 *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
344 return Error::success();
345}
346
347} // end anonymous namespace
348
350 StringTableBuilder &StrtabBuilder,
352 const Triple &TT = Mods[0]->getTargetTriple();
353 return Builder(Symtab, StrtabBuilder, Alloc, TT).build(Mods);
354}
355
356// Upgrade a vector of bitcode modules created by an old version of LLVM by
357// creating an irsymtab for them in the current format.
359 FileContents FC;
360
361 LLVMContext Ctx;
362 std::vector<Module *> Mods;
363 std::vector<std::unique_ptr<Module>> OwnedMods;
364 for (auto BM : BMs) {
366 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
367 /*IsImporting*/ false);
368 if (!MOrErr)
369 return MOrErr.takeError();
370
371 Mods.push_back(MOrErr->get());
372 OwnedMods.push_back(std::move(*MOrErr));
373 }
374
377 if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
378 return std::move(E);
379
380 StrtabBuilder.finalizeInOrder();
381 FC.Strtab.resize(StrtabBuilder.getSize());
382 StrtabBuilder.write((uint8_t *)FC.Strtab.data());
383
384 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
385 {FC.Strtab.data(), FC.Strtab.size()}};
386 return std::move(FC);
387}
388
390 if (BFC.Mods.empty())
391 return make_error<StringError>("Bitcode file does not contain any modules",
393
395 if (BFC.StrtabForSymtab.empty() ||
396 BFC.Symtab.size() < sizeof(storage::Header))
397 return upgrade(BFC.Mods);
398
399 // We cannot use the regular reader to read the version and producer,
400 // because it will expect the header to be in the current format. The only
401 // thing we can rely on is that the version and producer will be present as
402 // the first struct elements.
403 auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
404 unsigned Version = Hdr->Version;
405 StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
407 Producer != kExpectedProducerName)
408 return upgrade(BFC.Mods);
409 }
410
411 FileContents FC;
412 FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
414
415 // Finally, make sure that the number of modules in the symbol table matches
416 // the number of modules in the bitcode file. If they differ, it may mean that
417 // the bitcode file was created by binary concatenation, so we need to create
418 // a new symbol table from scratch.
419 if (FC.TheReader.getNumModules() != BFC.Mods.size())
420 return upgrade(std::move(BFC.Mods));
421
422 return std::move(FC);
423}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Prepare AGPR Alloc
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
static cl::opt< bool > DisableBitcodeVersionUpgrade("disable-bitcode-version-upgrade", cl::Hidden, cl::desc("Disable automatic bitcode upgrade for version mismatch"))
static Expected< FileContents > upgrade(ArrayRef< BitcodeModule > BMs)
Definition IRSymtab.cpp:358
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
StringRef getSection() const
Get the custom section of this global if it has one.
const Comdat * getComdat() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
bool hasLocalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:442
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:133
bool hasGlobalUnnamedAddr() const
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:467
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition Mangler.cpp:121
LLVM_ABI void addModule(Module *M)
LLVM_ABI void printSymbolName(raw_ostream &OS, Symbol S) const
PointerUnion< GlobalValue *, AsmSymbol * > Symbol
LLVM_ABI uint32_t getSymbolFlags(Symbol S) const
ArrayRef< Symbol > symbols() const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
void resize(size_type N)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
StringRef save(const char *S)
Definition StringSaver.h:31
Utility for building string tables with deduplicated suffixes.
LLVM_ABI void finalizeInOrder()
Finalize the string table without reording it.
LLVM_ABI void write(raw_ostream &OS) const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition IRSymtab.cpp:389
LLVM_ABI 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:349
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:302
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition Mangler.cpp:214
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:875
#define N
std::vector< BitcodeModule > Mods
The contents of the irsymtab in a bitcode file.
Definition IRSymtab.h:372
Word Version
Version number of the symtab format.
Definition IRSymtab.h:139
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition IRSymtab.h:156
Range< Str > DependentLibraries
Dependent Library Specifiers.
Definition IRSymtab.h:159
Range< Uncommon > Uncommons
Definition IRSymtab.h:151
Str Producer
The producer's version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition IRSymtab.h:146
StringRef get(StringRef Strtab) const
Definition IRSymtab.h:59
Str Name
The mangled symbol name.
Definition IRSymtab.h:94
Str IRName
The unmangled symbol name, or the empty string if this is not an IR symbol.
Definition IRSymtab.h:98
Word ComdatIndex
The index into Header::Comdats, or -1 if not a comdat member.
Definition IRSymtab.h:101
Str SectionName
Specified section name, if any.
Definition IRSymtab.h:131
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition IRSymtab.h:128