LLVM 22.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"
31#include "llvm/Support/Debug.h"
33
34#include <atomic>
35#include <deque>
36#include <future>
37#include <memory>
38#include <vector>
39
40namespace llvm {
41namespace orc {
42
43// Forward declare some classes.
47class JITDylib;
48class ResourceTracker;
50
51enum class SymbolState : uint8_t;
52
55
58
59/// A definition of a Symbol within a JITDylib.
61public:
64
66 : JD(std::move(JD)), Name(std::move(Name)) {}
67
68 const JITDylib &getJITDylib() const { return *JD; }
69 const SymbolStringPtr &getName() const { return Name; }
70
72 LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const;
73
74private:
75 JITDylibSP JD;
76 SymbolStringPtr Name;
77};
78
79using ResourceKey = uintptr_t;
80
81/// API to remove / transfer ownership of JIT resources.
82class ResourceTracker : public ThreadSafeRefCountedBase<ResourceTracker> {
83private:
84 friend class ExecutionSession;
85 friend class JITDylib;
87
88public:
93
95
96 /// Return the JITDylib targeted by this tracker.
98 return *reinterpret_cast<JITDylib *>(JDAndFlag.load() &
99 ~static_cast<uintptr_t>(1));
100 }
101
102 /// Runs the given callback under the session lock, passing in the associated
103 /// ResourceKey. This is the safe way to associate resources with trackers.
104 template <typename Func> Error withResourceKeyDo(Func &&F);
105
106 /// Remove all resources associated with this key.
108
109 /// Transfer all resources associated with this key to the given
110 /// tracker, which must target the same JITDylib as this one.
112
113 /// Return true if this tracker has become defunct.
114 bool isDefunct() const { return JDAndFlag.load() & 0x1; }
115
116 /// Returns the key associated with this tracker.
117 /// This method should not be used except for debug logging: there is no
118 /// guarantee that the returned value will remain valid.
119 ResourceKey getKeyUnsafe() const { return reinterpret_cast<uintptr_t>(this); }
120
121private:
123
124 void makeDefunct();
125
126 std::atomic_uintptr_t JDAndFlag;
127};
128
129/// Listens for ResourceTracker operations.
131public:
133
134 /// This function will be called *outside* the session lock. ResourceManagers
135 /// should perform book-keeping under the session lock, and any expensive
136 /// cleanup outside the session lock.
138
139 /// This function will be called *inside* the session lock. ResourceManagers
140 /// DO NOT need to re-lock the session.
142 ResourceKey SrcK) = 0;
143};
144
145/// Lookup flags that apply to each dylib in the search order for a lookup.
146///
147/// If MatchHiddenSymbolsOnly is used (the default) for a given dylib, then
148/// only symbols in that Dylib's interface will be searched. If
149/// MatchHiddenSymbols is used then symbols with hidden visibility will match
150/// as well.
152
153/// Lookup flags that apply to each symbol in a lookup.
154///
155/// If RequiredSymbol is used (the default) for a given symbol then that symbol
156/// must be found during the lookup or the lookup will fail returning a
157/// SymbolNotFound error. If WeaklyReferencedSymbol is used and the given
158/// symbol is not found then the query will continue, and no result for the
159/// missing symbol will be present in the result (assuming the rest of the
160/// lookup succeeds).
162
163/// Describes the kind of lookup being performed. The lookup kind is passed to
164/// symbol generators (if they're invoked) to help them determine what
165/// definitions to generate.
166///
167/// Static -- Lookup is being performed as-if at static link time (e.g.
168/// generators representing static archives should pull in new
169/// definitions).
170///
171/// DLSym -- Lookup is being performed as-if at runtime (e.g. generators
172/// representing static archives should not pull in new definitions).
173enum class LookupKind { Static, DLSym };
174
175/// A list of (JITDylib*, JITDylibLookupFlags) pairs to be used as a search
176/// order during symbol lookup.
178 std::vector<std::pair<JITDylib *, JITDylibLookupFlags>>;
179
180/// Convenience function for creating a search order from an ArrayRef of
181/// JITDylib*, all with the same flags.
186 O.reserve(JDs.size());
187 for (auto *JD : JDs)
188 O.push_back(std::make_pair(JD, Flags));
189 return O;
190}
191
192/// A set of symbols to look up, each associated with a SymbolLookupFlags
193/// value.
194///
195/// This class is backed by a vector and optimized for fast insertion,
196/// deletion and iteration. It does not guarantee a stable order between
197/// operations, and will not automatically detect duplicate elements (they
198/// can be manually checked by calling the validate method).
200public:
201 using value_type = std::pair<SymbolStringPtr, SymbolLookupFlags>;
202 using UnderlyingVector = std::vector<value_type>;
203 using iterator = UnderlyingVector::iterator;
204 using const_iterator = UnderlyingVector::const_iterator;
205
206 SymbolLookupSet() = default;
207
208 SymbolLookupSet(std::initializer_list<value_type> Elems) {
209 for (auto &E : Elems)
210 Symbols.push_back(std::move(E));
211 }
212
214 SymbolStringPtr Name,
216 add(std::move(Name), Flags);
217 }
218
219 /// Construct a SymbolLookupSet from an initializer list of SymbolStringPtrs.
221 std::initializer_list<SymbolStringPtr> Names,
223 Symbols.reserve(Names.size());
224 for (const auto &Name : Names)
225 add(std::move(Name), Flags);
226 }
227
228 /// Construct a SymbolLookupSet from a SymbolNameSet with the given
229 /// Flags used for each value.
231 const SymbolNameSet &Names,
233 Symbols.reserve(Names.size());
234 for (const auto &Name : Names)
235 add(Name, Flags);
236 }
237
238 /// Construct a SymbolLookupSet from a vector of symbols with the given Flags
239 /// used for each value.
240 /// If the ArrayRef contains duplicates it is up to the client to remove these
241 /// before using this instance for lookup.
245 Symbols.reserve(Names.size());
246 for (const auto &Name : Names)
247 add(Name, Flags);
248 }
249
250 /// Construct a SymbolLookupSet from DenseMap keys.
251 template <typename ValT>
252 static SymbolLookupSet
256 Result.Symbols.reserve(M.size());
257 for (const auto &[Name, Val] : M)
258 Result.add(Name, Flags);
259 return Result;
260 }
261
262 /// Add an element to the set. The client is responsible for checking that
263 /// duplicates are not added.
267 Symbols.push_back(std::make_pair(std::move(Name), Flags));
268 return *this;
269 }
270
271 /// Quickly append one lookup set to another.
273 Symbols.reserve(Symbols.size() + Other.size());
274 for (auto &KV : Other)
275 Symbols.push_back(std::move(KV));
276 return *this;
277 }
278
279 bool empty() const { return Symbols.empty(); }
280 UnderlyingVector::size_type size() const { return Symbols.size(); }
281 iterator begin() { return Symbols.begin(); }
282 iterator end() { return Symbols.end(); }
283 const_iterator begin() const { return Symbols.begin(); }
284 const_iterator end() const { return Symbols.end(); }
285
286 /// Removes the Ith element of the vector, replacing it with the last element.
287 void remove(UnderlyingVector::size_type I) {
288 std::swap(Symbols[I], Symbols.back());
289 Symbols.pop_back();
290 }
291
292 /// Removes the element pointed to by the given iterator. This iterator and
293 /// all subsequent ones (including end()) are invalidated.
294 void remove(iterator I) { remove(I - begin()); }
295
296 /// Removes all elements matching the given predicate, which must be callable
297 /// as bool(const SymbolStringPtr &, SymbolLookupFlags Flags).
298 template <typename PredFn> void remove_if(PredFn &&Pred) {
299 UnderlyingVector::size_type I = 0;
300 while (I != Symbols.size()) {
301 const auto &Name = Symbols[I].first;
302 auto Flags = Symbols[I].second;
303 if (Pred(Name, Flags))
304 remove(I);
305 else
306 ++I;
307 }
308 }
309
310 /// Loop over the elements of this SymbolLookupSet, applying the Body function
311 /// to each one. Body must be callable as
312 /// bool(const SymbolStringPtr &, SymbolLookupFlags).
313 /// If Body returns true then the element just passed in is removed from the
314 /// set. If Body returns false then the element is retained.
315 template <typename BodyFn>
316 auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t<
317 std::is_same<decltype(Body(std::declval<const SymbolStringPtr &>(),
318 std::declval<SymbolLookupFlags>())),
319 bool>::value> {
320 UnderlyingVector::size_type I = 0;
321 while (I != Symbols.size()) {
322 const auto &Name = Symbols[I].first;
323 auto Flags = Symbols[I].second;
324 if (Body(Name, Flags))
325 remove(I);
326 else
327 ++I;
328 }
329 }
330
331 /// Loop over the elements of this SymbolLookupSet, applying the Body function
332 /// to each one. Body must be callable as
333 /// Expected<bool>(const SymbolStringPtr &, SymbolLookupFlags).
334 /// If Body returns a failure value, the loop exits immediately. If Body
335 /// returns true then the element just passed in is removed from the set. If
336 /// Body returns false then the element is retained.
337 template <typename BodyFn>
338 auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t<
339 std::is_same<decltype(Body(std::declval<const SymbolStringPtr &>(),
340 std::declval<SymbolLookupFlags>())),
341 Expected<bool>>::value,
342 Error> {
343 UnderlyingVector::size_type I = 0;
344 while (I != Symbols.size()) {
345 const auto &Name = Symbols[I].first;
346 auto Flags = Symbols[I].second;
347 auto Remove = Body(Name, Flags);
348 if (!Remove)
349 return Remove.takeError();
350 if (*Remove)
351 remove(I);
352 else
353 ++I;
354 }
355 return Error::success();
356 }
357
358 /// Construct a SymbolNameVector from this instance by dropping the Flags
359 /// values.
361 SymbolNameVector Names;
362 Names.reserve(Symbols.size());
363 for (const auto &KV : Symbols)
364 Names.push_back(KV.first);
365 return Names;
366 }
367
368 /// Sort the lookup set by pointer value. This sort is fast but sensitive to
369 /// allocation order and so should not be used where a consistent order is
370 /// required.
372
373 /// Sort the lookup set lexicographically. This sort is slow but the order
374 /// is unaffected by allocation order.
375 void sortByName() {
376 llvm::sort(Symbols, [](const value_type &LHS, const value_type &RHS) {
377 return *LHS.first < *RHS.first;
378 });
379 }
380
381 /// Remove any duplicate elements. If a SymbolLookupSet is not duplicate-free
382 /// by construction, this method can be used to turn it into a proper set.
385 auto LastI = llvm::unique(Symbols);
386 Symbols.erase(LastI, Symbols.end());
387 }
388
389#ifndef NDEBUG
390 /// Returns true if this set contains any duplicates. This should only be used
391 /// in assertions.
393 if (Symbols.size() < 2)
394 return false;
396 for (UnderlyingVector::size_type I = 1; I != Symbols.size(); ++I)
397 if (Symbols[I].first == Symbols[I - 1].first)
398 return true;
399 return false;
400 }
401#endif
402
403private:
404 UnderlyingVector Symbols;
405};
406
415
416/// A map of Symbols to (Symbol, Flags) pairs.
418
419/// Callback to notify client that symbols have been resolved.
421
422/// Callback to register the dependencies for a given query.
424 std::function<void(const SymbolDependenceMap &)>;
425
426/// This can be used as the value for a RegisterDependenciesFunction if there
427/// are no dependants to register with.
429
431 : public ErrorInfo<ResourceTrackerDefunct> {
432public:
433 static char ID;
434
436 std::error_code convertToErrorCode() const override;
437 void log(raw_ostream &OS) const override;
438
439private:
441};
442
443/// Used to notify a JITDylib that the given set of symbols failed to
444/// materialize.
445class LLVM_ABI FailedToMaterialize : public ErrorInfo<FailedToMaterialize> {
446public:
447 static char ID;
448
449 FailedToMaterialize(std::shared_ptr<SymbolStringPool> SSP,
450 std::shared_ptr<SymbolDependenceMap> Symbols);
451 ~FailedToMaterialize() override;
452 std::error_code convertToErrorCode() const override;
453 void log(raw_ostream &OS) const override;
454 const SymbolDependenceMap &getSymbols() const { return *Symbols; }
455
456private:
457 std::shared_ptr<SymbolStringPool> SSP;
458 std::shared_ptr<SymbolDependenceMap> Symbols;
459};
460
461/// Used to report failure due to unsatisfiable symbol dependencies.
463 : public ErrorInfo<UnsatisfiedSymbolDependencies> {
464public:
465 static char ID;
466
467 UnsatisfiedSymbolDependencies(std::shared_ptr<SymbolStringPool> SSP,
468 JITDylibSP JD, SymbolNameSet FailedSymbols,
469 SymbolDependenceMap BadDeps,
470 std::string Explanation);
471 std::error_code convertToErrorCode() const override;
472 void log(raw_ostream &OS) const override;
473
474private:
475 std::shared_ptr<SymbolStringPool> SSP;
476 JITDylibSP JD;
477 SymbolNameSet FailedSymbols;
478 SymbolDependenceMap BadDeps;
479 std::string Explanation;
480};
481
482/// Used to notify clients when symbols can not be found during a lookup.
483class LLVM_ABI SymbolsNotFound : public ErrorInfo<SymbolsNotFound> {
484public:
485 static char ID;
486
487 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols);
488 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
489 SymbolNameVector Symbols);
490 std::error_code convertToErrorCode() const override;
491 void log(raw_ostream &OS) const override;
492 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
493 const SymbolNameVector &getSymbols() const { return Symbols; }
494
495private:
496 std::shared_ptr<SymbolStringPool> SSP;
497 SymbolNameVector Symbols;
498};
499
500/// Used to notify clients that a set of symbols could not be removed.
502 : public ErrorInfo<SymbolsCouldNotBeRemoved> {
503public:
504 static char ID;
505
506 SymbolsCouldNotBeRemoved(std::shared_ptr<SymbolStringPool> SSP,
507 SymbolNameSet Symbols);
508 std::error_code convertToErrorCode() const override;
509 void log(raw_ostream &OS) const override;
510 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
511 const SymbolNameSet &getSymbols() const { return Symbols; }
512
513private:
514 std::shared_ptr<SymbolStringPool> SSP;
515 SymbolNameSet Symbols;
516};
517
518/// Errors of this type should be returned if a module fails to include
519/// definitions that are claimed by the module's associated
520/// MaterializationResponsibility. If this error is returned it is indicative of
521/// a broken transformation / compiler / object cache.
523 : public ErrorInfo<MissingSymbolDefinitions> {
524public:
525 static char ID;
526
527 MissingSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
528 std::string ModuleName, SymbolNameVector Symbols)
529 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
530 Symbols(std::move(Symbols)) {}
531 std::error_code convertToErrorCode() const override;
532 void log(raw_ostream &OS) const override;
533 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
534 const std::string &getModuleName() const { return ModuleName; }
535 const SymbolNameVector &getSymbols() const { return Symbols; }
536private:
537 std::shared_ptr<SymbolStringPool> SSP;
538 std::string ModuleName;
539 SymbolNameVector Symbols;
540};
541
542/// Errors of this type should be returned if a module contains definitions for
543/// symbols that are not claimed by the module's associated
544/// MaterializationResponsibility. If this error is returned it is indicative of
545/// a broken transformation / compiler / object cache.
547 : public ErrorInfo<UnexpectedSymbolDefinitions> {
548public:
549 static char ID;
550
551 UnexpectedSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
552 std::string ModuleName, SymbolNameVector Symbols)
553 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
554 Symbols(std::move(Symbols)) {}
555 std::error_code convertToErrorCode() const override;
556 void log(raw_ostream &OS) const override;
557 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
558 const std::string &getModuleName() const { return ModuleName; }
559 const SymbolNameVector &getSymbols() const { return Symbols; }
560private:
561 std::shared_ptr<SymbolStringPool> SSP;
562 std::string ModuleName;
563 SymbolNameVector Symbols;
564};
565
566/// A set of symbols and the their dependencies. Used to describe dependencies
567/// for the MaterializationResponsibility::notifyEmitted operation.
572
573/// Tracks responsibility for materialization, and mediates interactions between
574/// MaterializationUnits and JDs.
575///
576/// An instance of this class is passed to MaterializationUnits when their
577/// materialize method is called. It allows MaterializationUnits to resolve and
578/// emit symbols, or abandon materialization by notifying any unmaterialized
579/// symbols of an error.
581 friend class ExecutionSession;
582 friend class JITDylib;
583
584public:
588
589 /// Destruct a MaterializationResponsibility instance. In debug mode
590 /// this asserts that all symbols being tracked have been either
591 /// emitted or notified of an error.
593
594 /// Return the ResourceTracker associated with this instance.
595 const ResourceTrackerSP &getResourceTracker() const { return RT; }
596
597 /// Runs the given callback under the session lock, passing in the associated
598 /// ResourceKey. This is the safe way to associate resources with trackers.
599 template <typename Func> Error withResourceKeyDo(Func &&F) const {
600 return RT->withResourceKeyDo(std::forward<Func>(F));
601 }
602
603 /// Returns the target JITDylib that these symbols are being materialized
604 /// into.
605 JITDylib &getTargetJITDylib() const { return JD; }
606
607 /// Returns the ExecutionSession for this instance.
609
610 /// Returns the symbol flags map for this responsibility instance.
611 /// Note: The returned flags may have transient flags (Lazy, Materializing)
612 /// set. These should be stripped with JITSymbolFlags::stripTransientFlags
613 /// before using.
614 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
615
616 /// Returns the initialization pseudo-symbol, if any. This symbol will also
617 /// be present in the SymbolFlagsMap for this MaterializationResponsibility
618 /// object.
619 const SymbolStringPtr &getInitializerSymbol() const { return InitSymbol; }
620
621 /// Returns the names of any symbols covered by this
622 /// MaterializationResponsibility object that have queries pending. This
623 /// information can be used to return responsibility for unrequested symbols
624 /// back to the JITDylib via the delegate method.
626
627 /// Notifies the target JITDylib that the given symbols have been resolved.
628 /// This will update the given symbols' addresses in the JITDylib, and notify
629 /// any pending queries on the given symbols of their resolution. The given
630 /// symbols must be ones covered by this MaterializationResponsibility
631 /// instance. Individual calls to this method may resolve a subset of the
632 /// symbols, but all symbols must have been resolved prior to calling emit.
633 ///
634 /// This method will return an error if any symbols being resolved have been
635 /// moved to the error state due to the failure of a dependency. If this
636 /// method returns an error then clients should log it and call
637 /// failMaterialize. If no dependencies have been registered for the
638 /// symbols covered by this MaterializationResponsibility then this method
639 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
640 Error notifyResolved(const SymbolMap &Symbols);
641
642 /// Notifies the target JITDylib (and any pending queries on that JITDylib)
643 /// that all symbols covered by this MaterializationResponsibility instance
644 /// have been emitted.
645 ///
646 /// The DepGroups array describes the dependencies of symbols being emitted on
647 /// symbols that are outside this MaterializationResponsibility object. Each
648 /// group consists of a pair of a set of symbols and a SymbolDependenceMap
649 /// that describes the dependencies for the symbols in the first set. The
650 /// elements of DepGroups must be non-overlapping (no symbol should appear in
651 /// more than one of hte symbol sets), but do not have to be exhaustive. Any
652 /// symbol in this MaterializationResponsibility object that is not covered
653 /// by an entry will be treated as having no dependencies.
654 ///
655 /// This method will return an error if any symbols being resolved have been
656 /// moved to the error state due to the failure of a dependency. If this
657 /// method returns an error then clients should log it and call
658 /// failMaterialize. If no dependencies have been registered for the
659 /// symbols covered by this MaterializationResponsibility then this method
660 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
662
663 /// Attempt to claim responsibility for new definitions. This method can be
664 /// used to claim responsibility for symbols that are added to a
665 /// materialization unit during the compilation process (e.g. literal pool
666 /// symbols). Symbol linkage rules are the same as for symbols that are
667 /// defined up front: duplicate strong definitions will result in errors.
668 /// Duplicate weak definitions will be discarded (in which case they will
669 /// not be added to this responsibility instance).
670 ///
671 /// This method can be used by materialization units that want to add
672 /// additional symbols at materialization time (e.g. stubs, compile
673 /// callbacks, metadata).
675
676 /// Notify all not-yet-emitted covered by this MaterializationResponsibility
677 /// instance that an error has occurred.
678 /// This will remove all symbols covered by this MaterializationResponsibility
679 /// from the target JITDylib, and send an error to any queries waiting on
680 /// these symbols.
681 void failMaterialization();
682
683 /// Transfers responsibility to the given MaterializationUnit for all
684 /// symbols defined by that MaterializationUnit. This allows
685 /// materializers to break up work based on run-time information (e.g.
686 /// by introspecting which symbols have actually been looked up and
687 /// materializing only those).
688 Error replace(std::unique_ptr<MaterializationUnit> MU);
689
690 /// Delegates responsibility for the given symbols to the returned
691 /// materialization responsibility. Useful for breaking up work between
692 /// threads, or different kinds of materialization processes.
694 delegate(const SymbolNameSet &Symbols);
695
696private:
697 /// Create a MaterializationResponsibility for the given JITDylib and
698 /// initial symbols.
700 SymbolFlagsMap SymbolFlags,
701 SymbolStringPtr InitSymbol)
702 : JD(RT->getJITDylib()), RT(std::move(RT)),
703 SymbolFlags(std::move(SymbolFlags)), InitSymbol(std::move(InitSymbol)) {
704 assert(!this->SymbolFlags.empty() && "Materializing nothing?");
705 }
706
707 JITDylib &JD;
709 SymbolFlagsMap SymbolFlags;
710 SymbolStringPtr InitSymbol;
711};
712
713/// A materialization unit for symbol aliases. Allows existing symbols to be
714/// aliased with alternate flags.
716public:
717 /// SourceJD is allowed to be nullptr, in which case the source JITDylib is
718 /// taken to be whatever JITDylib these definitions are materialized in (and
719 /// MatchNonExported has no effect). This is useful for defining aliases
720 /// within a JITDylib.
721 ///
722 /// Note: Care must be taken that no sets of aliases form a cycle, as such
723 /// a cycle will result in a deadlock when any symbol in the cycle is
724 /// resolved.
726 JITDylibLookupFlags SourceJDLookupFlags,
727 SymbolAliasMap Aliases);
728
729 StringRef getName() const override;
730
731private:
732 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
733 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
735 extractFlags(const SymbolAliasMap &Aliases);
736
737 JITDylib *SourceJD = nullptr;
738 JITDylibLookupFlags SourceJDLookupFlags;
739 SymbolAliasMap Aliases;
740};
741
742/// Create a ReExportsMaterializationUnit with the given aliases.
743/// Useful for defining symbol aliases.: E.g., given a JITDylib JD containing
744/// symbols "foo" and "bar", we can define aliases "baz" (for "foo") and "qux"
745/// (for "bar") with: \code{.cpp}
746/// SymbolStringPtr Baz = ...;
747/// SymbolStringPtr Qux = ...;
748/// if (auto Err = JD.define(symbolAliases({
749/// {Baz, { Foo, JITSymbolFlags::Exported }},
750/// {Qux, { Bar, JITSymbolFlags::Weak }}}))
751/// return Err;
752/// \endcode
753inline std::unique_ptr<ReExportsMaterializationUnit>
755 return std::make_unique<ReExportsMaterializationUnit>(
756 nullptr, JITDylibLookupFlags::MatchAllSymbols, std::move(Aliases));
757}
758
759/// Create a materialization unit for re-exporting symbols from another JITDylib
760/// with alternative names/flags.
761/// SourceJD will be searched using the given JITDylibLookupFlags.
762inline std::unique_ptr<ReExportsMaterializationUnit>
764 JITDylibLookupFlags SourceJDLookupFlags =
766 return std::make_unique<ReExportsMaterializationUnit>(
767 &SourceJD, SourceJDLookupFlags, std::move(Aliases));
768}
769
770/// Build a SymbolAliasMap for the common case where you want to re-export
771/// symbols from another JITDylib with the same linkage/flags.
774
775/// Represents the state that a symbol has reached during materialization.
776enum class SymbolState : uint8_t {
777 Invalid, /// No symbol should be in this state.
778 NeverSearched, /// Added to the symbol table, never queried.
779 Materializing, /// Queried, materialization begun.
780 Resolved, /// Assigned address, still materializing.
781 Emitted, /// Emitted to memory, but waiting on transitive dependencies.
782 Ready = 0x3f /// Ready and safe for clients to access.
783};
784
785/// A symbol query that returns results via a callback when results are
786/// ready.
787///
788/// makes a callback when all symbols are available.
790 friend class ExecutionSession;
792 friend class JITDylib;
795
796public:
797 /// Create a query for the given symbols. The NotifyComplete
798 /// callback will be called once all queried symbols reach the given
799 /// minimum state.
801 SymbolState RequiredState,
802 SymbolsResolvedCallback NotifyComplete);
803
804 /// Notify the query that a requested symbol has reached the required state.
807
808 /// Returns true if all symbols covered by this query have been
809 /// resolved.
810 bool isComplete() const { return OutstandingSymbolsCount == 0; }
811
812
813private:
814 void handleComplete(ExecutionSession &ES);
815
816 SymbolState getRequiredState() { return RequiredState; }
817
818 void addQueryDependence(JITDylib &JD, SymbolStringPtr Name);
819
820 void removeQueryDependence(JITDylib &JD, const SymbolStringPtr &Name);
821
822 void dropSymbol(const SymbolStringPtr &Name);
823
824 void handleFailed(Error Err);
825
826 void detach();
827
828 SymbolsResolvedCallback NotifyComplete;
829 SymbolDependenceMap QueryRegistrations;
830 SymbolMap ResolvedSymbols;
831 size_t OutstandingSymbolsCount;
832 SymbolState RequiredState;
833};
834
835/// Wraps state for a lookup-in-progress.
836/// DefinitionGenerators can optionally take ownership of a LookupState object
837/// to suspend a lookup-in-progress while they search for definitions.
839 friend class OrcV2CAPIHelper;
840 friend class ExecutionSession;
841
842public:
847
848 /// Continue the lookup. This can be called by DefinitionGenerators
849 /// to re-start a captured query-application operation.
850 LLVM_ABI void continueLookup(Error Err);
851
852private:
853 LookupState(std::unique_ptr<InProgressLookupState> IPLS);
854
855 // For C API.
856 void reset(InProgressLookupState *IPLS);
857
858 std::unique_ptr<InProgressLookupState> IPLS;
859};
860
861/// Definition generators can be attached to JITDylibs to generate new
862/// definitions for otherwise unresolved symbols during lookup.
864 friend class ExecutionSession;
865
866public:
867 virtual ~DefinitionGenerator();
868
869 /// DefinitionGenerators should override this method to insert new
870 /// definitions into the parent JITDylib. K specifies the kind of this
871 /// lookup. JD specifies the target JITDylib being searched, and
872 /// JDLookupFlags specifies whether the search should match against
873 /// hidden symbols. Finally, Symbols describes the set of unresolved
874 /// symbols and their associated lookup flags.
876 JITDylibLookupFlags JDLookupFlags,
877 const SymbolLookupSet &LookupSet) = 0;
878
879private:
880 std::mutex M;
881 bool InUse = false;
882 std::deque<LookupState> PendingLookups;
883};
884
885/// Represents a JIT'd dynamic library.
886///
887/// This class aims to mimic the behavior of a regular dylib or shared object,
888/// but without requiring the contained program representations to be compiled
889/// up-front. The JITDylib's content is defined by adding MaterializationUnits,
890/// and contained MaterializationUnits will typically rely on the JITDylib's
891/// links-against order to resolve external references (similar to a regular
892/// dylib).
893///
894/// The JITDylib object is a thin wrapper that references state held by the
895/// ExecutionSession. JITDylibs can be removed, clearing this underlying state
896/// and leaving the JITDylib object in a defunct state. In this state the
897/// JITDylib's name is guaranteed to remain accessible. If the ExecutionSession
898/// is still alive then other operations are callable but will return an Error
899/// or null result (depending on the API). It is illegal to call any operation
900/// other than getName on a JITDylib after the ExecutionSession has been torn
901/// down.
902///
903/// JITDylibs cannot be moved or copied. Their address is stable, and useful as
904/// a key in some JIT data structures.
905class JITDylib : public ThreadSafeRefCountedBase<JITDylib>,
906 public jitlink::JITLinkDylib {
908 friend class ExecutionSession;
909 friend class Platform;
911public:
912
913 JITDylib(const JITDylib &) = delete;
914 JITDylib &operator=(const JITDylib &) = delete;
915 JITDylib(JITDylib &&) = delete;
918
919 /// Get a reference to the ExecutionSession for this JITDylib.
920 ///
921 /// It is legal to call this method on a defunct JITDylib, however the result
922 /// will only usable if the ExecutionSession is still alive. If this JITDylib
923 /// is held by an error that may have torn down the JIT then the result
924 /// should not be used.
925 ExecutionSession &getExecutionSession() const { return ES; }
926
927 /// Dump current JITDylib state to OS.
928 ///
929 /// It is legal to call this method on a defunct JITDylib.
930 LLVM_ABI void dump(raw_ostream &OS);
931
932 /// Calls remove on all trackers currently associated with this JITDylib.
933 /// Does not run static deinits.
934 ///
935 /// Note that removal happens outside the session lock, so new code may be
936 /// added concurrently while the clear is underway, and the newly added
937 /// code will *not* be cleared. Adding new code concurrently with a clear
938 /// is usually a bug and should be avoided.
939 ///
940 /// It is illegal to call this method on a defunct JITDylib and the client
941 /// is responsible for ensuring that they do not do so.
943
944 /// Get the default resource tracker for this JITDylib.
945 ///
946 /// It is illegal to call this method on a defunct JITDylib and the client
947 /// is responsible for ensuring that they do not do so.
949
950 /// Create a resource tracker for this JITDylib.
951 ///
952 /// It is illegal to call this method on a defunct JITDylib and the client
953 /// is responsible for ensuring that they do not do so.
955
956 /// Adds a definition generator to this JITDylib and returns a referenece to
957 /// it.
958 ///
959 /// When JITDylibs are searched during lookup, if no existing definition of
960 /// a symbol is found, then any generators that have been added are run (in
961 /// the order that they were added) to potentially generate a definition.
962 ///
963 /// It is illegal to call this method on a defunct JITDylib and the client
964 /// is responsible for ensuring that they do not do so.
965 template <typename GeneratorT>
966 GeneratorT &addGenerator(std::unique_ptr<GeneratorT> DefGenerator);
967
968 /// Remove a definition generator from this JITDylib.
969 ///
970 /// The given generator must exist in this JITDylib's generators list (i.e.
971 /// have been added and not yet removed).
972 ///
973 /// It is illegal to call this method on a defunct JITDylib and the client
974 /// is responsible for ensuring that they do not do so.
976
977 /// Set the link order to be used when fixing up definitions in JITDylib.
978 /// This will replace the previous link order, and apply to any symbol
979 /// resolutions made for definitions in this JITDylib after the call to
980 /// setLinkOrder (even if the definition itself was added before the
981 /// call).
982 ///
983 /// If LinkAgainstThisJITDylibFirst is true (the default) then this JITDylib
984 /// will add itself to the beginning of the LinkOrder (Clients should not
985 /// put this JITDylib in the list in this case, to avoid redundant lookups).
986 ///
987 /// If LinkAgainstThisJITDylibFirst is false then the link order will be used
988 /// as-is. The primary motivation for this feature is to support deliberate
989 /// shadowing of symbols in this JITDylib by a facade JITDylib. For example,
990 /// the facade may resolve function names to stubs, and the stubs may compile
991 /// lazily by looking up symbols in this dylib. Adding the facade dylib
992 /// as the first in the link order (instead of this dylib) ensures that
993 /// definitions within this dylib resolve to the lazy-compiling stubs,
994 /// rather than immediately materializing the definitions in this dylib.
995 ///
996 /// It is illegal to call this method on a defunct JITDylib and the client
997 /// is responsible for ensuring that they do not do so.
998 LLVM_ABI void setLinkOrder(JITDylibSearchOrder NewSearchOrder,
999 bool LinkAgainstThisJITDylibFirst = true);
1000
1001 /// Append the given JITDylibSearchOrder to the link order for this
1002 /// JITDylib (discarding any elements already present in this JITDylib's
1003 /// link order).
1004 LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks);
1005
1006 /// Add the given JITDylib to the link order for definitions in this
1007 /// JITDylib.
1008 ///
1009 /// It is illegal to call this method on a defunct JITDylib and the client
1010 /// is responsible for ensuring that they do not do so.
1011 LLVM_ABI void
1013 JITDylibLookupFlags JDLookupFlags =
1015
1016 /// Replace OldJD with NewJD in the link order if OldJD is present.
1017 /// Otherwise this operation is a no-op.
1018 ///
1019 /// It is illegal to call this method on a defunct JITDylib and the client
1020 /// is responsible for ensuring that they do not do so.
1021 LLVM_ABI void
1022 replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1023 JITDylibLookupFlags JDLookupFlags =
1025
1026 /// Remove the given JITDylib from the link order for this JITDylib if it is
1027 /// present. Otherwise this operation is a no-op.
1028 ///
1029 /// It is illegal to call this method on a defunct JITDylib and the client
1030 /// is responsible for ensuring that they do not do so.
1032
1033 /// Do something with the link order (run under the session lock).
1034 ///
1035 /// It is illegal to call this method on a defunct JITDylib and the client
1036 /// is responsible for ensuring that they do not do so.
1037 template <typename Func>
1038 auto withLinkOrderDo(Func &&F)
1039 -> decltype(F(std::declval<const JITDylibSearchOrder &>()));
1040
1041 /// Define all symbols provided by the materialization unit to be part of this
1042 /// JITDylib.
1043 ///
1044 /// If RT is not specified then the default resource tracker will be used.
1045 ///
1046 /// This overload always takes ownership of the MaterializationUnit. If any
1047 /// errors occur, the MaterializationUnit consumed.
1048 ///
1049 /// It is illegal to call this method on a defunct JITDylib and the client
1050 /// is responsible for ensuring that they do not do so.
1051 template <typename MaterializationUnitType>
1052 Error define(std::unique_ptr<MaterializationUnitType> &&MU,
1053 ResourceTrackerSP RT = nullptr);
1054
1055 /// Define all symbols provided by the materialization unit to be part of this
1056 /// JITDylib.
1057 ///
1058 /// This overload only takes ownership of the MaterializationUnit no error is
1059 /// generated. If an error occurs, ownership remains with the caller. This
1060 /// may allow the caller to modify the MaterializationUnit to correct the
1061 /// issue, then re-call define.
1062 ///
1063 /// It is illegal to call this method on a defunct JITDylib and the client
1064 /// is responsible for ensuring that they do not do so.
1065 template <typename MaterializationUnitType>
1066 Error define(std::unique_ptr<MaterializationUnitType> &MU,
1067 ResourceTrackerSP RT = nullptr);
1068
1069 /// Tries to remove the given symbols.
1070 ///
1071 /// If any symbols are not defined in this JITDylib this method will return
1072 /// a SymbolsNotFound error covering the missing symbols.
1073 ///
1074 /// If all symbols are found but some symbols are in the process of being
1075 /// materialized this method will return a SymbolsCouldNotBeRemoved error.
1076 ///
1077 /// On success, all symbols are removed. On failure, the JITDylib state is
1078 /// left unmodified (no symbols are removed).
1079 ///
1080 /// It is illegal to call this method on a defunct JITDylib and the client
1081 /// is responsible for ensuring that they do not do so.
1082 LLVM_ABI Error remove(const SymbolNameSet &Names);
1083
1084 /// Returns the given JITDylibs and all of their transitive dependencies in
1085 /// DFS order (based on linkage relationships). Each JITDylib will appear
1086 /// only once.
1087 ///
1088 /// If any JITDylib in the order is defunct then this method will return an
1089 /// error, otherwise returns the order.
1092
1093 /// Returns the given JITDylibs and all of their transitive dependencies in
1094 /// reverse DFS order (based on linkage relationships). Each JITDylib will
1095 /// appear only once.
1096 ///
1097 /// If any JITDylib in the order is defunct then this method will return an
1098 /// error, otherwise returns the order.
1101
1102 /// Return this JITDylib and its transitive dependencies in DFS order
1103 /// based on linkage relationships.
1104 ///
1105 /// If any JITDylib in the order is defunct then this method will return an
1106 /// error, otherwise returns the order.
1108
1109 /// Rteurn this JITDylib and its transitive dependencies in reverse DFS order
1110 /// based on linkage relationships.
1111 ///
1112 /// If any JITDylib in the order is defunct then this method will return an
1113 /// error, otherwise returns the order.
1115
1116private:
1117 using AsynchronousSymbolQuerySet =
1118 std::set<std::shared_ptr<AsynchronousSymbolQuery>>;
1119
1120 using AsynchronousSymbolQueryList =
1121 std::vector<std::shared_ptr<AsynchronousSymbolQuery>>;
1122
1123 struct UnmaterializedInfo {
1124 UnmaterializedInfo(std::unique_ptr<MaterializationUnit> MU,
1125 ResourceTracker *RT)
1126 : MU(std::move(MU)), RT(RT) {}
1127
1128 std::unique_ptr<MaterializationUnit> MU;
1129 ResourceTracker *RT;
1130 };
1131
1132 using UnmaterializedInfosMap =
1133 DenseMap<SymbolStringPtr, std::shared_ptr<UnmaterializedInfo>>;
1134
1135 using UnmaterializedInfosList =
1136 std::vector<std::shared_ptr<UnmaterializedInfo>>;
1137
1138 // Information about not-yet-ready symbol.
1139 // * DefiningEDU will point to the EmissionDepUnit that defines the symbol.
1140 // * DependantEDUs will hold pointers to any EmissionDepUnits currently
1141 // waiting on this symbol.
1142 // * Pending queries holds any not-yet-completed queries that include this
1143 // symbol.
1144 struct MaterializingInfo {
1145 friend class ExecutionSession;
1146
1147 LLVM_ABI void addQuery(std::shared_ptr<AsynchronousSymbolQuery> Q);
1148 LLVM_ABI void removeQuery(const AsynchronousSymbolQuery &Q);
1149 LLVM_ABI AsynchronousSymbolQueryList
1150 takeQueriesMeeting(SymbolState RequiredState);
1151 AsynchronousSymbolQueryList takeAllPendingQueries() {
1152 return std::move(PendingQueries);
1153 }
1154 bool hasQueriesPending() const { return !PendingQueries.empty(); }
1155 const AsynchronousSymbolQueryList &pendingQueries() const {
1156 return PendingQueries;
1157 }
1158 private:
1159 AsynchronousSymbolQueryList PendingQueries;
1160 };
1161
1162 using MaterializingInfosMap = DenseMap<SymbolStringPtr, MaterializingInfo>;
1163
1164 class SymbolTableEntry {
1165 public:
1166 SymbolTableEntry() = default;
1167 SymbolTableEntry(JITSymbolFlags Flags)
1168 : Flags(Flags), State(static_cast<uint8_t>(SymbolState::NeverSearched)),
1169 MaterializerAttached(false) {}
1170
1171 ExecutorAddr getAddress() const { return Addr; }
1172 JITSymbolFlags getFlags() const { return Flags; }
1173 SymbolState getState() const { return static_cast<SymbolState>(State); }
1174
1175 bool hasMaterializerAttached() const { return MaterializerAttached; }
1176
1177 void setAddress(ExecutorAddr Addr) { this->Addr = Addr; }
1178 void setFlags(JITSymbolFlags Flags) { this->Flags = Flags; }
1179 void setState(SymbolState State) {
1180 assert(static_cast<uint8_t>(State) < (1 << 6) &&
1181 "State does not fit in bitfield");
1182 this->State = static_cast<uint8_t>(State);
1183 }
1184
1185 void setMaterializerAttached(bool MaterializerAttached) {
1186 this->MaterializerAttached = MaterializerAttached;
1187 }
1188
1189 ExecutorSymbolDef getSymbol() const { return {Addr, Flags}; }
1190
1191 private:
1192 ExecutorAddr Addr;
1193 JITSymbolFlags Flags;
1194 uint8_t State : 7;
1195 uint8_t MaterializerAttached : 1;
1196 };
1197
1198 using SymbolTable = DenseMap<SymbolStringPtr, SymbolTableEntry>;
1199
1200 JITDylib(ExecutionSession &ES, std::string Name);
1201
1202 struct RemoveTrackerResult {
1203 AsynchronousSymbolQuerySet QueriesToFail;
1204 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
1205 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1206 };
1207
1208 RemoveTrackerResult IL_removeTracker(ResourceTracker &RT);
1209
1210 void transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1211
1212 LLVM_ABI Error defineImpl(MaterializationUnit &MU);
1213
1214 LLVM_ABI void
1215 installMaterializationUnit(std::unique_ptr<MaterializationUnit> MU,
1216 ResourceTracker &RT);
1217
1218 void detachQueryHelper(AsynchronousSymbolQuery &Q,
1219 const SymbolNameSet &QuerySymbols);
1220
1221 void transferEmittedNodeDependencies(MaterializingInfo &DependantMI,
1222 const SymbolStringPtr &DependantName,
1223 MaterializingInfo &EmittedMI);
1224
1225 Expected<SymbolFlagsMap>
1226 defineMaterializing(MaterializationResponsibility &FromMR,
1227 SymbolFlagsMap SymbolFlags);
1228
1229 Error replace(MaterializationResponsibility &FromMR,
1230 std::unique_ptr<MaterializationUnit> MU);
1231
1232 Expected<std::unique_ptr<MaterializationResponsibility>>
1233 delegate(MaterializationResponsibility &FromMR, SymbolFlagsMap SymbolFlags,
1234 SymbolStringPtr InitSymbol);
1235
1236 SymbolNameSet getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const;
1237
1238 void addDependencies(const SymbolStringPtr &Name,
1239 const SymbolDependenceMap &Dependants);
1240
1242
1243 void unlinkMaterializationResponsibility(MaterializationResponsibility &MR);
1244
1245 /// Attempt to reduce memory usage from empty \c UnmaterializedInfos and
1246 /// \c MaterializingInfos tables.
1247 void shrinkMaterializationInfoMemory();
1248
1249 ExecutionSession &ES;
1250 enum { Open, Closing, Closed } State = Open;
1251 std::mutex GeneratorsMutex;
1252 SymbolTable Symbols;
1253 UnmaterializedInfosMap UnmaterializedInfos;
1254 MaterializingInfosMap MaterializingInfos;
1255 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1256 JITDylibSearchOrder LinkOrder;
1257 ResourceTrackerSP DefaultTracker;
1258
1259 // Map trackers to sets of symbols tracked.
1260 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1261 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1262 TrackerMRs;
1263};
1264
1265/// Platforms set up standard symbols and mediate interactions between dynamic
1266/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1267/// Note that Platforms do not automatically run initializers: clients are still
1268/// responsible for doing this.
1270public:
1271 virtual ~Platform();
1272
1273 /// This method will be called outside the session lock each time a JITDylib
1274 /// is created (unless it is created with EmptyJITDylib set) to allow the
1275 /// Platform to install any JITDylib specific standard symbols (e.g
1276 /// __dso_handle).
1277 virtual Error setupJITDylib(JITDylib &JD) = 0;
1278
1279 /// This method will be called outside the session lock each time a JITDylib
1280 /// is removed to allow the Platform to remove any JITDylib-specific data.
1282
1283 /// This method will be called under the ExecutionSession lock each time a
1284 /// MaterializationUnit is added to a JITDylib.
1286 const MaterializationUnit &MU) = 0;
1287
1288 /// This method will be called under the ExecutionSession lock when a
1289 /// ResourceTracker is removed.
1291
1292 /// A utility function for looking up initializer symbols. Performs a blocking
1293 /// lookup for the given symbols in each of the given JITDylibs.
1294 ///
1295 /// Note: This function is deprecated and will be removed in the near future.
1299
1300 /// Performs an async lookup for the given symbols in each of the given
1301 /// JITDylibs, calling the given handler once all lookups have completed.
1302 static void
1304 ExecutionSession &ES,
1306};
1307
1308/// A materialization task.
1310 : public RTTIExtends<MaterializationTask, Task> {
1311public:
1312 static char ID;
1313
1314 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1315 std::unique_ptr<MaterializationResponsibility> MR)
1316 : MU(std::move(MU)), MR(std::move(MR)) {}
1317 ~MaterializationTask() override;
1318 void printDescription(raw_ostream &OS) override;
1319 void run() override;
1320
1321private:
1322 std::unique_ptr<MaterializationUnit> MU;
1323 std::unique_ptr<MaterializationResponsibility> MR;
1324};
1325
1326/// Lookups are usually run on the current thread, but in some cases they may
1327/// be run as tasks, e.g. if the lookup has been continued from a suspended
1328/// state.
1329class LLVM_ABI LookupTask : public RTTIExtends<LookupTask, Task> {
1330public:
1331 static char ID;
1332
1333 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1334 void printDescription(raw_ostream &OS) override;
1335 void run() override;
1336
1337private:
1338 LookupState LS;
1339};
1340
1341/// An ExecutionSession represents a running JIT program.
1345 friend class JITDylib;
1346 friend class LookupState;
1348 friend class ResourceTracker;
1349
1350public:
1351 /// For reporting errors.
1353
1354 /// Send a result to the remote.
1356
1357 /// An asynchronous wrapper-function callable from the executor via
1358 /// jit-dispatch.
1360 SendResultFunction SendResult,
1361 const char *ArgData, size_t ArgSize)>;
1362
1363 /// A map associating tag names with asynchronous wrapper function
1364 /// implementations in the JIT.
1367
1368 /// Construct an ExecutionSession with the given ExecutorProcessControl
1369 /// object.
1370 LLVM_ABI ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1371
1372 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1373 /// destruction.
1375
1376 /// End the session. Closes all JITDylibs and disconnects from the
1377 /// executor. Clients must call this method before destroying the session.
1379
1380 /// Get the ExecutorProcessControl object associated with this
1381 /// ExecutionSession.
1383
1384 /// Return the triple for the executor.
1385 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1386
1387 // Return the page size for the executor.
1388 size_t getPageSize() const { return EPC->getPageSize(); }
1389
1390 /// Get the SymbolStringPool for this instance.
1391 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1392 return EPC->getSymbolStringPool();
1393 }
1394
1395 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1396 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1397
1398 /// Set the Platform for this ExecutionSession.
1399 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1400
1401 /// Get the Platform for this session.
1402 /// Will return null if no Platform has been set for this ExecutionSession.
1403 Platform *getPlatform() { return P.get(); }
1404
1405 /// Run the given lambda with the session mutex locked.
1406 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1407 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1408 return F();
1409 }
1410
1411 /// Register the given ResourceManager with this ExecutionSession.
1412 /// Managers will be notified of events in reverse order of registration.
1414
1415 /// Deregister the given ResourceManager with this ExecutionSession.
1416 /// Manager must have been previously registered.
1418
1419 /// Return a pointer to the "name" JITDylib.
1420 /// Ownership of JITDylib remains within Execution Session
1422
1423 /// Add a new bare JITDylib to this ExecutionSession.
1424 ///
1425 /// The JITDylib Name is required to be unique. Clients should verify that
1426 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1427 /// are based on user input.
1428 ///
1429 /// This call does not install any library code or symbols into the newly
1430 /// created JITDylib. The client is responsible for all configuration.
1431 LLVM_ABI JITDylib &createBareJITDylib(std::string Name);
1432
1433 /// Add a new JITDylib to this ExecutionSession.
1434 ///
1435 /// The JITDylib Name is required to be unique. Clients should verify that
1436 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1437 /// are based on user input.
1438 ///
1439 /// If a Platform is attached then Platform::setupJITDylib will be called to
1440 /// install standard platform symbols (e.g. standard library interposes).
1441 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1443
1444 /// Removes the given JITDylibs from the ExecutionSession.
1445 ///
1446 /// This method clears all resources held for the JITDylibs, puts them in the
1447 /// closed state, and clears all references to them that are held by the
1448 /// ExecutionSession or other JITDylibs. No further code can be added to the
1449 /// removed JITDylibs, and the JITDylib objects will be freed once any
1450 /// remaining JITDylibSPs pointing to them are destroyed.
1451 ///
1452 /// This method does *not* run static destructors for code contained in the
1453 /// JITDylibs, and each JITDylib can only be removed once.
1454 ///
1455 /// JITDylibs will be removed in the order given. Teardown is usually
1456 /// independent for each JITDylib, but not always. In particular, where the
1457 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1458 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1459 /// last. If the client has introduced any other dependencies they should be
1460 /// accounted for in the removal order too.
1461 LLVM_ABI Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1462
1463 /// Calls removeJTIDylibs on the gives JITDylib.
1465 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1466 }
1467
1468 /// Set the error reporter function.
1470 this->ReportError = std::move(ReportError);
1471 return *this;
1472 }
1473
1474 /// Report a error for this execution session.
1475 ///
1476 /// Unhandled errors can be sent here to log them.
1477 void reportError(Error Err) { ReportError(std::move(Err)); }
1478
1479 /// Search the given JITDylibs to find the flags associated with each of the
1480 /// given symbols.
1481 LLVM_ABI void
1483 SymbolLookupSet Symbols,
1484 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1485
1486 /// Blocking version of lookupFlags.
1488 JITDylibSearchOrder SearchOrder,
1489 SymbolLookupSet Symbols);
1490
1491 /// Search the given JITDylibs for the given symbols.
1492 ///
1493 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1494 /// boolean indicates whether the search should match against non-exported
1495 /// (hidden visibility) symbols in that dylib (true means match against
1496 /// non-exported symbols, false means do not match).
1497 ///
1498 /// The NotifyComplete callback will be called once all requested symbols
1499 /// reach the required state.
1500 ///
1501 /// If all symbols are found, the RegisterDependencies function will be called
1502 /// while the session lock is held. This gives clients a chance to register
1503 /// dependencies for on the queried symbols for any symbols they are
1504 /// materializing (if a MaterializationResponsibility instance is present,
1505 /// this can be implemented by calling
1506 /// MaterializationResponsibility::addDependencies). If there are no
1507 /// dependenant symbols for this query (e.g. it is being made by a top level
1508 /// client to get an address to call) then the value NoDependenciesToRegister
1509 /// can be used.
1510 LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1511 SymbolLookupSet Symbols, SymbolState RequiredState,
1512 SymbolsResolvedCallback NotifyComplete,
1513 RegisterDependenciesFunction RegisterDependencies);
1514
1515 /// Blocking version of lookup above. Returns the resolved symbol map.
1516 /// If WaitUntilReady is true (the default), will not return until all
1517 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1518 /// false, will return as soon as all requested symbols are resolved,
1519 /// or an error occurs. If WaitUntilReady is false and an error occurs
1520 /// after resolution, the function will return a success value, but the
1521 /// error will be reported via reportErrors.
1523 lookup(const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols,
1525 SymbolState RequiredState = SymbolState::Ready,
1526 RegisterDependenciesFunction RegisterDependencies =
1528
1529 /// Convenience version of blocking lookup.
1530 /// Searches each of the JITDylibs in the search order in turn for the given
1531 /// symbol.
1533 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1534 SymbolState RequiredState = SymbolState::Ready);
1535
1536 /// Convenience version of blocking lookup.
1537 /// Searches each of the JITDylibs in the search order in turn for the given
1538 /// symbol. The search will not find non-exported symbols.
1540 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1541 SymbolState RequiredState = SymbolState::Ready);
1542
1543 /// Convenience version of blocking lookup.
1544 /// Searches each of the JITDylibs in the search order in turn for the given
1545 /// symbol. The search will not find non-exported symbols.
1547 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1548 SymbolState RequiredState = SymbolState::Ready);
1549
1550 /// Materialize the given unit.
1551 void dispatchTask(std::unique_ptr<Task> T) {
1552 assert(T && "T must be non-null");
1553 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1554 EPC->getDispatcher().dispatch(std::move(T));
1555 }
1556
1557 /// Returns the bootstrap map.
1559 return EPC->getBootstrapMap();
1560 }
1561
1562 /// Look up and SPS-deserialize a bootstrap map value.
1563 template <typename T, typename SPSTagT>
1564 Error getBootstrapMapValue(StringRef Key, std::optional<T> &Val) const {
1565 return EPC->getBootstrapMapValue<T, SPSTagT>(Key, Val);
1566 }
1567
1568 /// Returns the bootstrap symbol map.
1570 return EPC->getBootstrapSymbolsMap();
1571 }
1572
1573 /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
1574 /// bootstrap symbols map and writes its address to the ExecutorAddr if
1575 /// found. If any symbol is not found then the function returns an error.
1577 ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
1578 return EPC->getBootstrapSymbols(Pairs);
1579 }
1580
1581 /// Run a wrapper function in the executor. The given WFRHandler will be
1582 /// called on the result when it is returned.
1583 ///
1584 /// The wrapper function should be callable as:
1585 ///
1586 /// \code{.cpp}
1587 /// CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
1588 /// \endcode{.cpp}
1589 void callWrapperAsync(ExecutorAddr WrapperFnAddr,
1591 ArrayRef<char> ArgBuffer) {
1592 EPC->callWrapperAsync(WrapperFnAddr, std::move(OnComplete), ArgBuffer);
1593 }
1594
1595 /// Run a wrapper function in the executor using the given Runner to dispatch
1596 /// OnComplete when the result is ready.
1597 template <typename RunPolicyT, typename FnT>
1598 void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
1599 FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
1600 EPC->callWrapperAsync(std::forward<RunPolicyT>(Runner), WrapperFnAddr,
1601 std::forward<FnT>(OnComplete), ArgBuffer);
1602 }
1603
1604 /// Run a wrapper function in the executor. OnComplete will be dispatched
1605 /// as a GenericNamedTask using this instance's TaskDispatch object.
1606 template <typename FnT>
1607 void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
1608 ArrayRef<char> ArgBuffer) {
1609 EPC->callWrapperAsync(WrapperFnAddr, std::forward<FnT>(OnComplete),
1610 ArgBuffer);
1611 }
1612
1613 /// Run a wrapper function in the executor. The wrapper function should be
1614 /// callable as:
1615 ///
1616 /// \code{.cpp}
1617 /// CWrapperFunctionResult fn(uint8_t *Data, uint64_t Size);
1618 /// \endcode{.cpp}
1620 ArrayRef<char> ArgBuffer) {
1621 return EPC->callWrapper(WrapperFnAddr, ArgBuffer);
1622 }
1623
1624 /// Run a wrapper function using SPS to serialize the arguments and
1625 /// deserialize the results.
1626 template <typename SPSSignature, typename SendResultT, typename... ArgTs>
1627 void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult,
1628 const ArgTs &...Args) {
1629 EPC->callSPSWrapperAsync<SPSSignature, SendResultT, ArgTs...>(
1630 WrapperFnAddr, std::forward<SendResultT>(SendResult), Args...);
1631 }
1632
1633 /// Run a wrapper function using SPS to serialize the arguments and
1634 /// deserialize the results.
1635 ///
1636 /// If SPSSignature is a non-void function signature then the second argument
1637 /// (the first in the Args list) should be a reference to a return value.
1638 template <typename SPSSignature, typename... WrapperCallArgTs>
1640 WrapperCallArgTs &&...WrapperCallArgs) {
1641 return EPC->callSPSWrapper<SPSSignature, WrapperCallArgTs...>(
1642 WrapperFnAddr, std::forward<WrapperCallArgTs>(WrapperCallArgs)...);
1643 }
1644
1645 /// Wrap a handler that takes concrete argument types (and a sender for a
1646 /// concrete return type) to produce an AsyncHandlerWrapperFunction. Uses SPS
1647 /// to unpack the arguments and pack the result.
1648 ///
1649 /// This function is intended to support easy construction of
1650 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1651 /// (using registerJITDispatchHandler) and called from the executor.
1652 template <typename SPSSignature, typename HandlerT>
1654 return [H = std::forward<HandlerT>(H)](SendResultFunction SendResult,
1655 const char *ArgData,
1656 size_t ArgSize) mutable {
1658 ArgData, ArgSize, std::move(SendResult), H);
1659 };
1660 }
1661
1662 /// Wrap a class method that takes concrete argument types (and a sender for
1663 /// a concrete return type) to produce an AsyncHandlerWrapperFunction. Uses
1664 /// SPS to unpack the arguments and pack the result.
1665 ///
1666 /// This function is intended to support easy construction of
1667 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1668 /// (using registerJITDispatchHandler) and called from the executor.
1669 template <typename SPSSignature, typename ClassT, typename... MethodArgTs>
1671 wrapAsyncWithSPS(ClassT *Instance, void (ClassT::*Method)(MethodArgTs...)) {
1673 [Instance, Method](MethodArgTs &&...MethodArgs) {
1674 (Instance->*Method)(std::forward<MethodArgTs>(MethodArgs)...);
1675 });
1676 }
1677
1678 /// For each tag symbol name, associate the corresponding
1679 /// AsyncHandlerWrapperFunction with the address of that symbol. The
1680 /// handler becomes callable from the executor using the ORC runtime
1681 /// __orc_rt_jit_dispatch function and the given tag.
1682 ///
1683 /// Tag symbols will be looked up in JD using LookupKind::Static,
1684 /// JITDylibLookupFlags::MatchAllSymbols (hidden tags will be found), and
1685 /// LookupFlags::WeaklyReferencedSymbol. Missing tag definitions will not
1686 /// cause an error, the handler will simply be dropped.
1689
1690 /// Run a registered jit-side wrapper function.
1691 /// This should be called by the ExecutorProcessControl instance in response
1692 /// to incoming jit-dispatch requests from the executor.
1694 ExecutorAddr HandlerFnTagAddr,
1695 ArrayRef<char> ArgBuffer);
1696
1697 /// Dump the state of all the JITDylibs in this session.
1698 LLVM_ABI void dump(raw_ostream &OS);
1699
1700 /// Check the internal consistency of ExecutionSession data structures.
1701#ifdef EXPENSIVE_CHECKS
1702 bool verifySessionState(Twine Phase);
1703#endif
1704
1705private:
1706 static void logErrorsToStdErr(Error Err) {
1707 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1708 }
1709
1710 void dispatchOutstandingMUs();
1711
1712 static std::unique_ptr<MaterializationResponsibility>
1713 createMaterializationResponsibility(ResourceTracker &RT,
1714 SymbolFlagsMap Symbols,
1715 SymbolStringPtr InitSymbol) {
1716 auto &JD = RT.getJITDylib();
1717 std::unique_ptr<MaterializationResponsibility> MR(
1718 new MaterializationResponsibility(&RT, std::move(Symbols),
1719 std::move(InitSymbol)));
1720 JD.TrackerMRs[&RT].insert(MR.get());
1721 return MR;
1722 }
1723
1724 Error removeResourceTracker(ResourceTracker &RT);
1725 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1726 void destroyResourceTracker(ResourceTracker &RT);
1727
1728 // State machine functions for query application..
1729
1730 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1731 /// match a given query from the set of candidate symbols to generate
1732 /// definitions for (no need to generate a definition if one already exists).
1733 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1734 SymbolLookupSet &Candidates,
1735 SymbolLookupSet *NonCandidates);
1736
1737 /// Handle resumption of a lookup after entering a generator.
1738 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1739
1740 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1741 /// definition generation. It is called when a lookup is performed, and again
1742 /// each time that LookupState::continueLookup is called.
1743 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1744 Error Err);
1745
1746 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1747 /// call. It attempts to attach the symbol to all symbol table entries and
1748 /// collect all MaterializationUnits to dispatch. If this method fails then
1749 /// all MaterializationUnits will be left un-materialized.
1750 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1751 std::shared_ptr<AsynchronousSymbolQuery> Q,
1752 RegisterDependenciesFunction RegisterDependencies);
1753
1754 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1755 /// lookupFlags call.
1756 void OL_completeLookupFlags(
1757 std::unique_ptr<InProgressLookupState> IPLS,
1758 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1759
1760 // State machine functions for MaterializationResponsibility.
1761 LLVM_ABI void
1762 OL_destroyMaterializationResponsibility(MaterializationResponsibility &MR);
1764 OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1765 LLVM_ABI Error OL_notifyResolved(MaterializationResponsibility &MR,
1766 const SymbolMap &Symbols);
1767
1768 // FIXME: We should be able to derive FailedSymsForQuery from each query once
1769 // we fix how the detach operation works.
1770 struct EmitQueries {
1771 JITDylib::AsynchronousSymbolQuerySet Completed;
1772 JITDylib::AsynchronousSymbolQuerySet Failed;
1773 DenseMap<AsynchronousSymbolQuery *, std::shared_ptr<SymbolDependenceMap>>
1774 FailedSymsForQuery;
1775 };
1776
1778 IL_getSymbolState(JITDylib *JD, NonOwningSymbolStringPtr Name);
1779
1780 template <typename UpdateSymbolFn, typename UpdateQueryFn>
1781 void IL_collectQueries(JITDylib::AsynchronousSymbolQuerySet &Qs,
1782 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
1783 UpdateSymbolFn &&UpdateSymbol,
1784 UpdateQueryFn &&UpdateQuery);
1785
1786 Expected<EmitQueries> IL_emit(MaterializationResponsibility &MR,
1787 WaitingOnGraph::SimplifyResult SR);
1788 LLVM_ABI Error OL_notifyEmitted(MaterializationResponsibility &MR,
1790
1791 LLVM_ABI Error OL_defineMaterializing(MaterializationResponsibility &MR,
1792 SymbolFlagsMap SymbolFlags);
1793
1794 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1795 std::shared_ptr<SymbolDependenceMap>>
1796 IL_failSymbols(JITDylib &JD, const SymbolNameVector &SymbolsToFail);
1797 LLVM_ABI void OL_notifyFailed(MaterializationResponsibility &MR);
1799 std::unique_ptr<MaterializationUnit> MU);
1800 LLVM_ABI Expected<std::unique_ptr<MaterializationResponsibility>>
1801 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1802
1803#ifndef NDEBUG
1804 void dumpDispatchInfo(Task &T);
1805#endif // NDEBUG
1806
1807 mutable std::recursive_mutex SessionMutex;
1808 bool SessionOpen = true;
1809 std::unique_ptr<ExecutorProcessControl> EPC;
1810 std::unique_ptr<Platform> P;
1811 ErrorReporter ReportError = logErrorsToStdErr;
1812
1813 std::vector<ResourceManager *> ResourceManagers;
1814
1815 std::vector<JITDylibSP> JDs;
1817
1818 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1819 // with callbacks from asynchronous queries.
1820 mutable std::recursive_mutex OutstandingMUsMutex;
1821 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1822 std::unique_ptr<MaterializationResponsibility>>>
1823 OutstandingMUs;
1824
1825 mutable std::mutex JITDispatchHandlersMutex;
1826 DenseMap<ExecutorAddr, std::shared_ptr<JITDispatchHandlerFunction>>
1827 JITDispatchHandlers;
1828};
1829
1831 return JD->getExecutionSession().lookup({JD.get()}, Name);
1832}
1833
1834template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1836 if (isDefunct())
1838 F(getKeyUnsafe());
1839 return Error::success();
1840 });
1841}
1842
1843inline ExecutionSession &
1845 return JD.getExecutionSession();
1846}
1847
1848template <typename GeneratorT>
1849GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1850 auto &G = *DefGenerator;
1851 ES.runSessionLocked([&] {
1852 assert(State == Open && "Cannot add generator to closed JITDylib");
1853 DefGenerators.push_back(std::move(DefGenerator));
1854 });
1855 return G;
1856}
1857
1858template <typename Func>
1860 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1861 assert(State == Open && "Cannot use link order of closed JITDylib");
1862 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1863}
1864
1865template <typename MaterializationUnitType>
1866Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1867 ResourceTrackerSP RT) {
1868 assert(MU && "Can not define with a null MU");
1869
1870 if (MU->getSymbols().empty()) {
1871 // Empty MUs are allowable but pathological, so issue a warning.
1872 DEBUG_WITH_TYPE("orc", {
1873 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1874 << getName() << "\n";
1875 });
1876 return Error::success();
1877 } else
1878 DEBUG_WITH_TYPE("orc", {
1879 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1880 << " (tracker: ";
1881 if (RT == getDefaultResourceTracker())
1882 dbgs() << "default)";
1883 else if (RT)
1884 dbgs() << RT.get() << ")\n";
1885 else
1886 dbgs() << "0x0, default will be used)\n";
1887 });
1888
1889 return ES.runSessionLocked([&, this]() -> Error {
1890 assert(State == Open && "JD is defunct");
1891
1892 if (auto Err = defineImpl(*MU))
1893 return Err;
1894
1895 if (!RT)
1897
1898 if (auto *P = ES.getPlatform()) {
1899 if (auto Err = P->notifyAdding(*RT, *MU))
1900 return Err;
1901 }
1902
1903 installMaterializationUnit(std::move(MU), *RT);
1904 return Error::success();
1905 });
1906}
1907
1908template <typename MaterializationUnitType>
1909Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1910 ResourceTrackerSP RT) {
1911 assert(MU && "Can not define with a null MU");
1912
1913 if (MU->getSymbols().empty()) {
1914 // Empty MUs are allowable but pathological, so issue a warning.
1915 DEBUG_WITH_TYPE("orc", {
1916 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1917 << "\n";
1918 });
1919 return Error::success();
1920 } else
1921 DEBUG_WITH_TYPE("orc", {
1922 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1923 << " (tracker: ";
1924 if (RT == getDefaultResourceTracker())
1925 dbgs() << "default)";
1926 else if (RT)
1927 dbgs() << RT.get() << ")\n";
1928 else
1929 dbgs() << "0x0, default will be used)\n";
1930 });
1931
1932 return ES.runSessionLocked([&, this]() -> Error {
1933 assert(State == Open && "JD is defunct");
1934
1935 if (auto Err = defineImpl(*MU))
1936 return Err;
1937
1938 if (!RT)
1940
1941 if (auto *P = ES.getPlatform()) {
1942 if (auto Err = P->notifyAdding(*RT, *MU))
1943 return Err;
1944 }
1945
1946 installMaterializationUnit(std::move(MU), *RT);
1947 return Error::success();
1948 });
1949}
1950
1951/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1952/// re-export a subset of the source JITDylib's symbols in the target.
1954public:
1955 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1956
1957 /// Create a reexports generator. If an Allow predicate is passed, only
1958 /// symbols for which the predicate returns true will be reexported. If no
1959 /// Allow predicate is passed, all symbols will be exported.
1960 ReexportsGenerator(JITDylib &SourceJD,
1961 JITDylibLookupFlags SourceJDLookupFlags,
1963
1965 JITDylibLookupFlags JDLookupFlags,
1966 const SymbolLookupSet &LookupSet) override;
1967
1968private:
1969 JITDylib &SourceJD;
1970 JITDylibLookupFlags SourceJDLookupFlags;
1971 SymbolPredicate Allow;
1972};
1973
1974// --------------- IMPLEMENTATION --------------
1975// Implementations for inline functions/methods.
1976// ---------------------------------------------
1977
1979 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
1980}
1981
1983 return getExecutionSession().OL_getRequestedSymbols(*this);
1984}
1985
1987 const SymbolMap &Symbols) {
1988 return getExecutionSession().OL_notifyResolved(*this, Symbols);
1989}
1990
1992 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
1993 return getExecutionSession().OL_notifyEmitted(*this, EmittedDeps);
1994}
1995
1997 SymbolFlagsMap SymbolFlags) {
1998 return getExecutionSession().OL_defineMaterializing(*this,
1999 std::move(SymbolFlags));
2000}
2001
2003 getExecutionSession().OL_notifyFailed(*this);
2004}
2005
2007 std::unique_ptr<MaterializationUnit> MU) {
2008 return getExecutionSession().OL_replace(*this, std::move(MU));
2009}
2010
2013 return getExecutionSession().OL_delegate(*this, Symbols);
2014}
2015
2016} // End namespace orc
2017} // End namespace llvm
2018
2019#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
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
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:55
#define I(x, y, z)
Definition MD5.cpp:58
#define G(x, y, z)
Definition MD5.cpp:56
#define H(x, y, z)
Definition MD5.cpp:57
#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
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:147
bool empty() const
Definition DenseMap.h:109
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:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
size_type size() const
Definition DenseSet.h:87
A symbol query that returns results via a callback when results are ready.
Definition Core.h:789
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:201
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
Definition Core.h:810
friend class InProgressFullLookupState
Definition Core.h:791
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:215
friend class JITSymbolResolverAdapter
Definition Core.h:793
friend class MaterializationResponsibility
Definition Core.h:794
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:863
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:864
An ExecutionSession represents a running JIT program.
Definition Core.h:1342
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1585
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition Core.h:1382
unique_function< void(shared::WrapperFunctionResult)> SendResultFunction
Send a result to the remote.
Definition Core.h:1355
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1477
void callWrapperAsync(ExecutorAddr WrapperFnAddr, ExecutorProcessControl::IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1589
friend class JITDylib
Definition Core.h:1345
friend class InProgressLookupFlagsState
Definition Core.h:1343
const StringMap< ExecutorAddr > & getBootstrapSymbolsMap() const
Returns the bootstrap symbol map.
Definition Core.h:1569
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition Core.h:1399
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1385
Platform * getPlatform()
Get the Platform for this session.
Definition Core.h:1403
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition Core.h:1639
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:1745
shared::WrapperFunctionResult callWrapper(ExecutorAddr WrapperFnAddr, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1619
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1396
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1624
static JITDispatchHandlerFunction wrapAsyncWithSPS(ClassT *Instance, void(ClassT::*Method)(MethodArgTs...))
Wrap a class method that takes concrete argument types (and a sender for a concrete return type) to p...
Definition Core.h:1671
friend class LookupState
Definition Core.h:1346
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:1598
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1633
static JITDispatchHandlerFunction wrapAsyncWithSPS(HandlerT &&H)
Wrap a handler that takes concrete argument types (and a sender for a concrete return type) to produc...
Definition Core.h:1653
void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult, const ArgTs &...Args)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition Core.h:1627
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1391
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
Definition Core.h:1564
friend class InProgressFullLookupState
Definition Core.h:1344
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:1576
const StringMap< std::vector< char > > & getBootstrapMap() const
Returns the bootstrap map.
Definition Core.h:1558
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:1771
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition Core.cpp:1866
friend class MaterializationResponsibility
Definition Core.h:1347
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1607
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1579
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, ArrayRef< char > ArgBuffer)
Run a registered jit-side wrapper function.
Definition Core.cpp:1905
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1611
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1573
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1406
unique_function< void( SendResultFunction SendResult, const char *ArgData, size_t ArgSize)> JITDispatchHandlerFunction
An asynchronous wrapper-function callable from the executor via jit-dispatch.
Definition Core.h:1359
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1926
friend class ResourceTracker
Definition Core.h:1348
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition Core.h:1469
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1650
size_t getPageSize() const
Definition Core.h:1388
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1642
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1551
unique_function< void(Error)> ErrorReporter
For reporting errors.
Definition Core.h:1352
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition Core.h:1464
void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1607
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1365
Represents an address in the executor process.
A handler or incoming WrapperFunctionResults – 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:82
const SymbolDependenceMap & getSymbols() const
Definition Core.h:454
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:100
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:104
Represents a JIT'd dynamic library.
Definition Core.h:906
LLVM_ABI ~JITDylib()
Definition Core.cpp:652
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1059
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:656
JITDylib & operator=(JITDylib &&)=delete
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1120
friend class AsynchronousSymbolQuery
Definition Core.h:907
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:1035
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:1866
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:925
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:1019
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:680
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition Core.h:1859
friend class MaterializationResponsibility
Definition Core.h:910
friend class Platform
Definition Core.h:909
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1047
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:1004
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:1741
friend class ExecutionSession
Definition Core.h:908
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:671
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1849
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:688
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1737
Wraps state for a lookup-in-progress.
Definition Core.h:838
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:632
LLVM_ABI LookupState & operator=(LookupState &&)
friend class ExecutionSession
Definition Core.h:840
friend class OrcV2CAPIHelper
Definition Core.h:839
LLVM_ABI LookupState(LookupState &&)
LookupTask(LookupState LS)
Definition Core.h:1333
static char ID
Definition Core.h:1331
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:580
MaterializationResponsibility & operator=(MaterializationResponsibility &&)=delete
ExecutionSession & getExecutionSession() const
Returns the ExecutionSession for this instance.
Definition Core.h:1844
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition Core.h:1986
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition Core.h:1978
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition Core.h:2006
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:599
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition Core.h:1996
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition Core.h:1982
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition Core.h:2012
const ResourceTrackerSP & getResourceTracker() const
Return the ResourceTracker associated with this instance.
Definition Core.h:595
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:619
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:1991
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition Core.h:2002
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:605
const SymbolFlagsMap & getSymbols() const
Returns the symbol flags map for this responsibility instance.
Definition Core.h:614
A materialization task.
Definition Core.h:1310
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition Core.h:1314
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
const SymbolNameVector & getSymbols() const
Definition Core.h:535
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:533
MissingSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:527
const std::string & getModuleName() const
Definition Core.h:534
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition Core.h:1269
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:1509
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:1460
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:300
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1955
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:597
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:591
Listens for ResourceTracker operations.
Definition Core.h:130
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:71
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:78
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:74
API to remove / transfer ownership of JIT resources.
Definition Core.h:82
JITDylib & getJITDylib() const
Return the JITDylib targeted by this tracker.
Definition Core.h:97
friend class JITDylib
Definition Core.h:85
ResourceTracker & operator=(const ResourceTracker &)=delete
ResourceKey getKeyUnsafe() const
Returns the key associated with this tracker.
Definition Core.h:119
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:59
ResourceTracker & operator=(ResourceTracker &&)=delete
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:50
ResourceTracker(const ResourceTracker &)=delete
friend class MaterializationResponsibility
Definition Core.h:86
bool isDefunct() const
Return true if this tracker has become defunct.
Definition Core.h:114
ResourceTracker(ResourceTracker &&)=delete
Error withResourceKeyDo(Func &&F)
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:1834
friend class ExecutionSession
Definition Core.h:84
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:55
Expected< ExecutorSymbolDef > lookup() const
Definition Core.h:1830
SymbolInstance(JITDylibSP JD, SymbolStringPtr Name)
Definition Core.h:65
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition Core.cpp:180
unique_function< void(Expected< ExecutorSymbolDef >)> LookupAsyncOnCompleteFn
Definition Core.h:62
const JITDylib & getJITDylib() const
Definition Core.h:68
const SymbolStringPtr & getName() const
Definition Core.h:69
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition Core.h:199
std::pair< SymbolStringPtr, SymbolLookupFlags > value_type
Definition Core.h:201
const_iterator begin() const
Definition Core.h:283
void removeDuplicates()
Remove any duplicate elements.
Definition Core.h:383
UnderlyingVector::const_iterator const_iterator
Definition Core.h:204
void sortByAddress()
Sort the lookup set by pointer value.
Definition Core.h:371
SymbolLookupSet(std::initializer_list< SymbolStringPtr > Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from an initializer list of SymbolStringPtrs.
Definition Core.h:220
UnderlyingVector::size_type size() const
Definition Core.h:280
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
Definition Core.h:265
static SymbolLookupSet fromMapKeys(const DenseMap< SymbolStringPtr, ValT > &M, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from DenseMap keys.
Definition Core.h:253
SymbolLookupSet & append(SymbolLookupSet Other)
Quickly append one lookup set to another.
Definition Core.h:272
SymbolLookupSet(ArrayRef< SymbolStringPtr > Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from a vector of symbols with the given Flags used for each value.
Definition Core.h:242
SymbolLookupSet(std::initializer_list< value_type > Elems)
Definition Core.h:208
void sortByName()
Sort the lookup set lexicographically.
Definition Core.h:375
void remove(iterator I)
Removes the element pointed to by the given iterator.
Definition Core.h:294
auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t< std::is_same< decltype(Body(std::declval< const SymbolStringPtr & >(), std::declval< SymbolLookupFlags >())), bool >::value >
Loop over the elements of this SymbolLookupSet, applying the Body function to each one.
Definition Core.h:316
bool containsDuplicates()
Returns true if this set contains any duplicates.
Definition Core.h:392
UnderlyingVector::iterator iterator
Definition Core.h:203
bool empty() const
Definition Core.h:279
void remove_if(PredFn &&Pred)
Removes all elements matching the given predicate, which must be callable as bool(const SymbolStringP...
Definition Core.h:298
SymbolLookupSet(const SymbolNameSet &Names, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Construct a SymbolLookupSet from a SymbolNameSet with the given Flags used for each value.
Definition Core.h:230
SymbolLookupSet(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Definition Core.h:213
SymbolNameVector getSymbolNames() const
Construct a SymbolNameVector from this instance by dropping the Flags values.
Definition Core.h:360
const_iterator end() const
Definition Core.h:284
auto forEachWithRemoval(BodyFn &&Body) -> std::enable_if_t< std::is_same< decltype(Body(std::declval< const SymbolStringPtr & >(), std::declval< SymbolLookupFlags >())), Expected< bool > >::value, Error >
Loop over the elements of this SymbolLookupSet, applying the Body function to each one.
Definition Core.h:338
void remove(UnderlyingVector::size_type I)
Removes the Ith element of the vector, replacing it with the last element.
Definition Core.h:287
std::vector< value_type > UnderlyingVector
Definition Core.h:202
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:154
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:158
const SymbolNameSet & getSymbols() const
Definition Core.h:511
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:148
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:510
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:144
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:127
const SymbolNameVector & getSymbols() const
Definition Core.h:493
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:140
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:492
UnexpectedSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:551
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:557
const std::string & getModuleName() const
Definition Core.h:558
const SymbolNameVector & getSymbols() const
Definition Core.h:559
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:120
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:116
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition Core.cpp:108
WaitingOnGraph class template.
C++ wrapper function result: Same as CWrapperFunctionResult 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:182
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:177
IntrusiveRefCntPtr< JITDylib > JITDylibSP
Definition Core.h:57
IntrusiveRefCntPtr< ResourceTracker > ResourceTrackerSP
Definition Core.h:56
std::unique_ptr< ReExportsMaterializationUnit > symbolAliases(SymbolAliasMap Aliases)
Create a ReExportsMaterializationUnit with the given aliases.
Definition Core.h:754
std::function< void(const SymbolDependenceMap &)> RegisterDependenciesFunction
Callback to register the dependencies for a given query.
Definition Core.h:423
uintptr_t ResourceKey
Definition Core.h:79
SymbolLookupFlags
Lookup flags that apply to each symbol in a lookup.
Definition Core.h:161
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:763
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 ...
JITDylibLookupFlags
Lookup flags that apply to each dylib in the search order for a lookup.
Definition Core.h:151
detail::WaitingOnGraph< JITDylib *, NonOwningSymbolStringPtr > WaitingOnGraph
Definition Core.h:53
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
static std::unique_ptr< UnwindInfoManager > Instance
LookupKind
Describes the kind of lookup being performed.
Definition Core.h:173
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:38
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:776
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:779
@ NeverSearched
No symbol should be in this state.
Definition Core.h:778
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:782
@ Emitted
Assigned address, still materializing.
Definition Core.h:781
@ Resolved
Queried, materialization begun.
Definition Core.h:780
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:417
unique_function< void(Expected< SymbolMap >)> SymbolsResolvedCallback
Callback to notify client that symbols have been resolved.
Definition Core.h:420
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:65
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2076
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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.
@ Other
Any other memory.
Definition ModRef.h:68
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:1867
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:867
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:869
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1425
JITSymbolFlags AliasFlags
Definition Core.h:413
SymbolAliasMapEntry(SymbolStringPtr Aliasee, JITSymbolFlags AliasFlags)
Definition Core.h:409
SymbolStringPtr Aliasee
Definition Core.h:412
A set of symbols and the their dependencies.
Definition Core.h:568
SymbolDependenceMap Dependencies
Definition Core.h:570