1
0
mirror of https://github.com/RPCS3/llvm-mirror.git synced 2024-11-23 03:02:36 +01:00
llvm-mirror/lib/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.cpp

356 lines
11 KiB
C++
Raw Normal View History

//===-- RTDyldObjectLinkingLayer.cpp - RuntimeDyld backed ORC ObjectLayer -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
#include "llvm/Object/COFF.h"
namespace {
using namespace llvm;
using namespace llvm::orc;
class JITDylibSearchOrderResolver : public JITSymbolResolver {
public:
JITDylibSearchOrderResolver(MaterializationResponsibility &MR) : MR(MR) {}
2020-07-17 05:38:41 +02:00
void lookup(const LookupSet &Symbols, OnResolvedFunction OnResolved) override {
auto &ES = MR.getTargetJITDylib().getExecutionSession();
[ORC][JITLink] Add support for weak references, and improve handling of static libraries. This patch substantially updates ORCv2's lookup API in order to support weak references, and to better support static archives. Key changes: -- Each symbol being looked for is now associated with a SymbolLookupFlags value. If the associated value is SymbolLookupFlags::RequiredSymbol then the symbol must be defined in one of the JITDylibs being searched (or be able to be generated in one of these JITDylibs via an attached definition generator) or the lookup will fail with an error. If the associated value is SymbolLookupFlags::WeaklyReferencedSymbol then the symbol is permitted to be undefined, in which case it will simply not appear in the resulting SymbolMap if the rest of the lookup succeeds. Since lookup now requires these flags for each symbol, the lookup method now takes an instance of a new SymbolLookupSet type rather than a SymbolNameSet. SymbolLookupSet is a vector-backed set of (name, flags) pairs. Clients are responsible for ensuring that the set property (i.e. unique elements) holds, though this is usually simple and SymbolLookupSet provides convenience methods to support this. -- Lookups now have an associated LookupKind value, which is either LookupKind::Static or LookupKind::DLSym. Definition generators can inspect the lookup kind when determining whether or not to generate new definitions. The StaticLibraryDefinitionGenerator is updated to only pull in new objects from the archive if the lookup kind is Static. This allows lookup to be re-used to emulate dlsym for JIT'd symbols without pulling in new objects from archives (which would not happen in a normal dlsym call). -- JITLink is updated to allow externals to be assigned weak linkage, and weak externals now use the SymbolLookupFlags::WeaklyReferencedSymbol value for lookups. Unresolved weak references will be assigned the default value of zero. Since this patch was modifying the lookup API anyway, it alo replaces all of the "MatchNonExported" boolean arguments with a "JITDylibLookupFlags" enum for readability. If a JITDylib's associated value is JITDylibLookupFlags::MatchExportedSymbolsOnly then the lookup will only match against exported (non-hidden) symbols in that JITDylib. If a JITDylib's associated value is JITDylibLookupFlags::MatchAllSymbols then the lookup will match against any symbol defined in the JITDylib.
2019-11-26 06:57:27 +01:00
SymbolLookupSet InternedSymbols;
// Intern the requested symbols: lookup takes interned strings.
for (auto &S : Symbols)
[ORC][JITLink] Add support for weak references, and improve handling of static libraries. This patch substantially updates ORCv2's lookup API in order to support weak references, and to better support static archives. Key changes: -- Each symbol being looked for is now associated with a SymbolLookupFlags value. If the associated value is SymbolLookupFlags::RequiredSymbol then the symbol must be defined in one of the JITDylibs being searched (or be able to be generated in one of these JITDylibs via an attached definition generator) or the lookup will fail with an error. If the associated value is SymbolLookupFlags::WeaklyReferencedSymbol then the symbol is permitted to be undefined, in which case it will simply not appear in the resulting SymbolMap if the rest of the lookup succeeds. Since lookup now requires these flags for each symbol, the lookup method now takes an instance of a new SymbolLookupSet type rather than a SymbolNameSet. SymbolLookupSet is a vector-backed set of (name, flags) pairs. Clients are responsible for ensuring that the set property (i.e. unique elements) holds, though this is usually simple and SymbolLookupSet provides convenience methods to support this. -- Lookups now have an associated LookupKind value, which is either LookupKind::Static or LookupKind::DLSym. Definition generators can inspect the lookup kind when determining whether or not to generate new definitions. The StaticLibraryDefinitionGenerator is updated to only pull in new objects from the archive if the lookup kind is Static. This allows lookup to be re-used to emulate dlsym for JIT'd symbols without pulling in new objects from archives (which would not happen in a normal dlsym call). -- JITLink is updated to allow externals to be assigned weak linkage, and weak externals now use the SymbolLookupFlags::WeaklyReferencedSymbol value for lookups. Unresolved weak references will be assigned the default value of zero. Since this patch was modifying the lookup API anyway, it alo replaces all of the "MatchNonExported" boolean arguments with a "JITDylibLookupFlags" enum for readability. If a JITDylib's associated value is JITDylibLookupFlags::MatchExportedSymbolsOnly then the lookup will only match against exported (non-hidden) symbols in that JITDylib. If a JITDylib's associated value is JITDylibLookupFlags::MatchAllSymbols then the lookup will match against any symbol defined in the JITDylib.
2019-11-26 06:57:27 +01:00
InternedSymbols.add(ES.intern(S));
// Build an OnResolve callback to unwrap the interned strings and pass them
// to the OnResolved callback.
auto OnResolvedWithUnwrap =
[OnResolved = std::move(OnResolved)](
Expected<SymbolMap> InternedResult) mutable {
if (!InternedResult) {
OnResolved(InternedResult.takeError());
return;
}
LookupResult Result;
for (auto &KV : *InternedResult)
Result[*KV.first] = std::move(KV.second);
OnResolved(Result);
};
// Register dependencies for all symbols contained in this set.
auto RegisterDependencies = [&](const SymbolDependenceMap &Deps) {
MR.addDependenciesForAll(Deps);
};
JITDylibSearchOrder LinkOrder;
MR.getTargetJITDylib().withLinkOrderDo(
[&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
ES.lookup(LookupKind::Static, LinkOrder, InternedSymbols,
[ORC][JITLink] Add support for weak references, and improve handling of static libraries. This patch substantially updates ORCv2's lookup API in order to support weak references, and to better support static archives. Key changes: -- Each symbol being looked for is now associated with a SymbolLookupFlags value. If the associated value is SymbolLookupFlags::RequiredSymbol then the symbol must be defined in one of the JITDylibs being searched (or be able to be generated in one of these JITDylibs via an attached definition generator) or the lookup will fail with an error. If the associated value is SymbolLookupFlags::WeaklyReferencedSymbol then the symbol is permitted to be undefined, in which case it will simply not appear in the resulting SymbolMap if the rest of the lookup succeeds. Since lookup now requires these flags for each symbol, the lookup method now takes an instance of a new SymbolLookupSet type rather than a SymbolNameSet. SymbolLookupSet is a vector-backed set of (name, flags) pairs. Clients are responsible for ensuring that the set property (i.e. unique elements) holds, though this is usually simple and SymbolLookupSet provides convenience methods to support this. -- Lookups now have an associated LookupKind value, which is either LookupKind::Static or LookupKind::DLSym. Definition generators can inspect the lookup kind when determining whether or not to generate new definitions. The StaticLibraryDefinitionGenerator is updated to only pull in new objects from the archive if the lookup kind is Static. This allows lookup to be re-used to emulate dlsym for JIT'd symbols without pulling in new objects from archives (which would not happen in a normal dlsym call). -- JITLink is updated to allow externals to be assigned weak linkage, and weak externals now use the SymbolLookupFlags::WeaklyReferencedSymbol value for lookups. Unresolved weak references will be assigned the default value of zero. Since this patch was modifying the lookup API anyway, it alo replaces all of the "MatchNonExported" boolean arguments with a "JITDylibLookupFlags" enum for readability. If a JITDylib's associated value is JITDylibLookupFlags::MatchExportedSymbolsOnly then the lookup will only match against exported (non-hidden) symbols in that JITDylib. If a JITDylib's associated value is JITDylibLookupFlags::MatchAllSymbols then the lookup will match against any symbol defined in the JITDylib.
2019-11-26 06:57:27 +01:00
SymbolState::Resolved, std::move(OnResolvedWithUnwrap),
RegisterDependencies);
}
2020-07-17 05:38:41 +02:00
Expected<LookupSet> getResponsibilitySet(const LookupSet &Symbols) override {
LookupSet Result;
for (auto &KV : MR.getSymbols()) {
if (Symbols.count(*KV.first))
Result.insert(*KV.first);
}
return Result;
}
private:
MaterializationResponsibility &MR;
};
} // end anonymous namespace
namespace llvm {
namespace orc {
char RTDyldObjectLinkingLayer::ID;
using BaseT = RTTIExtends<RTDyldObjectLinkingLayer, ObjectLayer>;
RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager)
: BaseT(ES), GetMemoryManager(GetMemoryManager) {
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
ES.registerResourceManager(*this);
}
RTDyldObjectLinkingLayer::~RTDyldObjectLinkingLayer() {
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
assert(MemMgrs.empty() && "Layer destroyed with resources still attached");
}
void RTDyldObjectLinkingLayer::emit(
std::unique_ptr<MaterializationResponsibility> R,
std::unique_ptr<MemoryBuffer> O) {
assert(O && "Object must not be null");
2020-02-24 12:10:13 +01:00
auto &ES = getExecutionSession();
auto Obj = object::ObjectFile::createObjectFile(*O);
if (!Obj) {
getExecutionSession().reportError(Obj.takeError());
R->failMaterialization();
return;
}
// Collect the internal symbols from the object file: We will need to
// filter these later.
auto InternalSymbols = std::make_shared<std::set<StringRef>>();
{
for (auto &Sym : (*Obj)->symbols()) {
// Skip file symbols.
if (auto SymType = Sym.getType()) {
if (*SymType == object::SymbolRef::ST_File)
continue;
} else {
ES.reportError(SymType.takeError());
R->failMaterialization();
return;
}
Expected<uint32_t> SymFlagsOrErr = Sym.getFlags();
if (!SymFlagsOrErr) {
// TODO: Test this error.
ES.reportError(SymFlagsOrErr.takeError());
R->failMaterialization();
return;
}
// Don't include symbols that aren't global.
if (!(*SymFlagsOrErr & object::BasicSymbolRef::SF_Global)) {
if (auto SymName = Sym.getName())
InternalSymbols->insert(*SymName);
else {
ES.reportError(SymName.takeError());
R->failMaterialization();
return;
}
}
}
}
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
auto MemMgr = GetMemoryManager();
auto &MemMgrRef = *MemMgr;
// Switch to shared ownership of MR so that it can be captured by both
// lambdas below.
std::shared_ptr<MaterializationResponsibility> SharedR(std::move(R));
JITDylibSearchOrderResolver Resolver(*SharedR);
jitLinkForORC(
object::OwningBinary<object::ObjectFile>(std::move(*Obj), std::move(O)),
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
MemMgrRef, Resolver, ProcessAllSections,
[this, SharedR, &MemMgrRef, InternalSymbols](
const object::ObjectFile &Obj,
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
RuntimeDyld::LoadedObjectInfo &LoadedObjInfo,
std::map<StringRef, JITEvaluatedSymbol> ResolvedSymbols) {
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
return onObjLoad(*SharedR, Obj, MemMgrRef, LoadedObjInfo,
ResolvedSymbols, *InternalSymbols);
},
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
[this, SharedR, MemMgr = std::move(MemMgr)](
object::OwningBinary<object::ObjectFile> Obj,
std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo,
Error Err) mutable {
onObjEmit(*SharedR, std::move(Obj), std::move(MemMgr),
std::move(LoadedObjInfo), std::move(Err));
});
}
void RTDyldObjectLinkingLayer::registerJITEventListener(JITEventListener &L) {
std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
assert(!llvm::is_contained(EventListeners, &L) &&
"Listener has already been registered");
EventListeners.push_back(&L);
}
void RTDyldObjectLinkingLayer::unregisterJITEventListener(JITEventListener &L) {
std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
auto I = llvm::find(EventListeners, &L);
assert(I != EventListeners.end() && "Listener not registered");
EventListeners.erase(I);
}
Error RTDyldObjectLinkingLayer::onObjLoad(
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
MaterializationResponsibility &R, const object::ObjectFile &Obj,
RuntimeDyld::MemoryManager &MemMgr,
RuntimeDyld::LoadedObjectInfo &LoadedObjInfo,
std::map<StringRef, JITEvaluatedSymbol> Resolved,
std::set<StringRef> &InternalSymbols) {
SymbolFlagsMap ExtraSymbolsToClaim;
SymbolMap Symbols;
// Hack to support COFF constant pool comdats introduced during compilation:
// (See http://llvm.org/PR40074)
if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(&Obj)) {
auto &ES = getExecutionSession();
// For all resolved symbols that are not already in the responsibilty set:
// check whether the symbol is in a comdat section and if so mark it as
// weak.
for (auto &Sym : COFFObj->symbols()) {
// getFlags() on COFF symbols can't fail.
uint32_t SymFlags = cantFail(Sym.getFlags());
if (SymFlags & object::BasicSymbolRef::SF_Undefined)
continue;
auto Name = Sym.getName();
if (!Name)
return Name.takeError();
auto I = Resolved.find(*Name);
// Skip unresolved symbols, internal symbols, and symbols that are
// already in the responsibility set.
if (I == Resolved.end() || InternalSymbols.count(*Name) ||
R.getSymbols().count(ES.intern(*Name)))
continue;
auto Sec = Sym.getSection();
if (!Sec)
return Sec.takeError();
if (*Sec == COFFObj->section_end())
continue;
auto &COFFSec = *COFFObj->getCOFFSection(**Sec);
if (COFFSec.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
I->second.setFlags(I->second.getFlags() | JITSymbolFlags::Weak);
}
}
for (auto &KV : Resolved) {
// Scan the symbols and add them to the Symbols map for resolution.
// We never claim internal symbols.
if (InternalSymbols.count(KV.first))
continue;
auto InternedName = getExecutionSession().intern(KV.first);
auto Flags = KV.second.getFlags();
// Override object flags and claim responsibility for symbols if
// requested.
if (OverrideObjectFlags || AutoClaimObjectSymbols) {
auto I = R.getSymbols().find(InternedName);
if (OverrideObjectFlags && I != R.getSymbols().end())
Flags = I->second;
else if (AutoClaimObjectSymbols && I == R.getSymbols().end())
ExtraSymbolsToClaim[InternedName] = Flags;
}
Symbols[InternedName] = JITEvaluatedSymbol(KV.second.getAddress(), Flags);
}
if (!ExtraSymbolsToClaim.empty()) {
if (auto Err = R.defineMaterializing(ExtraSymbolsToClaim))
return Err;
// If we claimed responsibility for any weak symbols but were rejected then
// we need to remove them from the resolved set.
for (auto &KV : ExtraSymbolsToClaim)
if (KV.second.isWeak() && !R.getSymbols().count(KV.first))
Symbols.erase(KV.first);
}
if (auto Err = R.notifyResolved(Symbols)) {
R.failMaterialization();
return Err;
}
if (NotifyLoaded)
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
NotifyLoaded(R, Obj, LoadedObjInfo);
return Error::success();
}
void RTDyldObjectLinkingLayer::onObjEmit(
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
MaterializationResponsibility &R,
object::OwningBinary<object::ObjectFile> O,
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
std::unique_ptr<RuntimeDyld::MemoryManager> MemMgr,
std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObjInfo, Error Err) {
if (Err) {
getExecutionSession().reportError(std::move(Err));
R.failMaterialization();
return;
}
if (auto Err = R.notifyEmitted()) {
getExecutionSession().reportError(std::move(Err));
R.failMaterialization();
return;
}
std::unique_ptr<object::ObjectFile> Obj;
std::unique_ptr<MemoryBuffer> ObjBuffer;
std::tie(Obj, ObjBuffer) = O.takeBinary();
// Run EventListener notifyLoaded callbacks.
{
std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
for (auto *L : EventListeners)
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
L->notifyObjectLoaded(pointerToJITTargetAddress(MemMgr.get()), *Obj,
*LoadedObjInfo);
}
if (NotifyEmitted)
[ORC] Add support for resource tracking/removal (removable code). This patch introduces new APIs to support resource tracking and removal in Orc. It is intended as a thread-safe generalization of the removeModule concept from OrcV1. Clients can now create ResourceTracker objects (using JITDylib::createResourceTracker) to track resources for each MaterializationUnit (code, data, aliases, absolute symbols, etc.) added to the JIT. Every MaterializationUnit will be associated with a ResourceTracker, and ResourceTrackers can be re-used for multiple MaterializationUnits. Each JITDylib has a default ResourceTracker that will be used for MaterializationUnits added to that JITDylib if no ResourceTracker is explicitly specified. Two operations can be performed on ResourceTrackers: transferTo and remove. The transferTo operation transfers tracking of the resources to a different ResourceTracker object, allowing ResourceTrackers to be merged to reduce administrative overhead (the source tracker is invalidated in the process). The remove operation removes all resources associated with a ResourceTracker, including any symbols defined by MaterializationUnits associated with the tracker, and also invalidates the tracker. These operations are thread safe, and should work regardless of the the state of the MaterializationUnits. In the case of resource transfer any existing resources associated with the source tracker will be transferred to the destination tracker, and all future resources for those units will be automatically associated with the destination tracker. In the case of resource removal all already-allocated resources will be deallocated, any if any program representations associated with the tracker have not been compiled yet they will be destroyed. If any program representations are currently being compiled then they will be prevented from completing: their MaterializationResponsibility will return errors on any attempt to update the JIT state. Clients (usually Layer writers) wishing to track resources can implement the ResourceManager API to receive notifications when ResourceTrackers are transferred or removed. The MaterializationResponsibility::withResourceKeyDo method can be used to create associations between the key for a ResourceTracker and an allocated resource in a thread-safe way. RTDyldObjectLinkingLayer and ObjectLinkingLayer are updated to use the ResourceManager API to enable tracking and removal of memory allocated by the JIT linker. The new JITDylib::clear method can be used to trigger removal of every ResourceTracker associated with the JITDylib (note that this will only remove resources for the JITDylib, it does not run static destructors). This patch includes unit tests showing basic usage. A follow-up patch will update the Kaleidoscope and BuildingAJIT tutorial series to OrcV2 and will use this API to release code associated with anonymous expressions.
2020-09-11 18:50:41 +02:00
NotifyEmitted(R, std::move(ObjBuffer));
if (auto Err = R.withResourceKeyDo(
[&](ResourceKey K) { MemMgrs[K].push_back(std::move(MemMgr)); })) {
getExecutionSession().reportError(std::move(Err));
R.failMaterialization();
}
}
Error RTDyldObjectLinkingLayer::handleRemoveResources(ResourceKey K) {
std::vector<MemoryManagerUP> MemMgrsToRemove;
getExecutionSession().runSessionLocked([&] {
auto I = MemMgrs.find(K);
if (I != MemMgrs.end()) {
std::swap(MemMgrsToRemove, I->second);
MemMgrs.erase(I);
}
});
{
std::lock_guard<std::mutex> Lock(RTDyldLayerMutex);
for (auto &MemMgr : MemMgrsToRemove) {
for (auto *L : EventListeners)
L->notifyFreeingObject(pointerToJITTargetAddress(MemMgr.get()));
MemMgr->deregisterEHFrames();
}
}
return Error::success();
}
void RTDyldObjectLinkingLayer::handleTransferResources(ResourceKey DstKey,
ResourceKey SrcKey) {
auto I = MemMgrs.find(SrcKey);
if (I != MemMgrs.end()) {
auto &SrcMemMgrs = I->second;
auto &DstMemMgrs = MemMgrs[DstKey];
DstMemMgrs.reserve(DstMemMgrs.size() + SrcMemMgrs.size());
for (auto &MemMgr : SrcMemMgrs)
DstMemMgrs.push_back(std::move(MemMgr));
// Erase SrcKey entry using value rather than iterator I: I may have been
// invalidated when we looked up DstKey.
MemMgrs.erase(SrcKey);
}
}
} // End namespace orc.
} // End namespace llvm.