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/// Returned by operations that fail because a JITDylib has been closed.
444class LLVM_ABI JITDylibDefunct : public ErrorInfo<JITDylibDefunct> {
445public:
446 static char ID;
447
449 std::error_code convertToErrorCode() const override;
450 void log(raw_ostream &OS) const override;
451
452private:
453 JITDylibSP JD;
454};
455
456/// Used to notify a JITDylib that the given set of symbols failed to
457/// materialize.
458class LLVM_ABI FailedToMaterialize : public ErrorInfo<FailedToMaterialize> {
459public:
460 static char ID;
461
462 FailedToMaterialize(std::shared_ptr<SymbolStringPool> SSP,
463 std::shared_ptr<SymbolDependenceMap> Symbols);
464 ~FailedToMaterialize() override;
465 std::error_code convertToErrorCode() const override;
466 void log(raw_ostream &OS) const override;
467 const SymbolDependenceMap &getSymbols() const { return *Symbols; }
468
469private:
470 std::shared_ptr<SymbolStringPool> SSP;
471 std::shared_ptr<SymbolDependenceMap> Symbols;
472};
473
474/// Used to report failure due to unsatisfiable symbol dependencies.
476 : public ErrorInfo<UnsatisfiedSymbolDependencies> {
477public:
478 static char ID;
479
480 UnsatisfiedSymbolDependencies(std::shared_ptr<SymbolStringPool> SSP,
481 JITDylibSP JD, SymbolNameSet FailedSymbols,
482 SymbolDependenceMap BadDeps,
483 std::string Explanation);
484 std::error_code convertToErrorCode() const override;
485 void log(raw_ostream &OS) const override;
486
487private:
488 std::shared_ptr<SymbolStringPool> SSP;
489 JITDylibSP JD;
490 SymbolNameSet FailedSymbols;
491 SymbolDependenceMap BadDeps;
492 std::string Explanation;
493};
494
495/// Used to notify clients when symbols can not be found during a lookup.
496class LLVM_ABI SymbolsNotFound : public ErrorInfo<SymbolsNotFound> {
497public:
498 static char ID;
499
500 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP, SymbolNameSet Symbols);
501 SymbolsNotFound(std::shared_ptr<SymbolStringPool> SSP,
502 SymbolNameVector Symbols);
503 std::error_code convertToErrorCode() const override;
504 void log(raw_ostream &OS) const override;
505 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
506 const SymbolNameVector &getSymbols() const { return Symbols; }
507
508private:
509 std::shared_ptr<SymbolStringPool> SSP;
510 SymbolNameVector Symbols;
511};
512
513/// Used to notify clients that a set of symbols could not be removed.
515 : public ErrorInfo<SymbolsCouldNotBeRemoved> {
516public:
517 static char ID;
518
519 SymbolsCouldNotBeRemoved(std::shared_ptr<SymbolStringPool> SSP,
520 SymbolNameSet Symbols);
521 std::error_code convertToErrorCode() const override;
522 void log(raw_ostream &OS) const override;
523 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
524 const SymbolNameSet &getSymbols() const { return Symbols; }
525
526private:
527 std::shared_ptr<SymbolStringPool> SSP;
528 SymbolNameSet Symbols;
529};
530
531/// Errors of this type should be returned if a module fails to include
532/// definitions that are claimed by the module's associated
533/// MaterializationResponsibility. If this error is returned it is indicative of
534/// a broken transformation / compiler / object cache.
536 : public ErrorInfo<MissingSymbolDefinitions> {
537public:
538 static char ID;
539
540 MissingSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
541 std::string ModuleName, SymbolNameVector Symbols)
542 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
543 Symbols(std::move(Symbols)) {}
544 std::error_code convertToErrorCode() const override;
545 void log(raw_ostream &OS) const override;
546 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
547 const std::string &getModuleName() const { return ModuleName; }
548 const SymbolNameVector &getSymbols() const { return Symbols; }
549private:
550 std::shared_ptr<SymbolStringPool> SSP;
551 std::string ModuleName;
552 SymbolNameVector Symbols;
553};
554
555/// Errors of this type should be returned if a module contains definitions for
556/// symbols that are not claimed by the module's associated
557/// MaterializationResponsibility. If this error is returned it is indicative of
558/// a broken transformation / compiler / object cache.
560 : public ErrorInfo<UnexpectedSymbolDefinitions> {
561public:
562 static char ID;
563
564 UnexpectedSymbolDefinitions(std::shared_ptr<SymbolStringPool> SSP,
565 std::string ModuleName, SymbolNameVector Symbols)
566 : SSP(std::move(SSP)), ModuleName(std::move(ModuleName)),
567 Symbols(std::move(Symbols)) {}
568 std::error_code convertToErrorCode() const override;
569 void log(raw_ostream &OS) const override;
570 std::shared_ptr<SymbolStringPool> getSymbolStringPool() { return SSP; }
571 const std::string &getModuleName() const { return ModuleName; }
572 const SymbolNameVector &getSymbols() const { return Symbols; }
573private:
574 std::shared_ptr<SymbolStringPool> SSP;
575 std::string ModuleName;
576 SymbolNameVector Symbols;
577};
578
579/// A set of symbols and the their dependencies. Used to describe dependencies
580/// for the MaterializationResponsibility::notifyEmitted operation.
585
586/// Tracks responsibility for materialization, and mediates interactions between
587/// MaterializationUnits and JDs.
588///
589/// An instance of this class is passed to MaterializationUnits when their
590/// materialize method is called. It allows MaterializationUnits to resolve and
591/// emit symbols, or abandon materialization by notifying any unmaterialized
592/// symbols of an error.
594 friend class ExecutionSession;
595 friend class JITDylib;
596
597public:
601
602 /// Destruct a MaterializationResponsibility instance. In debug mode
603 /// this asserts that all symbols being tracked have been either
604 /// emitted or notified of an error.
606
607 /// Return the ResourceTracker associated with this instance.
608 const ResourceTrackerSP &getResourceTracker() const { return RT; }
609
610 /// Runs the given callback under the session lock, passing in the associated
611 /// ResourceKey. This is the safe way to associate resources with trackers.
612 template <typename Func> Error withResourceKeyDo(Func &&F) const {
613 return RT->withResourceKeyDo(std::forward<Func>(F));
614 }
615
616 /// Returns the target JITDylib that these symbols are being materialized
617 /// into.
618 JITDylib &getTargetJITDylib() const { return JD; }
619
620 /// Returns the ExecutionSession for this instance.
622
623 /// Returns the symbol flags map for this responsibility instance.
624 /// Note: The returned flags may have transient flags (Lazy, Materializing)
625 /// set. These should be stripped with JITSymbolFlags::stripTransientFlags
626 /// before using.
627 const SymbolFlagsMap &getSymbols() const { return SymbolFlags; }
628
629 /// Returns the initialization pseudo-symbol, if any. This symbol will also
630 /// be present in the SymbolFlagsMap for this MaterializationResponsibility
631 /// object.
632 const SymbolStringPtr &getInitializerSymbol() const { return InitSymbol; }
633
634 /// Returns the names of any symbols covered by this
635 /// MaterializationResponsibility object that have queries pending. This
636 /// information can be used to return responsibility for unrequested symbols
637 /// back to the JITDylib via the delegate method.
639
640 /// Notifies the target JITDylib that the given symbols have been resolved.
641 /// This will update the given symbols' addresses in the JITDylib, and notify
642 /// any pending queries on the given symbols of their resolution. The given
643 /// symbols must be ones covered by this MaterializationResponsibility
644 /// instance. Individual calls to this method may resolve a subset of the
645 /// symbols, but all symbols must have been resolved prior to calling emit.
646 ///
647 /// This method will return an error if any symbols being resolved have been
648 /// moved to the error state due to the failure of a dependency. If this
649 /// method returns an error then clients should log it and call
650 /// failMaterialize. If no dependencies have been registered for the
651 /// symbols covered by this MaterializationResponsibility then this method
652 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
653 Error notifyResolved(const SymbolMap &Symbols);
654
655 /// Notifies the target JITDylib (and any pending queries on that JITDylib)
656 /// that all symbols covered by this MaterializationResponsibility instance
657 /// have been emitted.
658 ///
659 /// The DepGroups array describes the dependencies of symbols being emitted on
660 /// symbols that are outside this MaterializationResponsibility object. Each
661 /// group consists of a pair of a set of symbols and a SymbolDependenceMap
662 /// that describes the dependencies for the symbols in the first set. The
663 /// elements of DepGroups must be non-overlapping (no symbol should appear in
664 /// more than one of hte symbol sets), but do not have to be exhaustive. Any
665 /// symbol in this MaterializationResponsibility object that is not covered
666 /// by an entry will be treated as having no dependencies.
667 ///
668 /// This method will return an error if any symbols being resolved have been
669 /// moved to the error state due to the failure of a dependency. If this
670 /// method returns an error then clients should log it and call
671 /// failMaterialize. If no dependencies have been registered for the
672 /// symbols covered by this MaterializationResponsibility then this method
673 /// is guaranteed to return Error::success() and can be wrapped with cantFail.
675
676 /// Attempt to claim responsibility for new definitions. This method can be
677 /// used to claim responsibility for symbols that are added to a
678 /// materialization unit during the compilation process (e.g. literal pool
679 /// symbols). Symbol linkage rules are the same as for symbols that are
680 /// defined up front: duplicate strong definitions will result in errors.
681 /// Duplicate weak definitions will be discarded (in which case they will
682 /// not be added to this responsibility instance).
683 ///
684 /// This method can be used by materialization units that want to add
685 /// additional symbols at materialization time (e.g. stubs, compile
686 /// callbacks, metadata).
688
689 /// Notify all not-yet-emitted covered by this MaterializationResponsibility
690 /// instance that an error has occurred.
691 /// This will remove all symbols covered by this MaterializationResponsibility
692 /// from the target JITDylib, and send an error to any queries waiting on
693 /// these symbols.
694 void failMaterialization();
695
696 /// Transfers responsibility to the given MaterializationUnit for all
697 /// symbols defined by that MaterializationUnit. This allows
698 /// materializers to break up work based on run-time information (e.g.
699 /// by introspecting which symbols have actually been looked up and
700 /// materializing only those).
701 Error replace(std::unique_ptr<MaterializationUnit> MU);
702
703 /// Delegates responsibility for the given symbols to the returned
704 /// materialization responsibility. Useful for breaking up work between
705 /// threads, or different kinds of materialization processes.
707 delegate(const SymbolNameSet &Symbols);
708
709private:
710 /// Create a MaterializationResponsibility for the given JITDylib and
711 /// initial symbols.
713 SymbolFlagsMap SymbolFlags,
714 SymbolStringPtr InitSymbol)
715 : JD(RT->getJITDylib()), RT(std::move(RT)),
716 SymbolFlags(std::move(SymbolFlags)), InitSymbol(std::move(InitSymbol)) {
717 assert(!this->SymbolFlags.empty() && "Materializing nothing?");
718 }
719
720 JITDylib &JD;
722 SymbolFlagsMap SymbolFlags;
723 SymbolStringPtr InitSymbol;
724};
725
726/// A materialization unit for symbol aliases. Allows existing symbols to be
727/// aliased with alternate flags.
729public:
730 /// SourceJD is allowed to be nullptr, in which case the source JITDylib is
731 /// taken to be whatever JITDylib these definitions are materialized in (and
732 /// MatchNonExported has no effect). This is useful for defining aliases
733 /// within a JITDylib.
734 ///
735 /// Note: Care must be taken that no sets of aliases form a cycle, as such
736 /// a cycle will result in a deadlock when any symbol in the cycle is
737 /// resolved.
739 JITDylibLookupFlags SourceJDLookupFlags,
740 SymbolAliasMap Aliases);
741
742 StringRef getName() const override;
743
744private:
745 void materialize(std::unique_ptr<MaterializationResponsibility> R) override;
746 void discard(const JITDylib &JD, const SymbolStringPtr &Name) override;
748 extractFlags(const SymbolAliasMap &Aliases);
749
750 JITDylib *SourceJD = nullptr;
751 JITDylibLookupFlags SourceJDLookupFlags;
752 SymbolAliasMap Aliases;
753};
754
755/// Create a ReExportsMaterializationUnit with the given aliases.
756/// Useful for defining symbol aliases.: E.g., given a JITDylib JD containing
757/// symbols "foo" and "bar", we can define aliases "baz" (for "foo") and "qux"
758/// (for "bar") with: \code{.cpp}
759/// SymbolStringPtr Baz = ...;
760/// SymbolStringPtr Qux = ...;
761/// if (auto Err = JD.define(symbolAliases({
762/// {Baz, { Foo, JITSymbolFlags::Exported }},
763/// {Qux, { Bar, JITSymbolFlags::Weak }}}))
764/// return Err;
765/// \endcode
766inline std::unique_ptr<ReExportsMaterializationUnit>
768 return std::make_unique<ReExportsMaterializationUnit>(
769 nullptr, JITDylibLookupFlags::MatchAllSymbols, std::move(Aliases));
770}
771
772/// Create a materialization unit for re-exporting symbols from another JITDylib
773/// with alternative names/flags.
774/// SourceJD will be searched using the given JITDylibLookupFlags.
775inline std::unique_ptr<ReExportsMaterializationUnit>
777 JITDylibLookupFlags SourceJDLookupFlags =
779 return std::make_unique<ReExportsMaterializationUnit>(
780 &SourceJD, SourceJDLookupFlags, std::move(Aliases));
781}
782
783/// Build a SymbolAliasMap for the common case where you want to re-export
784/// symbols from another JITDylib with the same linkage/flags.
787
788/// Represents the state that a symbol has reached during materialization.
789enum class SymbolState : uint8_t {
790 Invalid, /// No symbol should be in this state.
791 NeverSearched, /// Added to the symbol table, never queried.
792 Materializing, /// Queried, materialization begun.
793 Resolved, /// Assigned address, still materializing.
794 Emitted, /// Emitted to memory, but waiting on transitive dependencies.
795 Ready = 0x3f /// Ready and safe for clients to access.
796};
797
798/// A symbol query that returns results via a callback when results are
799/// ready.
800///
801/// makes a callback when all symbols are available.
803 friend class ExecutionSession;
805 friend class JITDylib;
808
809public:
810 /// Create a query for the given symbols. The NotifyComplete
811 /// callback will be called once all queried symbols reach the given
812 /// minimum state.
814 SymbolState RequiredState,
815 SymbolsResolvedCallback NotifyComplete);
816
817 /// Notify the query that a requested symbol has reached the required state.
820
821 /// Returns true if all symbols covered by this query have been
822 /// resolved.
823 bool isComplete() const { return OutstandingSymbolsCount == 0; }
824
825
826private:
827 void handleComplete(ExecutionSession &ES);
828
829 SymbolState getRequiredState() { return RequiredState; }
830
831 void addQueryDependence(JITDylib &JD, SymbolStringPtr Name);
832
833 void removeQueryDependence(JITDylib &JD, const SymbolStringPtr &Name);
834
835 void dropSymbol(const SymbolStringPtr &Name);
836
837 void handleFailed(Error Err);
838
839 void detach();
840
841 SymbolsResolvedCallback NotifyComplete;
842 SymbolDependenceMap QueryRegistrations;
843 SymbolMap ResolvedSymbols;
844 size_t OutstandingSymbolsCount;
845 SymbolState RequiredState;
846};
847
848/// Wraps state for a lookup-in-progress.
849/// DefinitionGenerators can optionally take ownership of a LookupState object
850/// to suspend a lookup-in-progress while they search for definitions.
852 friend class OrcV2CAPIHelper;
853 friend class ExecutionSession;
854
855public:
860
861 /// Continue the lookup. This can be called by DefinitionGenerators
862 /// to re-start a captured query-application operation.
863 LLVM_ABI void continueLookup(Error Err);
864
865private:
866 LookupState(std::unique_ptr<InProgressLookupState> IPLS);
867
868 // For C API.
869 void reset(InProgressLookupState *IPLS);
870
871 std::unique_ptr<InProgressLookupState> IPLS;
872};
873
874/// Definition generators can be attached to JITDylibs to generate new
875/// definitions for otherwise unresolved symbols during lookup.
877 friend class ExecutionSession;
878
879public:
880 virtual ~DefinitionGenerator();
881
882 /// DefinitionGenerators should override this method to insert new
883 /// definitions into the parent JITDylib. K specifies the kind of this
884 /// lookup. JD specifies the target JITDylib being searched, and
885 /// JDLookupFlags specifies whether the search should match against
886 /// hidden symbols. Finally, Symbols describes the set of unresolved
887 /// symbols and their associated lookup flags.
889 JITDylibLookupFlags JDLookupFlags,
890 const SymbolLookupSet &LookupSet) = 0;
891
892private:
893 std::mutex M;
894 bool InUse = false;
895 std::deque<LookupState> PendingLookups;
896};
897
898/// Represents a JIT'd dynamic library.
899///
900/// This class aims to mimic the behavior of a regular dylib or shared object,
901/// but without requiring the contained program representations to be compiled
902/// up-front. The JITDylib's content is defined by adding MaterializationUnits,
903/// and contained MaterializationUnits will typically rely on the JITDylib's
904/// links-against order to resolve external references (similar to a regular
905/// dylib).
906///
907/// The JITDylib object is a thin wrapper that references state held by the
908/// ExecutionSession. JITDylibs can be removed, clearing this underlying state
909/// and leaving the JITDylib object in a defunct state. In this state the
910/// JITDylib's name is guaranteed to remain accessible. If the ExecutionSession
911/// is still alive then other operations are callable but will return an Error
912/// or null result (depending on the API). It is illegal to call any operation
913/// other than getName on a JITDylib after the ExecutionSession has been torn
914/// down.
915///
916/// JITDylibs cannot be moved or copied. Their address is stable, and useful as
917/// a key in some JIT data structures.
918class JITDylib : public ThreadSafeRefCountedBase<JITDylib>,
919 public jitlink::JITLinkDylib {
921 friend class ExecutionSession;
922 friend class Platform;
924public:
925
926 JITDylib(const JITDylib &) = delete;
927 JITDylib &operator=(const JITDylib &) = delete;
928 JITDylib(JITDylib &&) = delete;
931
932 /// Get a reference to the ExecutionSession for this JITDylib.
933 ///
934 /// It is legal to call this method on a defunct JITDylib, however the result
935 /// will only usable if the ExecutionSession is still alive. If this JITDylib
936 /// is held by an error that may have torn down the JIT then the result
937 /// should not be used.
938 ExecutionSession &getExecutionSession() const { return ES; }
939
940 /// Dump current JITDylib state to OS.
941 ///
942 /// It is legal to call this method on a defunct JITDylib.
943 LLVM_ABI void dump(raw_ostream &OS);
944
945 /// Calls remove on all trackers currently associated with this JITDylib.
946 /// Does not run static deinits.
947 ///
948 /// Note that removal happens outside the session lock, so new code may be
949 /// added concurrently while the clear is underway, and the newly added
950 /// code will *not* be cleared. Adding new code concurrently with a clear
951 /// is usually a bug and should be avoided.
952 ///
953 /// It is illegal to call this method on a defunct JITDylib and the client
954 /// is responsible for ensuring that they do not do so.
956
957 /// Get the default resource tracker for this JITDylib.
958 ///
959 /// It is illegal to call this method on a defunct JITDylib and the client
960 /// is responsible for ensuring that they do not do so.
962
963 /// Create a resource tracker for this JITDylib.
964 ///
965 /// It is illegal to call this method on a defunct JITDylib and the client
966 /// is responsible for ensuring that they do not do so.
968
969 /// Adds a definition generator to this JITDylib and returns a referenece to
970 /// it.
971 ///
972 /// When JITDylibs are searched during lookup, if no existing definition of
973 /// a symbol is found, then any generators that have been added are run (in
974 /// the order that they were added) to potentially generate a definition.
975 ///
976 /// It is illegal to call this method on a defunct JITDylib and the client
977 /// is responsible for ensuring that they do not do so.
978 template <typename GeneratorT>
979 GeneratorT &addGenerator(std::unique_ptr<GeneratorT> DefGenerator);
980
981 /// Remove a definition generator from this JITDylib.
982 ///
983 /// The given generator must exist in this JITDylib's generators list (i.e.
984 /// have been added and not yet removed).
985 ///
986 /// It is illegal to call this method on a defunct JITDylib and the client
987 /// is responsible for ensuring that they do not do so.
989
990 /// Set the link order to be used when fixing up definitions in JITDylib.
991 /// This will replace the previous link order, and apply to any symbol
992 /// resolutions made for definitions in this JITDylib after the call to
993 /// setLinkOrder (even if the definition itself was added before the
994 /// call).
995 ///
996 /// If LinkAgainstThisJITDylibFirst is true (the default) then this JITDylib
997 /// will add itself to the beginning of the LinkOrder (Clients should not
998 /// put this JITDylib in the list in this case, to avoid redundant lookups).
999 ///
1000 /// If LinkAgainstThisJITDylibFirst is false then the link order will be used
1001 /// as-is. The primary motivation for this feature is to support deliberate
1002 /// shadowing of symbols in this JITDylib by a facade JITDylib. For example,
1003 /// the facade may resolve function names to stubs, and the stubs may compile
1004 /// lazily by looking up symbols in this dylib. Adding the facade dylib
1005 /// as the first in the link order (instead of this dylib) ensures that
1006 /// definitions within this dylib resolve to the lazy-compiling stubs,
1007 /// rather than immediately materializing the definitions in this dylib.
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 setLinkOrder(JITDylibSearchOrder NewSearchOrder,
1012 bool LinkAgainstThisJITDylibFirst = true);
1013
1014 /// Append the given JITDylibSearchOrder to the link order for this
1015 /// JITDylib (discarding any elements already present in this JITDylib's
1016 /// link order).
1017 LLVM_ABI void addToLinkOrder(const JITDylibSearchOrder &NewLinks);
1018
1019 /// Add the given JITDylib to the link order for definitions in this
1020 /// JITDylib.
1021 ///
1022 /// It is illegal to call this method on a defunct JITDylib and the client
1023 /// is responsible for ensuring that they do not do so.
1024 LLVM_ABI void
1026 JITDylibLookupFlags JDLookupFlags =
1028
1029 /// Replace OldJD with NewJD in the link order if OldJD is present.
1030 /// Otherwise this operation is a no-op.
1031 ///
1032 /// It is illegal to call this method on a defunct JITDylib and the client
1033 /// is responsible for ensuring that they do not do so.
1034 LLVM_ABI void
1035 replaceInLinkOrder(JITDylib &OldJD, JITDylib &NewJD,
1036 JITDylibLookupFlags JDLookupFlags =
1038
1039 /// Remove the given JITDylib from the link order for this JITDylib if it is
1040 /// present. Otherwise this operation is a no-op.
1041 ///
1042 /// It is illegal to call this method on a defunct JITDylib and the client
1043 /// is responsible for ensuring that they do not do so.
1045
1046 /// Do something with the link order (run under the session lock).
1047 ///
1048 /// It is illegal to call this method on a defunct JITDylib and the client
1049 /// is responsible for ensuring that they do not do so.
1050 template <typename Func>
1051 auto withLinkOrderDo(Func &&F)
1052 -> decltype(F(std::declval<const JITDylibSearchOrder &>()));
1053
1054 /// Define all symbols provided by the materialization unit to be part of this
1055 /// JITDylib.
1056 ///
1057 /// If RT is not specified then the default resource tracker will be used.
1058 ///
1059 /// This overload always takes ownership of the MaterializationUnit. If any
1060 /// errors occur, the MaterializationUnit consumed.
1061 ///
1062 /// It is illegal to call this method on a defunct JITDylib and the client
1063 /// is responsible for ensuring that they do not do so.
1064 template <typename MaterializationUnitType>
1065 Error define(std::unique_ptr<MaterializationUnitType> &&MU,
1066 ResourceTrackerSP RT = nullptr);
1067
1068 /// Define all symbols provided by the materialization unit to be part of this
1069 /// JITDylib.
1070 ///
1071 /// This overload only takes ownership of the MaterializationUnit no error is
1072 /// generated. If an error occurs, ownership remains with the caller. This
1073 /// may allow the caller to modify the MaterializationUnit to correct the
1074 /// issue, then re-call define.
1075 ///
1076 /// It is illegal to call this method on a defunct JITDylib and the client
1077 /// is responsible for ensuring that they do not do so.
1078 template <typename MaterializationUnitType>
1079 Error define(std::unique_ptr<MaterializationUnitType> &MU,
1080 ResourceTrackerSP RT = nullptr);
1081
1082 /// Tries to remove the given symbols.
1083 ///
1084 /// If any symbols are not defined in this JITDylib this method will return
1085 /// a SymbolsNotFound error covering the missing symbols.
1086 ///
1087 /// If all symbols are found but some symbols are in the process of being
1088 /// materialized this method will return a SymbolsCouldNotBeRemoved error.
1089 ///
1090 /// On success, all symbols are removed. On failure, the JITDylib state is
1091 /// left unmodified (no symbols are removed).
1092 ///
1093 /// It is illegal to call this method on a defunct JITDylib and the client
1094 /// is responsible for ensuring that they do not do so.
1095 LLVM_ABI Error remove(const SymbolNameSet &Names);
1096
1097 /// Returns the given JITDylibs and all of their transitive dependencies in
1098 /// DFS order (based on linkage relationships). Each JITDylib will appear
1099 /// only once.
1100 ///
1101 /// If any JITDylib in the order is defunct then this method will return an
1102 /// error, otherwise returns the order.
1105
1106 /// Returns the given JITDylibs and all of their transitive dependencies in
1107 /// reverse DFS order (based on linkage relationships). Each JITDylib will
1108 /// appear only once.
1109 ///
1110 /// If any JITDylib in the order is defunct then this method will return an
1111 /// error, otherwise returns the order.
1114
1115 /// Return this JITDylib and its transitive dependencies in DFS order
1116 /// based on linkage relationships.
1117 ///
1118 /// If any JITDylib in the order is defunct then this method will return an
1119 /// error, otherwise returns the order.
1121
1122 /// Rteurn this JITDylib and its transitive dependencies in reverse DFS order
1123 /// based on linkage relationships.
1124 ///
1125 /// If any JITDylib in the order is defunct then this method will return an
1126 /// error, otherwise returns the order.
1128
1129private:
1130 using AsynchronousSymbolQuerySet =
1131 std::set<std::shared_ptr<AsynchronousSymbolQuery>>;
1132
1133 using AsynchronousSymbolQueryList =
1134 std::vector<std::shared_ptr<AsynchronousSymbolQuery>>;
1135
1136 struct UnmaterializedInfo {
1137 UnmaterializedInfo(std::unique_ptr<MaterializationUnit> MU,
1138 ResourceTracker *RT)
1139 : MU(std::move(MU)), RT(RT) {}
1140
1141 std::unique_ptr<MaterializationUnit> MU;
1142 ResourceTracker *RT;
1143 };
1144
1145 using UnmaterializedInfosMap =
1146 DenseMap<SymbolStringPtr, std::shared_ptr<UnmaterializedInfo>>;
1147
1148 using UnmaterializedInfosList =
1149 std::vector<std::shared_ptr<UnmaterializedInfo>>;
1150
1151 // Information about not-yet-ready symbol.
1152 // * DefiningEDU will point to the EmissionDepUnit that defines the symbol.
1153 // * DependantEDUs will hold pointers to any EmissionDepUnits currently
1154 // waiting on this symbol.
1155 // * Pending queries holds any not-yet-completed queries that include this
1156 // symbol.
1157 struct MaterializingInfo {
1158 friend class ExecutionSession;
1159
1160 LLVM_ABI void addQuery(std::shared_ptr<AsynchronousSymbolQuery> Q);
1161 LLVM_ABI void removeQuery(const AsynchronousSymbolQuery &Q);
1162 LLVM_ABI AsynchronousSymbolQueryList
1163 takeQueriesMeeting(SymbolState RequiredState);
1164 AsynchronousSymbolQueryList takeAllPendingQueries() {
1165 return std::move(PendingQueries);
1166 }
1167 bool hasQueriesPending() const { return !PendingQueries.empty(); }
1168 const AsynchronousSymbolQueryList &pendingQueries() const {
1169 return PendingQueries;
1170 }
1171 private:
1172 AsynchronousSymbolQueryList PendingQueries;
1173 };
1174
1175 using MaterializingInfosMap = DenseMap<SymbolStringPtr, MaterializingInfo>;
1176
1177 class SymbolTableEntry {
1178 public:
1179 SymbolTableEntry() = default;
1180 SymbolTableEntry(JITSymbolFlags Flags)
1181 : Flags(Flags), State(static_cast<uint8_t>(SymbolState::NeverSearched)),
1182 MaterializerAttached(false) {}
1183
1184 ExecutorAddr getAddress() const { return Addr; }
1185 JITSymbolFlags getFlags() const { return Flags; }
1186 SymbolState getState() const { return static_cast<SymbolState>(State); }
1187
1188 bool hasMaterializerAttached() const { return MaterializerAttached; }
1189
1190 void setAddress(ExecutorAddr Addr) { this->Addr = Addr; }
1191 void setFlags(JITSymbolFlags Flags) { this->Flags = Flags; }
1192 void setState(SymbolState State) {
1193 assert(static_cast<uint8_t>(State) < (1 << 6) &&
1194 "State does not fit in bitfield");
1195 this->State = static_cast<uint8_t>(State);
1196 }
1197
1198 void setMaterializerAttached(bool MaterializerAttached) {
1199 this->MaterializerAttached = MaterializerAttached;
1200 }
1201
1202 ExecutorSymbolDef getSymbol() const { return {Addr, Flags}; }
1203
1204 private:
1205 ExecutorAddr Addr;
1206 JITSymbolFlags Flags;
1207 uint8_t State : 7;
1208 uint8_t MaterializerAttached : 1;
1209 };
1210
1211 using SymbolTable = DenseMap<SymbolStringPtr, SymbolTableEntry>;
1212
1213 JITDylib(ExecutionSession &ES, std::string Name);
1214
1215 struct RemoveTrackerResult {
1216 AsynchronousSymbolQuerySet QueriesToFail;
1217 std::shared_ptr<SymbolDependenceMap> FailedSymbols;
1218 std::vector<std::unique_ptr<MaterializationUnit>> DefunctMUs;
1219 };
1220
1221 RemoveTrackerResult IL_removeTracker(ResourceTracker &RT);
1222
1223 void transferTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1224
1225 LLVM_ABI Error defineImpl(MaterializationUnit &MU);
1226
1227 LLVM_ABI void
1228 installMaterializationUnit(std::unique_ptr<MaterializationUnit> MU,
1229 ResourceTracker &RT);
1230
1231 void detachQueryHelper(AsynchronousSymbolQuery &Q,
1232 const SymbolNameSet &QuerySymbols);
1233
1234 void transferEmittedNodeDependencies(MaterializingInfo &DependantMI,
1235 const SymbolStringPtr &DependantName,
1236 MaterializingInfo &EmittedMI);
1237
1238 Expected<SymbolFlagsMap>
1239 defineMaterializing(MaterializationResponsibility &FromMR,
1240 SymbolFlagsMap SymbolFlags);
1241
1242 Error replace(MaterializationResponsibility &FromMR,
1243 std::unique_ptr<MaterializationUnit> MU);
1244
1245 Expected<std::unique_ptr<MaterializationResponsibility>>
1246 delegate(MaterializationResponsibility &FromMR, SymbolFlagsMap SymbolFlags,
1247 SymbolStringPtr InitSymbol);
1248
1249 SymbolNameSet getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const;
1250
1251 void addDependencies(const SymbolStringPtr &Name,
1252 const SymbolDependenceMap &Dependants);
1253
1255
1256 void unlinkMaterializationResponsibility(MaterializationResponsibility &MR);
1257
1258 /// Attempt to reduce memory usage from empty \c UnmaterializedInfos and
1259 /// \c MaterializingInfos tables.
1260 void shrinkMaterializationInfoMemory();
1261
1262 ExecutionSession &ES;
1263 enum { Open, Closing, Closed } State = Open;
1264 std::mutex GeneratorsMutex;
1265 SymbolTable Symbols;
1266 UnmaterializedInfosMap UnmaterializedInfos;
1267 MaterializingInfosMap MaterializingInfos;
1268 std::vector<std::shared_ptr<DefinitionGenerator>> DefGenerators;
1269 JITDylibSearchOrder LinkOrder;
1270 ResourceTrackerSP DefaultTracker;
1271
1272 // Map trackers to sets of symbols tracked.
1273 DenseMap<ResourceTracker *, SymbolNameVector> TrackerSymbols;
1274 DenseMap<ResourceTracker *, DenseSet<MaterializationResponsibility *>>
1275 TrackerMRs;
1276};
1277
1278/// Platforms set up standard symbols and mediate interactions between dynamic
1279/// initializers (e.g. C++ static constructors) and ExecutionSession state.
1280/// Note that Platforms do not automatically run initializers: clients are still
1281/// responsible for doing this.
1283public:
1284 virtual ~Platform();
1285
1286 /// This method will be called outside the session lock each time a JITDylib
1287 /// is created (unless it is created with EmptyJITDylib set) to allow the
1288 /// Platform to install any JITDylib specific standard symbols (e.g
1289 /// __dso_handle).
1290 virtual Error setupJITDylib(JITDylib &JD) = 0;
1291
1292 /// This method will be called outside the session lock each time a JITDylib
1293 /// is removed to allow the Platform to remove any JITDylib-specific data.
1295
1296 /// This method will be called under the ExecutionSession lock each time a
1297 /// MaterializationUnit is added to a JITDylib.
1299 const MaterializationUnit &MU) = 0;
1300
1301 /// This method will be called under the ExecutionSession lock when a
1302 /// ResourceTracker is removed.
1304
1305 /// A utility function for looking up initializer symbols. Performs a blocking
1306 /// lookup for the given symbols in each of the given JITDylibs.
1307 ///
1308 /// Note: This function is deprecated and will be removed in the near future.
1312
1313 /// Performs an async lookup for the given symbols in each of the given
1314 /// JITDylibs, calling the given handler once all lookups have completed.
1315 static void
1317 ExecutionSession &ES,
1319};
1320
1321/// A materialization task.
1323 : public RTTIExtends<MaterializationTask, Task> {
1324public:
1325 static char ID;
1326
1327 MaterializationTask(std::unique_ptr<MaterializationUnit> MU,
1328 std::unique_ptr<MaterializationResponsibility> MR)
1329 : MU(std::move(MU)), MR(std::move(MR)) {}
1330 ~MaterializationTask() override;
1331 void printDescription(raw_ostream &OS) override;
1332 void run() override;
1333
1334private:
1335 std::unique_ptr<MaterializationUnit> MU;
1336 std::unique_ptr<MaterializationResponsibility> MR;
1337};
1338
1339/// Lookups are usually run on the current thread, but in some cases they may
1340/// be run as tasks, e.g. if the lookup has been continued from a suspended
1341/// state.
1342class LLVM_ABI LookupTask : public RTTIExtends<LookupTask, Task> {
1343public:
1344 static char ID;
1345
1346 LookupTask(LookupState LS) : LS(std::move(LS)) {}
1347 void printDescription(raw_ostream &OS) override;
1348 void run() override;
1349
1350private:
1351 LookupState LS;
1352};
1353
1354/// An ExecutionSession represents a running JIT program.
1358 friend class JITDylib;
1359 friend class LookupState;
1361 friend class ResourceTracker;
1362
1363public:
1364 /// For reporting errors.
1366
1367 /// Send a result to the remote.
1369
1370 /// An asynchronous wrapper-function callable from the executor via
1371 /// jit-dispatch.
1373 SendResultFunction SendResult,
1374 const char *ArgData, size_t ArgSize)>;
1375
1376 /// A map associating tag names with asynchronous wrapper function
1377 /// implementations in the JIT.
1380
1381 /// Construct an ExecutionSession with the given ExecutorProcessControl
1382 /// object.
1383 LLVM_ABI ExecutionSession(std::unique_ptr<ExecutorProcessControl> EPC);
1384
1385 /// Destroy an ExecutionSession. Verifies that endSession was called prior to
1386 /// destruction.
1388
1389 /// End the session. Closes all JITDylibs and disconnects from the
1390 /// executor. Clients must call this method before destroying the session.
1392
1393 /// Get the ExecutorProcessControl object associated with this
1394 /// ExecutionSession.
1396
1397 /// Return the triple for the executor.
1398 const Triple &getTargetTriple() const { return EPC->getTargetTriple(); }
1399
1400 // Return the page size for the executor.
1401 size_t getPageSize() const { return EPC->getPageSize(); }
1402
1403 /// Get the SymbolStringPool for this instance.
1404 std::shared_ptr<SymbolStringPool> getSymbolStringPool() {
1405 return EPC->getSymbolStringPool();
1406 }
1407
1408 /// Add a symbol name to the SymbolStringPool and return a pointer to it.
1409 SymbolStringPtr intern(StringRef SymName) { return EPC->intern(SymName); }
1410
1411 /// Set the Platform for this ExecutionSession.
1412 void setPlatform(std::unique_ptr<Platform> P) { this->P = std::move(P); }
1413
1414 /// Get the Platform for this session.
1415 /// Will return null if no Platform has been set for this ExecutionSession.
1416 Platform *getPlatform() { return P.get(); }
1417
1418 /// Run the given lambda with the session mutex locked.
1419 template <typename Func> decltype(auto) runSessionLocked(Func &&F) {
1420 std::lock_guard<std::recursive_mutex> Lock(SessionMutex);
1421 return F();
1422 }
1423
1424 /// Register the given ResourceManager with this ExecutionSession.
1425 /// Managers will be notified of events in reverse order of registration.
1427
1428 /// Deregister the given ResourceManager with this ExecutionSession.
1429 /// Manager must have been previously registered.
1431
1432 /// Return a pointer to the "name" JITDylib.
1433 /// Ownership of JITDylib remains within Execution Session
1435
1436 /// Add a new bare JITDylib to this ExecutionSession.
1437 ///
1438 /// The JITDylib Name is required to be unique. Clients should verify that
1439 /// names are not being re-used (E.g. by calling getJITDylibByName) if names
1440 /// are based on user input.
1441 ///
1442 /// This call does not install any library code or symbols into the newly
1443 /// created JITDylib. The client is responsible for all configuration.
1444 LLVM_ABI JITDylib &createBareJITDylib(std::string Name);
1445
1446 /// Add a new JITDylib to this ExecutionSession.
1447 ///
1448 /// The JITDylib Name is required to be unique. Clients should verify that
1449 /// names are not being re-used (e.g. by calling getJITDylibByName) if names
1450 /// are based on user input.
1451 ///
1452 /// If a Platform is attached then Platform::setupJITDylib will be called to
1453 /// install standard platform symbols (e.g. standard library interposes).
1454 /// If no Platform is attached this call is equivalent to createBareJITDylib.
1456
1457 /// Removes the given JITDylibs from the ExecutionSession.
1458 ///
1459 /// This method clears all resources held for the JITDylibs, puts them in the
1460 /// closed state, and clears all references to them that are held by the
1461 /// ExecutionSession or other JITDylibs. No further code can be added to the
1462 /// removed JITDylibs, and the JITDylib objects will be freed once any
1463 /// remaining JITDylibSPs pointing to them are destroyed.
1464 ///
1465 /// This method does *not* run static destructors for code contained in the
1466 /// JITDylibs, and each JITDylib can only be removed once.
1467 ///
1468 /// JITDylibs will be removed in the order given. Teardown is usually
1469 /// independent for each JITDylib, but not always. In particular, where the
1470 /// ORC runtime is used it is expected that teardown off all JITDylibs will
1471 /// depend on it, so the JITDylib containing the ORC runtime must be removed
1472 /// last. If the client has introduced any other dependencies they should be
1473 /// accounted for in the removal order too.
1474 LLVM_ABI Error removeJITDylibs(std::vector<JITDylibSP> JDsToRemove);
1475
1476 /// Calls removeJTIDylibs on the gives JITDylib.
1478 return removeJITDylibs(std::vector<JITDylibSP>({&JD}));
1479 }
1480
1481 /// Set the error reporter function.
1483 this->ReportError = std::move(ReportError);
1484 return *this;
1485 }
1486
1487 /// Report a error for this execution session.
1488 ///
1489 /// Unhandled errors can be sent here to log them.
1490 void reportError(Error Err) { ReportError(std::move(Err)); }
1491
1492 /// Search the given JITDylibs to find the flags associated with each of the
1493 /// given symbols.
1494 LLVM_ABI void
1496 SymbolLookupSet Symbols,
1497 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1498
1499 /// Blocking version of lookupFlags.
1501 JITDylibSearchOrder SearchOrder,
1502 SymbolLookupSet Symbols);
1503
1504 /// Search the given JITDylibs for the given symbols.
1505 ///
1506 /// SearchOrder lists the JITDylibs to search. For each dylib, the associated
1507 /// boolean indicates whether the search should match against non-exported
1508 /// (hidden visibility) symbols in that dylib (true means match against
1509 /// non-exported symbols, false means do not match).
1510 ///
1511 /// The NotifyComplete callback will be called once all requested symbols
1512 /// reach the required state.
1513 ///
1514 /// If all symbols are found, the RegisterDependencies function will be called
1515 /// while the session lock is held. This gives clients a chance to register
1516 /// dependencies for on the queried symbols for any symbols they are
1517 /// materializing (if a MaterializationResponsibility instance is present,
1518 /// this can be implemented by calling
1519 /// MaterializationResponsibility::addDependencies). If there are no
1520 /// dependenant symbols for this query (e.g. it is being made by a top level
1521 /// client to get an address to call) then the value NoDependenciesToRegister
1522 /// can be used.
1523 LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder,
1524 SymbolLookupSet Symbols, SymbolState RequiredState,
1525 SymbolsResolvedCallback NotifyComplete,
1526 RegisterDependenciesFunction RegisterDependencies);
1527
1528 /// Blocking version of lookup above. Returns the resolved symbol map.
1529 /// If WaitUntilReady is true (the default), will not return until all
1530 /// requested symbols are ready (or an error occurs). If WaitUntilReady is
1531 /// false, will return as soon as all requested symbols are resolved,
1532 /// or an error occurs. If WaitUntilReady is false and an error occurs
1533 /// after resolution, the function will return a success value, but the
1534 /// error will be reported via reportErrors.
1536 lookup(const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols,
1538 SymbolState RequiredState = SymbolState::Ready,
1539 RegisterDependenciesFunction RegisterDependencies =
1541
1542 /// Convenience version of blocking lookup.
1543 /// Searches each of the JITDylibs in the search order in turn for the given
1544 /// symbol.
1546 lookup(const JITDylibSearchOrder &SearchOrder, SymbolStringPtr Symbol,
1547 SymbolState RequiredState = SymbolState::Ready);
1548
1549 /// Convenience version of blocking lookup.
1550 /// Searches each of the JITDylibs in the search order in turn for the given
1551 /// symbol. The search will not find non-exported symbols.
1553 lookup(ArrayRef<JITDylib *> SearchOrder, SymbolStringPtr Symbol,
1554 SymbolState RequiredState = SymbolState::Ready);
1555
1556 /// Convenience version of blocking lookup.
1557 /// Searches each of the JITDylibs in the search order in turn for the given
1558 /// symbol. The search will not find non-exported symbols.
1560 lookup(ArrayRef<JITDylib *> SearchOrder, StringRef Symbol,
1561 SymbolState RequiredState = SymbolState::Ready);
1562
1563 /// Materialize the given unit.
1564 void dispatchTask(std::unique_ptr<Task> T) {
1565 assert(T && "T must be non-null");
1566 DEBUG_WITH_TYPE("orc", dumpDispatchInfo(*T));
1567 EPC->getDispatcher().dispatch(std::move(T));
1568 }
1569
1570 /// Returns the bootstrap map.
1572 return EPC->getBootstrapMap();
1573 }
1574
1575 /// Look up and SPS-deserialize a bootstrap map value.
1576 template <typename T, typename SPSTagT>
1577 Error getBootstrapMapValue(StringRef Key, std::optional<T> &Val) const {
1578 return EPC->getBootstrapMapValue<T, SPSTagT>(Key, Val);
1579 }
1580
1581 /// Returns the bootstrap symbol map.
1583 return EPC->getBootstrapSymbolsMap();
1584 }
1585
1586 /// For each (ExecutorAddr&, StringRef) pair, looks up the string in the
1587 /// bootstrap symbols map and writes its address to the ExecutorAddr if
1588 /// found. If any symbol is not found then the function returns an error.
1590 ArrayRef<std::pair<ExecutorAddr &, StringRef>> Pairs) const {
1591 return EPC->getBootstrapSymbols(Pairs);
1592 }
1593
1594 /// Run a wrapper function in the executor. The given WFRHandler will be
1595 /// called on the result when it is returned.
1596 ///
1597 /// The wrapper function should be callable as:
1598 ///
1599 /// \code{.cpp}
1600 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1601 /// \endcode{.cpp}
1602 void callWrapperAsync(ExecutorAddr WrapperFnAddr,
1604 ArrayRef<char> ArgBuffer) {
1605 EPC->callWrapperAsync(WrapperFnAddr, std::move(OnComplete), ArgBuffer);
1606 }
1607
1608 /// Run a wrapper function in the executor using the given Runner to dispatch
1609 /// OnComplete when the result is ready.
1610 template <typename RunPolicyT, typename FnT>
1611 void callWrapperAsync(RunPolicyT &&Runner, ExecutorAddr WrapperFnAddr,
1612 FnT &&OnComplete, ArrayRef<char> ArgBuffer) {
1613 EPC->callWrapperAsync(std::forward<RunPolicyT>(Runner), WrapperFnAddr,
1614 std::forward<FnT>(OnComplete), ArgBuffer);
1615 }
1616
1617 /// Run a wrapper function in the executor. OnComplete will be dispatched
1618 /// as a GenericNamedTask using this instance's TaskDispatch object.
1619 template <typename FnT>
1620 void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete,
1621 ArrayRef<char> ArgBuffer) {
1622 EPC->callWrapperAsync(WrapperFnAddr, std::forward<FnT>(OnComplete),
1623 ArgBuffer);
1624 }
1625
1626 /// Run a wrapper function in the executor. The wrapper function should be
1627 /// callable as:
1628 ///
1629 /// \code{.cpp}
1630 /// CWrapperFunctionBuffer fn(uint8_t *Data, uint64_t Size);
1631 /// \endcode{.cpp}
1633 ArrayRef<char> ArgBuffer) {
1634 return EPC->callWrapper(WrapperFnAddr, ArgBuffer);
1635 }
1636
1637 /// Run a wrapper function using SPS to serialize the arguments and
1638 /// deserialize the results.
1639 template <typename SPSSignature, typename SendResultT, typename... ArgTs>
1640 void callSPSWrapperAsync(ExecutorAddr WrapperFnAddr, SendResultT &&SendResult,
1641 const ArgTs &...Args) {
1642 EPC->callSPSWrapperAsync<SPSSignature, SendResultT, ArgTs...>(
1643 WrapperFnAddr, std::forward<SendResultT>(SendResult), Args...);
1644 }
1645
1646 /// Run a wrapper function using SPS to serialize the arguments and
1647 /// deserialize the results.
1648 ///
1649 /// If SPSSignature is a non-void function signature then the second argument
1650 /// (the first in the Args list) should be a reference to a return value.
1651 template <typename SPSSignature, typename... WrapperCallArgTs>
1653 WrapperCallArgTs &&...WrapperCallArgs) {
1654 return EPC->callSPSWrapper<SPSSignature, WrapperCallArgTs...>(
1655 WrapperFnAddr, std::forward<WrapperCallArgTs>(WrapperCallArgs)...);
1656 }
1657
1658 /// Wrap a handler that takes concrete argument types (and a sender for a
1659 /// concrete return type) to produce an AsyncHandlerWrapperFunction. Uses SPS
1660 /// to unpack the arguments and pack the result.
1661 ///
1662 /// This function is intended to support easy construction of
1663 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1664 /// (using registerJITDispatchHandler) and called from the executor.
1665 template <typename SPSSignature, typename HandlerT>
1667 return [H = std::forward<HandlerT>(H)](SendResultFunction SendResult,
1668 const char *ArgData,
1669 size_t ArgSize) mutable {
1671 ArgData, ArgSize, std::move(SendResult), H);
1672 };
1673 }
1674
1675 /// Wrap a class method that takes concrete argument types (and a sender for
1676 /// a concrete return type) to produce an AsyncHandlerWrapperFunction. Uses
1677 /// SPS to unpack the arguments and pack the result.
1678 ///
1679 /// This function is intended to support easy construction of
1680 /// AsyncHandlerWrapperFunctions that can be associated with a tag
1681 /// (using registerJITDispatchHandler) and called from the executor.
1682 template <typename SPSSignature, typename ClassT, typename... MethodArgTs>
1684 wrapAsyncWithSPS(ClassT *Instance, void (ClassT::*Method)(MethodArgTs...)) {
1686 [Instance, Method](MethodArgTs &&...MethodArgs) {
1687 (Instance->*Method)(std::forward<MethodArgTs>(MethodArgs)...);
1688 });
1689 }
1690
1691 /// For each tag symbol name, associate the corresponding
1692 /// AsyncHandlerWrapperFunction with the address of that symbol. The
1693 /// handler becomes callable from the executor using the ORC runtime
1694 /// __orc_rt_jit_dispatch function and the given tag.
1695 ///
1696 /// Tag symbols will be looked up in JD using LookupKind::Static,
1697 /// JITDylibLookupFlags::MatchAllSymbols (hidden tags will be found), and
1698 /// LookupFlags::WeaklyReferencedSymbol. Missing tag definitions will not
1699 /// cause an error, the handler will simply be dropped.
1702
1703 /// Run a registered jit-side wrapper function.
1704 /// This should be called by the ExecutorProcessControl instance in response
1705 /// to incoming jit-dispatch requests from the executor.
1707 ExecutorAddr HandlerFnTagAddr,
1709
1710 /// Dump the state of all the JITDylibs in this session.
1711 LLVM_ABI void dump(raw_ostream &OS);
1712
1713 /// Check the internal consistency of ExecutionSession data structures.
1714#ifdef EXPENSIVE_CHECKS
1715 bool verifySessionState(Twine Phase);
1716#endif
1717
1718private:
1719 static void logErrorsToStdErr(Error Err) {
1720 logAllUnhandledErrors(std::move(Err), errs(), "JIT session error: ");
1721 }
1722
1723 void dispatchOutstandingMUs();
1724
1725 static std::unique_ptr<MaterializationResponsibility>
1726 createMaterializationResponsibility(ResourceTracker &RT,
1727 SymbolFlagsMap Symbols,
1728 SymbolStringPtr InitSymbol) {
1729 auto &JD = RT.getJITDylib();
1730 std::unique_ptr<MaterializationResponsibility> MR(
1731 new MaterializationResponsibility(&RT, std::move(Symbols),
1732 std::move(InitSymbol)));
1733 JD.TrackerMRs[&RT].insert(MR.get());
1734 return MR;
1735 }
1736
1737 Error removeResourceTracker(ResourceTracker &RT);
1738 void transferResourceTracker(ResourceTracker &DstRT, ResourceTracker &SrcRT);
1739 void destroyResourceTracker(ResourceTracker &RT);
1740
1741 // State machine functions for query application..
1742
1743 /// IL_updateCandidatesFor is called to remove already-defined symbols that
1744 /// match a given query from the set of candidate symbols to generate
1745 /// definitions for (no need to generate a definition if one already exists).
1746 Error IL_updateCandidatesFor(JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
1747 SymbolLookupSet &Candidates,
1748 SymbolLookupSet *NonCandidates);
1749
1750 /// Handle resumption of a lookup after entering a generator.
1751 void OL_resumeLookupAfterGeneration(InProgressLookupState &IPLS);
1752
1753 /// OL_applyQueryPhase1 is an optionally re-startable loop for triggering
1754 /// definition generation. It is called when a lookup is performed, and again
1755 /// each time that LookupState::continueLookup is called.
1756 void OL_applyQueryPhase1(std::unique_ptr<InProgressLookupState> IPLS,
1757 Error Err);
1758
1759 /// OL_completeLookup is run once phase 1 successfully completes for a lookup
1760 /// call. It attempts to attach the symbol to all symbol table entries and
1761 /// collect all MaterializationUnits to dispatch. If this method fails then
1762 /// all MaterializationUnits will be left un-materialized.
1763 void OL_completeLookup(std::unique_ptr<InProgressLookupState> IPLS,
1764 std::shared_ptr<AsynchronousSymbolQuery> Q,
1765 RegisterDependenciesFunction RegisterDependencies);
1766
1767 /// OL_completeLookupFlags is run once phase 1 successfully completes for a
1768 /// lookupFlags call.
1769 void OL_completeLookupFlags(
1770 std::unique_ptr<InProgressLookupState> IPLS,
1771 unique_function<void(Expected<SymbolFlagsMap>)> OnComplete);
1772
1773 // State machine functions for MaterializationResponsibility.
1774 LLVM_ABI void
1775 OL_destroyMaterializationResponsibility(MaterializationResponsibility &MR);
1777 OL_getRequestedSymbols(const MaterializationResponsibility &MR);
1778 LLVM_ABI Error OL_notifyResolved(MaterializationResponsibility &MR,
1779 const SymbolMap &Symbols);
1780
1781 // FIXME: We should be able to derive FailedSymsForQuery from each query once
1782 // we fix how the detach operation works.
1783 struct EmitQueries {
1784 JITDylib::AsynchronousSymbolQuerySet Completed;
1785 JITDylib::AsynchronousSymbolQuerySet Failed;
1786 DenseMap<AsynchronousSymbolQuery *, std::shared_ptr<SymbolDependenceMap>>
1787 FailedSymsForQuery;
1788 };
1789
1791 IL_getSymbolState(JITDylib *JD, NonOwningSymbolStringPtr Name);
1792
1793 template <typename UpdateSymbolFn, typename UpdateQueryFn>
1794 void IL_collectQueries(JITDylib::AsynchronousSymbolQuerySet &Qs,
1795 WaitingOnGraph::ContainerElementsMap &QualifiedSymbols,
1796 UpdateSymbolFn &&UpdateSymbol,
1797 UpdateQueryFn &&UpdateQuery);
1798
1799 Expected<EmitQueries> IL_emit(MaterializationResponsibility &MR,
1800 WaitingOnGraph::SimplifyResult SR);
1801 LLVM_ABI Error OL_notifyEmitted(MaterializationResponsibility &MR,
1803
1804 LLVM_ABI Error OL_defineMaterializing(MaterializationResponsibility &MR,
1805 SymbolFlagsMap SymbolFlags);
1806
1807 std::pair<JITDylib::AsynchronousSymbolQuerySet,
1808 std::shared_ptr<SymbolDependenceMap>>
1809 IL_failSymbols(JITDylib &JD, const SymbolNameVector &SymbolsToFail);
1810 LLVM_ABI void OL_notifyFailed(MaterializationResponsibility &MR);
1812 std::unique_ptr<MaterializationUnit> MU);
1813 LLVM_ABI Expected<std::unique_ptr<MaterializationResponsibility>>
1814 OL_delegate(MaterializationResponsibility &MR, const SymbolNameSet &Symbols);
1815
1816#ifndef NDEBUG
1817 void dumpDispatchInfo(Task &T);
1818#endif // NDEBUG
1819
1820 mutable std::recursive_mutex SessionMutex;
1821 bool SessionOpen = true;
1822 std::unique_ptr<ExecutorProcessControl> EPC;
1823 std::unique_ptr<Platform> P;
1824 ErrorReporter ReportError = logErrorsToStdErr;
1825
1826 std::vector<ResourceManager *> ResourceManagers;
1827
1828 std::vector<JITDylibSP> JDs;
1830
1831 // FIXME: Remove this (and runOutstandingMUs) once the linking layer works
1832 // with callbacks from asynchronous queries.
1833 mutable std::recursive_mutex OutstandingMUsMutex;
1834 std::vector<std::pair<std::unique_ptr<MaterializationUnit>,
1835 std::unique_ptr<MaterializationResponsibility>>>
1836 OutstandingMUs;
1837
1838 mutable std::mutex JITDispatchHandlersMutex;
1839 DenseMap<ExecutorAddr, std::shared_ptr<JITDispatchHandlerFunction>>
1840 JITDispatchHandlers;
1841};
1842
1844 return JD->getExecutionSession().lookup({JD.get()}, Name);
1845}
1846
1847template <typename Func> Error ResourceTracker::withResourceKeyDo(Func &&F) {
1849 if (isDefunct())
1851 F(getKeyUnsafe());
1852 return Error::success();
1853 });
1854}
1855
1856inline ExecutionSession &
1858 return JD.getExecutionSession();
1859}
1860
1861template <typename GeneratorT>
1862GeneratorT &JITDylib::addGenerator(std::unique_ptr<GeneratorT> DefGenerator) {
1863 auto &G = *DefGenerator;
1864 ES.runSessionLocked([&] {
1865 assert(State == Open && "Cannot add generator to closed JITDylib");
1866 DefGenerators.push_back(std::move(DefGenerator));
1867 });
1868 return G;
1869}
1870
1871template <typename Func>
1873 -> decltype(F(std::declval<const JITDylibSearchOrder &>())) {
1874 assert(State == Open && "Cannot use link order of closed JITDylib");
1875 return ES.runSessionLocked([&]() { return F(LinkOrder); });
1876}
1877
1878template <typename MaterializationUnitType>
1879Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &&MU,
1880 ResourceTrackerSP RT) {
1881 assert(MU && "Can not define with a null MU");
1882
1883 if (MU->getSymbols().empty()) {
1884 // Empty MUs are allowable but pathological, so issue a warning.
1885 DEBUG_WITH_TYPE("orc", {
1886 dbgs() << "Warning: Discarding empty MU " << MU->getName() << " for "
1887 << getName() << "\n";
1888 });
1889 return Error::success();
1890 } else
1891 DEBUG_WITH_TYPE("orc", {
1892 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1893 << " (tracker: ";
1894 if (RT == getDefaultResourceTracker())
1895 dbgs() << "default)";
1896 else if (RT)
1897 dbgs() << RT.get() << ")\n";
1898 else
1899 dbgs() << "0x0, default will be used)\n";
1900 });
1901
1902 return ES.runSessionLocked([&, this]() -> Error {
1903 if (State != Open)
1904 return make_error<JITDylibDefunct>(this);
1905
1906 if (auto Err = defineImpl(*MU))
1907 return Err;
1908
1909 if (!RT)
1911
1912 if (auto *P = ES.getPlatform()) {
1913 if (auto Err = P->notifyAdding(*RT, *MU))
1914 return Err;
1915 }
1916
1917 installMaterializationUnit(std::move(MU), *RT);
1918 return Error::success();
1919 });
1920}
1921
1922template <typename MaterializationUnitType>
1923Error JITDylib::define(std::unique_ptr<MaterializationUnitType> &MU,
1924 ResourceTrackerSP RT) {
1925 assert(MU && "Can not define with a null MU");
1926
1927 if (MU->getSymbols().empty()) {
1928 // Empty MUs are allowable but pathological, so issue a warning.
1929 DEBUG_WITH_TYPE("orc", {
1930 dbgs() << "Warning: Discarding empty MU " << MU->getName() << getName()
1931 << "\n";
1932 });
1933 return Error::success();
1934 } else
1935 DEBUG_WITH_TYPE("orc", {
1936 dbgs() << "Defining MU " << MU->getName() << " for " << getName()
1937 << " (tracker: ";
1938 if (RT == getDefaultResourceTracker())
1939 dbgs() << "default)";
1940 else if (RT)
1941 dbgs() << RT.get() << ")\n";
1942 else
1943 dbgs() << "0x0, default will be used)\n";
1944 });
1945
1946 return ES.runSessionLocked([&, this]() -> Error {
1947 assert(State == Open && "JD is defunct");
1948
1949 if (auto Err = defineImpl(*MU))
1950 return Err;
1951
1952 if (!RT)
1954
1955 if (auto *P = ES.getPlatform()) {
1956 if (auto Err = P->notifyAdding(*RT, *MU))
1957 return Err;
1958 }
1959
1960 installMaterializationUnit(std::move(MU), *RT);
1961 return Error::success();
1962 });
1963}
1964
1965/// ReexportsGenerator can be used with JITDylib::addGenerator to automatically
1966/// re-export a subset of the source JITDylib's symbols in the target.
1968public:
1969 using SymbolPredicate = std::function<bool(SymbolStringPtr)>;
1970
1971 /// Create a reexports generator. If an Allow predicate is passed, only
1972 /// symbols for which the predicate returns true will be reexported. If no
1973 /// Allow predicate is passed, all symbols will be exported.
1974 ReexportsGenerator(JITDylib &SourceJD,
1975 JITDylibLookupFlags SourceJDLookupFlags,
1977
1979 JITDylibLookupFlags JDLookupFlags,
1980 const SymbolLookupSet &LookupSet) override;
1981
1982private:
1983 JITDylib &SourceJD;
1984 JITDylibLookupFlags SourceJDLookupFlags;
1985 SymbolPredicate Allow;
1986};
1987
1988// --------------- IMPLEMENTATION --------------
1989// Implementations for inline functions/methods.
1990// ---------------------------------------------
1991
1993 getExecutionSession().OL_destroyMaterializationResponsibility(*this);
1994}
1995
1997 return getExecutionSession().OL_getRequestedSymbols(*this);
1998}
1999
2001 const SymbolMap &Symbols) {
2002 return getExecutionSession().OL_notifyResolved(*this, Symbols);
2003}
2004
2006 ArrayRef<SymbolDependenceGroup> EmittedDeps) {
2007 return getExecutionSession().OL_notifyEmitted(*this, EmittedDeps);
2008}
2009
2011 SymbolFlagsMap SymbolFlags) {
2012 return getExecutionSession().OL_defineMaterializing(*this,
2013 std::move(SymbolFlags));
2014}
2015
2017 getExecutionSession().OL_notifyFailed(*this);
2018}
2019
2021 std::unique_ptr<MaterializationUnit> MU) {
2022 return getExecutionSession().OL_replace(*this, std::move(MU));
2023}
2024
2027 return getExecutionSession().OL_delegate(*this, Symbols);
2028}
2029
2030} // End namespace orc
2031} // End namespace llvm
2032
2033#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:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define H(x, y, z)
Definition MD5.cpp:56
#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:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
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:802
LLVM_ABI AsynchronousSymbolQuery(const SymbolLookupSet &Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete)
Create a query for the given symbols.
Definition Core.cpp:211
bool isComplete() const
Returns true if all symbols covered by this query have been resolved.
Definition Core.h:823
friend class InProgressFullLookupState
Definition Core.h:804
LLVM_ABI void notifySymbolMetRequiredState(const SymbolStringPtr &Name, ExecutorSymbolDef Sym)
Notify the query that a requested symbol has reached the required state.
Definition Core.cpp:225
friend class JITSymbolResolverAdapter
Definition Core.h:806
friend class MaterializationResponsibility
Definition Core.h:807
Definition generators can be attached to JITDylibs to generate new definitions for otherwise unresolv...
Definition Core.h:876
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:877
An ExecutionSession represents a running JIT program.
Definition Core.h:1355
LLVM_ABI void runJITDispatchHandler(SendResultFunction SendResult, ExecutorAddr HandlerFnTagAddr, shared::WrapperFunctionBuffer ArgBytes)
Run a registered jit-side wrapper function.
Definition Core.cpp:1910
LLVM_ABI Error endSession()
End the session.
Definition Core.cpp:1590
ExecutorProcessControl & getExecutorProcessControl()
Get the ExecutorProcessControl object associated with this ExecutionSession.
Definition Core.h:1395
shared::WrapperFunctionBuffer callWrapper(ExecutorAddr WrapperFnAddr, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1632
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1490
void callWrapperAsync(ExecutorAddr WrapperFnAddr, ExecutorProcessControl::IncomingWFRHandler OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1602
friend class JITDylib
Definition Core.h:1358
friend class InProgressLookupFlagsState
Definition Core.h:1356
const StringMap< ExecutorAddr > & getBootstrapSymbolsMap() const
Returns the bootstrap symbol map.
Definition Core.h:1582
void setPlatform(std::unique_ptr< Platform > P)
Set the Platform for this ExecutionSession.
Definition Core.h:1412
const Triple & getTargetTriple() const
Return the triple for the executor.
Definition Core.h:1398
Platform * getPlatform()
Get the Platform for this session.
Definition Core.h:1416
Error callSPSWrapper(ExecutorAddr WrapperFnAddr, WrapperCallArgTs &&...WrapperCallArgs)
Run a wrapper function using SPS to serialize the arguments and deserialize the results.
Definition Core.h:1652
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:1750
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1409
LLVM_ABI JITDylib * getJITDylibByName(StringRef Name)
Return a pointer to the "name" JITDylib.
Definition Core.cpp:1629
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:1684
friend class LookupState
Definition Core.h:1359
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:1611
LLVM_ABI JITDylib & createBareJITDylib(std::string Name)
Add a new bare JITDylib to this ExecutionSession.
Definition Core.cpp:1638
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:1666
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:1640
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition Core.h:1404
Error getBootstrapMapValue(StringRef Key, std::optional< T > &Val) const
Look up and SPS-deserialize a bootstrap map value.
Definition Core.h:1577
friend class InProgressFullLookupState
Definition Core.h:1357
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:1589
const StringMap< std::vector< char > > & getBootstrapMap() const
Returns the bootstrap map.
Definition Core.h:1571
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:1776
LLVM_ABI Error registerJITDispatchHandlers(JITDylib &JD, JITDispatchHandlerAssociationMap WFs)
For each tag symbol name, associate the corresponding AsyncHandlerWrapperFunction with the address of...
Definition Core.cpp:1871
friend class MaterializationResponsibility
Definition Core.h:1360
LLVM_ABI void registerResourceManager(ResourceManager &RM)
Register the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1612
LLVM_ABI ~ExecutionSession()
Destroy an ExecutionSession.
Definition Core.cpp:1584
LLVM_ABI void deregisterResourceManager(ResourceManager &RM)
Deregister the given ResourceManager with this ExecutionSession.
Definition Core.cpp:1616
LLVM_ABI ExecutionSession(std::unique_ptr< ExecutorProcessControl > EPC)
Construct an ExecutionSession with the given ExecutorProcessControl object.
Definition Core.cpp:1578
decltype(auto) runSessionLocked(Func &&F)
Run the given lambda with the session mutex locked.
Definition Core.h:1419
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:1372
LLVM_ABI void dump(raw_ostream &OS)
Dump the state of all the JITDylibs in this session.
Definition Core.cpp:1931
unique_function< void(shared::WrapperFunctionBuffer)> SendResultFunction
Send a result to the remote.
Definition Core.h:1368
friend class ResourceTracker
Definition Core.h:1361
ExecutionSession & setErrorReporter(ErrorReporter ReportError)
Set the error reporter function.
Definition Core.h:1482
LLVM_ABI Error removeJITDylibs(std::vector< JITDylibSP > JDsToRemove)
Removes the given JITDylibs from the ExecutionSession.
Definition Core.cpp:1655
size_t getPageSize() const
Definition Core.h:1401
LLVM_ABI Expected< JITDylib & > createJITDylib(std::string Name)
Add a new JITDylib to this ExecutionSession.
Definition Core.cpp:1647
void dispatchTask(std::unique_ptr< Task > T)
Materialize the given unit.
Definition Core.h:1564
unique_function< void(Error)> ErrorReporter
For reporting errors.
Definition Core.h:1365
Error removeJITDylib(JITDylib &JD)
Calls removeJTIDylibs on the gives JITDylib.
Definition Core.h:1477
void callWrapperAsync(ExecutorAddr WrapperFnAddr, FnT &&OnComplete, ArrayRef< char > ArgBuffer)
Run a wrapper function in the executor.
Definition Core.h:1620
DenseMap< SymbolStringPtr, JITDispatchHandlerFunction > JITDispatchHandlerAssociationMap
A map associating tag names with asynchronous wrapper function implementations in the JIT.
Definition Core.h:1378
Represents an address in the executor process.
A handler or incoming WrapperFunctionBuffers – either return values from callWrapper* calls,...
ExecutorProcessControl supports interaction with a JIT target process.
Represents a defining location for a JIT symbol.
FailedToMaterialize(std::shared_ptr< SymbolStringPool > SSP, std::shared_ptr< SymbolDependenceMap > Symbols)
Definition Core.cpp:92
const SymbolDependenceMap & getSymbols() const
Definition Core.h:467
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:110
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:114
JITDylibDefunct(JITDylibSP JD)
Definition Core.h:448
Represents a JIT'd dynamic library.
Definition Core.h:919
LLVM_ABI ~JITDylib()
Definition Core.cpp:662
LLVM_ABI Error remove(const SymbolNameSet &Names)
Tries to remove the given symbols.
Definition Core.cpp:1064
LLVM_ABI Error clear()
Calls remove on all trackers currently associated with this JITDylib.
Definition Core.cpp:666
JITDylib & operator=(JITDylib &&)=delete
LLVM_ABI void dump(raw_ostream &OS)
Dump current JITDylib state to OS.
Definition Core.cpp:1125
friend class AsynchronousSymbolQuery
Definition Core.h:920
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:1040
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:1879
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition Core.h:938
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:1024
LLVM_ABI ResourceTrackerSP createResourceTracker()
Create a resource tracker for this JITDylib.
Definition Core.cpp:690
auto withLinkOrderDo(Func &&F) -> decltype(F(std::declval< const JITDylibSearchOrder & >()))
Do something with the link order (run under the session lock).
Definition Core.h:1872
friend class MaterializationResponsibility
Definition Core.h:923
friend class Platform
Definition Core.h:922
LLVM_ABI void removeFromLinkOrder(JITDylib &JD)
Remove the given JITDylib from the link order for this JITDylib if it is present.
Definition Core.cpp:1052
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:1009
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:1746
friend class ExecutionSession
Definition Core.h:921
LLVM_ABI ResourceTrackerSP getDefaultResourceTracker()
Get the default resource tracker for this JITDylib.
Definition Core.cpp:681
GeneratorT & addGenerator(std::unique_ptr< GeneratorT > DefGenerator)
Adds a definition generator to this JITDylib and returns a referenece to it.
Definition Core.h:1862
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:698
LLVM_ABI Expected< std::vector< JITDylibSP > > getDFSLinkOrder()
Return this JITDylib and its transitive dependencies in DFS order based on linkage relationships.
Definition Core.cpp:1742
Wraps state for a lookup-in-progress.
Definition Core.h:851
LLVM_ABI void continueLookup(Error Err)
Continue the lookup.
Definition Core.cpp:642
LLVM_ABI LookupState & operator=(LookupState &&)
friend class ExecutionSession
Definition Core.h:853
friend class OrcV2CAPIHelper
Definition Core.h:852
LLVM_ABI LookupState(LookupState &&)
LookupTask(LookupState LS)
Definition Core.h:1346
static char ID
Definition Core.h:1344
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:593
MaterializationResponsibility & operator=(MaterializationResponsibility &&)=delete
ExecutionSession & getExecutionSession() const
Returns the ExecutionSession for this instance.
Definition Core.h:1857
Error notifyResolved(const SymbolMap &Symbols)
Notifies the target JITDylib that the given symbols have been resolved.
Definition Core.h:2000
~MaterializationResponsibility()
Destruct a MaterializationResponsibility instance.
Definition Core.h:1992
Error replace(std::unique_ptr< MaterializationUnit > MU)
Transfers responsibility to the given MaterializationUnit for all symbols defined by that Materializa...
Definition Core.h:2020
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition Core.h:612
Error defineMaterializing(SymbolFlagsMap SymbolFlags)
Attempt to claim responsibility for new definitions.
Definition Core.h:2010
SymbolNameSet getRequestedSymbols() const
Returns the names of any symbols covered by this MaterializationResponsibility object that have queri...
Definition Core.h:1996
Expected< std::unique_ptr< MaterializationResponsibility > > delegate(const SymbolNameSet &Symbols)
Delegates responsibility for the given symbols to the returned materialization responsibility.
Definition Core.h:2026
const ResourceTrackerSP & getResourceTracker() const
Return the ResourceTracker associated with this instance.
Definition Core.h:608
const SymbolStringPtr & getInitializerSymbol() const
Returns the initialization pseudo-symbol, if any.
Definition Core.h:632
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:2005
void failMaterialization()
Notify all not-yet-emitted covered by this MaterializationResponsibility instance that an error has o...
Definition Core.h:2016
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:618
const SymbolFlagsMap & getSymbols() const
Returns the symbol flags map for this responsibility instance.
Definition Core.h:627
A materialization task.
Definition Core.h:1323
MaterializationTask(std::unique_ptr< MaterializationUnit > MU, std::unique_ptr< MaterializationResponsibility > MR)
Definition Core.h:1327
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group,...
const SymbolNameVector & getSymbols() const
Definition Core.h:548
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:546
MissingSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:540
const std::string & getModuleName() const
Definition Core.h:547
Platforms set up standard symbols and mediate interactions between dynamic initializers (e....
Definition Core.h:1282
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:1514
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:1465
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:310
std::function< bool(SymbolStringPtr)> SymbolPredicate
Definition Core.h:1969
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:607
ReexportsGenerator(JITDylib &SourceJD, JITDylibLookupFlags SourceJDLookupFlags, SymbolPredicate Allow=SymbolPredicate())
Create a reexports generator.
Definition Core.cpp:601
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:72
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:79
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:75
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:60
ResourceTracker & operator=(ResourceTracker &&)=delete
LLVM_ABI ~ResourceTracker()
Definition Core.cpp:51
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:1847
friend class ExecutionSession
Definition Core.h:84
LLVM_ABI Error remove()
Remove all resources associated with this key.
Definition Core.cpp:56
Expected< ExecutorSymbolDef > lookup() const
Definition Core.h:1843
SymbolInstance(JITDylibSP JD, SymbolStringPtr Name)
Definition Core.h:65
LLVM_ABI void lookupAsync(LookupAsyncOnCompleteFn OnComplete) const
Definition Core.cpp:190
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:164
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:168
const SymbolNameSet & getSymbols() const
Definition Core.h:524
SymbolsCouldNotBeRemoved(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:158
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:523
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:154
SymbolsNotFound(std::shared_ptr< SymbolStringPool > SSP, SymbolNameSet Symbols)
Definition Core.cpp:137
const SymbolNameVector & getSymbols() const
Definition Core.h:506
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:150
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:505
UnexpectedSymbolDefinitions(std::shared_ptr< SymbolStringPool > SSP, std::string ModuleName, SymbolNameVector Symbols)
Definition Core.h:564
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Definition Core.h:570
const std::string & getModuleName() const
Definition Core.h:571
const SymbolNameVector & getSymbols() const
Definition Core.h:572
void log(raw_ostream &OS) const override
Print an error message to an output stream.
Definition Core.cpp:130
std::error_code convertToErrorCode() const override
Convert this error to a std::error_code.
Definition Core.cpp:126
UnsatisfiedSymbolDependencies(std::shared_ptr< SymbolStringPool > SSP, JITDylibSP JD, SymbolNameSet FailedSymbols, SymbolDependenceMap BadDeps, std::string Explanation)
Definition Core.cpp:118
WaitingOnGraph class template.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h: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:767
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:776
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:39
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:789
@ Materializing
Added to the symbol table, never queried.
Definition Core.h:792
@ NeverSearched
No symbol should be in this state.
Definition Core.h:791
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:795
@ Emitted
Assigned address, still materializing.
Definition Core.h:794
@ Resolved
Queried, materialization begun.
Definition Core.h:793
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.
Definition Types.h:26
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:2124
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
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:1915
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1437
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:581
SymbolDependenceMap Dependencies
Definition Core.h:583