17#include "llvm/Config/llvm-config.h"
33#include "llvm/Support/VCSRevision.h"
42using namespace irsymtab;
46 cl::desc(
"Disable automatic bitcode upgrade for version mismatch"));
49#define HANDLE_LIBCALL(code, name) name,
50#include "llvm/IR/RuntimeLibcalls.def"
61const char *getExpectedProducerName() {
62 static char DefaultName[] = LLVM_VERSION_STRING
69 if (
char *OverrideName = getenv(
"LLVM_OVERRIDE_PRODUCER"))
74const char *kExpectedProducerName = getExpectedProducerName();
87 : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
93 std::vector<storage::Comdat> Comdats;
94 std::vector<storage::Module> Mods;
95 std::vector<storage::Symbol> Syms;
96 std::vector<storage::Uncommon> Uncommons;
98 std::string COFFLinkerOpts;
101 std::vector<storage::Str> DependentLibraries;
108 template <
typename T>
110 R.Offset = Symtab.
size();
111 R.Size = Objs.size();
112 Symtab.
insert(Symtab.
end(),
reinterpret_cast<const char *
>(Objs.data()),
113 reinterpret_cast<const char *
>(Objs.data() + Objs.size()));
127 if (
M->getDataLayoutStr().empty())
128 return make_error<StringError>(
"input module has no datalayout",
153 Mod.UncBegin = Uncommons.
size();
156 if (
TT.isOSBinFormatCOFF()) {
157 if (
auto E =
M->materializeMetadata())
160 M->getNamedMetadata(
"llvm.linker.options")) {
162 for (
const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
163 COFFLinkerOptsOS <<
" " << cast<MDString>(MDOption)->getString();
167 if (
TT.isOSBinFormatELF()) {
168 if (
auto E =
M->materializeMetadata())
170 if (
NamedMDNode *
N =
M->getNamedMetadata(
"llvm.dependent-libraries")) {
171 for (
MDNode *MDOptions :
N->operands()) {
172 const auto OperandStr =
173 cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
175 setStr(Specifier, OperandStr);
176 DependentLibraries.emplace_back(Specifier);
189 auto P = ComdatMap.
insert(std::make_pair(
C, Comdats.size()));
192 if (
TT.isOSBinFormatCOFF()) {
195 return make_error<StringError>(
"Could not find leader",
200 P.first->second = -1;
206 Name = std::string(
C->getName());
212 Comdats.push_back(
Comdat);
215 return P.first->second;
235 Uncommons.emplace_back();
236 Unc = &Uncommons.back();
267 auto *GV = dyn_cast_if_present<GlobalValue *>(Msym);
279 buildPreservedSymbolsSet();
282 if (
Used.count(GV) || IsPreservedSymbol)
293 auto *GVar = dyn_cast<GlobalVariable>(GV);
295 return make_error<StringError>(
"Only variables can have common linkage!",
297 Uncommon().CommonSize =
299 Uncommon().CommonAlign = GVar->getAlign() ? GVar->getAlign()->value() : 0;
304 if (isa<GlobalIFunc>(GV))
305 GO = cast<GlobalIFunc>(GV)->getResolverFunction();
307 return make_error<StringError>(
"Unable to determine comdat of alias!",
312 if (!ComdatIndexOrErr)
317 if (
TT.isOSBinFormatCOFF()) {
322 auto *
Fallback = dyn_cast<GlobalValue>(
323 cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
325 return make_error<StringError>(
"Invalid weak external",
327 std::string FallbackName;
331 setStr(Uncommon().COFFWeakExternFallbackName, Saver.
save(FallbackName));
346 setStr(Hdr.
Producer, kExpectedProducerName);
349 TT =
Triple(IRMods[0]->getTargetTriple());
351 for (
auto *M : IRMods)
352 if (
Error Err = addModule(M))
355 COFFLinkerOptsOS.flush();
362 writeRange(Hdr.
Comdats, Comdats);
375 return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
384 std::vector<Module *> Mods;
385 std::vector<std::unique_ptr<Module>> OwnedMods;
386 for (
auto BM : BMs) {
388 BM.getLazyModule(Ctx,
true,
393 Mods.push_back(MOrErr->
get());
394 OwnedMods.push_back(std::move(*MOrErr));
399 if (
Error E =
build(Mods, FC.Symtab, StrtabBuilder, Alloc))
403 FC.Strtab.resize(StrtabBuilder.
getSize());
404 StrtabBuilder.
write((uint8_t *)FC.Strtab.data());
406 FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
407 {FC.Strtab.data(), FC.Strtab.size()}};
408 return std::move(FC);
412 if (BFC.
Mods.empty())
413 return make_error<StringError>(
"Bitcode file does not contain any modules",
426 unsigned Version = Hdr->
Version;
429 Producer != kExpectedProducerName)
441 if (FC.TheReader.getNumModules() != BFC.
Mods.size())
444 return std::move(FC);
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
static void addSymbol(Object &Obj, const NewSymbolInfo &SymInfo, uint8_t DefaultVisibility)
static const char * PreservedSymbols[]
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)
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
Allocate memory in an ever growing pool, as if by bump-pointer.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
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...
const GlobalObject * getAliaseeObject() const
bool hasGlobalUnnamedAddr() const
bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
Type * getValueType() const
This is an important class for using LLVM in a threaded context.
ArrayRef< MDOperand > operands() const
Tracking metadata reference owned by Metadata.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
void addModule(Module *M)
void printSymbolName(raw_ostream &OS, Symbol S) const
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.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
iterator insert(iterator I, T &&Elt)
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.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
Utility for building string tables with deduplicated suffixes.
void finalizeInOrder()
Finalize the string table without reording it.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
Triple - Helper class for working with autoconf configuration names.
LLVM Value Representation.
StringRef getName() const
Return a constant reference to the value's name.
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
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.
Expected< FileContents > readBitcode(const BitcodeFileContents &BFC)
Reads the contents of a bitcode file, creating its irsymtab if necessary.
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.
This is an optimization pass for GlobalISel generic memory operations.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
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 ...
StringRef StrtabForSymtab
std::vector< BitcodeModule > Mods
The contents of the irsymtab in a bitcode file.
This is equivalent to an IR comdat.
Describes the range of a particular module's symbols within the symbol table.
A reference to a range of objects in the symbol table.
A reference to a string in the string table.
StringRef get(StringRef Strtab) const
Contains the information needed by linkers for symbol resolution, as well as by the LTO implementatio...
This data structure contains rarely used symbol fields and is optionally referenced by a Symbol.
Str SectionName
Specified section name, if any.
Str COFFWeakExternFallbackName
COFF-specific: the name of the symbol that a weak external resolves to if not defined.