1 //===--- Core.cpp - Core ORC APIs (MaterializationUnit, JITDylib, etc.) ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/ExecutionEngine/Orc/Core.h" 11 #include "llvm/Config/llvm-config.h" 12 #include "llvm/ExecutionEngine/Orc/OrcError.h" 13 #include "llvm/IR/Mangler.h" 14 #include "llvm/Support/CommandLine.h" 15 #include "llvm/Support/Debug.h" 16 #include "llvm/Support/Format.h" 17 18 #if LLVM_ENABLE_THREADS 19 #include <future> 20 #endif 21 22 #define DEBUG_TYPE "orc" 23 24 using namespace llvm; 25 26 namespace { 27 28 #ifndef NDEBUG 29 30 cl::opt<bool> PrintHidden("debug-orc-print-hidden", cl::init(false), 31 cl::desc("debug print hidden symbols defined by " 32 "materialization units"), 33 cl::Hidden); 34 35 cl::opt<bool> PrintCallable("debug-orc-print-callable", cl::init(false), 36 cl::desc("debug print callable symbols defined by " 37 "materialization units"), 38 cl::Hidden); 39 40 cl::opt<bool> PrintData("debug-orc-print-data", cl::init(false), 41 cl::desc("debug print data symbols defined by " 42 "materialization units"), 43 cl::Hidden); 44 45 #endif // NDEBUG 46 47 // SetPrinter predicate that prints every element. 48 template <typename T> struct PrintAll { 49 bool operator()(const T &E) { return true; } 50 }; 51 52 bool anyPrintSymbolOptionSet() { 53 #ifndef NDEBUG 54 return PrintHidden || PrintCallable || PrintData; 55 #else 56 return false; 57 #endif // NDEBUG 58 } 59 60 bool flagsMatchCLOpts(const JITSymbolFlags &Flags) { 61 #ifndef NDEBUG 62 // Bail out early if this is a hidden symbol and we're not printing hiddens. 63 if (!PrintHidden && !Flags.isExported()) 64 return false; 65 66 // Return true if this is callable and we're printing callables. 67 if (PrintCallable && Flags.isCallable()) 68 return true; 69 70 // Return true if this is data and we're printing data. 71 if (PrintData && !Flags.isCallable()) 72 return true; 73 74 // otherwise return false. 75 return false; 76 #else 77 return false; 78 #endif // NDEBUG 79 } 80 81 // Prints a set of items, filtered by an user-supplied predicate. 82 template <typename Set, typename Pred = PrintAll<typename Set::value_type>> 83 class SetPrinter { 84 public: 85 SetPrinter(const Set &S, Pred ShouldPrint = Pred()) 86 : S(S), ShouldPrint(std::move(ShouldPrint)) {} 87 88 void printTo(llvm::raw_ostream &OS) const { 89 bool PrintComma = false; 90 OS << "{"; 91 for (auto &E : S) { 92 if (ShouldPrint(E)) { 93 if (PrintComma) 94 OS << ','; 95 OS << ' ' << E; 96 PrintComma = true; 97 } 98 } 99 OS << " }"; 100 } 101 102 private: 103 const Set &S; 104 mutable Pred ShouldPrint; 105 }; 106 107 template <typename Set, typename Pred> 108 SetPrinter<Set, Pred> printSet(const Set &S, Pred P = Pred()) { 109 return SetPrinter<Set, Pred>(S, std::move(P)); 110 } 111 112 // Render a SetPrinter by delegating to its printTo method. 113 template <typename Set, typename Pred> 114 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 115 const SetPrinter<Set, Pred> &Printer) { 116 Printer.printTo(OS); 117 return OS; 118 } 119 120 struct PrintSymbolFlagsMapElemsMatchingCLOpts { 121 bool operator()(const orc::SymbolFlagsMap::value_type &KV) { 122 return flagsMatchCLOpts(KV.second); 123 } 124 }; 125 126 struct PrintSymbolMapElemsMatchingCLOpts { 127 bool operator()(const orc::SymbolMap::value_type &KV) { 128 return flagsMatchCLOpts(KV.second.getFlags()); 129 } 130 }; 131 132 } // end anonymous namespace 133 134 namespace llvm { 135 namespace orc { 136 137 char FailedToMaterialize::ID = 0; 138 char SymbolsNotFound::ID = 0; 139 char SymbolsCouldNotBeRemoved::ID = 0; 140 141 RegisterDependenciesFunction NoDependenciesToRegister = 142 RegisterDependenciesFunction(); 143 144 void MaterializationUnit::anchor() {} 145 146 raw_ostream &operator<<(raw_ostream &OS, const SymbolStringPtr &Sym) { 147 return OS << *Sym; 148 } 149 150 raw_ostream &operator<<(raw_ostream &OS, const SymbolNameSet &Symbols) { 151 return OS << printSet(Symbols, PrintAll<SymbolStringPtr>()); 152 } 153 154 raw_ostream &operator<<(raw_ostream &OS, const JITSymbolFlags &Flags) { 155 if (Flags.isCallable()) 156 OS << "[Callable]"; 157 else 158 OS << "[Data]"; 159 if (Flags.isWeak()) 160 OS << "[Weak]"; 161 else if (Flags.isCommon()) 162 OS << "[Common]"; 163 164 if (!Flags.isExported()) 165 OS << "[Hidden]"; 166 167 return OS; 168 } 169 170 raw_ostream &operator<<(raw_ostream &OS, const JITEvaluatedSymbol &Sym) { 171 return OS << format("0x%016x", Sym.getAddress()) << " " << Sym.getFlags(); 172 } 173 174 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap::value_type &KV) { 175 return OS << "(\"" << KV.first << "\", " << KV.second << ")"; 176 } 177 178 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap::value_type &KV) { 179 return OS << "(\"" << KV.first << "\": " << KV.second << ")"; 180 } 181 182 raw_ostream &operator<<(raw_ostream &OS, const SymbolFlagsMap &SymbolFlags) { 183 return OS << printSet(SymbolFlags, PrintSymbolFlagsMapElemsMatchingCLOpts()); 184 } 185 186 raw_ostream &operator<<(raw_ostream &OS, const SymbolMap &Symbols) { 187 return OS << printSet(Symbols, PrintSymbolMapElemsMatchingCLOpts()); 188 } 189 190 raw_ostream &operator<<(raw_ostream &OS, 191 const SymbolDependenceMap::value_type &KV) { 192 return OS << "(" << KV.first << ", " << KV.second << ")"; 193 } 194 195 raw_ostream &operator<<(raw_ostream &OS, const SymbolDependenceMap &Deps) { 196 return OS << printSet(Deps, PrintAll<SymbolDependenceMap::value_type>()); 197 } 198 199 raw_ostream &operator<<(raw_ostream &OS, const MaterializationUnit &MU) { 200 OS << "MU@" << &MU << " (\"" << MU.getName() << "\""; 201 if (anyPrintSymbolOptionSet()) 202 OS << ", " << MU.getSymbols(); 203 return OS << ")"; 204 } 205 206 raw_ostream &operator<<(raw_ostream &OS, const JITDylibList &JDs) { 207 OS << "["; 208 if (!JDs.empty()) { 209 assert(JDs.front() && "JITDylibList entries must not be null"); 210 OS << " " << JDs.front()->getName(); 211 for (auto *JD : make_range(std::next(JDs.begin()), JDs.end())) { 212 assert(JD && "JITDylibList entries must not be null"); 213 OS << ", " << JD->getName(); 214 } 215 } 216 OS << " ]"; 217 return OS; 218 } 219 220 FailedToMaterialize::FailedToMaterialize(SymbolNameSet Symbols) 221 : Symbols(std::move(Symbols)) { 222 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 223 } 224 225 std::error_code FailedToMaterialize::convertToErrorCode() const { 226 return orcError(OrcErrorCode::UnknownORCError); 227 } 228 229 void FailedToMaterialize::log(raw_ostream &OS) const { 230 OS << "Failed to materialize symbols: " << Symbols; 231 } 232 233 SymbolsNotFound::SymbolsNotFound(SymbolNameSet Symbols) 234 : Symbols(std::move(Symbols)) { 235 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 236 } 237 238 std::error_code SymbolsNotFound::convertToErrorCode() const { 239 return orcError(OrcErrorCode::UnknownORCError); 240 } 241 242 void SymbolsNotFound::log(raw_ostream &OS) const { 243 OS << "Symbols not found: " << Symbols; 244 } 245 246 SymbolsCouldNotBeRemoved::SymbolsCouldNotBeRemoved(SymbolNameSet Symbols) 247 : Symbols(std::move(Symbols)) { 248 assert(!this->Symbols.empty() && "Can not fail to resolve an empty set"); 249 } 250 251 std::error_code SymbolsCouldNotBeRemoved::convertToErrorCode() const { 252 return orcError(OrcErrorCode::UnknownORCError); 253 } 254 255 void SymbolsCouldNotBeRemoved::log(raw_ostream &OS) const { 256 OS << "Symbols could not be removed: " << Symbols; 257 } 258 259 AsynchronousSymbolQuery::AsynchronousSymbolQuery( 260 const SymbolNameSet &Symbols, SymbolsResolvedCallback NotifySymbolsResolved, 261 SymbolsReadyCallback NotifySymbolsReady) 262 : NotifySymbolsResolved(std::move(NotifySymbolsResolved)), 263 NotifySymbolsReady(std::move(NotifySymbolsReady)) { 264 NotYetResolvedCount = NotYetReadyCount = Symbols.size(); 265 266 for (auto &S : Symbols) 267 ResolvedSymbols[S] = nullptr; 268 } 269 270 void AsynchronousSymbolQuery::resolve(const SymbolStringPtr &Name, 271 JITEvaluatedSymbol Sym) { 272 auto I = ResolvedSymbols.find(Name); 273 assert(I != ResolvedSymbols.end() && 274 "Resolving symbol outside the requested set"); 275 assert(I->second.getAddress() == 0 && "Redundantly resolving symbol Name"); 276 I->second = std::move(Sym); 277 --NotYetResolvedCount; 278 } 279 280 void AsynchronousSymbolQuery::handleFullyResolved() { 281 assert(NotYetResolvedCount == 0 && "Not fully resolved?"); 282 283 if (!NotifySymbolsResolved) { 284 // handleFullyResolved may be called by handleFullyReady (see comments in 285 // that method), in which case this is a no-op, so bail out. 286 assert(!NotifySymbolsReady && 287 "NotifySymbolsResolved already called or an error occurred"); 288 return; 289 } 290 291 auto TmpNotifySymbolsResolved = std::move(NotifySymbolsResolved); 292 NotifySymbolsResolved = SymbolsResolvedCallback(); 293 TmpNotifySymbolsResolved(std::move(ResolvedSymbols)); 294 } 295 296 void AsynchronousSymbolQuery::notifySymbolReady() { 297 assert(NotYetReadyCount != 0 && "All symbols already emitted"); 298 --NotYetReadyCount; 299 } 300 301 void AsynchronousSymbolQuery::handleFullyReady() { 302 assert(NotifySymbolsReady && 303 "NotifySymbolsReady already called or an error occurred"); 304 305 auto TmpNotifySymbolsReady = std::move(NotifySymbolsReady); 306 NotifySymbolsReady = SymbolsReadyCallback(); 307 308 if (NotYetResolvedCount == 0 && NotifySymbolsResolved) { 309 // The NotifyResolved callback of one query must have caused this query to 310 // become ready (i.e. there is still a handleFullyResolved callback waiting 311 // to be made back up the stack). Fold the handleFullyResolved call into 312 // this one before proceeding. This will cause the call further up the 313 // stack to become a no-op. 314 handleFullyResolved(); 315 } 316 317 assert(QueryRegistrations.empty() && 318 "Query is still registered with some symbols"); 319 assert(!NotifySymbolsResolved && "Resolution not applied yet"); 320 TmpNotifySymbolsReady(Error::success()); 321 } 322 323 bool AsynchronousSymbolQuery::canStillFail() { 324 return (NotifySymbolsResolved || NotifySymbolsReady); 325 } 326 327 void AsynchronousSymbolQuery::handleFailed(Error Err) { 328 assert(QueryRegistrations.empty() && ResolvedSymbols.empty() && 329 NotYetResolvedCount == 0 && NotYetReadyCount == 0 && 330 "Query should already have been abandoned"); 331 if (NotifySymbolsResolved) { 332 NotifySymbolsResolved(std::move(Err)); 333 NotifySymbolsResolved = SymbolsResolvedCallback(); 334 } else { 335 assert(NotifySymbolsReady && "Failed after both callbacks issued?"); 336 NotifySymbolsReady(std::move(Err)); 337 } 338 NotifySymbolsReady = SymbolsReadyCallback(); 339 } 340 341 void AsynchronousSymbolQuery::addQueryDependence(JITDylib &JD, 342 SymbolStringPtr Name) { 343 bool Added = QueryRegistrations[&JD].insert(std::move(Name)).second; 344 (void)Added; 345 assert(Added && "Duplicate dependence notification?"); 346 } 347 348 void AsynchronousSymbolQuery::removeQueryDependence( 349 JITDylib &JD, const SymbolStringPtr &Name) { 350 auto QRI = QueryRegistrations.find(&JD); 351 assert(QRI != QueryRegistrations.end() && 352 "No dependencies registered for JD"); 353 assert(QRI->second.count(Name) && "No dependency on Name in JD"); 354 QRI->second.erase(Name); 355 if (QRI->second.empty()) 356 QueryRegistrations.erase(QRI); 357 } 358 359 void AsynchronousSymbolQuery::detach() { 360 ResolvedSymbols.clear(); 361 NotYetResolvedCount = 0; 362 NotYetReadyCount = 0; 363 for (auto &KV : QueryRegistrations) 364 KV.first->detachQueryHelper(*this, KV.second); 365 QueryRegistrations.clear(); 366 } 367 368 MaterializationResponsibility::MaterializationResponsibility( 369 JITDylib &JD, SymbolFlagsMap SymbolFlags) 370 : JD(JD), SymbolFlags(std::move(SymbolFlags)) { 371 assert(!this->SymbolFlags.empty() && "Materializing nothing?"); 372 373 #ifndef NDEBUG 374 for (auto &KV : this->SymbolFlags) 375 KV.second |= JITSymbolFlags::Materializing; 376 #endif 377 } 378 379 MaterializationResponsibility::~MaterializationResponsibility() { 380 assert(SymbolFlags.empty() && 381 "All symbols should have been explicitly materialized or failed"); 382 } 383 384 SymbolNameSet MaterializationResponsibility::getRequestedSymbols() const { 385 return JD.getRequestedSymbols(SymbolFlags); 386 } 387 388 void MaterializationResponsibility::resolve(const SymbolMap &Symbols) { 389 LLVM_DEBUG(dbgs() << "In " << JD.getName() << " resolving " << Symbols 390 << "\n"); 391 #ifndef NDEBUG 392 for (auto &KV : Symbols) { 393 auto I = SymbolFlags.find(KV.first); 394 assert(I != SymbolFlags.end() && 395 "Resolving symbol outside this responsibility set"); 396 assert(I->second.isMaterializing() && "Duplicate resolution"); 397 I->second &= ~JITSymbolFlags::Materializing; 398 if (I->second.isWeak()) 399 assert(I->second == (KV.second.getFlags() | JITSymbolFlags::Weak) && 400 "Resolving symbol with incorrect flags"); 401 else 402 assert(I->second == KV.second.getFlags() && 403 "Resolving symbol with incorrect flags"); 404 } 405 #endif 406 407 JD.resolve(Symbols); 408 } 409 410 void MaterializationResponsibility::emit() { 411 #ifndef NDEBUG 412 for (auto &KV : SymbolFlags) 413 assert(!KV.second.isMaterializing() && 414 "Failed to resolve symbol before emission"); 415 #endif // NDEBUG 416 417 JD.emit(SymbolFlags); 418 SymbolFlags.clear(); 419 } 420 421 Error MaterializationResponsibility::defineMaterializing( 422 const SymbolFlagsMap &NewSymbolFlags) { 423 // Add the given symbols to this responsibility object. 424 // It's ok if we hit a duplicate here: In that case the new version will be 425 // discarded, and the JITDylib::defineMaterializing method will return a 426 // duplicate symbol error. 427 for (auto &KV : NewSymbolFlags) { 428 auto I = SymbolFlags.insert(KV).first; 429 (void)I; 430 #ifndef NDEBUG 431 I->second |= JITSymbolFlags::Materializing; 432 #endif 433 } 434 435 return JD.defineMaterializing(NewSymbolFlags); 436 } 437 438 void MaterializationResponsibility::failMaterialization() { 439 440 SymbolNameSet FailedSymbols; 441 for (auto &KV : SymbolFlags) 442 FailedSymbols.insert(KV.first); 443 444 JD.notifyFailed(FailedSymbols); 445 SymbolFlags.clear(); 446 } 447 448 void MaterializationResponsibility::replace( 449 std::unique_ptr<MaterializationUnit> MU) { 450 for (auto &KV : MU->getSymbols()) 451 SymbolFlags.erase(KV.first); 452 453 LLVM_DEBUG(JD.getExecutionSession().runSessionLocked([&]() { 454 dbgs() << "In " << JD.getName() << " replacing symbols with " << *MU 455 << "\n"; 456 });); 457 458 JD.replace(std::move(MU)); 459 } 460 461 MaterializationResponsibility 462 MaterializationResponsibility::delegate(const SymbolNameSet &Symbols) { 463 SymbolFlagsMap DelegatedFlags; 464 465 for (auto &Name : Symbols) { 466 auto I = SymbolFlags.find(Name); 467 assert(I != SymbolFlags.end() && 468 "Symbol is not tracked by this MaterializationResponsibility " 469 "instance"); 470 471 DelegatedFlags[Name] = std::move(I->second); 472 SymbolFlags.erase(I); 473 } 474 475 return MaterializationResponsibility(JD, std::move(DelegatedFlags)); 476 } 477 478 void MaterializationResponsibility::addDependencies( 479 const SymbolStringPtr &Name, const SymbolDependenceMap &Dependencies) { 480 assert(SymbolFlags.count(Name) && 481 "Symbol not covered by this MaterializationResponsibility instance"); 482 JD.addDependencies(Name, Dependencies); 483 } 484 485 void MaterializationResponsibility::addDependenciesForAll( 486 const SymbolDependenceMap &Dependencies) { 487 for (auto &KV : SymbolFlags) 488 JD.addDependencies(KV.first, Dependencies); 489 } 490 491 AbsoluteSymbolsMaterializationUnit::AbsoluteSymbolsMaterializationUnit( 492 SymbolMap Symbols) 493 : MaterializationUnit(extractFlags(Symbols)), Symbols(std::move(Symbols)) {} 494 495 StringRef AbsoluteSymbolsMaterializationUnit::getName() const { 496 return "<Absolute Symbols>"; 497 } 498 499 void AbsoluteSymbolsMaterializationUnit::materialize( 500 MaterializationResponsibility R) { 501 R.resolve(Symbols); 502 R.emit(); 503 } 504 505 void AbsoluteSymbolsMaterializationUnit::discard(const JITDylib &JD, 506 const SymbolStringPtr &Name) { 507 assert(Symbols.count(Name) && "Symbol is not part of this MU"); 508 Symbols.erase(Name); 509 } 510 511 SymbolFlagsMap 512 AbsoluteSymbolsMaterializationUnit::extractFlags(const SymbolMap &Symbols) { 513 SymbolFlagsMap Flags; 514 for (const auto &KV : Symbols) 515 Flags[KV.first] = KV.second.getFlags(); 516 return Flags; 517 } 518 519 ReExportsMaterializationUnit::ReExportsMaterializationUnit( 520 JITDylib *SourceJD, SymbolAliasMap Aliases) 521 : MaterializationUnit(extractFlags(Aliases)), SourceJD(SourceJD), 522 Aliases(std::move(Aliases)) {} 523 524 StringRef ReExportsMaterializationUnit::getName() const { 525 return "<Reexports>"; 526 } 527 528 void ReExportsMaterializationUnit::materialize( 529 MaterializationResponsibility R) { 530 531 auto &ES = R.getTargetJITDylib().getExecutionSession(); 532 JITDylib &TgtJD = R.getTargetJITDylib(); 533 JITDylib &SrcJD = SourceJD ? *SourceJD : TgtJD; 534 535 // Find the set of requested aliases and aliasees. Return any unrequested 536 // aliases back to the JITDylib so as to not prematurely materialize any 537 // aliasees. 538 auto RequestedSymbols = R.getRequestedSymbols(); 539 SymbolAliasMap RequestedAliases; 540 541 for (auto &Name : RequestedSymbols) { 542 auto I = Aliases.find(Name); 543 assert(I != Aliases.end() && "Symbol not found in aliases map?"); 544 RequestedAliases[Name] = std::move(I->second); 545 Aliases.erase(I); 546 } 547 548 if (!Aliases.empty()) { 549 if (SourceJD) 550 R.replace(reexports(*SourceJD, std::move(Aliases))); 551 else 552 R.replace(symbolAliases(std::move(Aliases))); 553 } 554 555 // The OnResolveInfo struct will hold the aliases and responsibilty for each 556 // query in the list. 557 struct OnResolveInfo { 558 OnResolveInfo(MaterializationResponsibility R, SymbolAliasMap Aliases) 559 : R(std::move(R)), Aliases(std::move(Aliases)) {} 560 561 MaterializationResponsibility R; 562 SymbolAliasMap Aliases; 563 }; 564 565 // Build a list of queries to issue. In each round we build the largest set of 566 // aliases that we can resolve without encountering a chain definition of the 567 // form Foo -> Bar, Bar -> Baz. Such a form would deadlock as the query would 568 // be waitin on a symbol that it itself had to resolve. Usually this will just 569 // involve one round and a single query. 570 571 std::vector<std::pair<SymbolNameSet, std::shared_ptr<OnResolveInfo>>> 572 QueryInfos; 573 while (!RequestedAliases.empty()) { 574 SymbolNameSet ResponsibilitySymbols; 575 SymbolNameSet QuerySymbols; 576 SymbolAliasMap QueryAliases; 577 578 for (auto I = RequestedAliases.begin(), E = RequestedAliases.end(); 579 I != E;) { 580 auto Tmp = I++; 581 582 // Chain detected. Skip this symbol for this round. 583 if (&SrcJD == &TgtJD && (QueryAliases.count(Tmp->second.Aliasee) || 584 RequestedAliases.count(Tmp->second.Aliasee))) 585 continue; 586 587 ResponsibilitySymbols.insert(Tmp->first); 588 QuerySymbols.insert(Tmp->second.Aliasee); 589 QueryAliases[Tmp->first] = std::move(Tmp->second); 590 RequestedAliases.erase(Tmp); 591 } 592 assert(!QuerySymbols.empty() && "Alias cycle detected!"); 593 594 auto QueryInfo = std::make_shared<OnResolveInfo>( 595 R.delegate(ResponsibilitySymbols), std::move(QueryAliases)); 596 QueryInfos.push_back( 597 make_pair(std::move(QuerySymbols), std::move(QueryInfo))); 598 } 599 600 // Issue the queries. 601 while (!QueryInfos.empty()) { 602 auto QuerySymbols = std::move(QueryInfos.back().first); 603 auto QueryInfo = std::move(QueryInfos.back().second); 604 605 QueryInfos.pop_back(); 606 607 auto RegisterDependencies = [QueryInfo, 608 &SrcJD](const SymbolDependenceMap &Deps) { 609 // If there were no materializing symbols, just bail out. 610 if (Deps.empty()) 611 return; 612 613 // Otherwise the only deps should be on SrcJD. 614 assert(Deps.size() == 1 && Deps.count(&SrcJD) && 615 "Unexpected dependencies for reexports"); 616 617 auto &SrcJDDeps = Deps.find(&SrcJD)->second; 618 SymbolDependenceMap PerAliasDepsMap; 619 auto &PerAliasDeps = PerAliasDepsMap[&SrcJD]; 620 621 for (auto &KV : QueryInfo->Aliases) 622 if (SrcJDDeps.count(KV.second.Aliasee)) { 623 PerAliasDeps = {KV.second.Aliasee}; 624 QueryInfo->R.addDependencies(KV.first, PerAliasDepsMap); 625 } 626 }; 627 628 auto OnResolve = [QueryInfo](Expected<SymbolMap> Result) { 629 if (Result) { 630 SymbolMap ResolutionMap; 631 for (auto &KV : QueryInfo->Aliases) { 632 assert(Result->count(KV.second.Aliasee) && 633 "Result map missing entry?"); 634 ResolutionMap[KV.first] = JITEvaluatedSymbol( 635 (*Result)[KV.second.Aliasee].getAddress(), KV.second.AliasFlags); 636 } 637 QueryInfo->R.resolve(ResolutionMap); 638 QueryInfo->R.emit(); 639 } else { 640 auto &ES = QueryInfo->R.getTargetJITDylib().getExecutionSession(); 641 ES.reportError(Result.takeError()); 642 QueryInfo->R.failMaterialization(); 643 } 644 }; 645 646 auto OnReady = [&ES](Error Err) { ES.reportError(std::move(Err)); }; 647 648 ES.lookup({&SrcJD}, QuerySymbols, std::move(OnResolve), std::move(OnReady), 649 std::move(RegisterDependencies), nullptr, true); 650 } 651 } 652 653 void ReExportsMaterializationUnit::discard(const JITDylib &JD, 654 const SymbolStringPtr &Name) { 655 assert(Aliases.count(Name) && 656 "Symbol not covered by this MaterializationUnit"); 657 Aliases.erase(Name); 658 } 659 660 SymbolFlagsMap 661 ReExportsMaterializationUnit::extractFlags(const SymbolAliasMap &Aliases) { 662 SymbolFlagsMap SymbolFlags; 663 for (auto &KV : Aliases) 664 SymbolFlags[KV.first] = KV.second.AliasFlags; 665 666 return SymbolFlags; 667 } 668 669 Expected<SymbolAliasMap> 670 buildSimpleReexportsAliasMap(JITDylib &SourceJD, const SymbolNameSet &Symbols) { 671 auto Flags = SourceJD.lookupFlags(Symbols); 672 673 if (Flags.size() != Symbols.size()) { 674 SymbolNameSet Unresolved = Symbols; 675 for (auto &KV : Flags) 676 Unresolved.erase(KV.first); 677 return make_error<SymbolsNotFound>(std::move(Unresolved)); 678 } 679 680 SymbolAliasMap Result; 681 for (auto &Name : Symbols) { 682 assert(Flags.count(Name) && "Missing entry in flags map"); 683 Result[Name] = SymbolAliasMapEntry(Name, Flags[Name]); 684 } 685 686 return Result; 687 } 688 689 ReexportsGenerator::ReexportsGenerator(JITDylib &SourceJD, 690 SymbolPredicate Allow) 691 : SourceJD(SourceJD), Allow(std::move(Allow)) {} 692 693 SymbolNameSet ReexportsGenerator::operator()(JITDylib &JD, 694 const SymbolNameSet &Names) { 695 orc::SymbolNameSet Added; 696 orc::SymbolAliasMap AliasMap; 697 698 auto Flags = SourceJD.lookupFlags(Names); 699 700 for (auto &KV : Flags) { 701 if (Allow && !Allow(KV.first)) 702 continue; 703 AliasMap[KV.first] = SymbolAliasMapEntry(KV.first, KV.second); 704 Added.insert(KV.first); 705 } 706 707 if (!Added.empty()) 708 cantFail(JD.define(reexports(SourceJD, AliasMap))); 709 710 return Added; 711 } 712 713 Error JITDylib::defineMaterializing(const SymbolFlagsMap &SymbolFlags) { 714 return ES.runSessionLocked([&]() -> Error { 715 std::vector<SymbolMap::iterator> AddedSyms; 716 717 for (auto &KV : SymbolFlags) { 718 SymbolMap::iterator EntryItr; 719 bool Added; 720 721 auto NewFlags = KV.second; 722 NewFlags |= JITSymbolFlags::Materializing; 723 724 std::tie(EntryItr, Added) = Symbols.insert( 725 std::make_pair(KV.first, JITEvaluatedSymbol(0, NewFlags))); 726 727 if (Added) 728 AddedSyms.push_back(EntryItr); 729 else { 730 // Remove any symbols already added. 731 for (auto &SI : AddedSyms) 732 Symbols.erase(SI); 733 734 // FIXME: Return all duplicates. 735 return make_error<DuplicateDefinition>(*KV.first); 736 } 737 } 738 739 return Error::success(); 740 }); 741 } 742 743 void JITDylib::replace(std::unique_ptr<MaterializationUnit> MU) { 744 assert(MU != nullptr && "Can not replace with a null MaterializationUnit"); 745 746 auto MustRunMU = 747 ES.runSessionLocked([&, this]() -> std::unique_ptr<MaterializationUnit> { 748 749 #ifndef NDEBUG 750 for (auto &KV : MU->getSymbols()) { 751 auto SymI = Symbols.find(KV.first); 752 assert(SymI != Symbols.end() && "Replacing unknown symbol"); 753 assert(!SymI->second.getFlags().isLazy() && 754 SymI->second.getFlags().isMaterializing() && 755 "Can not replace symbol that is not materializing"); 756 assert(UnmaterializedInfos.count(KV.first) == 0 && 757 "Symbol being replaced should have no UnmaterializedInfo"); 758 } 759 #endif // NDEBUG 760 761 // If any symbol has pending queries against it then we need to 762 // materialize MU immediately. 763 for (auto &KV : MU->getSymbols()) { 764 auto MII = MaterializingInfos.find(KV.first); 765 if (MII != MaterializingInfos.end()) { 766 if (!MII->second.PendingQueries.empty()) 767 return std::move(MU); 768 } 769 } 770 771 // Otherwise, make MU responsible for all the symbols. 772 auto UMI = std::make_shared<UnmaterializedInfo>(std::move(MU)); 773 for (auto &KV : UMI->MU->getSymbols()) { 774 assert(!KV.second.isLazy() && 775 "Lazy flag should be managed internally."); 776 assert(!KV.second.isMaterializing() && 777 "Materializing flags should be managed internally."); 778 779 auto SymI = Symbols.find(KV.first); 780 JITSymbolFlags ReplaceFlags = KV.second; 781 ReplaceFlags |= JITSymbolFlags::Lazy; 782 SymI->second = JITEvaluatedSymbol(SymI->second.getAddress(), 783 std::move(ReplaceFlags)); 784 UnmaterializedInfos[KV.first] = UMI; 785 } 786 787 return nullptr; 788 }); 789 790 if (MustRunMU) 791 ES.dispatchMaterialization(*this, std::move(MustRunMU)); 792 } 793 794 SymbolNameSet 795 JITDylib::getRequestedSymbols(const SymbolFlagsMap &SymbolFlags) const { 796 return ES.runSessionLocked([&]() { 797 SymbolNameSet RequestedSymbols; 798 799 for (auto &KV : SymbolFlags) { 800 assert(Symbols.count(KV.first) && "JITDylib does not cover this symbol?"); 801 assert(Symbols.find(KV.first)->second.getFlags().isMaterializing() && 802 "getRequestedSymbols can only be called for materializing " 803 "symbols"); 804 auto I = MaterializingInfos.find(KV.first); 805 if (I == MaterializingInfos.end()) 806 continue; 807 808 if (!I->second.PendingQueries.empty()) 809 RequestedSymbols.insert(KV.first); 810 } 811 812 return RequestedSymbols; 813 }); 814 } 815 816 void JITDylib::addDependencies(const SymbolStringPtr &Name, 817 const SymbolDependenceMap &Dependencies) { 818 assert(Symbols.count(Name) && "Name not in symbol table"); 819 assert((Symbols[Name].getFlags().isLazy() || 820 Symbols[Name].getFlags().isMaterializing()) && 821 "Symbol is not lazy or materializing"); 822 823 auto &MI = MaterializingInfos[Name]; 824 assert(!MI.IsEmitted && "Can not add dependencies to an emitted symbol"); 825 826 for (auto &KV : Dependencies) { 827 assert(KV.first && "Null JITDylib in dependency?"); 828 auto &OtherJITDylib = *KV.first; 829 auto &DepsOnOtherJITDylib = MI.UnemittedDependencies[&OtherJITDylib]; 830 831 for (auto &OtherSymbol : KV.second) { 832 #ifndef NDEBUG 833 // Assert that this symbol exists and has not been emitted already. 834 auto SymI = OtherJITDylib.Symbols.find(OtherSymbol); 835 assert(SymI != OtherJITDylib.Symbols.end() && 836 (SymI->second.getFlags().isLazy() || 837 SymI->second.getFlags().isMaterializing()) && 838 "Dependency on emitted symbol"); 839 #endif 840 841 auto &OtherMI = OtherJITDylib.MaterializingInfos[OtherSymbol]; 842 843 if (OtherMI.IsEmitted) 844 transferEmittedNodeDependencies(MI, Name, OtherMI); 845 else if (&OtherJITDylib != this || OtherSymbol != Name) { 846 OtherMI.Dependants[this].insert(Name); 847 DepsOnOtherJITDylib.insert(OtherSymbol); 848 } 849 } 850 851 if (DepsOnOtherJITDylib.empty()) 852 MI.UnemittedDependencies.erase(&OtherJITDylib); 853 } 854 } 855 856 void JITDylib::resolve(const SymbolMap &Resolved) { 857 auto FullyResolvedQueries = ES.runSessionLocked([&, this]() { 858 AsynchronousSymbolQuerySet FullyResolvedQueries; 859 for (const auto &KV : Resolved) { 860 auto &Name = KV.first; 861 auto Sym = KV.second; 862 863 assert(!Sym.getFlags().isLazy() && !Sym.getFlags().isMaterializing() && 864 "Materializing flags should be managed internally"); 865 866 auto I = Symbols.find(Name); 867 868 assert(I != Symbols.end() && "Symbol not found"); 869 assert(!I->second.getFlags().isLazy() && 870 I->second.getFlags().isMaterializing() && 871 "Symbol should be materializing"); 872 assert(I->second.getAddress() == 0 && "Symbol has already been resolved"); 873 874 assert((Sym.getFlags() & ~JITSymbolFlags::Weak) == 875 (JITSymbolFlags::stripTransientFlags(I->second.getFlags()) & 876 ~JITSymbolFlags::Weak) && 877 "Resolved flags should match the declared flags"); 878 879 // Once resolved, symbols can never be weak. 880 JITSymbolFlags ResolvedFlags = Sym.getFlags(); 881 ResolvedFlags &= ~JITSymbolFlags::Weak; 882 ResolvedFlags |= JITSymbolFlags::Materializing; 883 I->second = JITEvaluatedSymbol(Sym.getAddress(), ResolvedFlags); 884 885 auto &MI = MaterializingInfos[Name]; 886 for (auto &Q : MI.PendingQueries) { 887 Q->resolve(Name, Sym); 888 if (Q->isFullyResolved()) 889 FullyResolvedQueries.insert(Q); 890 } 891 } 892 893 return FullyResolvedQueries; 894 }); 895 896 for (auto &Q : FullyResolvedQueries) { 897 assert(Q->isFullyResolved() && "Q not fully resolved"); 898 Q->handleFullyResolved(); 899 } 900 } 901 902 void JITDylib::emit(const SymbolFlagsMap &Emitted) { 903 auto FullyReadyQueries = ES.runSessionLocked([&, this]() { 904 AsynchronousSymbolQuerySet ReadyQueries; 905 906 for (const auto &KV : Emitted) { 907 const auto &Name = KV.first; 908 909 auto MII = MaterializingInfos.find(Name); 910 assert(MII != MaterializingInfos.end() && 911 "Missing MaterializingInfo entry"); 912 913 auto &MI = MII->second; 914 915 // For each dependant, transfer this node's emitted dependencies to 916 // it. If the dependant node is ready (i.e. has no unemitted 917 // dependencies) then notify any pending queries. 918 for (auto &KV : MI.Dependants) { 919 auto &DependantJD = *KV.first; 920 for (auto &DependantName : KV.second) { 921 auto DependantMII = 922 DependantJD.MaterializingInfos.find(DependantName); 923 assert(DependantMII != DependantJD.MaterializingInfos.end() && 924 "Dependant should have MaterializingInfo"); 925 926 auto &DependantMI = DependantMII->second; 927 928 // Remove the dependant's dependency on this node. 929 assert(DependantMI.UnemittedDependencies[this].count(Name) && 930 "Dependant does not count this symbol as a dependency?"); 931 DependantMI.UnemittedDependencies[this].erase(Name); 932 if (DependantMI.UnemittedDependencies[this].empty()) 933 DependantMI.UnemittedDependencies.erase(this); 934 935 // Transfer unemitted dependencies from this node to the dependant. 936 DependantJD.transferEmittedNodeDependencies(DependantMI, 937 DependantName, MI); 938 939 // If the dependant is emitted and this node was the last of its 940 // unemitted dependencies then the dependant node is now ready, so 941 // notify any pending queries on the dependant node. 942 if (DependantMI.IsEmitted && 943 DependantMI.UnemittedDependencies.empty()) { 944 assert(DependantMI.Dependants.empty() && 945 "Dependants should be empty by now"); 946 for (auto &Q : DependantMI.PendingQueries) { 947 Q->notifySymbolReady(); 948 if (Q->isFullyReady()) 949 ReadyQueries.insert(Q); 950 Q->removeQueryDependence(DependantJD, DependantName); 951 } 952 953 // Since this dependant is now ready, we erase its MaterializingInfo 954 // and update its materializing state. 955 assert(DependantJD.Symbols.count(DependantName) && 956 "Dependant has no entry in the Symbols table"); 957 auto &DependantSym = DependantJD.Symbols[DependantName]; 958 DependantSym.setFlags(DependantSym.getFlags() & 959 ~JITSymbolFlags::Materializing); 960 DependantJD.MaterializingInfos.erase(DependantMII); 961 } 962 } 963 } 964 MI.Dependants.clear(); 965 MI.IsEmitted = true; 966 967 if (MI.UnemittedDependencies.empty()) { 968 for (auto &Q : MI.PendingQueries) { 969 Q->notifySymbolReady(); 970 if (Q->isFullyReady()) 971 ReadyQueries.insert(Q); 972 Q->removeQueryDependence(*this, Name); 973 } 974 assert(Symbols.count(Name) && 975 "Symbol has no entry in the Symbols table"); 976 auto &Sym = Symbols[Name]; 977 Sym.setFlags(Sym.getFlags() & ~JITSymbolFlags::Materializing); 978 MaterializingInfos.erase(MII); 979 } 980 } 981 982 return ReadyQueries; 983 }); 984 985 for (auto &Q : FullyReadyQueries) { 986 assert(Q->isFullyReady() && "Q is not fully ready"); 987 Q->handleFullyReady(); 988 } 989 } 990 991 void JITDylib::notifyFailed(const SymbolNameSet &FailedSymbols) { 992 993 // FIXME: This should fail any transitively dependant symbols too. 994 995 auto FailedQueriesToNotify = ES.runSessionLocked([&, this]() { 996 AsynchronousSymbolQuerySet FailedQueries; 997 998 for (auto &Name : FailedSymbols) { 999 auto I = Symbols.find(Name); 1000 assert(I != Symbols.end() && "Symbol not present in this JITDylib"); 1001 Symbols.erase(I); 1002 1003 auto MII = MaterializingInfos.find(Name); 1004 1005 // If we have not created a MaterializingInfo for this symbol yet then 1006 // there is nobody to notify. 1007 if (MII == MaterializingInfos.end()) 1008 continue; 1009 1010 // Copy all the queries to the FailedQueries list, then abandon them. 1011 // This has to be a copy, and the copy has to come before the abandon 1012 // operation: Each Q.detach() call will reach back into this 1013 // PendingQueries list to remove Q. 1014 for (auto &Q : MII->second.PendingQueries) 1015 FailedQueries.insert(Q); 1016 1017 for (auto &Q : FailedQueries) 1018 Q->detach(); 1019 1020 assert(MII->second.PendingQueries.empty() && 1021 "Queries remain after symbol was failed"); 1022 1023 MaterializingInfos.erase(MII); 1024 } 1025 1026 return FailedQueries; 1027 }); 1028 1029 for (auto &Q : FailedQueriesToNotify) 1030 Q->handleFailed(make_error<FailedToMaterialize>(FailedSymbols)); 1031 } 1032 1033 void JITDylib::setSearchOrder(JITDylibList NewSearchOrder, 1034 bool SearchThisJITDylibFirst) { 1035 if (SearchThisJITDylibFirst && NewSearchOrder.front() != this) 1036 NewSearchOrder.insert(NewSearchOrder.begin(), this); 1037 1038 ES.runSessionLocked([&]() { SearchOrder = std::move(NewSearchOrder); }); 1039 } 1040 1041 void JITDylib::addToSearchOrder(JITDylib &JD) { 1042 ES.runSessionLocked([&]() { SearchOrder.push_back(&JD); }); 1043 } 1044 1045 void JITDylib::replaceInSearchOrder(JITDylib &OldJD, JITDylib &NewJD) { 1046 ES.runSessionLocked([&]() { 1047 auto I = std::find(SearchOrder.begin(), SearchOrder.end(), &OldJD); 1048 1049 if (I != SearchOrder.end()) 1050 *I = &NewJD; 1051 }); 1052 } 1053 1054 void JITDylib::removeFromSearchOrder(JITDylib &JD) { 1055 ES.runSessionLocked([&]() { 1056 auto I = std::find(SearchOrder.begin(), SearchOrder.end(), &JD); 1057 if (I != SearchOrder.end()) 1058 SearchOrder.erase(I); 1059 }); 1060 } 1061 1062 Error JITDylib::remove(const SymbolNameSet &Names) { 1063 return ES.runSessionLocked([&]() -> Error { 1064 using SymbolMaterializerItrPair = 1065 std::pair<SymbolMap::iterator, UnmaterializedInfosMap::iterator>; 1066 std::vector<SymbolMaterializerItrPair> SymbolsToRemove; 1067 SymbolNameSet Missing; 1068 SymbolNameSet Materializing; 1069 1070 for (auto &Name : Names) { 1071 auto I = Symbols.find(Name); 1072 1073 // Note symbol missing. 1074 if (I == Symbols.end()) { 1075 Missing.insert(Name); 1076 continue; 1077 } 1078 1079 // Note symbol materializing. 1080 if (I->second.getFlags().isMaterializing()) { 1081 Materializing.insert(Name); 1082 continue; 1083 } 1084 1085 auto UMII = I->second.getFlags().isLazy() ? UnmaterializedInfos.find(Name) 1086 : UnmaterializedInfos.end(); 1087 SymbolsToRemove.push_back(std::make_pair(I, UMII)); 1088 } 1089 1090 // If any of the symbols are not defined, return an error. 1091 if (!Missing.empty()) 1092 return make_error<SymbolsNotFound>(std::move(Missing)); 1093 1094 // If any of the symbols are currently materializing, return an error. 1095 if (!Materializing.empty()) 1096 return make_error<SymbolsCouldNotBeRemoved>(std::move(Materializing)); 1097 1098 // Remove the symbols. 1099 for (auto &SymbolMaterializerItrPair : SymbolsToRemove) { 1100 auto UMII = SymbolMaterializerItrPair.second; 1101 1102 // If there is a materializer attached, call discard. 1103 if (UMII != UnmaterializedInfos.end()) { 1104 UMII->second->MU->doDiscard(*this, UMII->first); 1105 UnmaterializedInfos.erase(UMII); 1106 } 1107 1108 auto SymI = SymbolMaterializerItrPair.first; 1109 Symbols.erase(SymI); 1110 } 1111 1112 return Error::success(); 1113 }); 1114 } 1115 1116 SymbolFlagsMap JITDylib::lookupFlags(const SymbolNameSet &Names) { 1117 return ES.runSessionLocked([&, this]() { 1118 SymbolFlagsMap Result; 1119 auto Unresolved = lookupFlagsImpl(Result, Names); 1120 if (DefGenerator && !Unresolved.empty()) { 1121 auto NewDefs = DefGenerator(*this, Unresolved); 1122 if (!NewDefs.empty()) { 1123 auto Unresolved2 = lookupFlagsImpl(Result, NewDefs); 1124 (void)Unresolved2; 1125 assert(Unresolved2.empty() && 1126 "All fallback defs should have been found by lookupFlagsImpl"); 1127 } 1128 }; 1129 return Result; 1130 }); 1131 } 1132 1133 SymbolNameSet JITDylib::lookupFlagsImpl(SymbolFlagsMap &Flags, 1134 const SymbolNameSet &Names) { 1135 SymbolNameSet Unresolved; 1136 1137 for (auto &Name : Names) { 1138 auto I = Symbols.find(Name); 1139 1140 if (I == Symbols.end()) { 1141 Unresolved.insert(Name); 1142 continue; 1143 } 1144 1145 assert(!Flags.count(Name) && "Symbol already present in Flags map"); 1146 Flags[Name] = JITSymbolFlags::stripTransientFlags(I->second.getFlags()); 1147 } 1148 1149 return Unresolved; 1150 } 1151 1152 void JITDylib::lodgeQuery(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1153 SymbolNameSet &Unresolved, 1154 JITDylib *MatchNonExportedInJD, bool MatchNonExported, 1155 MaterializationUnitList &MUs) { 1156 assert(Q && "Query can not be null"); 1157 1158 lodgeQueryImpl(Q, Unresolved, MatchNonExportedInJD, MatchNonExported, MUs); 1159 if (DefGenerator && !Unresolved.empty()) { 1160 auto NewDefs = DefGenerator(*this, Unresolved); 1161 if (!NewDefs.empty()) { 1162 for (auto &D : NewDefs) 1163 Unresolved.erase(D); 1164 lodgeQueryImpl(Q, NewDefs, MatchNonExportedInJD, MatchNonExported, MUs); 1165 assert(NewDefs.empty() && 1166 "All fallback defs should have been found by lookupImpl"); 1167 } 1168 } 1169 } 1170 1171 void JITDylib::lodgeQueryImpl( 1172 std::shared_ptr<AsynchronousSymbolQuery> &Q, SymbolNameSet &Unresolved, 1173 JITDylib *MatchNonExportedInJD, bool MatchNonExported, 1174 std::vector<std::unique_ptr<MaterializationUnit>> &MUs) { 1175 for (auto I = Unresolved.begin(), E = Unresolved.end(); I != E;) { 1176 auto TmpI = I++; 1177 auto Name = *TmpI; 1178 1179 // Search for the name in Symbols. Skip it if not found. 1180 auto SymI = Symbols.find(Name); 1181 if (SymI == Symbols.end()) 1182 continue; 1183 1184 // If this is a non-exported symbol, then check the values of 1185 // MatchNonExportedInJD and MatchNonExported. Skip if we should not match 1186 // against this symbol. 1187 if (!SymI->second.getFlags().isExported()) 1188 if (!MatchNonExported && MatchNonExportedInJD != this) 1189 continue; 1190 1191 // If we matched against Name in JD, remove it frome the Unresolved set and 1192 // add it to the added set. 1193 Unresolved.erase(TmpI); 1194 1195 // If the symbol has an address then resolve it. 1196 if (SymI->second.getAddress() != 0) 1197 Q->resolve(Name, SymI->second); 1198 1199 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1200 if (SymI->second.getFlags().isLazy()) { 1201 assert(SymI->second.getAddress() == 0 && 1202 "Lazy symbol should not have a resolved address"); 1203 assert(!SymI->second.getFlags().isMaterializing() && 1204 "Materializing and lazy should not both be set"); 1205 auto UMII = UnmaterializedInfos.find(Name); 1206 assert(UMII != UnmaterializedInfos.end() && 1207 "Lazy symbol should have UnmaterializedInfo"); 1208 auto MU = std::move(UMII->second->MU); 1209 assert(MU != nullptr && "Materializer should not be null"); 1210 1211 // Move all symbols associated with this MaterializationUnit into 1212 // materializing state. 1213 for (auto &KV : MU->getSymbols()) { 1214 auto SymK = Symbols.find(KV.first); 1215 auto Flags = SymK->second.getFlags(); 1216 Flags &= ~JITSymbolFlags::Lazy; 1217 Flags |= JITSymbolFlags::Materializing; 1218 SymK->second.setFlags(Flags); 1219 UnmaterializedInfos.erase(KV.first); 1220 } 1221 1222 // Add MU to the list of MaterializationUnits to be materialized. 1223 MUs.push_back(std::move(MU)); 1224 } else if (!SymI->second.getFlags().isMaterializing()) { 1225 // The symbol is neither lazy nor materializing, so it must be 1226 // ready. Notify the query and continue. 1227 Q->notifySymbolReady(); 1228 continue; 1229 } 1230 1231 // Add the query to the PendingQueries list. 1232 assert(SymI->second.getFlags().isMaterializing() && 1233 "By this line the symbol should be materializing"); 1234 auto &MI = MaterializingInfos[Name]; 1235 MI.PendingQueries.push_back(Q); 1236 Q->addQueryDependence(*this, Name); 1237 } 1238 } 1239 1240 SymbolNameSet JITDylib::legacyLookup(std::shared_ptr<AsynchronousSymbolQuery> Q, 1241 SymbolNameSet Names) { 1242 assert(Q && "Query can not be null"); 1243 1244 ES.runOutstandingMUs(); 1245 1246 LookupImplActionFlags ActionFlags = None; 1247 std::vector<std::unique_ptr<MaterializationUnit>> MUs; 1248 1249 SymbolNameSet Unresolved = std::move(Names); 1250 ES.runSessionLocked([&, this]() { 1251 ActionFlags = lookupImpl(Q, MUs, Unresolved); 1252 if (DefGenerator && !Unresolved.empty()) { 1253 assert(ActionFlags == None && 1254 "ActionFlags set but unresolved symbols remain?"); 1255 auto NewDefs = DefGenerator(*this, Unresolved); 1256 if (!NewDefs.empty()) { 1257 for (auto &D : NewDefs) 1258 Unresolved.erase(D); 1259 ActionFlags = lookupImpl(Q, MUs, NewDefs); 1260 assert(NewDefs.empty() && 1261 "All fallback defs should have been found by lookupImpl"); 1262 } 1263 } 1264 }); 1265 1266 assert((MUs.empty() || ActionFlags == None) && 1267 "If action flags are set, there should be no work to do (so no MUs)"); 1268 1269 if (ActionFlags & NotifyFullyResolved) 1270 Q->handleFullyResolved(); 1271 1272 if (ActionFlags & NotifyFullyReady) 1273 Q->handleFullyReady(); 1274 1275 // FIXME: Swap back to the old code below once RuntimeDyld works with 1276 // callbacks from asynchronous queries. 1277 // Add MUs to the OutstandingMUs list. 1278 { 1279 std::lock_guard<std::recursive_mutex> Lock(ES.OutstandingMUsMutex); 1280 for (auto &MU : MUs) 1281 ES.OutstandingMUs.push_back(make_pair(this, std::move(MU))); 1282 } 1283 ES.runOutstandingMUs(); 1284 1285 // Dispatch any required MaterializationUnits for materialization. 1286 // for (auto &MU : MUs) 1287 // ES.dispatchMaterialization(*this, std::move(MU)); 1288 1289 return Unresolved; 1290 } 1291 1292 JITDylib::LookupImplActionFlags 1293 JITDylib::lookupImpl(std::shared_ptr<AsynchronousSymbolQuery> &Q, 1294 std::vector<std::unique_ptr<MaterializationUnit>> &MUs, 1295 SymbolNameSet &Unresolved) { 1296 LookupImplActionFlags ActionFlags = None; 1297 1298 for (auto I = Unresolved.begin(), E = Unresolved.end(); I != E;) { 1299 auto TmpI = I++; 1300 auto Name = *TmpI; 1301 1302 // Search for the name in Symbols. Skip it if not found. 1303 auto SymI = Symbols.find(Name); 1304 if (SymI == Symbols.end()) 1305 continue; 1306 1307 // If we found Name, remove it frome the Unresolved set and add it 1308 // to the dependencies set. 1309 Unresolved.erase(TmpI); 1310 1311 // If the symbol has an address then resolve it. 1312 if (SymI->second.getAddress() != 0) { 1313 Q->resolve(Name, SymI->second); 1314 if (Q->isFullyResolved()) 1315 ActionFlags |= NotifyFullyResolved; 1316 } 1317 1318 // If the symbol is lazy, get the MaterialiaztionUnit for it. 1319 if (SymI->second.getFlags().isLazy()) { 1320 assert(SymI->second.getAddress() == 0 && 1321 "Lazy symbol should not have a resolved address"); 1322 assert(!SymI->second.getFlags().isMaterializing() && 1323 "Materializing and lazy should not both be set"); 1324 auto UMII = UnmaterializedInfos.find(Name); 1325 assert(UMII != UnmaterializedInfos.end() && 1326 "Lazy symbol should have UnmaterializedInfo"); 1327 auto MU = std::move(UMII->second->MU); 1328 assert(MU != nullptr && "Materializer should not be null"); 1329 1330 // Kick all symbols associated with this MaterializationUnit into 1331 // materializing state. 1332 for (auto &KV : MU->getSymbols()) { 1333 auto SymK = Symbols.find(KV.first); 1334 auto Flags = SymK->second.getFlags(); 1335 Flags &= ~JITSymbolFlags::Lazy; 1336 Flags |= JITSymbolFlags::Materializing; 1337 SymK->second.setFlags(Flags); 1338 UnmaterializedInfos.erase(KV.first); 1339 } 1340 1341 // Add MU to the list of MaterializationUnits to be materialized. 1342 MUs.push_back(std::move(MU)); 1343 } else if (!SymI->second.getFlags().isMaterializing()) { 1344 // The symbol is neither lazy nor materializing, so it must be ready. 1345 // Notify the query and continue. 1346 Q->notifySymbolReady(); 1347 if (Q->isFullyReady()) 1348 ActionFlags |= NotifyFullyReady; 1349 continue; 1350 } 1351 1352 // Add the query to the PendingQueries list. 1353 assert(SymI->second.getFlags().isMaterializing() && 1354 "By this line the symbol should be materializing"); 1355 auto &MI = MaterializingInfos[Name]; 1356 MI.PendingQueries.push_back(Q); 1357 Q->addQueryDependence(*this, Name); 1358 } 1359 1360 return ActionFlags; 1361 } 1362 1363 void JITDylib::dump(raw_ostream &OS) { 1364 ES.runSessionLocked([&, this]() { 1365 OS << "JITDylib \"" << JITDylibName 1366 << "\" (ES: " << format("0x%016x", reinterpret_cast<uintptr_t>(&ES)) 1367 << "):\n" 1368 << "Symbol table:\n"; 1369 1370 for (auto &KV : Symbols) { 1371 OS << " \"" << *KV.first << "\": "; 1372 if (auto Addr = KV.second.getAddress()) 1373 OS << format("0x%016x", Addr); 1374 else 1375 OS << "<not resolved>"; 1376 if (KV.second.getFlags().isLazy() || 1377 KV.second.getFlags().isMaterializing()) { 1378 OS << " ("; 1379 if (KV.second.getFlags().isLazy()) { 1380 auto I = UnmaterializedInfos.find(KV.first); 1381 assert(I != UnmaterializedInfos.end() && 1382 "Lazy symbol should have UnmaterializedInfo"); 1383 OS << " Lazy (MU=" << I->second->MU.get() << ")"; 1384 } 1385 if (KV.second.getFlags().isMaterializing()) 1386 OS << " Materializing"; 1387 OS << " )\n"; 1388 } else 1389 OS << "\n"; 1390 } 1391 1392 if (!MaterializingInfos.empty()) 1393 OS << " MaterializingInfos entries:\n"; 1394 for (auto &KV : MaterializingInfos) { 1395 OS << " \"" << *KV.first << "\":\n" 1396 << " IsEmitted = " << (KV.second.IsEmitted ? "true" : "false") 1397 << "\n" 1398 << " " << KV.second.PendingQueries.size() 1399 << " pending queries: { "; 1400 for (auto &Q : KV.second.PendingQueries) 1401 OS << Q.get() << " "; 1402 OS << "}\n Dependants:\n"; 1403 for (auto &KV2 : KV.second.Dependants) 1404 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1405 OS << " Unemitted Dependencies:\n"; 1406 for (auto &KV2 : KV.second.UnemittedDependencies) 1407 OS << " " << KV2.first->getName() << ": " << KV2.second << "\n"; 1408 } 1409 }); 1410 } 1411 1412 JITDylib::JITDylib(ExecutionSession &ES, std::string Name) 1413 : ES(ES), JITDylibName(std::move(Name)) { 1414 SearchOrder.push_back(this); 1415 } 1416 1417 Error JITDylib::defineImpl(MaterializationUnit &MU) { 1418 SymbolNameSet Duplicates; 1419 SymbolNameSet MUDefsOverridden; 1420 1421 struct ExistingDefOverriddenEntry { 1422 SymbolMap::iterator ExistingDefItr; 1423 JITSymbolFlags NewFlags; 1424 }; 1425 std::vector<ExistingDefOverriddenEntry> ExistingDefsOverridden; 1426 1427 for (auto &KV : MU.getSymbols()) { 1428 assert(!KV.second.isLazy() && "Lazy flag should be managed internally."); 1429 assert(!KV.second.isMaterializing() && 1430 "Materializing flags should be managed internally."); 1431 1432 SymbolMap::iterator EntryItr; 1433 bool Added; 1434 1435 auto NewFlags = KV.second; 1436 NewFlags |= JITSymbolFlags::Lazy; 1437 1438 std::tie(EntryItr, Added) = Symbols.insert( 1439 std::make_pair(KV.first, JITEvaluatedSymbol(0, NewFlags))); 1440 1441 if (!Added) { 1442 if (KV.second.isStrong()) { 1443 if (EntryItr->second.getFlags().isStrong() || 1444 (EntryItr->second.getFlags() & JITSymbolFlags::Materializing)) 1445 Duplicates.insert(KV.first); 1446 else 1447 ExistingDefsOverridden.push_back({EntryItr, NewFlags}); 1448 } else 1449 MUDefsOverridden.insert(KV.first); 1450 } 1451 } 1452 1453 if (!Duplicates.empty()) { 1454 // We need to remove the symbols we added. 1455 for (auto &KV : MU.getSymbols()) { 1456 if (Duplicates.count(KV.first)) 1457 continue; 1458 1459 bool Found = false; 1460 for (const auto &EDO : ExistingDefsOverridden) 1461 if (EDO.ExistingDefItr->first == KV.first) 1462 Found = true; 1463 1464 if (!Found) 1465 Symbols.erase(KV.first); 1466 } 1467 1468 // FIXME: Return all duplicates. 1469 return make_error<DuplicateDefinition>(**Duplicates.begin()); 1470 } 1471 1472 // Update flags on existing defs and call discard on their materializers. 1473 for (auto &EDO : ExistingDefsOverridden) { 1474 assert(EDO.ExistingDefItr->second.getFlags().isLazy() && 1475 !EDO.ExistingDefItr->second.getFlags().isMaterializing() && 1476 "Overridden existing def should be in the Lazy state"); 1477 1478 EDO.ExistingDefItr->second.setFlags(EDO.NewFlags); 1479 1480 auto UMII = UnmaterializedInfos.find(EDO.ExistingDefItr->first); 1481 assert(UMII != UnmaterializedInfos.end() && 1482 "Overridden existing def should have an UnmaterializedInfo"); 1483 1484 UMII->second->MU->doDiscard(*this, EDO.ExistingDefItr->first); 1485 } 1486 1487 // Discard overridden symbols povided by MU. 1488 for (auto &Sym : MUDefsOverridden) 1489 MU.doDiscard(*this, Sym); 1490 1491 return Error::success(); 1492 } 1493 1494 void JITDylib::detachQueryHelper(AsynchronousSymbolQuery &Q, 1495 const SymbolNameSet &QuerySymbols) { 1496 for (auto &QuerySymbol : QuerySymbols) { 1497 assert(MaterializingInfos.count(QuerySymbol) && 1498 "QuerySymbol does not have MaterializingInfo"); 1499 auto &MI = MaterializingInfos[QuerySymbol]; 1500 1501 auto IdenticalQuery = 1502 [&](const std::shared_ptr<AsynchronousSymbolQuery> &R) { 1503 return R.get() == &Q; 1504 }; 1505 1506 auto I = std::find_if(MI.PendingQueries.begin(), MI.PendingQueries.end(), 1507 IdenticalQuery); 1508 assert(I != MI.PendingQueries.end() && 1509 "Query Q should be in the PendingQueries list for QuerySymbol"); 1510 MI.PendingQueries.erase(I); 1511 } 1512 } 1513 1514 void JITDylib::transferEmittedNodeDependencies( 1515 MaterializingInfo &DependantMI, const SymbolStringPtr &DependantName, 1516 MaterializingInfo &EmittedMI) { 1517 for (auto &KV : EmittedMI.UnemittedDependencies) { 1518 auto &DependencyJD = *KV.first; 1519 SymbolNameSet *UnemittedDependenciesOnDependencyJD = nullptr; 1520 1521 for (auto &DependencyName : KV.second) { 1522 auto &DependencyMI = DependencyJD.MaterializingInfos[DependencyName]; 1523 1524 // Do not add self dependencies. 1525 if (&DependencyMI == &DependantMI) 1526 continue; 1527 1528 // If we haven't looked up the dependencies for DependencyJD yet, do it 1529 // now and cache the result. 1530 if (!UnemittedDependenciesOnDependencyJD) 1531 UnemittedDependenciesOnDependencyJD = 1532 &DependantMI.UnemittedDependencies[&DependencyJD]; 1533 1534 DependencyMI.Dependants[this].insert(DependantName); 1535 UnemittedDependenciesOnDependencyJD->insert(DependencyName); 1536 } 1537 } 1538 } 1539 1540 ExecutionSession::ExecutionSession(std::shared_ptr<SymbolStringPool> SSP) 1541 : SSP(SSP ? std::move(SSP) : std::make_shared<SymbolStringPool>()) { 1542 // Construct the main dylib. 1543 JDs.push_back(std::unique_ptr<JITDylib>(new JITDylib(*this, "<main>"))); 1544 } 1545 1546 JITDylib &ExecutionSession::getMainJITDylib() { 1547 return runSessionLocked([this]() -> JITDylib & { return *JDs.front(); }); 1548 } 1549 1550 JITDylib &ExecutionSession::createJITDylib(std::string Name, 1551 bool AddToMainDylibSearchOrder) { 1552 return runSessionLocked([&, this]() -> JITDylib & { 1553 JDs.push_back( 1554 std::unique_ptr<JITDylib>(new JITDylib(*this, std::move(Name)))); 1555 if (AddToMainDylibSearchOrder) 1556 JDs.front()->addToSearchOrder(*JDs.back()); 1557 return *JDs.back(); 1558 }); 1559 } 1560 1561 void ExecutionSession::legacyFailQuery(AsynchronousSymbolQuery &Q, Error Err) { 1562 assert(!!Err && "Error should be in failure state"); 1563 1564 bool SendErrorToQuery; 1565 runSessionLocked([&]() { 1566 Q.detach(); 1567 SendErrorToQuery = Q.canStillFail(); 1568 }); 1569 1570 if (SendErrorToQuery) 1571 Q.handleFailed(std::move(Err)); 1572 else 1573 reportError(std::move(Err)); 1574 } 1575 1576 Expected<SymbolMap> ExecutionSession::legacyLookup( 1577 LegacyAsyncLookupFunction AsyncLookup, SymbolNameSet Names, 1578 bool WaitUntilReady, RegisterDependenciesFunction RegisterDependencies) { 1579 #if LLVM_ENABLE_THREADS 1580 // In the threaded case we use promises to return the results. 1581 std::promise<SymbolMap> PromisedResult; 1582 std::mutex ErrMutex; 1583 Error ResolutionError = Error::success(); 1584 std::promise<void> PromisedReady; 1585 Error ReadyError = Error::success(); 1586 auto OnResolve = [&](Expected<SymbolMap> R) { 1587 if (R) 1588 PromisedResult.set_value(std::move(*R)); 1589 else { 1590 { 1591 ErrorAsOutParameter _(&ResolutionError); 1592 std::lock_guard<std::mutex> Lock(ErrMutex); 1593 ResolutionError = R.takeError(); 1594 } 1595 PromisedResult.set_value(SymbolMap()); 1596 } 1597 }; 1598 1599 std::function<void(Error)> OnReady; 1600 if (WaitUntilReady) { 1601 OnReady = [&](Error Err) { 1602 if (Err) { 1603 ErrorAsOutParameter _(&ReadyError); 1604 std::lock_guard<std::mutex> Lock(ErrMutex); 1605 ReadyError = std::move(Err); 1606 } 1607 PromisedReady.set_value(); 1608 }; 1609 } else { 1610 OnReady = [&](Error Err) { 1611 if (Err) 1612 reportError(std::move(Err)); 1613 }; 1614 } 1615 1616 #else 1617 SymbolMap Result; 1618 Error ResolutionError = Error::success(); 1619 Error ReadyError = Error::success(); 1620 1621 auto OnResolve = [&](Expected<SymbolMap> R) { 1622 ErrorAsOutParameter _(&ResolutionError); 1623 if (R) 1624 Result = std::move(*R); 1625 else 1626 ResolutionError = R.takeError(); 1627 }; 1628 1629 std::function<void(Error)> OnReady; 1630 if (WaitUntilReady) { 1631 OnReady = [&](Error Err) { 1632 ErrorAsOutParameter _(&ReadyError); 1633 if (Err) 1634 ReadyError = std::move(Err); 1635 }; 1636 } else { 1637 OnReady = [&](Error Err) { 1638 if (Err) 1639 reportError(std::move(Err)); 1640 }; 1641 } 1642 #endif 1643 1644 auto Query = std::make_shared<AsynchronousSymbolQuery>( 1645 Names, std::move(OnResolve), std::move(OnReady)); 1646 // FIXME: This should be run session locked along with the registration code 1647 // and error reporting below. 1648 SymbolNameSet UnresolvedSymbols = AsyncLookup(Query, std::move(Names)); 1649 1650 // If the query was lodged successfully then register the dependencies, 1651 // otherwise fail it with an error. 1652 if (UnresolvedSymbols.empty()) 1653 RegisterDependencies(Query->QueryRegistrations); 1654 else { 1655 bool DeliverError = runSessionLocked([&]() { 1656 Query->detach(); 1657 return Query->canStillFail(); 1658 }); 1659 auto Err = make_error<SymbolsNotFound>(std::move(UnresolvedSymbols)); 1660 if (DeliverError) 1661 Query->handleFailed(std::move(Err)); 1662 else 1663 reportError(std::move(Err)); 1664 } 1665 1666 #if LLVM_ENABLE_THREADS 1667 auto ResultFuture = PromisedResult.get_future(); 1668 auto Result = ResultFuture.get(); 1669 1670 { 1671 std::lock_guard<std::mutex> Lock(ErrMutex); 1672 if (ResolutionError) { 1673 // ReadyError will never be assigned. Consume the success value. 1674 cantFail(std::move(ReadyError)); 1675 return std::move(ResolutionError); 1676 } 1677 } 1678 1679 if (WaitUntilReady) { 1680 auto ReadyFuture = PromisedReady.get_future(); 1681 ReadyFuture.get(); 1682 1683 { 1684 std::lock_guard<std::mutex> Lock(ErrMutex); 1685 if (ReadyError) 1686 return std::move(ReadyError); 1687 } 1688 } else 1689 cantFail(std::move(ReadyError)); 1690 1691 return std::move(Result); 1692 1693 #else 1694 if (ResolutionError) { 1695 // ReadyError will never be assigned. Consume the success value. 1696 cantFail(std::move(ReadyError)); 1697 return std::move(ResolutionError); 1698 } 1699 1700 if (ReadyError) 1701 return std::move(ReadyError); 1702 1703 return Result; 1704 #endif 1705 } 1706 1707 void ExecutionSession::lookup(const JITDylibList &JDs, SymbolNameSet Symbols, 1708 SymbolsResolvedCallback OnResolve, 1709 SymbolsReadyCallback OnReady, 1710 RegisterDependenciesFunction RegisterDependencies, 1711 JITDylib *MatchNonExportedInJD, 1712 bool MatchNonExported) { 1713 1714 // lookup can be re-entered recursively if running on a single thread. Run any 1715 // outstanding MUs in case this query depends on them, otherwise this lookup 1716 // will starve waiting for a result from an MU that is stuck in the queue. 1717 runOutstandingMUs(); 1718 1719 auto Unresolved = std::move(Symbols); 1720 std::map<JITDylib *, MaterializationUnitList> CollectedMUsMap; 1721 auto Q = std::make_shared<AsynchronousSymbolQuery>( 1722 Unresolved, std::move(OnResolve), std::move(OnReady)); 1723 bool QueryIsFullyResolved = false; 1724 bool QueryIsFullyReady = false; 1725 bool QueryFailed = false; 1726 1727 runSessionLocked([&]() { 1728 for (auto *JD : JDs) { 1729 assert(JD && "JITDylibList entries must not be null"); 1730 assert(!CollectedMUsMap.count(JD) && 1731 "JITDylibList should not contain duplicate entries"); 1732 JD->lodgeQuery(Q, Unresolved, MatchNonExportedInJD, MatchNonExported, 1733 CollectedMUsMap[JD]); 1734 } 1735 1736 if (Unresolved.empty()) { 1737 // Query lodged successfully. 1738 1739 // Record whether this query is fully ready / resolved. We will use 1740 // this to call handleFullyResolved/handleFullyReady outside the session 1741 // lock. 1742 QueryIsFullyResolved = Q->isFullyResolved(); 1743 QueryIsFullyReady = Q->isFullyReady(); 1744 1745 // Call the register dependencies function. 1746 if (RegisterDependencies && !Q->QueryRegistrations.empty()) 1747 RegisterDependencies(Q->QueryRegistrations); 1748 } else { 1749 // Query failed due to unresolved symbols. 1750 QueryFailed = true; 1751 1752 // Disconnect the query from its dependencies. 1753 Q->detach(); 1754 1755 // Replace the MUs. 1756 for (auto &KV : CollectedMUsMap) 1757 for (auto &MU : KV.second) 1758 KV.first->replace(std::move(MU)); 1759 } 1760 }); 1761 1762 if (QueryFailed) { 1763 Q->handleFailed(make_error<SymbolsNotFound>(std::move(Unresolved))); 1764 return; 1765 } else { 1766 if (QueryIsFullyResolved) 1767 Q->handleFullyResolved(); 1768 if (QueryIsFullyReady) 1769 Q->handleFullyReady(); 1770 } 1771 1772 // Move the MUs to the OutstandingMUs list, then materialize. 1773 { 1774 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1775 1776 for (auto &KV : CollectedMUsMap) 1777 for (auto &MU : KV.second) 1778 OutstandingMUs.push_back(std::make_pair(KV.first, std::move(MU))); 1779 } 1780 1781 runOutstandingMUs(); 1782 } 1783 1784 Expected<SymbolMap> 1785 ExecutionSession::lookup(const JITDylibList &JDs, const SymbolNameSet &Symbols, 1786 RegisterDependenciesFunction RegisterDependencies, 1787 bool WaitUntilReady, JITDylib *MatchNonExportedInJD, 1788 bool MatchNonExported) { 1789 #if LLVM_ENABLE_THREADS 1790 // In the threaded case we use promises to return the results. 1791 std::promise<SymbolMap> PromisedResult; 1792 std::mutex ErrMutex; 1793 Error ResolutionError = Error::success(); 1794 std::promise<void> PromisedReady; 1795 Error ReadyError = Error::success(); 1796 auto OnResolve = [&](Expected<SymbolMap> R) { 1797 if (R) 1798 PromisedResult.set_value(std::move(*R)); 1799 else { 1800 { 1801 ErrorAsOutParameter _(&ResolutionError); 1802 std::lock_guard<std::mutex> Lock(ErrMutex); 1803 ResolutionError = R.takeError(); 1804 } 1805 PromisedResult.set_value(SymbolMap()); 1806 } 1807 }; 1808 1809 std::function<void(Error)> OnReady; 1810 if (WaitUntilReady) { 1811 OnReady = [&](Error Err) { 1812 if (Err) { 1813 ErrorAsOutParameter _(&ReadyError); 1814 std::lock_guard<std::mutex> Lock(ErrMutex); 1815 ReadyError = std::move(Err); 1816 } 1817 PromisedReady.set_value(); 1818 }; 1819 } else { 1820 OnReady = [&](Error Err) { 1821 if (Err) 1822 reportError(std::move(Err)); 1823 }; 1824 } 1825 1826 #else 1827 SymbolMap Result; 1828 Error ResolutionError = Error::success(); 1829 Error ReadyError = Error::success(); 1830 1831 auto OnResolve = [&](Expected<SymbolMap> R) { 1832 ErrorAsOutParameter _(&ResolutionError); 1833 if (R) 1834 Result = std::move(*R); 1835 else 1836 ResolutionError = R.takeError(); 1837 }; 1838 1839 std::function<void(Error)> OnReady; 1840 if (WaitUntilReady) { 1841 OnReady = [&](Error Err) { 1842 ErrorAsOutParameter _(&ReadyError); 1843 if (Err) 1844 ReadyError = std::move(Err); 1845 }; 1846 } else { 1847 OnReady = [&](Error Err) { 1848 if (Err) 1849 reportError(std::move(Err)); 1850 }; 1851 } 1852 #endif 1853 1854 // Perform the asynchronous lookup. 1855 lookup(JDs, Symbols, OnResolve, OnReady, RegisterDependencies, 1856 MatchNonExportedInJD, MatchNonExported); 1857 1858 #if LLVM_ENABLE_THREADS 1859 auto ResultFuture = PromisedResult.get_future(); 1860 auto Result = ResultFuture.get(); 1861 1862 { 1863 std::lock_guard<std::mutex> Lock(ErrMutex); 1864 if (ResolutionError) { 1865 // ReadyError will never be assigned. Consume the success value. 1866 cantFail(std::move(ReadyError)); 1867 return std::move(ResolutionError); 1868 } 1869 } 1870 1871 if (WaitUntilReady) { 1872 auto ReadyFuture = PromisedReady.get_future(); 1873 ReadyFuture.get(); 1874 1875 { 1876 std::lock_guard<std::mutex> Lock(ErrMutex); 1877 if (ReadyError) 1878 return std::move(ReadyError); 1879 } 1880 } else 1881 cantFail(std::move(ReadyError)); 1882 1883 return std::move(Result); 1884 1885 #else 1886 if (ResolutionError) { 1887 // ReadyError will never be assigned. Consume the success value. 1888 cantFail(std::move(ReadyError)); 1889 return std::move(ResolutionError); 1890 } 1891 1892 if (ReadyError) 1893 return std::move(ReadyError); 1894 1895 return Result; 1896 #endif 1897 } 1898 1899 /// Look up a symbol by searching a list of JDs. 1900 Expected<JITEvaluatedSymbol> ExecutionSession::lookup(const JITDylibList &JDs, 1901 SymbolStringPtr Name, 1902 bool MatchNonExported) { 1903 SymbolNameSet Names({Name}); 1904 1905 if (auto ResultMap = lookup(JDs, std::move(Names), NoDependenciesToRegister, 1906 true, nullptr, MatchNonExported)) { 1907 assert(ResultMap->size() == 1 && "Unexpected number of results"); 1908 assert(ResultMap->count(Name) && "Missing result for symbol"); 1909 return std::move(ResultMap->begin()->second); 1910 } else 1911 return ResultMap.takeError(); 1912 } 1913 1914 Expected<JITEvaluatedSymbol> ExecutionSession::lookup(const JITDylibList &JDs, 1915 StringRef Name, 1916 bool MatchNonExported) { 1917 return lookup(JDs, intern(Name), MatchNonExported); 1918 } 1919 1920 void ExecutionSession::dump(raw_ostream &OS) { 1921 runSessionLocked([this, &OS]() { 1922 for (auto &JD : JDs) 1923 JD->dump(OS); 1924 }); 1925 } 1926 1927 void ExecutionSession::runOutstandingMUs() { 1928 while (1) { 1929 std::pair<JITDylib *, std::unique_ptr<MaterializationUnit>> JITDylibAndMU; 1930 1931 { 1932 std::lock_guard<std::recursive_mutex> Lock(OutstandingMUsMutex); 1933 if (!OutstandingMUs.empty()) { 1934 JITDylibAndMU = std::move(OutstandingMUs.back()); 1935 OutstandingMUs.pop_back(); 1936 } 1937 } 1938 1939 if (JITDylibAndMU.first) { 1940 assert(JITDylibAndMU.second && "JITDylib, but no MU?"); 1941 dispatchMaterialization(*JITDylibAndMU.first, 1942 std::move(JITDylibAndMU.second)); 1943 } else 1944 break; 1945 } 1946 } 1947 1948 MangleAndInterner::MangleAndInterner(ExecutionSession &ES, const DataLayout &DL) 1949 : ES(ES), DL(DL) {} 1950 1951 SymbolStringPtr MangleAndInterner::operator()(StringRef Name) { 1952 std::string MangledName; 1953 { 1954 raw_string_ostream MangledNameStream(MangledName); 1955 Mangler::getNameWithPrefix(MangledNameStream, Name, DL); 1956 } 1957 return ES.intern(MangledName); 1958 } 1959 1960 } // End namespace orc. 1961 } // End namespace llvm. 1962