LLVM 24.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"
16#include "llvm/Config/llvm-config.h"
17#include "llvm/IR/Comdat.h"
18#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/GlobalAlias.h"
21#include "llvm/IR/Mangler.h"
22#include "llvm/IR/Metadata.h"
23#include "llvm/IR/Module.h"
30#include "llvm/Support/Error.h"
32#include "llvm/Support/VCSRevision.h"
35#include <cassert>
36#include <string>
37#include <utility>
38#include <vector>
39
40using namespace llvm;
41using namespace irsymtab;
42
44 "disable-bitcode-version-upgrade", cl::Hidden,
45 cl::desc("Disable automatic bitcode upgrade for version mismatch"));
46
47namespace {
48
49const char *getExpectedProducerName() {
50 static char DefaultName[] = LLVM_VERSION_STRING
51#ifdef LLVM_REVISION
52 " " LLVM_REVISION
53#endif
54 ;
55 // Allows for testing of the irsymtab writer and upgrade mechanism. This
56 // environment variable should not be set by users.
57 if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
58 return OverrideName;
59 return DefaultName;
60}
61
62const char *kExpectedProducerName = getExpectedProducerName();
63
64/// Stores the temporary state that is required to build an IR symbol table.
65struct Builder {
66 SmallVector<char, 0> &Symtab;
67 StringTableBuilder &StrtabBuilder;
68 StringSaver Saver;
69
70 // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
71 // The StringTableBuilder does not create a copy of any strings added to it,
72 // so this provides somewhere to store any strings that we create.
73 Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
74 BumpPtrAllocator &Alloc, const Triple &TT)
75 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc), TT(TT) {}
76
77 DenseMap<const Comdat *, int> ComdatMap;
78 Mangler Mang;
79 const Triple &TT;
80
81 std::vector<storage::Comdat> Comdats;
82 std::vector<storage::Module> Mods;
83 std::vector<storage::Symbol> Syms;
84 std::vector<storage::Uncommon> Uncommons;
85
86 std::string COFFLinkerOpts;
87 raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
88
89 std::vector<storage::Str> DependentLibraries;
90
91 void setStr(storage::Str &S, StringRef Value) {
92 S.Offset = StrtabBuilder.add(Value);
93 S.Size = Value.size();
94 }
95
96 template <typename T>
97 void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
98 R.Offset = Symtab.size();
99 R.Size = Objs.size();
100 Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
101 reinterpret_cast<const char *>(Objs.data() + Objs.size()));
102 }
103
104 Expected<int> getComdatIndex(const Comdat *C, const Module *M);
105
106 Error addModule(Module *M);
107 Error addSymbol(const ModuleSymbolTable &Msymtab,
108 const SmallPtrSet<GlobalValue *, 4> &Used,
110
112};
113
114Error Builder::addModule(Module *M) {
115 if (M->getDataLayoutStr().empty())
116 return make_error<StringError>("input module has no datalayout",
118
119 // Symbols in the llvm.used list will get the FB_Used bit and will not be
120 // internalized. We do this for llvm.compiler.used as well:
121 //
122 // IR symbol table tracks module-level asm symbol references but not inline
123 // asm. A symbol only referenced by inline asm is not in the IR symbol table,
124 // so we may not know that the definition (in another translation unit) is
125 // referenced. That definition may have __attribute__((used)) (which lowers to
126 // llvm.compiler.used on ELF targets) to communicate to the compiler that it
127 // may be used by inline asm. The usage is perfectly fine, so we treat
128 // llvm.compiler.used conservatively as llvm.used to work around our own
129 // limitation.
131 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/false);
132 collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/true);
133 SmallPtrSet<GlobalValue *, 4> Used(llvm::from_range, UsedV);
134
135 ModuleSymbolTable Msymtab;
136 Msymtab.addModule(M);
137
138 storage::Module Mod;
139 Mod.Begin = Syms.size();
140 Mod.End = Syms.size() + Msymtab.symbols().size();
141 Mod.UncBegin = Uncommons.size();
142 Mods.push_back(Mod);
143
144 if (TT.isOSBinFormatCOFF()) {
145 if (auto E = M->materializeMetadata())
146 return E;
147 if (NamedMDNode *LinkerOptions =
148 M->getNamedMetadata("llvm.linker.options")) {
149 for (MDNode *MDOptions : LinkerOptions->operands())
150 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
151 COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
152 }
153 }
154
155 if (TT.isOSBinFormatELF()) {
156 if (auto E = M->materializeMetadata())
157 return E;
158 if (NamedMDNode *N = M->getNamedMetadata("llvm.dependent-libraries")) {
159 for (MDNode *MDOptions : N->operands()) {
160 const auto OperandStr =
161 cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
162 storage::Str Specifier;
163 setStr(Specifier, OperandStr);
164 DependentLibraries.emplace_back(Specifier);
165 }
166 }
167 }
168
169 for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
170 if (Error Err = addSymbol(Msymtab, Used, Msym))
171 return Err;
172
173 return Error::success();
174}
175
176Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
177 auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
178 if (P.second) {
179 std::string Name;
180 if (TT.isOSBinFormatCOFF()) {
181 const GlobalValue *GV = M->getNamedValue(C->getName());
182 if (!GV)
183 return make_error<StringError>("Could not find leader",
185 // Internal leaders do not affect symbol resolution, therefore they do not
186 // appear in the symbol table.
187 if (GV->hasLocalLinkage()) {
188 P.first->second = -1;
189 return -1;
190 }
191 llvm::raw_string_ostream OS(Name);
192 Mang.getNameWithPrefix(OS, GV, false);
193 } else {
194 Name = std::string(C->getName());
195 }
196
197 storage::Comdat Comdat;
198 setStr(Comdat.Name, Saver.save(Name));
199 Comdat.SelectionKind = C->getSelectionKind();
200 Comdats.push_back(Comdat);
201 }
202
203 return P.first->second;
204}
205
206Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
207 const SmallPtrSet<GlobalValue *, 4> &Used,
209 Syms.emplace_back();
210 storage::Symbol &Sym = Syms.back();
211 Sym = {};
212
213 storage::Uncommon *Unc = nullptr;
214 auto Uncommon = [&]() -> storage::Uncommon & {
215 if (Unc)
216 return *Unc;
218 Uncommons.emplace_back();
219 Unc = &Uncommons.back();
220 *Unc = {};
221 setStr(Unc->COFFWeakExternFallbackName, "");
222 setStr(Unc->SectionName, "");
223 return *Unc;
224 };
225
226 SmallString<64> Name;
227 {
228 raw_svector_ostream OS(Name);
229 Msymtab.printSymbolName(OS, Msym);
230 }
231 setStr(Sym.Name, Saver.save(Name.str()));
232
233 auto Flags = Msymtab.getSymbolFlags(Msym);
248
249 Sym.ComdatIndex = -1;
250 auto *GV = dyn_cast_if_present<GlobalValue *>(Msym);
251 if (!GV) {
252 // Undefined module asm symbols act as GC roots and are implicitly used.
255 setStr(Sym.IRName, "");
256 return Error::success();
257 }
258
259 StringRef GVName = GV->getName();
260 setStr(Sym.IRName, GVName);
261
262 if (Used.count(GV))
264 if (GV->isThreadLocal())
265 Sym.Flags |= 1 << storage::Symbol::FB_tls;
266 if (GV->hasGlobalUnnamedAddr())
270 Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
271
273 auto *GVar = dyn_cast<GlobalVariable>(GV);
274 if (!GVar)
275 return make_error<StringError>("Only variables can have common linkage!",
277 Uncommon().CommonSize = GVar->getGlobalSize(GV->getDataLayout());
278 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
279 }
280
281 const GlobalObject *GO = GV->getAliaseeObject();
282 if (!GO) {
283 if (isa<GlobalIFunc>(GV))
284 GO = cast<GlobalIFunc>(GV)->getResolverFunction();
285 if (!GO)
286 return make_error<StringError>("Unable to determine comdat of alias!",
288 }
289 if (const Comdat *C = GO->getComdat()) {
290 Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
291 if (!ComdatIndexOrErr)
292 return ComdatIndexOrErr.takeError();
293 Sym.ComdatIndex = *ComdatIndexOrErr;
294 }
295
296 if (TT.isOSBinFormatCOFF()) {
297 emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
298
299 if ((Flags & object::BasicSymbolRef::SF_Weak) &&
302 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
303 if (!Fallback)
304 return make_error<StringError>("Invalid weak external",
306 std::string FallbackName;
307 raw_string_ostream OS(FallbackName);
308 Msymtab.printSymbolName(OS, Fallback);
309 setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
310 }
311 }
312
313 if (!GO->getSection().empty())
314 setStr(Uncommon().SectionName, Saver.save(GO->getSection()));
315
316 return Error::success();
317}
318
319Error Builder::build(ArrayRef<Module *> IRMods) {
320 storage::Header Hdr;
321
322 assert(!IRMods.empty());
324 setStr(Hdr.Producer, kExpectedProducerName);
325 setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple().str());
326 setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
327
328 for (auto *M : IRMods)
329 if (Error Err = addModule(M))
330 return Err;
331
332 setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
333
334 // We are about to fill in the header's range fields, so reserve space for it
335 // and copy it in afterwards.
336 Symtab.resize(sizeof(storage::Header));
337 writeRange(Hdr.Modules, Mods);
338 writeRange(Hdr.Comdats, Comdats);
339 writeRange(Hdr.Symbols, Syms);
340 writeRange(Hdr.Uncommons, Uncommons);
341 writeRange(Hdr.DependentLibraries, DependentLibraries);
342 *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
343 return Error::success();
344}
345
346} // end anonymous namespace
347
349 StringTableBuilder &StrtabBuilder,
351 const Triple &TT = Mods[0]->getTargetTriple();
352 return Builder(Symtab, StrtabBuilder, Alloc, TT).build(Mods);
353}
354
355// Upgrade a vector of bitcode modules created by an old version of LLVM by
356// creating an irsymtab for them in the current format.
358 FileContents FC;
359
360 LLVMContext Ctx;
361 std::vector<Module *> Mods;
362 std::vector<std::unique_ptr<Module>> OwnedMods;
363 for (auto BM : BMs) {
365 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
366 /*IsImporting*/ false);
367 if (!MOrErr)
368 return MOrErr.takeError();
369
370 Mods.push_back(MOrErr->get());
371 OwnedMods.push_back(std::move(*MOrErr));
372 }
373
376 if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
377 return std::move(E);
378
379 StrtabBuilder.finalizeInOrder();
380 FC.Strtab.resize(StrtabBuilder.getSize());
381 StrtabBuilder.write((uint8_t *)FC.Strtab.data());
382
383 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
384 {FC.Strtab.data(), FC.Strtab.size()}};
385 return std::move(FC);
386}
387
389 if (BFC.Mods.empty())
390 return make_error<StringError>("Bitcode file does not contain any modules",
392
394 if (BFC.StrtabForSymtab.empty() ||
395 BFC.Symtab.size() < sizeof(storage::Header))
396 return upgrade(BFC.Mods);
397
398 // We cannot use the regular reader to read the version and producer,
399 // because it will expect the header to be in the current format. The only
400 // thing we can rely on is that the version and producer will be present as
401 // the first struct elements.
402 auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
403 unsigned Version = Hdr->Version;
404 StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
406 Producer != kExpectedProducerName)
407 return upgrade(BFC.Mods);
408 }
409
410 FileContents FC;
411 FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
413
414 // Finally, make sure that the number of modules in the symbol table matches
415 // the number of modules in the bitcode file. If they differ, it may mean that
416 // the bitcode file was created by binary concatenation, so we need to create
417 // a new symbol table from scratch.
418 if (FC.TheReader.getNumModules() != BFC.Mods.size())
419 return upgrade(std::move(BFC.Mods));
420
421 return std::move(FC);
422}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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:357
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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:521
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
bool hasGlobalUnnamedAddr() const
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Definition Globals.cpp:546
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:68
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
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:48
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
LLVM_ABI Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
Definition IRSymtab.cpp:388
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:348
This is an optimization pass for GlobalISel generic memory operations.
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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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:390
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:932
#define N
std::vector< BitcodeModule > Mods
The contents of the irsymtab in a bitcode file.
Definition IRSymtab.h:374
Word Version
Version number of the symtab format.
Definition IRSymtab.h:140
Str COFFLinkerOpts
COFF-specific: linker directives.
Definition IRSymtab.h:157
Range< Str > DependentLibraries
Dependent Library Specifiers.
Definition IRSymtab.h:160
Range< Uncommon > Uncommons
Definition IRSymtab.h:152
Str Producer
The producer's version string (LLVM_VERSION_STRING " " LLVM_REVISION).
Definition IRSymtab.h:147
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:132
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.
Definition IRSymtab.h:129