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 SymbolTable Symbols;
1007 UnmaterializedInfosMap UnmaterializedInfos;
1008 MaterializingInfosMap MaterializingInfos;
1009 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1010 JITDylibSearchOrder LinkOrder;
1011 ResourceTrackerSP DefaultTracker;
1012
1013 // Map trackers to sets of symbols tracked.
1014 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1015 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1016 TrackerMRs;
1017};
1018
1019/// Platforms set up standard symbols and mediate interactions between dynamic
1020/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1021/// Note that Platforms do not automatically run initializers: clients are still
1022/// responsible for doing this.
1024public:
1025 virtual ~Platform();
1026
1027 /// This method will be called outside the session lock each time a JITDylib
1028 /// is created (unless it is created with EmptyJITDylib set) to allow the
1029 /// Platform to install any JITDylib specific standard symbols (e.g
1030 /// __dso_handle).
1031 virtual Error setupJITDylib(JITDylib &JD) = 0;
1032
1033 /// This method will be called outside the session lock each time a JITDylib
1034 /// is removed to allow the Platform to remove any JITDylib-specific data.
1036
1037 /// This method will be called under the ExecutionSession lock each time a
1038 /// MaterializationUnit is added to a JITDylib.
1040 const MaterializationUnit &MU) = 0;
1041
1042 /// This method will be called under the ExecutionSession lock when a
1043 /// ResourceTracker is removed.
1045
1046 /// A utility function for looking up initializer symbols. Performs a blocking
1047 /// lookup for the given symbols in each of the given JITDylibs.
1048 ///
1049 /// Note: This function is deprecated and will be removed in the near future.
1053
1054 /// Performs an async lookup for the given symbols in each of the given
1055 /// JITDylibs, calling the given handler once all lookups have completed.
1056 static void
1058 ExecutionSession &ES,
1060};
1061
1062/// A materialization task.
1064 : public RTTIExtends<MaterializationTask, Task> {
1065public:
1066 static char ID;
1067
1068 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1069 std::unique_ptr<MaterializationResponsibility> MR)
1070 : MU(std::move(MU)), MR(std::move(MR)) {}
1071 ~MaterializationTask() override;
1072 void printDescription(raw_ostream &OS) override;
1073 void run() override;
1074
1075private:
1076 std::unique_ptr<MaterializationUnit> MU;
1077 std::unique_ptr<MaterializationResponsibility> MR;
1078};
1079
1080/// Lookups are usually run on the current thread, but in some cases they may
1081/// be run as tasks, e.g. if the lookup has been continued from a suspended
1082/// state.
1083class LLVM_ABI LookupTask : public RTTIExtends<LookupTask, Task> {
1084public:
1085 static char ID;
1086
1087 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1088 void printDescription(raw_ostream &OS) override;
1089 void run() override;
1090
1091private:
1092 LookupState LS;
1093};
1094
1095/// An ExecutionSession represents a running JIT program.
1099 friend class JITDylib;
1100 friend class LookupState;
1102 friend class ResourceTracker;
1103
1104public:
1105 /// For reporting errors.
1107
1108 /// Function type for returning results from a call-controller handler.
1111
1112 /// A call-controller handler: handles calls from the executor made via the
1113 /// ORC runtime's call-controller mechanism.
1116
1117 /// Associates a call-controller handler with the name of the tag symbol that
1118 /// the executor will use to call it, and the SymbolLookupFlags to use when
1119 /// looking that tag up.
1120 ///
1121 /// The name is not copied (see SymbolNameSpec): the referenced string must
1122 /// outlive the registerCallControllerHandlers call that the binding is
1123 /// passed to. Ordinary string literals have static storage duration, so
1124 /// they are always safe.
1126 public:
1130 : Name(Name), Handler(std::move(Handler)), LF(LF) {}
1131
1132 SymbolNameSpec getName() const { return Name; }
1133
1134 CallControllerHandlerFn takeHandler() { return std::move(Handler); }
1135
1136 SymbolLookupFlags getLookupFlags() const { return LF; }
1137
1138 private:
1139 SymbolNameSpec Name;
1142 };
1143
1144 /// Construct an ExecutionSession with the given ExecutorProcessControl
1145 /// object.
1146 LLVM_ABI ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1147
1152
1153 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1154 /// destruction.
1156
1157 /// End the session. Closes all JITDylibs and disconnects from the
1158 /// executor. Clients must call this method before destroying the session.
1160
1161 /// Get the ExecutorProcessControl object associated with this
1162 /// ExecutionSession.
1164
1165 /// Return the triple for the executor.
1166 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1167
1168 // Return the page size for the executor.
1169 size_t getPageSize() const { return EPC->getPageSize(); }
1170
1171 /// Get the SymbolStringPool for this instance.
1172 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1173 return EPC->getSymbolStringPool();
1174 }
1175
1176 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1177 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1178
1179 /// Returns a reference to the bootstrap JITDylib.
1180 ///
1181 /// This is a bare JITDylib that is created for each ExecutionSession and
1182 /// populated with the bootstrap symbol definitions provided by the
1183 /// ExecutorProcessControl object.
1184 JITDylib &getBootstrapJITDylib() { return BootstrapJD; }
1185
1186 /// Set a WaitingOnGraph::Recorder to capture WaitingOnGraph operations.
1187 ///
1188 /// This method can be called at most once. If called, it should be called
1189 /// before any symbols are materialized.
1190 void setWaitingOnGraphOpRecorder(WaitingOnGraph::OpRecorder &R) {
1191 assert(!GOpRecorder && "WaitingOnGraph recorder already set");
1192 GOpRecorder = &R;
1193 }
1194
1195 /// Set the Platform for this ExecutionSession.
1196 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1197
1198 /// Get the Platform for this session.
1199 /// Will return null if no Platform has been set for this ExecutionSession.
1200 Platform *getPlatform() { return P.get(); }
1201
1202 /// Run the given lambda with the session mutex locked.
1203 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1204 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1205 return F();
1206 }
1207
1208 /// Register the given ResourceManager with this ExecutionSession.
1209 /// Managers will be notified of events in reverse order of registration.
1211
1212 /// Deregister the given ResourceManager with this ExecutionSession.
1213 /// Manager must have been previously registered.
1215
1216 /// Return a pointer to the "name" JITDylib.
1217 /// Ownership of JITDylib remains within Execution Session
1219
1220 /// Add a new bare JITDylib to this ExecutionSession.
1221 ///
1222 /// The JITDylib Name is required to be unique. Clients should verify that
1223 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1224 /// are based on user input.
1225 ///
1226 /// This call does not install any library code or symbols into the newly
1227 /// created JITDylib. The client is responsible for all configuration.
1228 LLVM_ABI JITDylib &createBareJITDylib(std::string Name);
1229
1230 /// Add a new JITDylib to this ExecutionSession.
1231 ///
1232 /// The JITDylib Name is required to be unique. Clients should verify that
1233 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1234 /// are based on user input.
1235 ///
1236 /// If a Platform is attached then Platform::setupJITDylib will be called to
1237 /// install standard platform symbols (e.g. standard library interposes).
1238 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1240
1241 /// Removes the given JITDylibs from the ExecutionSession.
1242 ///
1243 /// This method clears all resources held for the JITDylibs, puts them in the
1244 /// closed state, and clears all references to them that are held by the
1245 /// ExecutionSession or other JITDylibs. No further code can be added to the
1246 /// removed JITDylibs, and the JITDylib objects will be freed once any
1247 /// remaining JITDylibSPs pointing to them are destroyed.
1248 ///
1249 /// This method does *not* run static destructors for code contained in the
1250 /// JITDylibs, and each JITDylib can only be removed once.
1251 ///
1252 /// JITDylibs will be removed in the order given. Teardown is usually
1253 /// independent for each JITDylib, but not always. In particular, where the
1254 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1255 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1256 /// last. If the client has introduced any other dependencies they should be
1257 /// accounted for in the removal order too.
1258 LLVM_ABI Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1259
1260 /// Calls removeJTIDylibs on the gives JITDylib.
1262 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1263 }
1264
1265 /// Set the error reporter function.
1267 this->ReportError = std::move(ReportError);
1268 return *this;
1269 }
1270
1271 /// Report a error for this execution session.
1272 ///
1273 /// Unhandled errors can be sent here to log them.
1274 void reportError(Error Err) { ReportError(std::move(Err)); }
1275
1276 /// Search the given JITDylibs to find the flags associated with each of the
1277 /// given symbols.
1278 LLVM_ABI void
1280 SymbolLookupSet Symbols,
1281 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1282
1283 /// Blocking version of lookupFlags.
1285 JITDylibSearchOrder SearchOrder,
1286 SymbolLookupSet Symbols);
1287
1288 /// Search the given JITDylibs for the given symbols.
1289 ///
1290 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1291 /// boolean indicates whether the search should match against non-exported
1292 /// (hidden visibility) symbols in that dylib (true means match against
1293 /// non-exported symbols, false means do not match).
1294 ///
1295 /// The NotifyComplete callback will be called once all requested symbols
1296 /// reach the required state.
1297 ///
1298 /// If all symbols are found, the RegisterDependencies function will be called
1299 /// while the session lock is held. This gives clients a chance to register
1300 /// dependencies for on the queried symbols for any symbols they are
1301 /// materializing (if a MaterializationResponsibility instance is present,
1302 /// this can be implemented by calling
1303 /// MaterializationResponsibility::addDependencies). If there are no
1304 /// dependenant symbols for this query (e.g. it is being made by a top level
1305 /// client to get an address to call) then the value NoDependenciesToRegister
1306 /// can be used.
1307 LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1308 SymbolLookupSet Symbols, SymbolState RequiredState,
1309 SymbolsResolvedCallback NotifyComplete,
1310 RegisterDependenciesFunction RegisterDependencies);
1311
1312 /// Blocking version of lookup above. Returns the resolved symbol map.
1313 /// If WaitUntilReady is true (the default), will not return until all
1314 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1315 /// false, will return as soon as all requested symbols are resolved,
1316 /// or an error occurs. If WaitUntilReady is false and an error occurs
1317 /// after resolution, the function will return a success value, but the
1318 /// error will be reported via reportErrors.
1320 lookup(const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols,
1322 SymbolState RequiredState = SymbolState::Ready,
1323 RegisterDependenciesFunction RegisterDependencies =
1325
1326 /// Convenience version of blocking lookup.
1327 /// Searches each of the JITDylibs in the search order in turn for the given
1328 /// symbol.
1330 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1331 SymbolState RequiredState = SymbolState::Ready);
1332
1333 /// Convenience version of blocking lookup.
1334 /// Searches each of the JITDylibs in the search order in turn for the given
1335 /// symbol. The search will not find non-exported symbols.
1337 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1338 SymbolState RequiredState = SymbolState::Ready);
1339
1340 /// Convenience version of blocking lookup.
1341 /// Searches each of the JITDylibs in the search order in turn for the given
1342 /// symbol. The search will not find non-exported symbols.
1344 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1345 SymbolState RequiredState = SymbolState::Ready);
1346
1347 /// Materialize the given unit.
1348 void dispatchTask(std::unique_ptr<Task> T) {
1349 assert(T && "T must be non-null");
1350 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1351 EPC->getDispatcher().dispatch(std::move(T));
1352 }
1353
1354 /// Returns the bootstrap map.
1356 return EPC->getBootstrapMap();
1357 }
1358
1359 /// Look up and SPS-deserialize a bootstrap map value.
1360 template <typename T, typename SPSTagT>
1361 Error getBootstrapMapValue(StringRef Key, std::optional<T> &Val) const {
1362 return EPC->getBootstrapMapValue<T, SPSTagT>(Key, Val);
1363 }
1364
1365 /// Returns the bootstrap symbol map.
1367 return EPC->getBootstrapSymbolsMap();
1368 }
1369
1370 /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
1371 /// bootstrap symbols map and writes its address to the ExecutorAddr if
1372 /// found. If any symbol is not found then the function returns an error.
1374 ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
1375 return EPC->getBootstrapSymbols(Pairs);
1376 }
1377
1378 /// Run a wrapper function in the executor. The given WFRHandler will be
1379 /// called on the result when it is returned.
1380 ///
1381 /// The wrapper function should be callable as:
1382 ///
1383 /// \code{.cpp}
1384 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1385 /// \endcode{.cpp}
1386 void callWrapperAsync(ExecutorAddr WrapperFnAddr,
1388 ArrayRef<char> ArgBuffer) {
1389 EPC->callWrapperAsync(WrapperFnAddr, std::move(OnComplete), ArgBuffer);
1390 }
1391
1392 /// Run a wrapper function in the executor using the given Runner to dispatch
1393 /// OnComplete when the result is ready.
1394 template <typename RunPolicyT, typename FnT>
1395 void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
1396 FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
1397 EPC->callWrapperAsync(std::forward<RunPolicyT>(Runner), WrapperFnAddr,
1398 std::forward<FnT>(OnComplete), ArgBuffer);
1399 }
1400
1401 /// Run a wrapper function in the executor. OnComplete will be dispatched
1402 /// as a GenericNamedTask using this instance's TaskDispatch object.
1403 template <typename FnT>
1404 void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
1405 ArrayRef<char> ArgBuffer) {
1406 EPC->callWrapperAsync(WrapperFnAddr, std::forward<FnT>(OnComplete),
1407 ArgBuffer);
1408 }
1409
1410 /// For each binding, look up its tag symbol in JD and register the binding's
1411 /// call-controller handler for the tag's address. The handler becomes
1412 /// callable from the executor via the ORC runtime's call-controller
1413 /// mechanism, using the tag's address as the handler tag.
1414 ///
1415 /// Tag names are mangled for the session's target triple, then looked up
1416 /// in JD using LookupKind::Static and JITDylibLookupFlags::MatchAllSymbols
1417 /// (hidden tags will be found), with each binding's SymbolLookupFlags. If a
1418 /// weakly referenced tag is not found then its handler is dropped.
1419 ///
1420 /// On failure no handlers are registered.
1422 JITDylib &JD, std::vector<CallControllerHandlerBinding> Hs);
1423
1424 /// Convenience overload of registerCallControllerHandlers that takes the
1425 /// bindings as arguments, so that they can be constructed inline at the
1426 /// call site.
1427 template <typename... BindingTs>
1428 std::enable_if_t<
1429 (std::is_same_v<BindingTs, CallControllerHandlerBinding> && ...), Error>
1431 std::vector<CallControllerHandlerBinding> Bs;
1432 Bs.reserve(sizeof...(Hs));
1433 (Bs.push_back(std::move(Hs)), ...);
1434 return registerCallControllerHandlers(JD, std::move(Bs));
1435 }
1436
1437 /// Run the call-controller handler registered for the given tag address.
1438 /// This should be called by the ExecutorProcessControl instance in response
1439 /// to calls from the executor made via the ORC runtime's call-controller
1440 /// mechanism.
1441 LLVM_ABI void
1443 ExecutorAddr HandlerFnTagAddr,
1445
1446 /// Dump the state of all the JITDylibs in this session.
1447 LLVM_ABI void dump(raw_ostream &OS);
1448
1449 /// Check the internal consistency of ExecutionSession data structures.
1450#ifdef EXPENSIVE_CHECKS
1451 bool verifySessionState(Twine Phase);
1452#endif
1453
1454private:
1455 static void logErrorsToStdErr(Error Err) {
1456 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1457 }
1458
1459 void dispatchOutstandingMUs();
1460
1461 static std::unique_ptr<MaterializationResponsibility>
1462 createMaterializationResponsibility(ResourceTracker &RT,
1463 SymbolFlagsMap Symbols,
1464 SymbolStringPtr InitSymbol) {
1465 auto &JD = RT.getJITDylib();
1466 std::unique_ptr<MaterializationResponsibility> MR(
1467 new MaterializationResponsibility(&RT, std::move(Symbols),
1468 std::move(InitSymbol)));
1469 JD.TrackerMRs[&RT].insert(MR.get());
1470 return MR;
1471 }
1472
1473 Error removeResourceTracker(ResourceTracker &RT);
1474 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1475 void destroyResourceTracker(ResourceTracker &RT);
1476
1477 // State machine functions for query application..
1478
1479 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1480 /// match a given query from the set of candidate symbols to generate
1481 /// definitions for (no need to generate a definition if one already exists).
1482 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1483 SymbolLookupSet &Candidates,
1484 SymbolLookupSet *NonCandidates);
1485
1486 /// Handle resumption of a lookup after entering a generator.
1487 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1488
1489 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1490 /// definition generation. It is called when a lookup is performed, and again
1491 /// each time that LookupState::continueLookup is called.
1492 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1493 Error Err);
1494
1495 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1496 /// call. It attempts to attach the symbol to all symbol table entries and
1497 /// collect all MaterializationUnits to dispatch. If this method fails then
1498 /// all MaterializationUnits will be left un-materialized.
1499 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1500 std::shared_ptr<AsynchronousSymbolQuery> Q,
1501 RegisterDependenciesFunction RegisterDependencies);
1502
1503 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1504 /// lookupFlags call.
1505 void OL_completeLookupFlags(
1506 std::unique_ptr<InProgressLookupState> IPLS,
1507 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1508
1509 // State machine functions for MaterializationResponsibility.
1510 LLVM_ABI void
1511 OL_destroyMaterializationResponsibility(MaterializationResponsibility &MR);
1513 OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1514 LLVM_ABI Error OL_notifyResolved(MaterializationResponsibility &MR,
1515 const SymbolMap &Symbols);
1516
1517 // FIXME: We should be able to derive FailedSymsForQuery from each query once
1518 // we fix how the detach operation works.
1519 struct EmitQueries {
1520 JITDylib::AsynchronousSymbolQuerySet Completed;
1521 JITDylib::AsynchronousSymbolQuerySet Failed;
1522 DenseMap<AsynchronousSymbolQuery *, std::shared_ptr<SymbolDependenceMap>>
1523 FailedSymsForQuery;
1524 };
1525
1527 IL_getSymbolState(JITDylib *JD, NonOwningSymbolStringPtr Name);
1528
1529 template <typename UpdateSymbolFn, typename UpdateQueryFn>
1530 void IL_collectQueries(JITDylib::AsynchronousSymbolQuerySet &Qs,
1531 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
1532 UpdateSymbolFn &&UpdateSymbol,
1533 UpdateQueryFn &&UpdateQuery);
1534
1535 Expected<EmitQueries> IL_emit(MaterializationResponsibility &MR,
1536 WaitingOnGraph::SimplifyResult SR);
1537 LLVM_ABI Error OL_notifyEmitted(MaterializationResponsibility &MR,
1539
1540 LLVM_ABI Error OL_defineMaterializing(MaterializationResponsibility &MR,
1541 SymbolFlagsMap SymbolFlags);
1542
1543 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1544 std::shared_ptr<SymbolDependenceMap>>
1545 IL_failSymbols(JITDylib &JD, const SymbolNameVector &SymbolsToFail);
1546 LLVM_ABI void OL_notifyFailed(MaterializationResponsibility &MR);
1548 std::unique_ptr<MaterializationUnit> MU);
1549 LLVM_ABI Expected<std::unique_ptr<MaterializationResponsibility>>
1550 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1551
1552#ifndef NDEBUG
1553 void dumpDispatchInfo(Task &T);
1554#endif // NDEBUG
1555
1556 mutable std::recursive_mutex SessionMutex;
1557 bool SessionOpen = true;
1558 std::unique_ptr<ExecutorProcessControl> EPC;
1559 std::unique_ptr<Platform> P;
1560 ErrorReporter ReportError = logErrorsToStdErr;
1561
1562 std::vector<ResourceManager *> ResourceManagers;
1563
1564 std::vector<JITDylibSP> JDs;
1565 JITDylib &BootstrapJD;
1567 WaitingOnGraph::OpRecorder *GOpRecorder = nullptr;
1568
1569 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1570 // with callbacks from asynchronous queries.
1571 mutable std::recursive_mutex OutstandingMUsMutex;
1572 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1573 std::unique_ptr<MaterializationResponsibility>>>
1574 OutstandingMUs;
1575
1576 mutable std::mutex CallControllerHandlersMutex;
1577 DenseMap<ExecutorAddr, std::unique_ptr<CallControllerHandlerFn>>
1578 CallControllerHandlers;
1579};
1580
1581template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1583 if (isDefunct())
1585 F(getKeyUnsafe());
1586 return Error::success();
1587 });
1588}
1589
1590inline ExecutionSession &
1592 return JD.getExecutionSession();
1593}
1594
1595template <typename GeneratorT>
1596GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1597 return ES.runSessionLocked([&]() -> GeneratorT & {
1598 assert(State == Open && "Cannot add generator to closed JITDylib");
1599 DefGenerators.push_back(std::move(DefGenerator));
1600 return static_cast<GeneratorT &>(*DefGenerators.back());
1601 });
1602}
1603
1604template <typename Func>
1606 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1607 assert(State == Open && "Cannot use link order of closed JITDylib");
1608 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1609}
1610
1611template <typename MaterializationUnitType>
1612Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1613 ResourceTrackerSP RT) {
1614 assert(MU && "Can not define with a null MU");
1615
1616 if (MU->getSymbols().empty()) {
1617 // Empty MUs are allowable but pathological, so issue a warning.
1618 DEBUG_WITH_TYPE("orc", {
1619 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1620 << getName() << "\n";
1621 });
1622 return Error::success();
1623 } else
1624 DEBUG_WITH_TYPE("orc", {
1625 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1626 << " (tracker: ";
1627 if (RT == getDefaultResourceTracker())
1628 dbgs() << "default)";
1629 else if (RT)
1630 dbgs() << RT.get() << ")\n";
1631 else
1632 dbgs() << "0x0, default will be used)\n";
1633 });
1634
1635 return ES.runSessionLocked([&, this]() -> Error {
1636 if (State != Open)
1637 return make_error<JITDylibDefunct>(this);
1638
1639 if (auto Err = defineImpl(*MU))
1640 return Err;
1641
1642 if (!RT)
1644
1645 if (auto *P = ES.getPlatform()) {
1646 if (auto Err = P->notifyAdding(*RT, *MU))
1647 return Err;
1648 }
1649
1650 installMaterializationUnit(std::move(MU), *RT);
1651 return Error::success();
1652 });
1653}
1654
1655template <typename MaterializationUnitType>
1656Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1657 ResourceTrackerSP RT) {
1658 assert(MU && "Can not define with a null MU");
1659
1660 if (MU->getSymbols().empty()) {
1661 // Empty MUs are allowable but pathological, so issue a warning.
1662 DEBUG_WITH_TYPE("orc", {
1663 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1664 << "\n";
1665 });
1666 return Error::success();
1667 } else
1668 DEBUG_WITH_TYPE("orc", {
1669 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1670 << " (tracker: ";
1671 if (RT == getDefaultResourceTracker())
1672 dbgs() << "default)";
1673 else if (RT)
1674 dbgs() << RT.get() << ")\n";
1675 else
1676 dbgs() << "0x0, default will be used)\n";
1677 });
1678
1679 return ES.runSessionLocked([&, this]() -> Error {
1680 assert(State == Open && "JD is defunct");
1681
1682 if (auto Err = defineImpl(*MU))
1683 return Err;
1684
1685 if (!RT)
1687
1688 if (auto *P = ES.getPlatform()) {
1689 if (auto Err = P->notifyAdding(*RT, *MU))
1690 return Err;
1691 }
1692
1693 installMaterializationUnit(std::move(MU), *RT);
1694 return Error::success();
1695 });
1696}
1697
1698/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1699/// re-export a subset of the source JITDylib's symbols in the target.
1701public:
1702 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1703
1704 /// Create a reexports generator. If an Allow predicate is passed, only
1705 /// symbols for which the predicate returns true will be reexported. If no
1706 /// Allow predicate is passed, all symbols will be exported.
1707 ReexportsGenerator(JITDylib &SourceJD,
1708 JITDylibLookupFlags SourceJDLookupFlags,
1710
1712 JITDylibLookupFlags JDLookupFlags,
1713 const SymbolLookupSet &LookupSet) override;
1714
1715private:
1716 JITDylib &SourceJD;
1717 JITDylibLookupFlags SourceJDLookupFlags;
1718 SymbolPredicate Allow;
1719};
1720
1721// --------------- IMPLEMENTATION --------------
1722// Implementations for inline functions/methods.
1723// ---------------------------------------------
1724
1726 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
1727}
1728
1730 return getExecutionSession().OL_getRequestedSymbols(*this);
1731}
1732
1734 const SymbolMap &Symbols) {
1735 return getExecutionSession().OL_notifyResolved(*this, Symbols);
1736}
1737
1739 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
1740 return getExecutionSession().OL_notifyEmitted(*this, EmittedDeps);
1741}
1742
1744 SymbolFlagsMap SymbolFlags) {
1745 return getExecutionSession().OL_defineMaterializing(*this,
1746 std::move(SymbolFlags));
1747}
1748
1750 getExecutionSession().OL_notifyFailed(*this);
1751}
1752
1754 std::unique_ptr<MaterializationUnit> MU) {
1755 return getExecutionSession().OL_replace(*this, std::move(MU));
1756}
1757
1760 return getExecutionSession().OL_delegate(*this, Symbols);
1761}
1762
1763} // End namespace orc
1764} // End namespace llvm
1765
1766#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:1127
An ExecutionSession represents a running JIT program.
Definition Core.h:1096
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1591
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition Core.h:1163
unique_function< void(shared::WrapperFunctionBuffer)> CallControllerReturnFn
Function type for returning results from a call-controller handler.
Definition Core.h:1109
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1274
void callWrapperAsync(ExecutorAddr WrapperFnAddr, ExecutorProcessControl::IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1386
friend class JITDylib
Definition Core.h:1099
friend class InProgressLookupFlagsState
Definition Core.h:1097
ExecutionSession & operator=(const ExecutionSession &)=delete
const StringMap< ExecutorAddr > & getBootstrapSymbolsMap() const
Returns the bootstrap symbol map.
Definition Core.h:1366
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition Core.h:1196
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:1430
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1166
ExecutionSession(const ExecutionSession &)=delete
Platform * getPlatform()
Get the Platform for this session.
Definition Core.h:1200
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:1177
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:1100
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:1395
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:1184
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1172
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
Definition Core.h:1361
friend class InProgressFullLookupState
Definition Core.h:1098
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:1373
const StringMap< std::vector< char > > & getBootstrapMap() const
Returns the bootstrap map.
Definition Core.h:1355
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:1101
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:1190
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:1203
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:1102
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition Core.h:1266
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:1169
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:1348
unique_function< void(Error)> ErrorReporter
For reporting errors.
Definition Core.h:1106
ExecutionSession & operator=(ExecutionSession &&)=delete
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition Core.h:1261
void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1404
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:1114
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:1612
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:1605
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:1596
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:1087
static char ID
Definition Core.h:1085
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:1591
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition Core.h:1733
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition Core.h:1725
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition Core.h:1753
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:1743
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition Core.h:1729
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition Core.h:1759
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:1738
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition Core.h:1749
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:1064
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition Core.h:1068
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:1023
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:1702
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:1581
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