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