LLVM 24.0.0git
Core.h
Go to the documentation of this file.
1//===------ Core.h -- Core ORC APIs (Layer, JITDylib, etc.) -----*- C++ -*-===//
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//
9// Contains core ORC APIs.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_CORE_H
14#define LLVM_EXECUTIONENGINE_ORC_CORE_H
15
17#include "llvm/ADT/DenseSet.h"
33#include "llvm/Support/Debug.h"
35
36#include <atomic>
37#include <deque>
38#include <future>
39#include <memory>
40#include <vector>
41
42namespace llvm {
43namespace orc {
44
45// Forward declare some classes.
49class JITDylib;
50class ResourceTracker;
52
53enum class SymbolState : uint8_t;
54
57
60
62
63/// API to remove / transfer ownership of JIT resources.
64class ResourceTracker : public ThreadSafeRefCountedBase<ResourceTracker> {
65private:
66 friend class ExecutionSession;
67 friend class JITDylib;
69
70public:
75
77
78 /// Return the JITDylib targeted by this tracker.
80 return *reinterpret_cast<JITDylib *>(JDAndFlag.load() &
81 ~static_cast<uintptr_t>(1));
82 }
83
84 /// Runs the given callback under the session lock, passing in the associated
85 /// ResourceKey. This is the safe way to associate resources with trackers.
86 template <typename Func> Error withResourceKeyDo(Func &&F);
87
88 /// Remove all resources associated with this key.
90
91 /// Transfer all resources associated with this key to the given
92 /// tracker, which must target the same JITDylib as this one.
94
95 /// Return true if this tracker has become defunct.
96 bool isDefunct() const { return JDAndFlag.load() & 0x1; }
97
98 /// Returns the key associated with this tracker.
99 /// This method should not be used except for debug logging: there is no
100 /// guarantee that the returned value will remain valid.
101 ResourceKey getKeyUnsafe() const { return reinterpret_cast<uintptr_t>(this); }
102
103private:
105
106 void makeDefunct();
107
108 std::atomic_uintptr_t JDAndFlag;
109};
110
111/// Listens for ResourceTracker operations.
113public:
115
116 /// This function will be called *outside* the session lock. ResourceManagers
117 /// should perform book-keeping under the session lock, and any expensive
118 /// cleanup outside the session lock.
120
121 /// This function will be called *inside* the session lock. ResourceManagers
122 /// DO NOT need to re-lock the session.
124 ResourceKey SrcK) = 0;
125};
126
127/// Lookup flags that apply to each dylib in the search order for a lookup.
128///
129/// If MatchHiddenSymbolsOnly is used (the default) for a given dylib, then
130/// only symbols in that Dylib's interface will be searched. If
131/// MatchHiddenSymbols is used then symbols with hidden visibility will match
132/// as well.
134
135/// Describes the kind of lookup being performed. The lookup kind is passed to
136/// symbol generators (if they're invoked) to help them determine what
137/// definitions to generate.
138///
139/// Static -- Lookup is being performed as-if at static link time (e.g.
140/// generators representing static archives should pull in new
141/// definitions).
142///
143/// DLSym -- Lookup is being performed as-if at runtime (e.g. generators
144/// representing static archives should not pull in new definitions).
145enum class LookupKind { Static, DLSym };
146
147/// A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search
148/// order during symbol lookup.
150 std::vector<std::pair<JITDylib *, JITDylibLookupFlags>>;
151
152/// Convenience function for creating a search order from an ArrayRef of
153/// JITDylib*, all with the same flags.
158 O.reserve(JDs.size());
159 for (auto *JD : JDs)
160 O.push_back(std::make_pair(JD, Flags));
161 return O;
162}
163
172
173/// A map of Symbols to (Symbol, Flags) pairs.
175
176/// Callback to notify client that symbols have been resolved.
178
179/// Callback to register the dependencies for a given query.
181 std::function<void(const SymbolDependenceMap &)>;
182
183/// This can be used as the value for a RegisterDependenciesFunction if there
184/// are no dependants to register with.
186
188 : public ErrorInfo<ResourceTrackerDefunct> {
189public:
190 static char ID;
191
193 std::error_code convertToErrorCode() const override;
194 void log(raw_ostream &OS) const override;
195
196private:
198};
199
200/// Returned by operations that fail because a JITDylib has been closed.
201class LLVM_ABI JITDylibDefunct : public ErrorInfo<JITDylibDefunct> {
202public:
203 static char ID;
204
206 std::error_code convertToErrorCode() const override;
207 void log(raw_ostream &OS) const override;
208
209private:
210 JITDylibSP JD;
211};
212
213/// Used to notify a JITDylib that the given set of symbols failed to
214/// materialize.
215class LLVM_ABI FailedToMaterialize : public ErrorInfo<FailedToMaterialize> {
216public:
217 static char ID;
218
219 FailedToMaterialize(std::shared_ptr<SymbolStringPool> SSP,
220 std::shared_ptr<SymbolDependenceMap> Symbols);
221 ~FailedToMaterialize() override;
222 std::error_code convertToErrorCode() const override;
223 void log(raw_ostream &OS) const override;
224 const SymbolDependenceMap &getSymbols() const { return *Symbols; }
225
226private:
227 std::shared_ptr<SymbolStringPool> SSP;
228 std::shared_ptr<SymbolDependenceMap> Symbols;
229};
230
231/// Used to report failure due to unsatisfiable symbol dependencies.
233 : public ErrorInfo<UnsatisfiedSymbolDependencies> {
234public:
235 static char ID;
236
237 UnsatisfiedSymbolDependencies(std::shared_ptr<SymbolStringPool> SSP,
238 JITDylibSP JD, SymbolNameSet FailedSymbols,
239 SymbolDependenceMap BadDeps,
240 std::string Explanation);
241 std::error_code convertToErrorCode() const override;
242 void log(raw_ostream &OS) const override;
243
244private:
245 std::shared_ptr<SymbolStringPool> SSP;
246 JITDylibSP JD;
247 SymbolNameSet FailedSymbols;
248 SymbolDependenceMap BadDeps;
249 std::string Explanation;
250};
251
252/// Used to notify clients when symbols can not be found during a lookup.
253class LLVM_ABI SymbolsNotFound : public ErrorInfo<SymbolsNotFound> {
254public:
255 static char ID;
256
257 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols);
258 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
259 SymbolNameVector Symbols);
260 std::error_code convertToErrorCode() const override;
261 void log(raw_ostream &OS) const override;
262 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
263 const SymbolNameVector &getSymbols() const { return Symbols; }
264
265private:
266 std::shared_ptr<SymbolStringPool> SSP;
267 SymbolNameVector Symbols;
268};
269
270/// Used to notify clients that a set of symbols could not be removed.
272 : public ErrorInfo<SymbolsCouldNotBeRemoved> {
273public:
274 static char ID;
275
276 SymbolsCouldNotBeRemoved(std::shared_ptr<SymbolStringPool> SSP,
277 SymbolNameSet Symbols);
278 std::error_code convertToErrorCode() const override;
279 void log(raw_ostream &OS) const override;
280 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
281 const SymbolNameSet &getSymbols() const { return Symbols; }
282
283private:
284 std::shared_ptr<SymbolStringPool> SSP;
285 SymbolNameSet Symbols;
286};
287
288/// Errors of this type should be returned if a module fails to include
289/// definitions that are claimed by the module's associated
290/// MaterializationResponsibility. If this error is returned it is indicative of
291/// a broken transformation / compiler / object cache.
293 : public ErrorInfo<MissingSymbolDefinitions> {
294public:
295 static char ID;
296
297 MissingSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
298 std::string ModuleName, SymbolNameVector Symbols)
299 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
300 Symbols(std::move(Symbols)) {}
301 std::error_code convertToErrorCode() const override;
302 void log(raw_ostream &OS) const override;
303 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
304 const std::string &getModuleName() const { return ModuleName; }
305 const SymbolNameVector &getSymbols() const { return Symbols; }
306private:
307 std::shared_ptr<SymbolStringPool> SSP;
308 std::string ModuleName;
309 SymbolNameVector Symbols;
310};
311
312/// Errors of this type should be returned if a module contains definitions for
313/// symbols that are not claimed by the module's associated
314/// MaterializationResponsibility. If this error is returned it is indicative of
315/// a broken transformation / compiler / object cache.
317 : public ErrorInfo<UnexpectedSymbolDefinitions> {
318public:
319 static char ID;
320
321 UnexpectedSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
322 std::string ModuleName, SymbolNameVector Symbols)
323 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
324 Symbols(std::move(Symbols)) {}
325 std::error_code convertToErrorCode() const override;
326 void log(raw_ostream &OS) const override;
327 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
328 const std::string &getModuleName() const { return ModuleName; }
329 const SymbolNameVector &getSymbols() const { return Symbols; }
330private:
331 std::shared_ptr<SymbolStringPool> SSP;
332 std::string ModuleName;
333 SymbolNameVector Symbols;
334};
335
336/// A set of symbols and the their dependencies. Used to describe dependencies
337/// for the MaterializationResponsibility::notifyEmitted operation.
342
343/// Tracks responsibility for materialization, and mediates interactions between
344/// MaterializationUnits and JDs.
345///
346/// An instance of this class is passed to MaterializationUnits when their
347/// materialize method is called. It allows MaterializationUnits to resolve and
348/// emit symbols, or abandon materialization by notifying any unmaterialized
349/// symbols of an error.
351 friend class ExecutionSession;
352 friend class JITDylib;
353
354public:
358
359 /// Destruct a MaterializationResponsibility instance. In debug mode
360 /// this asserts that all symbols being tracked have been either
361 /// emitted or notified of an error.
363
364 /// Return the ResourceTracker associated with this instance.
365 const ResourceTrackerSP &getResourceTracker() const { return RT; }
366
367 /// Runs the given callback under the session lock, passing in the associated
368 /// ResourceKey. This is the safe way to associate resources with trackers.
369 template <typename Func> Error withResourceKeyDo(Func &&F) const {
370 return RT->withResourceKeyDo(std::forward<Func>(F));
371 }
372
373 /// Returns the target JITDylib that these symbols are being materialized
374 /// into.
375 JITDylib &getTargetJITDylib() const { return JD; }
376
377 /// Returns the ExecutionSession for this instance.
379
380 /// Returns the symbol flags map for this responsibility instance.
381 /// Note: The returned flags may have transient flags (Lazy, Materializing)
382 /// set. These should be stripped with JITSymbolFlags::stripTransientFlags
383 /// before using.
384 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
385
386 /// Returns the initialization pseudo-symbol, if any. This symbol will also
387 /// be present in the SymbolFlagsMap for this MaterializationResponsibility
388 /// object.
389 const SymbolStringPtr &getInitializerSymbol() const { return InitSymbol; }
390
391 /// Returns the names of any symbols covered by this
392 /// MaterializationResponsibility object that have queries pending. This
393 /// information can be used to return responsibility for unrequested symbols
394 /// back to the JITDylib via the delegate method.
396
397 /// Notifies the target JITDylib that the given symbols have been resolved.
398 /// This will update the given symbols' addresses in the JITDylib, and notify
399 /// any pending queries on the given symbols of their resolution. The given
400 /// symbols must be ones covered by this MaterializationResponsibility
401 /// instance. Individual calls to this method may resolve a subset of the
402 /// symbols, but all symbols must have been resolved prior to calling emit.
403 ///
404 /// This method will return an error if any symbols being resolved have been
405 /// moved to the error state due to the failure of a dependency. If this
406 /// method returns an error then clients should log it and call
407 /// failMaterialize. If no dependencies have been registered for the
408 /// symbols covered by this MaterializationResponsibility then this method
409 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
410 Error notifyResolved(const SymbolMap &Symbols);
411
412 /// Notifies the target JITDylib (and any pending queries on that JITDylib)
413 /// that all symbols covered by this MaterializationResponsibility instance
414 /// have been emitted.
415 ///
416 /// The DepGroups array describes the dependencies of symbols being emitted on
417 /// symbols that are outside this MaterializationResponsibility object. Each
418 /// group consists of a pair of a set of symbols and a SymbolDependenceMap
419 /// that describes the dependencies for the symbols in the first set. The
420 /// elements of DepGroups must be non-overlapping (no symbol should appear in
421 /// more than one of hte symbol sets), but do not have to be exhaustive. Any
422 /// symbol in this MaterializationResponsibility object that is not covered
423 /// by an entry will be treated as having no dependencies.
424 ///
425 /// This method will return an error if any symbols being resolved have been
426 /// moved to the error state due to the failure of a dependency. If this
427 /// method returns an error then clients should log it and call
428 /// failMaterialize. If no dependencies have been registered for the
429 /// symbols covered by this MaterializationResponsibility then this method
430 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
432
433 /// Attempt to claim responsibility for new definitions. This method can be
434 /// used to claim responsibility for symbols that are added to a
435 /// materialization unit during the compilation process (e.g. literal pool
436 /// symbols). Symbol linkage rules are the same as for symbols that are
437 /// defined up front: duplicate strong definitions will result in errors.
438 /// Duplicate weak definitions will be discarded (in which case they will
439 /// not be added to this responsibility instance).
440 ///
441 /// This method can be used by materialization units that want to add
442 /// additional symbols at materialization time (e.g. stubs, compile
443 /// callbacks, metadata).
445
446 /// Notify all not-yet-emitted covered by this MaterializationResponsibility
447 /// instance that an error has occurred.
448 /// This will remove all symbols covered by this MaterializationResponsibility
449 /// from the target JITDylib, and send an error to any queries waiting on
450 /// these symbols.
451 void failMaterialization();
452
453 /// Transfers responsibility to the given MaterializationUnit for all
454 /// symbols defined by that MaterializationUnit. This allows
455 /// materializers to break up work based on run-time information (e.g.
456 /// by introspecting which symbols have actually been looked up and
457 /// materializing only those).
458 Error replace(std::unique_ptr<MaterializationUnit> MU);
459
460 /// Delegates responsibility for the given symbols to the returned
461 /// materialization responsibility. Useful for breaking up work between
462 /// threads, or different kinds of materialization processes.
464 delegate(const SymbolNameSet &Symbols);
465
466private:
467 /// Create a MaterializationResponsibility for the given JITDylib and
468 /// initial symbols.
470 SymbolFlagsMap SymbolFlags,
471 SymbolStringPtr InitSymbol)
472 : JD(RT->getJITDylib()), RT(std::move(RT)),
473 SymbolFlags(std::move(SymbolFlags)), InitSymbol(std::move(InitSymbol)) {
474 assert(!this->SymbolFlags.empty() && "Materializing nothing?");
475 }
476
477 JITDylib &JD;
479 SymbolFlagsMap SymbolFlags;
480 SymbolStringPtr InitSymbol;
481};
482
483/// A materialization unit for symbol aliases. Allows existing symbols to be
484/// aliased with alternate flags.
486public:
487 /// SourceJD is allowed to be nullptr, in which case the source JITDylib is
488 /// taken to be whatever JITDylib these definitions are materialized in (and
489 /// MatchNonExported has no effect). This is useful for defining aliases
490 /// within a JITDylib.
491 ///
492 /// Note: Care must be taken that no sets of aliases form a cycle, as such
493 /// a cycle will result in a deadlock when any symbol in the cycle is
494 /// resolved.
496 JITDylibLookupFlags SourceJDLookupFlags,
497 SymbolAliasMap Aliases);
498
499 StringRef getName() const override;
500
501private:
502 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
503 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
505 extractFlags(const SymbolAliasMap &Aliases);
506
507 JITDylib *SourceJD = nullptr;
508 JITDylibLookupFlags SourceJDLookupFlags;
509 SymbolAliasMap Aliases;
510};
511
512/// Create a ReExportsMaterializationUnit with the given aliases.
513/// Useful for defining symbol aliases.: E.g., given a JITDylib JD containing
514/// symbols "foo" and "bar", we can define aliases "baz" (for "foo") and "qux"
515/// (for "bar") with: \code{.cpp}
516/// SymbolStringPtr Baz = ...;
517/// SymbolStringPtr Qux = ...;
518/// if (auto Err = JD.define(symbolAliases({
519/// {Baz, { Foo, JITSymbolFlags::Exported }},
520/// {Qux, { Bar, JITSymbolFlags::Weak }}}))
521/// return Err;
522/// \endcode
523inline std::unique_ptr<ReExportsMaterializationUnit>
525 return std::make_unique<ReExportsMaterializationUnit>(
526 nullptr, JITDylibLookupFlags::MatchAllSymbols, std::move(Aliases));
527}
528
529/// Create a materialization unit for re-exporting symbols from another JITDylib
530/// with alternative names/flags.
531/// SourceJD will be searched using the given JITDylibLookupFlags.
532inline std::unique_ptr<ReExportsMaterializationUnit>
534 JITDylibLookupFlags SourceJDLookupFlags =
536 return std::make_unique<ReExportsMaterializationUnit>(
537 &SourceJD, SourceJDLookupFlags, std::move(Aliases));
538}
539
540/// Build a SymbolAliasMap for the common case where you want to re-export
541/// symbols from another JITDylib with the same linkage/flags.
543buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols);
544
545/// Represents the state that a symbol has reached during materialization.
546enum class SymbolState : uint8_t {
547 Invalid, /// No symbol should be in this state.
548 NeverSearched, /// Added to the symbol table, never queried.
549 Materializing, /// Queried, materialization begun.
550 Resolved, /// Assigned address, still materializing.
551 Emitted, /// Emitted to memory, but waiting on transitive dependencies.
552 Ready = 0x3f /// Ready and safe for clients to access.
553};
554
555/// A symbol query that returns results via a callback when results are
556/// ready.
557///
558/// makes a callback when all symbols are available.
560 friend class ExecutionSession;
562 friend class JITDylib;
564
565public:
566 /// Create a query for the given symbols. The NotifyComplete
567 /// callback will be called once all queried symbols reach the given
568 /// minimum state.
570 SymbolState RequiredState,
571 SymbolsResolvedCallback NotifyComplete);
572
573 /// Notify the query that a requested symbol has reached the required state.
576
577 /// Returns true if all symbols covered by this query have been
578 /// resolved.
579 bool isComplete() const { return OutstandingSymbolsCount == 0; }
580
581
582private:
583 void handleComplete(ExecutionSession &ES);
584
585 SymbolState getRequiredState() { return RequiredState; }
586
587 void addQueryDependence(JITDylib &JD, SymbolStringPtr Name);
588
589 void removeQueryDependence(JITDylib &JD, const SymbolStringPtr &Name);
590
591 void dropSymbol(const SymbolStringPtr &Name);
592
593 void handleFailed(Error Err);
594
595 void detach();
596
597 SymbolsResolvedCallback NotifyComplete;
598 SymbolDependenceMap QueryRegistrations;
599 SymbolMap ResolvedSymbols;
600 size_t OutstandingSymbolsCount;
601 SymbolState RequiredState;
602};
603
604/// Wraps state for a lookup-in-progress.
605/// DefinitionGenerators can optionally take ownership of a LookupState object
606/// to suspend a lookup-in-progress while they search for definitions.
608 friend class OrcV2CAPIHelper;
609 friend class ExecutionSession;
610
611public:
616
617 /// Continue the lookup. This can be called by DefinitionGenerators
618 /// to re-start a captured query-application operation.
619 LLVM_ABI void continueLookup(Error Err);
620
621private:
622 LookupState(std::unique_ptr<InProgressLookupState> IPLS);
623
624 // For C API.
625 void reset(InProgressLookupState *IPLS);
626
627 std::unique_ptr<InProgressLookupState> IPLS;
628};
629
630/// Definition generators can be attached to JITDylibs to generate new
631/// definitions for otherwise unresolved symbols during lookup.
633 friend class ExecutionSession;
634
635public:
636 virtual ~DefinitionGenerator();
637
638 /// DefinitionGenerators should override this method to insert new
639 /// definitions into the parent JITDylib. K specifies the kind of this
640 /// lookup. JD specifies the target JITDylib being searched, and
641 /// JDLookupFlags specifies whether the search should match against
642 /// hidden symbols. Finally, Symbols describes the set of unresolved
643 /// symbols and their associated lookup flags.
645 JITDylibLookupFlags JDLookupFlags,
646 const SymbolLookupSet &LookupSet) = 0;
647
648private:
649 std::mutex M;
650 bool InUse = false;
651 std::deque<LookupState> PendingLookups;
652};
653
654/// Represents a JIT'd dynamic library.
655///
656/// This class aims to mimic the behavior of a regular dylib or shared object,
657/// but without requiring the contained program representations to be compiled
658/// up-front. The JITDylib's content is defined by adding MaterializationUnits,
659/// and contained MaterializationUnits will typically rely on the JITDylib's
660/// links-against order to resolve external references (similar to a regular
661/// dylib).
662///
663/// The JITDylib object is a thin wrapper that references state held by the
664/// ExecutionSession. JITDylibs can be removed, clearing this underlying state
665/// and leaving the JITDylib object in a defunct state. In this state the
666/// JITDylib's name is guaranteed to remain accessible. If the ExecutionSession
667/// is still alive then other operations are callable but will return an Error
668/// or null result (depending on the API). It is illegal to call any operation
669/// other than getName on a JITDylib after the ExecutionSession has been torn
670/// down.
671///
672/// JITDylibs cannot be moved or copied. Their address is stable, and useful as
673/// a key in some JIT data structures.
674class JITDylib : public ThreadSafeRefCountedBase<JITDylib>,
675 public jitlink::JITLinkDylib {
677 friend class ExecutionSession;
678 friend class Platform;
680public:
681
682 JITDylib(const JITDylib &) = delete;
683 JITDylib &operator=(const JITDylib &) = delete;
684 JITDylib(JITDylib &&) = delete;
687
688 /// Get a reference to the ExecutionSession for this JITDylib.
689 ///
690 /// It is legal to call this method on a defunct JITDylib, however the result
691 /// will only usable if the ExecutionSession is still alive. If this JITDylib
692 /// is held by an error that may have torn down the JIT then the result
693 /// should not be used.
694 ExecutionSession &getExecutionSession() const { return ES; }
695
696 /// Dump current JITDylib state to OS.
697 ///
698 /// It is legal to call this method on a defunct JITDylib.
699 LLVM_ABI void dump(raw_ostream &OS);
700
701 /// Calls remove on all trackers currently associated with this JITDylib.
702 /// Does not run static deinits.
703 ///
704 /// Note that removal happens outside the session lock, so new code may be
705 /// added concurrently while the clear is underway, and the newly added
706 /// code will *not* be cleared. Adding new code concurrently with a clear
707 /// is usually a bug and should be avoided.
708 ///
709 /// It is illegal to call this method on a defunct JITDylib and the client
710 /// is responsible for ensuring that they do not do so.
712
713 /// Get the default resource tracker for this JITDylib.
714 ///
715 /// It is illegal to call this method on a defunct JITDylib and the client
716 /// is responsible for ensuring that they do not do so.
718
719 /// Create a resource tracker for this JITDylib.
720 ///
721 /// It is illegal to call this method on a defunct JITDylib and the client
722 /// is responsible for ensuring that they do not do so.
724
725 /// Adds a definition generator to this JITDylib and returns a referenece to
726 /// it.
727 ///
728 /// When JITDylibs are searched during lookup, if no existing definition of
729 /// a symbol is found, then any generators that have been added are run (in
730 /// the order that they were added) to potentially generate a definition.
731 ///
732 /// It is illegal to call this method on a defunct JITDylib and the client
733 /// is responsible for ensuring that they do not do so.
734 template <typename GeneratorT>
735 GeneratorT &addGenerator(std::unique_ptr<GeneratorT> DefGenerator);
736
737 /// Remove a definition generator from this JITDylib.
738 ///
739 /// The given generator must exist in this JITDylib's generators list (i.e.
740 /// have been added and not yet removed).
741 ///
742 /// It is illegal to call this method on a defunct JITDylib and the client
743 /// is responsible for ensuring that they do not do so.
745
746 /// Set the link order to be used when fixing up definitions in JITDylib.
747 /// This will replace the previous link order, and apply to any symbol
748 /// resolutions made for definitions in this JITDylib after the call to
749 /// setLinkOrder (even if the definition itself was added before the
750 /// call).
751 ///
752 /// If LinkAgainstThisJITDylibFirst is true (the default) then this JITDylib
753 /// will add itself to the beginning of the LinkOrder (Clients should not
754 /// put this JITDylib in the list in this case, to avoid redundant lookups).
755 ///
756 /// If LinkAgainstThisJITDylibFirst is false then the link order will be used
757 /// as-is. The primary motivation for this feature is to support deliberate
758 /// shadowing of symbols in this JITDylib by a facade JITDylib. For example,
759 /// the facade may resolve function names to stubs, and the stubs may compile
760 /// lazily by looking up symbols in this dylib. Adding the facade dylib
761 /// as the first in the link order (instead of this dylib) ensures that
762 /// definitions within this dylib resolve to the lazy-compiling stubs,
763 /// rather than immediately materializing the definitions in this dylib.
764 ///
765 /// It is illegal to call this method on a defunct JITDylib and the client
766 /// is responsible for ensuring that they do not do so.
767 LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder,
768 bool LinkAgainstThisJITDylibFirst = true);
769
770 /// Append the given JITDylibSearchOrder to the link order for this
771 /// JITDylib (discarding any elements already present in this JITDylib's
772 /// link order).
773 LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks);
774
775 /// Add the given JITDylib to the link order for definitions in this
776 /// JITDylib.
777 ///
778 /// It is illegal to call this method on a defunct JITDylib and the client
779 /// is responsible for ensuring that they do not do so.
780 LLVM_ABI void
782 JITDylibLookupFlags JDLookupFlags =
784
785 /// Replace OldJD with NewJD in the link order if OldJD is present.
786 /// Otherwise this operation is a no-op.
787 ///
788 /// It is illegal to call this method on a defunct JITDylib and the client
789 /// is responsible for ensuring that they do not do so.
790 LLVM_ABI void
791 replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
792 JITDylibLookupFlags JDLookupFlags =
794
795 /// Remove the given JITDylib from the link order for this JITDylib if it is
796 /// present. Otherwise this operation is a no-op.
797 ///
798 /// It is illegal to call this method on a defunct JITDylib and the client
799 /// is responsible for ensuring that they do not do so.
801
802 /// Do something with the link order (run under the session lock).
803 ///
804 /// It is illegal to call this method on a defunct JITDylib and the client
805 /// is responsible for ensuring that they do not do so.
806 template <typename Func>
807 auto withLinkOrderDo(Func &&F)
808 -> decltype(F(std::declval<const JITDylibSearchOrder &>()));
809
810 /// Define all symbols provided by the materialization unit to be part of this
811 /// JITDylib.
812 ///
813 /// If RT is not specified then the default resource tracker will be used.
814 ///
815 /// This overload always takes ownership of the MaterializationUnit. If any
816 /// errors occur, the MaterializationUnit consumed.
817 ///
818 /// It is illegal to call this method on a defunct JITDylib and the client
819 /// is responsible for ensuring that they do not do so.
820 template <typename MaterializationUnitType>
821 Error define(std::unique_ptr<MaterializationUnitType> &&MU,
822 ResourceTrackerSP RT = nullptr);
823
824 /// Define all symbols provided by the materialization unit to be part of this
825 /// JITDylib.
826 ///
827 /// This overload only takes ownership of the MaterializationUnit no error is
828 /// generated. If an error occurs, ownership remains with the caller. This
829 /// may allow the caller to modify the MaterializationUnit to correct the
830 /// issue, then re-call define.
831 ///
832 /// It is illegal to call this method on a defunct JITDylib and the client
833 /// is responsible for ensuring that they do not do so.
834 template <typename MaterializationUnitType>
835 Error define(std::unique_ptr<MaterializationUnitType> &MU,
836 ResourceTrackerSP RT = nullptr);
837
838 /// Tries to remove the given symbols.
839 ///
840 /// If any symbols are not defined in this JITDylib this method will return
841 /// a SymbolsNotFound error covering the missing symbols.
842 ///
843 /// If all symbols are found but some symbols are in the process of being
844 /// materialized this method will return a SymbolsCouldNotBeRemoved error.
845 ///
846 /// On success, all symbols are removed. On failure, the JITDylib state is
847 /// left unmodified (no symbols are removed).
848 ///
849 /// It is illegal to call this method on a defunct JITDylib and the client
850 /// is responsible for ensuring that they do not do so.
851 LLVM_ABI Error remove(const SymbolNameSet &Names);
852
853 /// Returns the given JITDylibs and all of their transitive dependencies in
854 /// DFS order (based on linkage relationships). Each JITDylib will appear
855 /// only once.
856 ///
857 /// If any JITDylib in the order is defunct then this method will return an
858 /// error, otherwise returns the order.
861
862 /// Returns the given JITDylibs and all of their transitive dependencies in
863 /// reverse DFS order (based on linkage relationships). Each JITDylib will
864 /// appear only once.
865 ///
866 /// If any JITDylib in the order is defunct then this method will return an
867 /// error, otherwise returns the order.
870
871 /// Return this JITDylib and its transitive dependencies in DFS order
872 /// based on linkage relationships.
873 ///
874 /// If any JITDylib in the order is defunct then this method will return an
875 /// error, otherwise returns the order.
877
878 /// Rteurn this JITDylib and its transitive dependencies in reverse DFS order
879 /// based on linkage relationships.
880 ///
881 /// If any JITDylib in the order is defunct then this method will return an
882 /// error, otherwise returns the order.
884
885private:
886 using AsynchronousSymbolQuerySet =
887 std::set<std::shared_ptr<AsynchronousSymbolQuery>>;
888
889 using AsynchronousSymbolQueryList =
890 std::vector<std::shared_ptr<AsynchronousSymbolQuery>>;
891
892 struct UnmaterializedInfo {
893 UnmaterializedInfo(std::unique_ptr<MaterializationUnit> MU,
894 ResourceTracker *RT)
895 : MU(std::move(MU)), RT(RT) {}
896
897 std::unique_ptr<MaterializationUnit> MU;
898 ResourceTracker *RT;
899 };
900
901 using UnmaterializedInfosMap =
902 DenseMap<SymbolStringPtr, std::shared_ptr<UnmaterializedInfo>>;
903
904 using UnmaterializedInfosList =
905 std::vector<std::shared_ptr<UnmaterializedInfo>>;
906
907 // Information about not-yet-ready symbol.
908 // * DefiningEDU will point to the EmissionDepUnit that defines the symbol.
909 // * DependantEDUs will hold pointers to any EmissionDepUnits currently
910 // waiting on this symbol.
911 // * Pending queries holds any not-yet-completed queries that include this
912 // symbol.
913 struct MaterializingInfo {
914 friend class ExecutionSession;
915
916 LLVM_ABI void addQuery(std::shared_ptr<AsynchronousSymbolQuery> Q);
917 LLVM_ABI void removeQuery(const AsynchronousSymbolQuery &Q);
918 LLVM_ABI AsynchronousSymbolQueryList
919 takeQueriesMeeting(SymbolState RequiredState);
920 AsynchronousSymbolQueryList takeAllPendingQueries() {
921 return std::move(PendingQueries);
922 }
923 bool hasQueriesPending() const { return !PendingQueries.empty(); }
924 const AsynchronousSymbolQueryList &pendingQueries() const {
925 return PendingQueries;
926 }
927 private:
928 AsynchronousSymbolQueryList PendingQueries;
929 };
930
931 using MaterializingInfosMap = DenseMap<SymbolStringPtr, MaterializingInfo>;
932
933 class SymbolTableEntry {
934 public:
935 SymbolTableEntry() = default;
936 SymbolTableEntry(JITSymbolFlags Flags)
937 : Flags(Flags), State(static_cast<uint8_t>(SymbolState::NeverSearched)),
938 MaterializerAttached(false) {}
939
940 ExecutorAddr getAddress() const { return Addr; }
941 JITSymbolFlags getFlags() const { return Flags; }
942 SymbolState getState() const { return static_cast<SymbolState>(State); }
943
944 bool hasMaterializerAttached() const { return MaterializerAttached; }
945
946 void setAddress(ExecutorAddr Addr) { this->Addr = Addr; }
947 void setFlags(JITSymbolFlags Flags) { this->Flags = Flags; }
948 void setState(SymbolState State) {
949 assert(static_cast<uint8_t>(State) < (1 << 6) &&
950 "State does not fit in bitfield");
951 this->State = static_cast<uint8_t>(State);
952 }
953
954 void setMaterializerAttached(bool MaterializerAttached) {
955 this->MaterializerAttached = MaterializerAttached;
956 }
957
958 ExecutorSymbolDef getSymbol() const { return {Addr, Flags}; }
959
960 private:
961 ExecutorAddr Addr;
962 JITSymbolFlags Flags;
963 uint8_t State : 7;
964 uint8_t MaterializerAttached : 1;
965 };
966
967 using SymbolTable = DenseMap<SymbolStringPtr, SymbolTableEntry>;
968
969 JITDylib(ExecutionSession &ES, std::string Name);
970
971 struct RemoveTrackerResult {
972 AsynchronousSymbolQuerySet QueriesToFail;
973 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
974 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
975 };
976
977 RemoveTrackerResult IL_removeTracker(ResourceTracker &RT);
978
979 void transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
980
981 LLVM_ABI Error defineImpl(MaterializationUnit &MU);
982
983 LLVM_ABI void
984 installMaterializationUnit(std::unique_ptr<MaterializationUnit> MU,
985 ResourceTracker &RT);
986
987 void detachQueryHelper(AsynchronousSymbolQuery &Q,
988 const SymbolNameSet &QuerySymbols);
989
990 Expected<SymbolFlagsMap>
991 defineMaterializing(MaterializationResponsibility &FromMR,
992 SymbolFlagsMap SymbolFlags);
993
994 Error replace(MaterializationResponsibility &FromMR,
995 std::unique_ptr<MaterializationUnit> MU);
996
997 Expected<std::unique_ptr<MaterializationResponsibility>>
998 delegate(MaterializationResponsibility &FromMR, SymbolFlagsMap SymbolFlags,
999 SymbolStringPtr InitSymbol);
1000
1001 SymbolNameSet getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const;
1002
1004
1005 void unlinkMaterializationResponsibility(MaterializationResponsibility &MR);
1006
1007 /// Attempt to reduce memory usage from empty \c UnmaterializedInfos and
1008 /// \c MaterializingInfos tables.
1009 void shrinkMaterializationInfoMemory();
1010
1011 ExecutionSession &ES;
1012 enum { Open, Closing, Closed } State = Open;
1013 std::mutex GeneratorsMutex;
1014 SymbolTable Symbols;
1015 UnmaterializedInfosMap UnmaterializedInfos;
1016 MaterializingInfosMap MaterializingInfos;
1017 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1018 JITDylibSearchOrder LinkOrder;
1019 ResourceTrackerSP DefaultTracker;
1020
1021 // Map trackers to sets of symbols tracked.
1022 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1023 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1024 TrackerMRs;
1025};
1026
1027/// Platforms set up standard symbols and mediate interactions between dynamic
1028/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1029/// Note that Platforms do not automatically run initializers: clients are still
1030/// responsible for doing this.
1032public:
1033 virtual ~Platform();
1034
1035 /// This method will be called outside the session lock each time a JITDylib
1036 /// is created (unless it is created with EmptyJITDylib set) to allow the
1037 /// Platform to install any JITDylib specific standard symbols (e.g
1038 /// __dso_handle).
1039 virtual Error setupJITDylib(JITDylib &JD) = 0;
1040
1041 /// This method will be called outside the session lock each time a JITDylib
1042 /// is removed to allow the Platform to remove any JITDylib-specific data.
1044
1045 /// This method will be called under the ExecutionSession lock each time a
1046 /// MaterializationUnit is added to a JITDylib.
1048 const MaterializationUnit &MU) = 0;
1049
1050 /// This method will be called under the ExecutionSession lock when a
1051 /// ResourceTracker is removed.
1053
1054 /// A utility function for looking up initializer symbols. Performs a blocking
1055 /// lookup for the given symbols in each of the given JITDylibs.
1056 ///
1057 /// Note: This function is deprecated and will be removed in the near future.
1061
1062 /// Performs an async lookup for the given symbols in each of the given
1063 /// JITDylibs, calling the given handler once all lookups have completed.
1064 static void
1066 ExecutionSession &ES,
1068};
1069
1070/// A materialization task.
1072 : public RTTIExtends<MaterializationTask, Task> {
1073public:
1074 static char ID;
1075
1076 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1077 std::unique_ptr<MaterializationResponsibility> MR)
1078 : MU(std::move(MU)), MR(std::move(MR)) {}
1079 ~MaterializationTask() override;
1080 void printDescription(raw_ostream &OS) override;
1081 void run() override;
1082
1083private:
1084 std::unique_ptr<MaterializationUnit> MU;
1085 std::unique_ptr<MaterializationResponsibility> MR;
1086};
1087
1088/// Lookups are usually run on the current thread, but in some cases they may
1089/// be run as tasks, e.g. if the lookup has been continued from a suspended
1090/// state.
1091class LLVM_ABI LookupTask : public RTTIExtends<LookupTask, Task> {
1092public:
1093 static char ID;
1094
1095 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1096 void printDescription(raw_ostream &OS) override;
1097 void run() override;
1098
1099private:
1100 LookupState LS;
1101};
1102
1103/// An ExecutionSession represents a running JIT program.
1107 friend class JITDylib;
1108 friend class LookupState;
1110 friend class ResourceTracker;
1111
1112public:
1113 /// For reporting errors.
1115
1116 /// Function type for returning results from a call-controller handler.
1119
1120 /// A call-controller handler: handles calls from the executor made via the
1121 /// ORC runtime's call-controller mechanism.
1124
1125 /// Associates a call-controller handler with the name of the tag symbol that
1126 /// the executor will use to call it, and the SymbolLookupFlags to use when
1127 /// looking that tag up.
1128 ///
1129 /// The name is not copied (see SymbolNameSpec): the referenced string must
1130 /// outlive the registerCallControllerHandlers call that the binding is
1131 /// passed to. Ordinary string literals have static storage duration, so
1132 /// they are always safe.
1134 public:
1138 : Name(Name), Handler(std::move(Handler)), LF(LF) {}
1139
1140 SymbolNameSpec getName() const { return Name; }
1141
1142 CallControllerHandlerFn takeHandler() { return std::move(Handler); }
1143
1144 SymbolLookupFlags getLookupFlags() const { return LF; }
1145
1146 private:
1147 SymbolNameSpec Name;
1150 };
1151
1152 /// Construct an ExecutionSession with the given ExecutorProcessControl
1153 /// object.
1154 LLVM_ABI ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1155
1160
1161 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1162 /// destruction.
1164
1165 /// End the session. Closes all JITDylibs and disconnects from the
1166 /// executor. Clients must call this method before destroying the session.
1168
1169 /// Get the ExecutorProcessControl object associated with this
1170 /// ExecutionSession.
1172
1173 /// Return the triple for the executor.
1174 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1175
1176 // Return the page size for the executor.
1177 size_t getPageSize() const { return EPC->getPageSize(); }
1178
1179 /// Get the SymbolStringPool for this instance.
1180 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1181 return EPC->getSymbolStringPool();
1182 }
1183
1184 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1185 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1186
1187 /// Returns a reference to the bootstrap JITDylib.
1188 ///
1189 /// This is a bare JITDylib that is created for each ExecutionSession and
1190 /// populated with the bootstrap symbol definitions provided by the
1191 /// ExecutorProcessControl object.
1192 JITDylib &getBootstrapJITDylib() { return BootstrapJD; }
1193
1194 /// Set a WaitingOnGraph::Recorder to capture WaitingOnGraph operations.
1195 ///
1196 /// This method can be called at most once. If called, it should be called
1197 /// before any symbols are materialized.
1198 void setWaitingOnGraphOpRecorder(WaitingOnGraph::OpRecorder &R) {
1199 assert(!GOpRecorder && "WaitingOnGraph recorder already set");
1200 GOpRecorder = &R;
1201 }
1202
1203 /// Set the Platform for this ExecutionSession.
1204 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1205
1206 /// Get the Platform for this session.
1207 /// Will return null if no Platform has been set for this ExecutionSession.
1208 Platform *getPlatform() { return P.get(); }
1209
1210 /// Run the given lambda with the session mutex locked.
1211 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1212 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1213 return F();
1214 }
1215
1216 /// Register the given ResourceManager with this ExecutionSession.
1217 /// Managers will be notified of events in reverse order of registration.
1219
1220 /// Deregister the given ResourceManager with this ExecutionSession.
1221 /// Manager must have been previously registered.
1223
1224 /// Return a pointer to the "name" JITDylib.
1225 /// Ownership of JITDylib remains within Execution Session
1227
1228 /// Add a new bare JITDylib to this ExecutionSession.
1229 ///
1230 /// The JITDylib Name is required to be unique. Clients should verify that
1231 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1232 /// are based on user input.
1233 ///
1234 /// This call does not install any library code or symbols into the newly
1235 /// created JITDylib. The client is responsible for all configuration.
1236 LLVM_ABI JITDylib &createBareJITDylib(std::string Name);
1237
1238 /// Add a new JITDylib to this ExecutionSession.
1239 ///
1240 /// The JITDylib Name is required to be unique. Clients should verify that
1241 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1242 /// are based on user input.
1243 ///
1244 /// If a Platform is attached then Platform::setupJITDylib will be called to
1245 /// install standard platform symbols (e.g. standard library interposes).
1246 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1248
1249 /// Removes the given JITDylibs from the ExecutionSession.
1250 ///
1251 /// This method clears all resources held for the JITDylibs, puts them in the
1252 /// closed state, and clears all references to them that are held by the
1253 /// ExecutionSession or other JITDylibs. No further code can be added to the
1254 /// removed JITDylibs, and the JITDylib objects will be freed once any
1255 /// remaining JITDylibSPs pointing to them are destroyed.
1256 ///
1257 /// This method does *not* run static destructors for code contained in the
1258 /// JITDylibs, and each JITDylib can only be removed once.
1259 ///
1260 /// JITDylibs will be removed in the order given. Teardown is usually
1261 /// independent for each JITDylib, but not always. In particular, where the
1262 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1263 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1264 /// last. If the client has introduced any other dependencies they should be
1265 /// accounted for in the removal order too.
1266 LLVM_ABI Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1267
1268 /// Calls removeJTIDylibs on the gives JITDylib.
1270 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1271 }
1272
1273 /// Set the error reporter function.
1275 this->ReportError = std::move(ReportError);
1276 return *this;
1277 }
1278
1279 /// Report a error for this execution session.
1280 ///
1281 /// Unhandled errors can be sent here to log them.
1282 void reportError(Error Err) { ReportError(std::move(Err)); }
1283
1284 /// Search the given JITDylibs to find the flags associated with each of the
1285 /// given symbols.
1286 LLVM_ABI void
1288 SymbolLookupSet Symbols,
1289 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1290
1291 /// Blocking version of lookupFlags.
1293 JITDylibSearchOrder SearchOrder,
1294 SymbolLookupSet Symbols);
1295
1296 /// Search the given JITDylibs for the given symbols.
1297 ///
1298 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1299 /// boolean indicates whether the search should match against non-exported
1300 /// (hidden visibility) symbols in that dylib (true means match against
1301 /// non-exported symbols, false means do not match).
1302 ///
1303 /// The NotifyComplete callback will be called once all requested symbols
1304 /// reach the required state.
1305 ///
1306 /// If all symbols are found, the RegisterDependencies function will be called
1307 /// while the session lock is held. This gives clients a chance to register
1308 /// dependencies for on the queried symbols for any symbols they are
1309 /// materializing (if a MaterializationResponsibility instance is present,
1310 /// this can be implemented by calling
1311 /// MaterializationResponsibility::addDependencies). If there are no
1312 /// dependenant symbols for this query (e.g. it is being made by a top level
1313 /// client to get an address to call) then the value NoDependenciesToRegister
1314 /// can be used.
1315 LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1316 SymbolLookupSet Symbols, SymbolState RequiredState,
1317 SymbolsResolvedCallback NotifyComplete,
1318 RegisterDependenciesFunction RegisterDependencies);
1319
1320 /// Blocking version of lookup above. Returns the resolved symbol map.
1321 /// If WaitUntilReady is true (the default), will not return until all
1322 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1323 /// false, will return as soon as all requested symbols are resolved,
1324 /// or an error occurs. If WaitUntilReady is false and an error occurs
1325 /// after resolution, the function will return a success value, but the
1326 /// error will be reported via reportErrors.
1328 lookup(const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols,
1330 SymbolState RequiredState = SymbolState::Ready,
1331 RegisterDependenciesFunction RegisterDependencies =
1333
1334 /// Convenience version of blocking lookup.
1335 /// Searches each of the JITDylibs in the search order in turn for the given
1336 /// symbol.
1338 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1339 SymbolState RequiredState = SymbolState::Ready);
1340
1341 /// Convenience version of blocking lookup.
1342 /// Searches each of the JITDylibs in the search order in turn for the given
1343 /// symbol. The search will not find non-exported symbols.
1345 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1346 SymbolState RequiredState = SymbolState::Ready);
1347
1348 /// Convenience version of blocking lookup.
1349 /// Searches each of the JITDylibs in the search order in turn for the given
1350 /// symbol. The search will not find non-exported symbols.
1352 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1353 SymbolState RequiredState = SymbolState::Ready);
1354
1355 /// Materialize the given unit.
1356 void dispatchTask(std::unique_ptr<Task> T) {
1357 assert(T && "T must be non-null");
1358 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1359 EPC->getDispatcher().dispatch(std::move(T));
1360 }
1361
1362 /// Returns the bootstrap map.
1364 return EPC->getBootstrapMap();
1365 }
1366
1367 /// Look up and SPS-deserialize a bootstrap map value.
1368 template <typename T, typename SPSTagT>
1369 Error getBootstrapMapValue(StringRef Key, std::optional<T> &Val) const {
1370 return EPC->getBootstrapMapValue<T, SPSTagT>(Key, Val);
1371 }
1372
1373 /// Returns the bootstrap symbol map.
1375 return EPC->getBootstrapSymbolsMap();
1376 }
1377
1378 /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
1379 /// bootstrap symbols map and writes its address to the ExecutorAddr if
1380 /// found. If any symbol is not found then the function returns an error.
1382 ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
1383 return EPC->getBootstrapSymbols(Pairs);
1384 }
1385
1386 /// Run a wrapper function in the executor. The given WFRHandler will be
1387 /// called on the result when it is returned.
1388 ///
1389 /// The wrapper function should be callable as:
1390 ///
1391 /// \code{.cpp}
1392 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1393 /// \endcode{.cpp}
1394 void callWrapperAsync(ExecutorAddr WrapperFnAddr,
1396 ArrayRef<char> ArgBuffer) {
1397 EPC->callWrapperAsync(WrapperFnAddr, std::move(OnComplete), ArgBuffer);
1398 }
1399
1400 /// Run a wrapper function in the executor using the given Runner to dispatch
1401 /// OnComplete when the result is ready.
1402 template <typename RunPolicyT, typename FnT>
1403 void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
1404 FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
1405 EPC->callWrapperAsync(std::forward<RunPolicyT>(Runner), WrapperFnAddr,
1406 std::forward<FnT>(OnComplete), ArgBuffer);
1407 }
1408
1409 /// Run a wrapper function in the executor. OnComplete will be dispatched
1410 /// as a GenericNamedTask using this instance's TaskDispatch object.
1411 template <typename FnT>
1412 void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
1413 ArrayRef<char> ArgBuffer) {
1414 EPC->callWrapperAsync(WrapperFnAddr, std::forward<FnT>(OnComplete),
1415 ArgBuffer);
1416 }
1417
1418 /// For each binding, look up its tag symbol in JD and register the binding's
1419 /// call-controller handler for the tag's address. The handler becomes
1420 /// callable from the executor via the ORC runtime's call-controller
1421 /// mechanism, using the tag's address as the handler tag.
1422 ///
1423 /// Tag names are mangled for the session's target triple, then looked up
1424 /// in JD using LookupKind::Static and JITDylibLookupFlags::MatchAllSymbols
1425 /// (hidden tags will be found), with each binding's SymbolLookupFlags. If a
1426 /// weakly referenced tag is not found then its handler is dropped.
1427 ///
1428 /// On failure no handlers are registered.
1430 JITDylib &JD, std::vector<CallControllerHandlerBinding> Hs);
1431
1432 /// Convenience overload of registerCallControllerHandlers that takes the
1433 /// bindings as arguments, so that they can be constructed inline at the
1434 /// call site.
1435 template <typename... BindingTs>
1436 std::enable_if_t<
1437 (std::is_same_v<BindingTs, CallControllerHandlerBinding> && ...), Error>
1439 std::vector<CallControllerHandlerBinding> Bs;
1440 Bs.reserve(sizeof...(Hs));
1441 (Bs.push_back(std::move(Hs)), ...);
1442 return registerCallControllerHandlers(JD, std::move(Bs));
1443 }
1444
1445 /// Run the call-controller handler registered for the given tag address.
1446 /// This should be called by the ExecutorProcessControl instance in response
1447 /// to calls from the executor made via the ORC runtime's call-controller
1448 /// mechanism.
1449 LLVM_ABI void
1451 ExecutorAddr HandlerFnTagAddr,
1453
1454 /// Dump the state of all the JITDylibs in this session.
1455 LLVM_ABI void dump(raw_ostream &OS);
1456
1457 /// Check the internal consistency of ExecutionSession data structures.
1458#ifdef EXPENSIVE_CHECKS
1459 bool verifySessionState(Twine Phase);
1460#endif
1461
1462private:
1463 static void logErrorsToStdErr(Error Err) {
1464 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1465 }
1466
1467 void dispatchOutstandingMUs();
1468
1469 static std::unique_ptr<MaterializationResponsibility>
1470 createMaterializationResponsibility(ResourceTracker &RT,
1471 SymbolFlagsMap Symbols,
1472 SymbolStringPtr InitSymbol) {
1473 auto &JD = RT.getJITDylib();
1474 std::unique_ptr<MaterializationResponsibility> MR(
1475 new MaterializationResponsibility(&RT, std::move(Symbols),
1476 std::move(InitSymbol)));
1477 JD.TrackerMRs[&RT].insert(MR.get());
1478 return MR;
1479 }
1480
1481 Error removeResourceTracker(ResourceTracker &RT);
1482 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1483 void destroyResourceTracker(ResourceTracker &RT);
1484
1485 // State machine functions for query application..
1486
1487 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1488 /// match a given query from the set of candidate symbols to generate
1489 /// definitions for (no need to generate a definition if one already exists).
1490 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1491 SymbolLookupSet &Candidates,
1492 SymbolLookupSet *NonCandidates);
1493
1494 /// Handle resumption of a lookup after entering a generator.
1495 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1496
1497 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1498 /// definition generation. It is called when a lookup is performed, and again
1499 /// each time that LookupState::continueLookup is called.
1500 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1501 Error Err);
1502
1503 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1504 /// call. It attempts to attach the symbol to all symbol table entries and
1505 /// collect all MaterializationUnits to dispatch. If this method fails then
1506 /// all MaterializationUnits will be left un-materialized.
1507 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1508 std::shared_ptr<AsynchronousSymbolQuery> Q,
1509 RegisterDependenciesFunction RegisterDependencies);
1510
1511 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1512 /// lookupFlags call.
1513 void OL_completeLookupFlags(
1514 std::unique_ptr<InProgressLookupState> IPLS,
1515 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1516
1517 // State machine functions for MaterializationResponsibility.
1518 LLVM_ABI void
1519 OL_destroyMaterializationResponsibility(MaterializationResponsibility &MR);
1521 OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1522 LLVM_ABI Error OL_notifyResolved(MaterializationResponsibility &MR,
1523 const SymbolMap &Symbols);
1524
1525 // FIXME: We should be able to derive FailedSymsForQuery from each query once
1526 // we fix how the detach operation works.
1527 struct EmitQueries {
1528 JITDylib::AsynchronousSymbolQuerySet Completed;
1529 JITDylib::AsynchronousSymbolQuerySet Failed;
1530 DenseMap<AsynchronousSymbolQuery *, std::shared_ptr<SymbolDependenceMap>>
1531 FailedSymsForQuery;
1532 };
1533
1535 IL_getSymbolState(JITDylib *JD, NonOwningSymbolStringPtr Name);
1536
1537 template <typename UpdateSymbolFn, typename UpdateQueryFn>
1538 void IL_collectQueries(JITDylib::AsynchronousSymbolQuerySet &Qs,
1539 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
1540 UpdateSymbolFn &&UpdateSymbol,
1541 UpdateQueryFn &&UpdateQuery);
1542
1543 Expected<EmitQueries> IL_emit(MaterializationResponsibility &MR,
1544 WaitingOnGraph::SimplifyResult SR);
1545 LLVM_ABI Error OL_notifyEmitted(MaterializationResponsibility &MR,
1547
1548 LLVM_ABI Error OL_defineMaterializing(MaterializationResponsibility &MR,
1549 SymbolFlagsMap SymbolFlags);
1550
1551 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1552 std::shared_ptr<SymbolDependenceMap>>
1553 IL_failSymbols(JITDylib &JD, const SymbolNameVector &SymbolsToFail);
1554 LLVM_ABI void OL_notifyFailed(MaterializationResponsibility &MR);
1556 std::unique_ptr<MaterializationUnit> MU);
1557 LLVM_ABI Expected<std::unique_ptr<MaterializationResponsibility>>
1558 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1559
1560#ifndef NDEBUG
1561 void dumpDispatchInfo(Task &T);
1562#endif // NDEBUG
1563
1564 mutable std::recursive_mutex SessionMutex;
1565 bool SessionOpen = true;
1566 std::unique_ptr<ExecutorProcessControl> EPC;
1567 std::unique_ptr<Platform> P;
1568 ErrorReporter ReportError = logErrorsToStdErr;
1569
1570 std::vector<ResourceManager *> ResourceManagers;
1571
1572 std::vector<JITDylibSP> JDs;
1573 JITDylib &BootstrapJD;
1575 WaitingOnGraph::OpRecorder *GOpRecorder = nullptr;
1576
1577 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1578 // with callbacks from asynchronous queries.
1579 mutable std::recursive_mutex OutstandingMUsMutex;
1580 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1581 std::unique_ptr<MaterializationResponsibility>>>
1582 OutstandingMUs;
1583
1584 mutable std::mutex CallControllerHandlersMutex;
1585 DenseMap<ExecutorAddr, std::unique_ptr<CallControllerHandlerFn>>
1586 CallControllerHandlers;
1587};
1588
1589template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1591 if (isDefunct())
1593 F(getKeyUnsafe());
1594 return Error::success();
1595 });
1596}
1597
1598inline ExecutionSession &
1600 return JD.getExecutionSession();
1601}
1602
1603template <typename GeneratorT>
1604GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1605 auto &G = *DefGenerator;
1606 ES.runSessionLocked([&] {
1607 assert(State == Open && "Cannot add generator to closed JITDylib");
1608 DefGenerators.push_back(std::move(DefGenerator));
1609 });
1610 return G;
1611}
1612
1613template <typename Func>
1615 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1616 assert(State == Open && "Cannot use link order of closed JITDylib");
1617 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1618}
1619
1620template <typename MaterializationUnitType>
1621Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1622 ResourceTrackerSP RT) {
1623 assert(MU && "Can not define with a null MU");
1624
1625 if (MU->getSymbols().empty()) {
1626 // Empty MUs are allowable but pathological, so issue a warning.
1627 DEBUG_WITH_TYPE("orc", {
1628 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1629 << getName() << "\n";
1630 });
1631 return Error::success();
1632 } else
1633 DEBUG_WITH_TYPE("orc", {
1634 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1635 << " (tracker: ";
1636 if (RT == getDefaultResourceTracker())
1637 dbgs() << "default)";
1638 else if (RT)
1639 dbgs() << RT.get() << ")\n";
1640 else
1641 dbgs() << "0x0, default will be used)\n";
1642 });
1643
1644 return ES.runSessionLocked([&, this]() -> Error {
1645 if (State != Open)
1646 return make_error<JITDylibDefunct>(this);
1647
1648 if (auto Err = defineImpl(*MU))
1649 return Err;
1650
1651 if (!RT)
1653
1654 if (auto *P = ES.getPlatform()) {
1655 if (auto Err = P->notifyAdding(*RT, *MU))
1656 return Err;
1657 }
1658
1659 installMaterializationUnit(std::move(MU), *RT);
1660 return Error::success();
1661 });
1662}
1663
1664template <typename MaterializationUnitType>
1665Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1666 ResourceTrackerSP RT) {
1667 assert(MU && "Can not define with a null MU");
1668
1669 if (MU->getSymbols().empty()) {
1670 // Empty MUs are allowable but pathological, so issue a warning.
1671 DEBUG_WITH_TYPE("orc", {
1672 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1673 << "\n";
1674 });
1675 return Error::success();
1676 } else
1677 DEBUG_WITH_TYPE("orc", {
1678 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1679 << " (tracker: ";
1680 if (RT == getDefaultResourceTracker())
1681 dbgs() << "default)";
1682 else if (RT)
1683 dbgs() << RT.get() << ")\n";
1684 else
1685 dbgs() << "0x0, default will be used)\n";
1686 });
1687
1688 return ES.runSessionLocked([&, this]() -> Error {
1689 assert(State == Open && "JD is defunct");
1690
1691 if (auto Err = defineImpl(*MU))
1692 return Err;
1693
1694 if (!RT)
1696
1697 if (auto *P = ES.getPlatform()) {
1698 if (auto Err = P->notifyAdding(*RT, *MU))
1699 return Err;
1700 }
1701
1702 installMaterializationUnit(std::move(MU), *RT);
1703 return Error::success();
1704 });
1705}
1706
1707/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1708/// re-export a subset of the source JITDylib's symbols in the target.
1710public:
1711 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1712
1713 /// Create a reexports generator. If an Allow predicate is passed, only
1714 /// symbols for which the predicate returns true will be reexported. If no
1715 /// Allow predicate is passed, all symbols will be exported.
1716 ReexportsGenerator(JITDylib &SourceJD,
1717 JITDylibLookupFlags SourceJDLookupFlags,
1719
1721 JITDylibLookupFlags JDLookupFlags,
1722 const SymbolLookupSet &LookupSet) override;
1723
1724private:
1725 JITDylib &SourceJD;
1726 JITDylibLookupFlags SourceJDLookupFlags;
1727 SymbolPredicate Allow;
1728};
1729
1730// --------------- IMPLEMENTATION --------------
1731// Implementations for inline functions/methods.
1732// ---------------------------------------------
1733
1735 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
1736}
1737
1739 return getExecutionSession().OL_getRequestedSymbols(*this);
1740}
1741
1743 const SymbolMap &Symbols) {
1744 return getExecutionSession().OL_notifyResolved(*this, Symbols);
1745}
1746
1748 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
1749 return getExecutionSession().OL_notifyEmitted(*this, EmittedDeps);
1750}
1751
1753 SymbolFlagsMap SymbolFlags) {
1754 return getExecutionSession().OL_defineMaterializing(*this,
1755 std::move(SymbolFlags));
1756}
1757
1759 getExecutionSession().OL_notifyFailed(*this);
1760}
1761
1763 std::unique_ptr<MaterializationUnit> MU) {
1764 return getExecutionSession().OL_replace(*this, std::move(MU));
1765}
1766
1769 return getExecutionSession().OL_delegate(*this, Symbols);
1770}
1771
1772} // End namespace orc
1773} // End namespace llvm
1774
1775#endif // LLVM_EXECUTIONENGINE_ORC_CORE_H
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseSet and SmallDenseSet classes.
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define P(N)
static StringRef getName(Value *V)
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Definition DenseMap.h:716
Base class for user error types.
Definition Error.h:354
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
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
Flags for symbols in the JIT.
Definition JITSymbol.h:75
Inheritance utility for extensible RTTI.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
A symbol query that returns results via a callback when results are ready.
Definition Core.h:559
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:193
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
Definition Core.h:579
friend class InProgressFullLookupState
Definition Core.h:561
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:207
friend class MaterializationResponsibility
Definition Core.h:563
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:632
virtual Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet)=0
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
friend class ExecutionSession
Definition Core.h:633
CallControllerHandlerBinding(SymbolNameSpec Name, CallControllerHandlerFn Handler, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Definition Core.h:1135
An ExecutionSession represents a running JIT program.
Definition Core.h:1104
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1592
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition Core.h:1171
unique_function< void(shared::WrapperFunctionBuffer)> CallControllerReturnFn
Function type for returning results from a call-controller handler.
Definition Core.h:1117
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1282
void callWrapperAsync(ExecutorAddr WrapperFnAddr, ExecutorProcessControl::IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1394
friend class JITDylib
Definition Core.h:1107
friend class InProgressLookupFlagsState
Definition Core.h:1105
ExecutionSession & operator=(const ExecutionSession &)=delete
const StringMap< ExecutorAddr > & getBootstrapSymbolsMap() const
Returns the bootstrap symbol map.
Definition Core.h:1374
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition Core.h:1204
std::enable_if_t<(std::is_same_v< BindingTs, CallControllerHandlerBinding > &&...), Error > registerCallControllerHandlers(JITDylib &JD, BindingTs &&...Hs)
Convenience overload of registerCallControllerHandlers that takes the bindings as arguments,...
Definition Core.h:1438
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1174
ExecutionSession(const ExecutionSession &)=delete
Platform * getPlatform()
Get the Platform for this session.
Definition Core.h:1208
LLVM_ABI void lookupFlags(LookupKind K, JITDylibSearchOrder SearchOrder, SymbolLookupSet Symbols, unique_function< void(Expected< SymbolFlagsMap >)> OnComplete)
Search the given JITDylibs to find the flags associated with each of the given symbols.
Definition Core.cpp:1758
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1185
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1637
LLVM_ABI void runCallControllerHandler(CallControllerReturnFn Return, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run the call-controller handler registered for the given tag address.
Definition Core.cpp:1933
friend class LookupState
Definition Core.h:1108
void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor using the given Runner to dispatch OnComplete when the result ...
Definition Core.h:1403
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1646
LLVM_ABI Error registerCallControllerHandlers(JITDylib &JD, std::vector< CallControllerHandlerBinding > Hs)
For each binding, look up its tag symbol in JD and register the binding's call-controller handler for...
Definition Core.cpp:1879
JITDylib & getBootstrapJITDylib()
Returns a reference to the bootstrap JITDylib.
Definition Core.h:1192
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1180
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
Definition Core.h:1369
friend class InProgressFullLookupState
Definition Core.h:1106
Error getBootstrapSymbols(ArrayRef< std::pair< ExecutorAddr &, StringRef > > Pairs) const
For each (ExecutorAddr&, StringRef) pair, looks up the string in the bootstrap symbols map and writes...
Definition Core.h:1381
const StringMap< std::vector< char > > & getBootstrapMap() const
Returns the bootstrap map.
Definition Core.h:1363
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition Core.cpp:1784
friend class MaterializationResponsibility
Definition Core.h:1109
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1620
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1586
void setWaitingOnGraphOpRecorder(WaitingOnGraph::OpRecorder &R)
Set a WaitingOnGraph::Recorder to capture WaitingOnGraph operations.
Definition Core.h:1198
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1624
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1554
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1211
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1956
friend class ResourceTracker
Definition Core.h:1110
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition Core.h:1274
ExecutionSession(ExecutionSession &&)=delete
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1663
size_t getPageSize() const
Definition Core.h:1177
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1655
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1356
unique_function< void(Error)> ErrorReporter
For reporting errors.
Definition Core.h:1114
ExecutionSession & operator=(ExecutionSession &&)=delete
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition Core.h:1269
void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1412
unique_function< void( CallControllerReturnFn, shared::WrapperFunctionBuffer)> CallControllerHandlerFn
A call-controller handler: handles calls from the executor made via the ORC runtime's call-controller...
Definition Core.h:1122
Represents an address in the executor process.
A handler or incoming WrapperFunctionBuffers – either return values from callWrapper* calls,...
ExecutorProcessControl supports interaction with a JIT target process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
Definition Core.cpp:95
const SymbolDependenceMap & getSymbols() const
Definition Core.h:224
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:113
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:117
JITDylibDefunct(JITDylibSP JD)
Definition Core.h:205
Represents a JIT'd dynamic library.
Definition Core.h:675
LLVM_ABI ~JITDylib()
Definition Core.cpp:644
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1046
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:648
JITDylib & operator=(JITDylib &&)=delete
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1102
friend class AsynchronousSymbolQuery
Definition Core.h:676
LLVM_ABI void replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD, JITDylibLookupFlags JDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Replace OldJD with NewJD in the link order if OldJD is present.
Definition Core.cpp:1022
Error define(std::unique_ptr< MaterializationUnitType > &&MU, ResourceTrackerSP RT=nullptr)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition Core.h:1621
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:694
LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks)
Append the given JITDylibSearchOrder to the link order for this JITDylib (discarding any elements alr...
Definition Core.cpp:1006
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:672
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition Core.h:1614
friend class MaterializationResponsibility
Definition Core.h:679
friend class Platform
Definition Core.h:678
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1034
LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder, bool LinkAgainstThisJITDylibFirst=true)
Set the link order to be used when fixing up definitions in JITDylib.
Definition Core.cpp:991
LLVM_ABI Expected< std::vector< JITDylibSP > > getReverseDFSLinkOrder()
Rteurn this JITDylib and its transitive dependencies in reverse DFS order based on linkage relationsh...
Definition Core.cpp:1754
friend class ExecutionSession
Definition Core.h:677
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:663
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1604
JITDylib(const JITDylib &)=delete
JITDylib & operator=(const JITDylib &)=delete
JITDylib(JITDylib &&)=delete
LLVM_ABI void removeGenerator(DefinitionGenerator &G)
Remove a definition generator from this JITDylib.
Definition Core.cpp:680
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1750
Wraps state for a lookup-in-progress.
Definition Core.h:607
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:624
LLVM_ABI LookupState & operator=(LookupState &&)
friend class ExecutionSession
Definition Core.h:609
friend class OrcV2CAPIHelper
Definition Core.h:608
LLVM_ABI LookupState(LookupState &&)
LookupTask(LookupState LS)
Definition Core.h:1095
static char ID
Definition Core.h:1093
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:350
MaterializationResponsibility & operator=(MaterializationResponsibility &&)=delete
ExecutionSession & getExecutionSession() const
Returns the ExecutionSession for this instance.
Definition Core.h:1599
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition Core.h:1742
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition Core.h:1734
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition Core.h:1762
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:369
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition Core.h:1752
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition Core.h:1738
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition Core.h:1768
const ResourceTrackerSP & getResourceTracker() const
Return the ResourceTracker associated with this instance.
Definition Core.h:365
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:389
MaterializationResponsibility(MaterializationResponsibility &&)=delete
Error notifyEmitted(ArrayRef< SymbolDependenceGroup > DepGroups)
Notifies the target JITDylib (and any pending queries on that JITDylib) that all symbols covered by t...
Definition Core.h:1747
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition Core.h:1758
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:375
const SymbolFlagsMap & getSymbols() const
Returns the symbol flags map for this responsibility instance.
Definition Core.h:384
A materialization task.
Definition Core.h:1072
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition Core.h:1076
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
const SymbolNameVector & getSymbols() const
Definition Core.h:305
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:303
MissingSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:297
const std::string & getModuleName() const
Definition Core.h:304
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition Core.h:1031
virtual Error teardownJITDylib(JITDylib &JD)=0
This method will be called outside the session lock each time a JITDylib is removed to allow the Plat...
static void lookupInitSymbolsAsync(unique_function< void(Error)> OnComplete, ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
Performs an async lookup for the given symbols in each of the given JITDylibs, calling the given hand...
Definition Core.cpp:1490
virtual Error notifyRemoving(ResourceTracker &RT)=0
This method will be called under the ExecutionSession lock when a ResourceTracker is removed.
static Expected< DenseMap< JITDylib *, SymbolMap > > lookupInitSymbols(ExecutionSession &ES, const DenseMap< JITDylib *, SymbolLookupSet > &InitSyms)
A utility function for looking up initializer symbols.
Definition Core.cpp:1442
virtual Error notifyAdding(ResourceTracker &RT, const MaterializationUnit &MU)=0
This method will be called under the ExecutionSession lock each time a MaterializationUnit is added t...
virtual Error setupJITDylib(JITDylib &JD)=0
This method will be called outside the session lock each time a JITDylib is created (unless it is cre...
ReExportsMaterializationUnit(JITDylib *SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolAliasMap Aliases)
SourceJD is allowed to be nullptr, in which case the source JITDylib is taken to be whatever JITDylib...
Definition Core.cpp:292
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1711
Error tryToGenerate(LookupState &LS, LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags, const SymbolLookupSet &LookupSet) override
DefinitionGenerators should override this method to insert new definitions into the parent JITDylib.
Definition Core.cpp:589
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:583
Listens for ResourceTracker operations.
Definition Core.h:112
virtual Error handleRemoveResources(JITDylib &JD, ResourceKey K)=0
This function will be called outside the session lock.
virtual void handleTransferResources(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK)=0
This function will be called inside the session lock.
ResourceTrackerDefunct(ResourceTrackerSP RT)
Definition Core.cpp:75
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:82
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:78
API to remove / transfer ownership of JIT resources.
Definition Core.h:64
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:79
friend class JITDylib
Definition Core.h:67
ResourceTracker & operator=(const ResourceTracker &)=delete
ResourceKey getKeyUnsafe() const
Returns the key associated with this tracker.
Definition Core.h:101
LLVM_ABI void transferTo(ResourceTracker &DstRT)
Transfer all resources associated with this key to the given tracker, which must target the same JITD...
Definition Core.cpp:63
ResourceTracker & operator=(ResourceTracker &&)=delete
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:54
ResourceTracker(const ResourceTracker &)=delete
friend class MaterializationResponsibility
Definition Core.h:68
bool isDefunct() const
Return true if this tracker has become defunct.
Definition Core.h:96
ResourceTracker(ResourceTracker &&)=delete
Error withResourceKeyDo(Func &&F)
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:1589
friend class ExecutionSession
Definition Core.h:66
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:59
A set of symbols to look up, each associated with a SymbolLookupFlags value.
A symbol name together with the naming level (SymbolNameKind) it is expressed in, so that a Mangler /...
Pointer to a pooled string representing a symbol name.
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:167
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:171
const SymbolNameSet & getSymbols() const
Definition Core.h:281
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:161
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:280
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:157
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:140
const SymbolNameVector & getSymbols() const
Definition Core.h:263
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:153
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:262
UnexpectedSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:321
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:327
const std::string & getModuleName() const
Definition Core.h:328
const SymbolNameVector & getSymbols() const
Definition Core.h:329
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:133
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:129
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition Core.cpp:121
WaitingOnGraph class template.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:154
std::vector< std::pair< JITDylib *, JITDylibLookupFlags > > JITDylibSearchOrder
A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search order during symbol lookup.
Definition Core.h:149
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:59
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
Definition Core.h:58
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:524
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition Core.h:180
uintptr_t ResourceKey
Definition Core.h:61
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
std::unique_ptr< ReExportsMaterializationUnit > reexports(JITDylib &SourceJD, SymbolAliasMap Aliases, JITDylibLookupFlags SourceJDLookupFlags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Create a materialization unit for re-exporting symbols from another JITDylib with alternative names/f...
Definition Core.h:533
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:133
detail::WaitingOnGraph< JITDylib *, NonOwningSymbolStringPtr > WaitingOnGraph
Definition Core.h:55
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:145
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:42
std::vector< SymbolStringPtr > SymbolNameVector
A vector of symbol names.
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
SymbolState
Represents the state that a symbol has reached during materialization.
Definition Core.h:546
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:549
@ NeverSearched
No symbol should be in this state.
Definition Core.h:548
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:552
@ Emitted
Assigned address, still materializing.
Definition Core.h:551
@ Resolved
Queried, materialization begun.
Definition Core.h:550
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:174
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition Core.h:177
LLVM_ABI Expected< SymbolAliasMap > buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols)
Build a SymbolAliasMap for the common case where you want to re-export symbols from another JITDylib ...
Definition Core.cpp:484
DenseMap< SymbolStringPtr, JITSymbolFlags > SymbolFlagsMap
A map from symbol names (as SymbolStringPtrs) to JITSymbolFlags.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
JITSymbolFlags AliasFlags
Definition Core.h:170
SymbolAliasMapEntry(SymbolStringPtr Aliasee, JITSymbolFlags AliasFlags)
Definition Core.h:166
SymbolStringPtr Aliasee
Definition Core.h:169
A set of symbols and the their dependencies.
Definition Core.h:338
SymbolDependenceMap Dependencies
Definition Core.h:340