1 //===-- ClangASTSource.cpp ---------------------------------------*- 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 #include "ClangASTSource.h" 10 11 #include "ASTDumper.h" 12 #include "ClangDeclVendor.h" 13 #include "ClangModulesDeclVendor.h" 14 15 #include "lldb/Core/Module.h" 16 #include "lldb/Core/ModuleList.h" 17 #include "lldb/Symbol/ClangASTContext.h" 18 #include "lldb/Symbol/ClangUtil.h" 19 #include "lldb/Symbol/CompilerDeclContext.h" 20 #include "lldb/Symbol/Function.h" 21 #include "lldb/Symbol/SymbolFile.h" 22 #include "lldb/Symbol/TaggedASTType.h" 23 #include "lldb/Target/Target.h" 24 #include "lldb/Utility/Log.h" 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/RecordLayout.h" 27 28 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" 29 30 #include <memory> 31 #include <vector> 32 33 using namespace clang; 34 using namespace lldb_private; 35 36 // Scoped class that will remove an active lexical decl from the set when it 37 // goes out of scope. 38 namespace { 39 class ScopedLexicalDeclEraser { 40 public: 41 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls, 42 const clang::Decl *decl) 43 : m_active_lexical_decls(decls), m_decl(decl) {} 44 45 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); } 46 47 private: 48 std::set<const clang::Decl *> &m_active_lexical_decls; 49 const clang::Decl *m_decl; 50 }; 51 } 52 53 ClangASTSource::ClangASTSource(const lldb::TargetSP &target) 54 : m_import_in_progress(false), m_lookups_enabled(false), m_target(target), 55 m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() { 56 if (!target->GetUseModernTypeLookup()) { 57 m_ast_importer_sp = m_target->GetClangASTImporter(); 58 } 59 } 60 61 void ClangASTSource::InstallASTContext(clang::ASTContext &ast_context, 62 clang::FileManager &file_manager, 63 bool is_shared_context) { 64 m_ast_context = &ast_context; 65 m_file_manager = &file_manager; 66 if (m_target->GetUseModernTypeLookup()) { 67 // Configure the ExternalASTMerger. The merger needs to be able to import 68 // types from any source that we would do lookups in, which includes the 69 // persistent AST context as well as the modules and Objective-C runtime 70 // AST contexts. 71 72 lldbassert(!m_merger_up); 73 clang::ExternalASTMerger::ImporterTarget target = {ast_context, 74 file_manager}; 75 std::vector<clang::ExternalASTMerger::ImporterSource> sources; 76 for (lldb::ModuleSP module_sp : m_target->GetImages().Modules()) { 77 auto type_system_or_err = 78 module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeC); 79 if (auto err = type_system_or_err.takeError()) { 80 LLDB_LOG_ERROR( 81 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS), 82 std::move(err), "Failed to get ClangASTContext"); 83 } else if (auto *module_ast_ctx = llvm::cast_or_null<ClangASTContext>( 84 &type_system_or_err.get())) { 85 lldbassert(module_ast_ctx->getASTContext()); 86 lldbassert(module_ast_ctx->getFileManager()); 87 sources.push_back({*module_ast_ctx->getASTContext(), 88 *module_ast_ctx->getFileManager(), 89 module_ast_ctx->GetOriginMap()}); 90 } 91 } 92 93 do { 94 lldb::ProcessSP process(m_target->GetProcessSP()); 95 96 if (!process) 97 break; 98 99 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 100 101 if (!language_runtime) 102 break; 103 104 if (auto *runtime_decl_vendor = llvm::dyn_cast_or_null<ClangDeclVendor>( 105 language_runtime->GetDeclVendor())) { 106 sources.push_back(runtime_decl_vendor->GetImporterSource()); 107 } 108 } while (false); 109 110 do { 111 auto *modules_decl_vendor = m_target->GetClangModulesDeclVendor(); 112 113 if (!modules_decl_vendor) 114 break; 115 116 sources.push_back(modules_decl_vendor->GetImporterSource()); 117 } while (false); 118 119 if (!is_shared_context) { 120 // Update the scratch AST context's merger to reflect any new sources we 121 // might have come across since the last time an expression was parsed. 122 123 auto scratch_ast_context = static_cast<ClangASTContextForExpressions*>( 124 m_target->GetScratchClangASTContext()); 125 126 scratch_ast_context->GetMergerUnchecked().AddSources(sources); 127 128 sources.push_back({*scratch_ast_context->getASTContext(), 129 *scratch_ast_context->getFileManager(), 130 scratch_ast_context->GetOriginMap()}); 131 } 132 while (false) 133 ; 134 135 m_merger_up = 136 std::make_unique<clang::ExternalASTMerger>(target, sources); 137 } else { 138 m_ast_importer_sp->InstallMapCompleter(&ast_context, *this); 139 } 140 } 141 142 ClangASTSource::~ClangASTSource() { 143 if (m_ast_importer_sp) 144 m_ast_importer_sp->ForgetDestination(m_ast_context); 145 146 // We are in the process of destruction, don't create clang ast context on 147 // demand by passing false to 148 // Target::GetScratchClangASTContext(create_on_demand). 149 ClangASTContext *scratch_clang_ast_context = 150 m_target->GetScratchClangASTContext(false); 151 152 if (!scratch_clang_ast_context) 153 return; 154 155 clang::ASTContext *scratch_ast_context = 156 scratch_clang_ast_context->getASTContext(); 157 158 if (!scratch_ast_context) 159 return; 160 161 if (m_ast_context != scratch_ast_context && m_ast_importer_sp) 162 m_ast_importer_sp->ForgetSource(scratch_ast_context, m_ast_context); 163 } 164 165 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) { 166 if (!m_ast_context) 167 return; 168 169 m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage(); 170 m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage(); 171 } 172 173 // The core lookup interface. 174 bool ClangASTSource::FindExternalVisibleDeclsByName( 175 const DeclContext *decl_ctx, DeclarationName clang_decl_name) { 176 if (!m_ast_context) { 177 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 178 return false; 179 } 180 181 if (GetImportInProgress()) { 182 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 183 return false; 184 } 185 186 std::string decl_name(clang_decl_name.getAsString()); 187 188 // if (m_decl_map.DoingASTImport ()) 189 // return DeclContext::lookup_result(); 190 // 191 switch (clang_decl_name.getNameKind()) { 192 // Normal identifiers. 193 case DeclarationName::Identifier: { 194 clang::IdentifierInfo *identifier_info = 195 clang_decl_name.getAsIdentifierInfo(); 196 197 if (!identifier_info || identifier_info->getBuiltinID() != 0) { 198 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 199 return false; 200 } 201 } break; 202 203 // Operator names. 204 case DeclarationName::CXXOperatorName: 205 case DeclarationName::CXXLiteralOperatorName: 206 break; 207 208 // Using directives found in this context. 209 // Tell Sema we didn't find any or we'll end up getting asked a *lot*. 210 case DeclarationName::CXXUsingDirective: 211 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 212 return false; 213 214 case DeclarationName::ObjCZeroArgSelector: 215 case DeclarationName::ObjCOneArgSelector: 216 case DeclarationName::ObjCMultiArgSelector: { 217 llvm::SmallVector<NamedDecl *, 1> method_decls; 218 219 NameSearchContext method_search_context(*this, method_decls, 220 clang_decl_name, decl_ctx); 221 222 FindObjCMethodDecls(method_search_context); 223 224 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls); 225 return (method_decls.size() > 0); 226 } 227 // These aren't possible in the global context. 228 case DeclarationName::CXXConstructorName: 229 case DeclarationName::CXXDestructorName: 230 case DeclarationName::CXXConversionFunctionName: 231 case DeclarationName::CXXDeductionGuideName: 232 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 233 return false; 234 } 235 236 if (!GetLookupsEnabled()) { 237 // Wait until we see a '$' at the start of a name before we start doing any 238 // lookups so we can avoid lookup up all of the builtin types. 239 if (!decl_name.empty() && decl_name[0] == '$') { 240 SetLookupsEnabled(true); 241 } else { 242 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 243 return false; 244 } 245 } 246 247 ConstString const_decl_name(decl_name.c_str()); 248 249 const char *uniqued_const_decl_name = const_decl_name.GetCString(); 250 if (m_active_lookups.find(uniqued_const_decl_name) != 251 m_active_lookups.end()) { 252 // We are currently looking up this name... 253 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name); 254 return false; 255 } 256 m_active_lookups.insert(uniqued_const_decl_name); 257 // static uint32_t g_depth = 0; 258 // ++g_depth; 259 // printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth, 260 // uniqued_const_decl_name); 261 llvm::SmallVector<NamedDecl *, 4> name_decls; 262 NameSearchContext name_search_context(*this, name_decls, clang_decl_name, 263 decl_ctx); 264 FindExternalVisibleDecls(name_search_context); 265 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls); 266 // --g_depth; 267 m_active_lookups.erase(uniqued_const_decl_name); 268 return (name_decls.size() != 0); 269 } 270 271 void ClangASTSource::CompleteType(TagDecl *tag_decl) { 272 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 273 274 static unsigned int invocation_id = 0; 275 unsigned int current_id = invocation_id++; 276 277 if (log) { 278 LLDB_LOGF(log, 279 " CompleteTagDecl[%u] on (ASTContext*)%p Completing " 280 "(TagDecl*)%p named %s", 281 current_id, static_cast<void *>(m_ast_context), 282 static_cast<void *>(tag_decl), tag_decl->getName().str().c_str()); 283 284 LLDB_LOGF(log, " CTD[%u] Before:", current_id); 285 ASTDumper dumper((Decl *)tag_decl); 286 dumper.ToLog(log, " [CTD] "); 287 } 288 289 auto iter = m_active_lexical_decls.find(tag_decl); 290 if (iter != m_active_lexical_decls.end()) 291 return; 292 m_active_lexical_decls.insert(tag_decl); 293 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl); 294 295 if (!m_ast_importer_sp) { 296 if (HasMerger()) { 297 GetMergerUnchecked().CompleteType(tag_decl); 298 } 299 return; 300 } 301 302 if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) { 303 // We couldn't complete the type. Maybe there's a definition somewhere 304 // else that can be completed. 305 306 LLDB_LOGF(log, 307 " CTD[%u] Type could not be completed in the module in " 308 "which it was first found.", 309 current_id); 310 311 bool found = false; 312 313 DeclContext *decl_ctx = tag_decl->getDeclContext(); 314 315 if (const NamespaceDecl *namespace_context = 316 dyn_cast<NamespaceDecl>(decl_ctx)) { 317 ClangASTImporter::NamespaceMapSP namespace_map = 318 m_ast_importer_sp->GetNamespaceMap(namespace_context); 319 320 if (log && log->GetVerbose()) 321 LLDB_LOGF(log, " CTD[%u] Inspecting namespace map %p (%d entries)", 322 current_id, static_cast<void *>(namespace_map.get()), 323 static_cast<int>(namespace_map->size())); 324 325 if (!namespace_map) 326 return; 327 328 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), 329 e = namespace_map->end(); 330 i != e && !found; ++i) { 331 LLDB_LOGF(log, " CTD[%u] Searching namespace %s in module %s", 332 current_id, i->second.GetName().AsCString(), 333 i->first->GetFileSpec().GetFilename().GetCString()); 334 335 TypeList types; 336 337 ConstString name(tag_decl->getName().str().c_str()); 338 339 i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types); 340 341 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { 342 lldb::TypeSP type = types.GetTypeAtIndex(ti); 343 344 if (!type) 345 continue; 346 347 CompilerType clang_type(type->GetFullCompilerType()); 348 349 if (!ClangUtil::IsClangType(clang_type)) 350 continue; 351 352 const TagType *tag_type = 353 ClangUtil::GetQualType(clang_type)->getAs<TagType>(); 354 355 if (!tag_type) 356 continue; 357 358 TagDecl *candidate_tag_decl = 359 const_cast<TagDecl *>(tag_type->getDecl()); 360 361 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, 362 candidate_tag_decl)) 363 found = true; 364 } 365 } 366 } else { 367 TypeList types; 368 369 ConstString name(tag_decl->getName().str().c_str()); 370 CompilerDeclContext namespace_decl; 371 372 const ModuleList &module_list = m_target->GetImages(); 373 374 bool exact_match = false; 375 llvm::DenseSet<SymbolFile *> searched_symbol_files; 376 module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX, 377 searched_symbol_files, types); 378 379 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) { 380 lldb::TypeSP type = types.GetTypeAtIndex(ti); 381 382 if (!type) 383 continue; 384 385 CompilerType clang_type(type->GetFullCompilerType()); 386 387 if (!ClangUtil::IsClangType(clang_type)) 388 continue; 389 390 const TagType *tag_type = 391 ClangUtil::GetQualType(clang_type)->getAs<TagType>(); 392 393 if (!tag_type) 394 continue; 395 396 TagDecl *candidate_tag_decl = 397 const_cast<TagDecl *>(tag_type->getDecl()); 398 399 // We have found a type by basename and we need to make sure the decl 400 // contexts are the same before we can try to complete this type with 401 // another 402 if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl)) 403 continue; 404 405 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, 406 candidate_tag_decl)) 407 found = true; 408 } 409 } 410 } 411 412 if (log) { 413 LLDB_LOGF(log, " [CTD] After:"); 414 ASTDumper dumper((Decl *)tag_decl); 415 dumper.ToLog(log, " [CTD] "); 416 } 417 } 418 419 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) { 420 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 421 422 if (log) { 423 LLDB_LOGF(log, 424 " [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing " 425 "an ObjCInterfaceDecl named %s", 426 static_cast<void *>(m_ast_context), 427 interface_decl->getName().str().c_str()); 428 LLDB_LOGF(log, " [COID] Before:"); 429 ASTDumper dumper((Decl *)interface_decl); 430 dumper.ToLog(log, " [COID] "); 431 } 432 433 if (!m_ast_importer_sp) { 434 if (HasMerger()) { 435 ObjCInterfaceDecl *complete_iface_decl = 436 GetCompleteObjCInterface(interface_decl); 437 438 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 439 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 440 } 441 442 GetMergerUnchecked().CompleteType(interface_decl); 443 } else { 444 lldbassert(0 && "No mechanism for completing a type!"); 445 } 446 return; 447 } 448 449 Decl *original_decl = nullptr; 450 ASTContext *original_ctx = nullptr; 451 452 if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, 453 &original_ctx)) { 454 if (ObjCInterfaceDecl *original_iface_decl = 455 dyn_cast<ObjCInterfaceDecl>(original_decl)) { 456 ObjCInterfaceDecl *complete_iface_decl = 457 GetCompleteObjCInterface(original_iface_decl); 458 459 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { 460 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl); 461 } 462 } 463 } 464 465 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl); 466 467 if (interface_decl->getSuperClass() && 468 interface_decl->getSuperClass() != interface_decl) 469 CompleteType(interface_decl->getSuperClass()); 470 471 if (log) { 472 LLDB_LOGF(log, " [COID] After:"); 473 ASTDumper dumper((Decl *)interface_decl); 474 dumper.ToLog(log, " [COID] "); 475 } 476 } 477 478 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface( 479 const clang::ObjCInterfaceDecl *interface_decl) { 480 lldb::ProcessSP process(m_target->GetProcessSP()); 481 482 if (!process) 483 return nullptr; 484 485 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 486 487 if (!language_runtime) 488 return nullptr; 489 490 ConstString class_name(interface_decl->getNameAsString().c_str()); 491 492 lldb::TypeSP complete_type_sp( 493 language_runtime->LookupInCompleteClassCache(class_name)); 494 495 if (!complete_type_sp) 496 return nullptr; 497 498 TypeFromUser complete_type = 499 TypeFromUser(complete_type_sp->GetFullCompilerType()); 500 lldb::opaque_compiler_type_t complete_opaque_type = 501 complete_type.GetOpaqueQualType(); 502 503 if (!complete_opaque_type) 504 return nullptr; 505 506 const clang::Type *complete_clang_type = 507 QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr(); 508 const ObjCInterfaceType *complete_interface_type = 509 dyn_cast<ObjCInterfaceType>(complete_clang_type); 510 511 if (!complete_interface_type) 512 return nullptr; 513 514 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl()); 515 516 return complete_iface_decl; 517 } 518 519 void ClangASTSource::FindExternalLexicalDecls( 520 const DeclContext *decl_context, 521 llvm::function_ref<bool(Decl::Kind)> predicate, 522 llvm::SmallVectorImpl<Decl *> &decls) { 523 524 if (HasMerger()) { 525 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl_context)) { 526 ObjCInterfaceDecl *complete_iface_decl = 527 GetCompleteObjCInterface(interface_decl); 528 529 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 530 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 531 } 532 } 533 return GetMergerUnchecked().FindExternalLexicalDecls(decl_context, 534 predicate, 535 decls); 536 } else if (!m_ast_importer_sp) 537 return; 538 539 ClangASTMetrics::RegisterLexicalQuery(); 540 541 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 542 543 const Decl *context_decl = dyn_cast<Decl>(decl_context); 544 545 if (!context_decl) 546 return; 547 548 auto iter = m_active_lexical_decls.find(context_decl); 549 if (iter != m_active_lexical_decls.end()) 550 return; 551 m_active_lexical_decls.insert(context_decl); 552 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl); 553 554 static unsigned int invocation_id = 0; 555 unsigned int current_id = invocation_id++; 556 557 if (log) { 558 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl)) 559 LLDB_LOGF( 560 log, 561 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p", 562 current_id, static_cast<void *>(m_ast_context), 563 context_named_decl->getNameAsString().c_str(), 564 context_decl->getDeclKindName(), 565 static_cast<const void *>(context_decl)); 566 else if (context_decl) 567 LLDB_LOGF( 568 log, "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p", 569 current_id, static_cast<void *>(m_ast_context), 570 context_decl->getDeclKindName(), 571 static_cast<const void *>(context_decl)); 572 else 573 LLDB_LOGF( 574 log, 575 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context", 576 current_id, static_cast<const void *>(m_ast_context)); 577 } 578 579 Decl *original_decl = nullptr; 580 ASTContext *original_ctx = nullptr; 581 582 if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl, 583 &original_ctx)) 584 return; 585 586 if (log) { 587 LLDB_LOGF( 588 log, " FELD[%u] Original decl (ASTContext*)%p (Decl*)%p:", current_id, 589 static_cast<void *>(original_ctx), static_cast<void *>(original_decl)); 590 ASTDumper(original_decl).ToLog(log, " "); 591 } 592 593 if (ObjCInterfaceDecl *original_iface_decl = 594 dyn_cast<ObjCInterfaceDecl>(original_decl)) { 595 ObjCInterfaceDecl *complete_iface_decl = 596 GetCompleteObjCInterface(original_iface_decl); 597 598 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) { 599 original_decl = complete_iface_decl; 600 original_ctx = &complete_iface_decl->getASTContext(); 601 602 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl); 603 } 604 } 605 606 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl)) { 607 ExternalASTSource *external_source = original_ctx->getExternalSource(); 608 609 if (external_source) 610 external_source->CompleteType(original_tag_decl); 611 } 612 613 const DeclContext *original_decl_context = 614 dyn_cast<DeclContext>(original_decl); 615 616 if (!original_decl_context) 617 return; 618 619 // Indicates whether we skipped any Decls of the original DeclContext. 620 bool SkippedDecls = false; 621 for (TagDecl::decl_iterator iter = original_decl_context->decls_begin(); 622 iter != original_decl_context->decls_end(); ++iter) { 623 Decl *decl = *iter; 624 625 // The predicate function returns true if the passed declaration kind is 626 // the one we are looking for. 627 // See clang::ExternalASTSource::FindExternalLexicalDecls() 628 if (predicate(decl->getKind())) { 629 if (log) { 630 ASTDumper ast_dumper(decl); 631 if (const NamedDecl *context_named_decl = 632 dyn_cast<NamedDecl>(context_decl)) 633 LLDB_LOGF(log, " FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s", 634 current_id, context_named_decl->getDeclKindName(), 635 context_named_decl->getNameAsString().c_str(), 636 decl->getDeclKindName(), ast_dumper.GetCString()); 637 else 638 LLDB_LOGF(log, " FELD[%d] Adding lexical %sDecl %s", current_id, 639 decl->getDeclKindName(), ast_dumper.GetCString()); 640 } 641 642 Decl *copied_decl = CopyDecl(decl); 643 644 if (!copied_decl) 645 continue; 646 647 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) { 648 QualType copied_field_type = copied_field->getType(); 649 650 m_ast_importer_sp->RequireCompleteType(copied_field_type); 651 } 652 auto decl_context_non_const = const_cast<DeclContext *>(decl_context); 653 654 // The decl ended up in the wrong DeclContext. Let's fix that so 655 // the decl we copied will actually be found. 656 // FIXME: This is a horrible hack that shouldn't be necessary. However 657 // it seems our current setup sometimes fails to copy decls to the right 658 // place. See rdar://55129537. 659 if (copied_decl->getDeclContext() != decl_context) { 660 assert(copied_decl->getDeclContext()->containsDecl(copied_decl)); 661 copied_decl->getDeclContext()->removeDecl(copied_decl); 662 copied_decl->setDeclContext(decl_context_non_const); 663 assert(!decl_context_non_const->containsDecl(copied_decl)); 664 decl_context_non_const->addDeclInternal(copied_decl); 665 } 666 } else { 667 SkippedDecls = true; 668 } 669 } 670 671 // CopyDecl may build a lookup table which may set up ExternalLexicalStorage 672 // to false. However, since we skipped some of the external Decls we must 673 // set it back! 674 if (SkippedDecls) { 675 decl_context->setHasExternalLexicalStorage(true); 676 // This sets HasLazyExternalLexicalLookups to true. By setting this bit we 677 // ensure that the lookup table is rebuilt, which means the external source 678 // is consulted again when a clang::DeclContext::lookup is called. 679 const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable(); 680 } 681 682 return; 683 } 684 685 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) { 686 assert(m_ast_context); 687 688 ClangASTMetrics::RegisterVisibleQuery(); 689 690 const ConstString name(context.m_decl_name.getAsString().c_str()); 691 692 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 693 694 static unsigned int invocation_id = 0; 695 unsigned int current_id = invocation_id++; 696 697 if (log) { 698 if (!context.m_decl_context) 699 LLDB_LOGF(log, 700 "ClangASTSource::FindExternalVisibleDecls[%u] on " 701 "(ASTContext*)%p for '%s' in a NULL DeclContext", 702 current_id, static_cast<void *>(m_ast_context), 703 name.GetCString()); 704 else if (const NamedDecl *context_named_decl = 705 dyn_cast<NamedDecl>(context.m_decl_context)) 706 LLDB_LOGF(log, 707 "ClangASTSource::FindExternalVisibleDecls[%u] on " 708 "(ASTContext*)%p for '%s' in '%s'", 709 current_id, static_cast<void *>(m_ast_context), 710 name.GetCString(), 711 context_named_decl->getNameAsString().c_str()); 712 else 713 LLDB_LOGF(log, 714 "ClangASTSource::FindExternalVisibleDecls[%u] on " 715 "(ASTContext*)%p for '%s' in a '%s'", 716 current_id, static_cast<void *>(m_ast_context), 717 name.GetCString(), context.m_decl_context->getDeclKindName()); 718 } 719 720 if (HasMerger() && !isa<TranslationUnitDecl>(context.m_decl_context) 721 /* possibly handle NamespaceDecls here? */) { 722 if (auto *interface_decl = 723 dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) { 724 ObjCInterfaceDecl *complete_iface_decl = 725 GetCompleteObjCInterface(interface_decl); 726 727 if (complete_iface_decl && (complete_iface_decl != interface_decl)) { 728 GetMergerUnchecked().ForceRecordOrigin( 729 interface_decl, 730 {complete_iface_decl, &complete_iface_decl->getASTContext()}); 731 } 732 } 733 734 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context, 735 context.m_decl_name); 736 return; // otherwise we may need to fall back 737 } 738 739 context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>(); 740 741 if (const NamespaceDecl *namespace_context = 742 dyn_cast<NamespaceDecl>(context.m_decl_context)) { 743 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp ? 744 m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr; 745 746 if (log && log->GetVerbose()) 747 LLDB_LOGF(log, " CAS::FEVD[%u] Inspecting namespace map %p (%d entries)", 748 current_id, static_cast<void *>(namespace_map.get()), 749 static_cast<int>(namespace_map->size())); 750 751 if (!namespace_map) 752 return; 753 754 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(), 755 e = namespace_map->end(); 756 i != e; ++i) { 757 LLDB_LOGF(log, " CAS::FEVD[%u] Searching namespace %s in module %s", 758 current_id, i->second.GetName().AsCString(), 759 i->first->GetFileSpec().GetFilename().GetCString()); 760 761 FindExternalVisibleDecls(context, i->first, i->second, current_id); 762 } 763 } else if (isa<ObjCInterfaceDecl>(context.m_decl_context) && !HasMerger()) { 764 FindObjCPropertyAndIvarDecls(context); 765 } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) { 766 // we shouldn't be getting FindExternalVisibleDecls calls for these 767 return; 768 } else { 769 CompilerDeclContext namespace_decl; 770 771 LLDB_LOGF(log, " CAS::FEVD[%u] Searching the root namespace", current_id); 772 773 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl, 774 current_id); 775 } 776 777 if (!context.m_namespace_map->empty()) { 778 if (log && log->GetVerbose()) 779 LLDB_LOGF(log, 780 " CAS::FEVD[%u] Registering namespace map %p (%d entries)", 781 current_id, static_cast<void *>(context.m_namespace_map.get()), 782 static_cast<int>(context.m_namespace_map->size())); 783 784 NamespaceDecl *clang_namespace_decl = 785 AddNamespace(context, context.m_namespace_map); 786 787 if (clang_namespace_decl) 788 clang_namespace_decl->setHasExternalVisibleStorage(); 789 } 790 } 791 792 clang::Sema *ClangASTSource::getSema() { 793 return ClangASTContext::GetASTContext(m_ast_context)->getSema(); 794 } 795 796 bool ClangASTSource::IgnoreName(const ConstString name, 797 bool ignore_all_dollar_names) { 798 static const ConstString id_name("id"); 799 static const ConstString Class_name("Class"); 800 801 if (m_ast_context->getLangOpts().ObjC) 802 if (name == id_name || name == Class_name) 803 return true; 804 805 StringRef name_string_ref = name.GetStringRef(); 806 807 // The ClangASTSource is not responsible for finding $-names. 808 return name_string_ref.empty() || 809 (ignore_all_dollar_names && name_string_ref.startswith("$")) || 810 name_string_ref.startswith("_$"); 811 } 812 813 void ClangASTSource::FindExternalVisibleDecls( 814 NameSearchContext &context, lldb::ModuleSP module_sp, 815 CompilerDeclContext &namespace_decl, unsigned int current_id) { 816 assert(m_ast_context); 817 818 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 819 820 SymbolContextList sc_list; 821 822 const ConstString name(context.m_decl_name.getAsString().c_str()); 823 if (IgnoreName(name, true)) 824 return; 825 826 if (module_sp && namespace_decl) { 827 CompilerDeclContext found_namespace_decl; 828 829 if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) { 830 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); 831 832 if (found_namespace_decl) { 833 context.m_namespace_map->push_back( 834 std::pair<lldb::ModuleSP, CompilerDeclContext>( 835 module_sp, found_namespace_decl)); 836 837 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s", 838 current_id, name.GetCString(), 839 module_sp->GetFileSpec().GetFilename().GetCString()); 840 } 841 } 842 } else if (!HasMerger()) { 843 const ModuleList &target_images = m_target->GetImages(); 844 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex()); 845 846 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { 847 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); 848 849 if (!image) 850 continue; 851 852 CompilerDeclContext found_namespace_decl; 853 854 SymbolFile *symbol_file = image->GetSymbolFile(); 855 856 if (!symbol_file) 857 continue; 858 859 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl); 860 861 if (found_namespace_decl) { 862 context.m_namespace_map->push_back( 863 std::pair<lldb::ModuleSP, CompilerDeclContext>( 864 image, found_namespace_decl)); 865 866 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s", 867 current_id, name.GetCString(), 868 image->GetFileSpec().GetFilename().GetCString()); 869 } 870 } 871 } 872 873 do { 874 if (context.m_found.type) 875 break; 876 877 TypeList types; 878 const bool exact_match = true; 879 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 880 if (module_sp && namespace_decl) 881 module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types); 882 else { 883 m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1, 884 searched_symbol_files, types); 885 } 886 887 if (size_t num_types = types.GetSize()) { 888 for (size_t ti = 0; ti < num_types; ++ti) { 889 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti); 890 891 if (log) { 892 const char *name_string = type_sp->GetName().GetCString(); 893 894 LLDB_LOGF(log, " CAS::FEVD[%u] Matching type found for \"%s\": %s", 895 current_id, name.GetCString(), 896 (name_string ? name_string : "<anonymous>")); 897 } 898 899 CompilerType full_type = type_sp->GetFullCompilerType(); 900 901 CompilerType copied_clang_type(GuardedCopyType(full_type)); 902 903 if (!copied_clang_type) { 904 LLDB_LOGF(log, " CAS::FEVD[%u] - Couldn't export a type", 905 current_id); 906 907 continue; 908 } 909 910 context.AddTypeDecl(copied_clang_type); 911 912 context.m_found.type = true; 913 break; 914 } 915 } 916 917 if (!context.m_found.type) { 918 // Try the modules next. 919 920 do { 921 if (ClangModulesDeclVendor *modules_decl_vendor = 922 m_target->GetClangModulesDeclVendor()) { 923 bool append = false; 924 uint32_t max_matches = 1; 925 std::vector<clang::NamedDecl *> decls; 926 927 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls)) 928 break; 929 930 if (log) { 931 LLDB_LOGF(log, 932 " CAS::FEVD[%u] Matching entity found for \"%s\" in " 933 "the modules", 934 current_id, name.GetCString()); 935 } 936 937 clang::NamedDecl *const decl_from_modules = decls[0]; 938 939 if (llvm::isa<clang::TypeDecl>(decl_from_modules) || 940 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) || 941 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) { 942 clang::Decl *copied_decl = CopyDecl(decl_from_modules); 943 clang::NamedDecl *copied_named_decl = 944 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 945 946 if (!copied_named_decl) { 947 LLDB_LOGF( 948 log, 949 " CAS::FEVD[%u] - Couldn't export a type from the modules", 950 current_id); 951 952 break; 953 } 954 955 context.AddNamedDecl(copied_named_decl); 956 957 context.m_found.type = true; 958 } 959 } 960 } while (false); 961 } 962 963 if (!context.m_found.type) { 964 do { 965 // Couldn't find any types elsewhere. Try the Objective-C runtime if 966 // one exists. 967 968 lldb::ProcessSP process(m_target->GetProcessSP()); 969 970 if (!process) 971 break; 972 973 ObjCLanguageRuntime *language_runtime( 974 ObjCLanguageRuntime::Get(*process)); 975 976 if (!language_runtime) 977 break; 978 979 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 980 981 if (!decl_vendor) 982 break; 983 984 bool append = false; 985 uint32_t max_matches = 1; 986 std::vector<clang::NamedDecl *> decls; 987 988 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 989 if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls)) 990 break; 991 992 if (log) { 993 LLDB_LOGF( 994 log, 995 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime", 996 current_id, name.GetCString()); 997 } 998 999 clang::Decl *copied_decl = CopyDecl(decls[0]); 1000 clang::NamedDecl *copied_named_decl = 1001 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr; 1002 1003 if (!copied_named_decl) { 1004 LLDB_LOGF(log, 1005 " CAS::FEVD[%u] - Couldn't export a type from the runtime", 1006 current_id); 1007 1008 break; 1009 } 1010 1011 context.AddNamedDecl(copied_named_decl); 1012 } while (false); 1013 } 1014 1015 } while (false); 1016 } 1017 1018 template <class D> class TaggedASTDecl { 1019 public: 1020 TaggedASTDecl() : decl(nullptr) {} 1021 TaggedASTDecl(D *_decl) : decl(_decl) {} 1022 bool IsValid() const { return (decl != nullptr); } 1023 bool IsInvalid() const { return !IsValid(); } 1024 D *operator->() const { return decl; } 1025 D *decl; 1026 }; 1027 1028 template <class D2, template <class D> class TD, class D1> 1029 TD<D2> DynCast(TD<D1> source) { 1030 return TD<D2>(dyn_cast<D2>(source.decl)); 1031 } 1032 1033 template <class D = Decl> class DeclFromParser; 1034 template <class D = Decl> class DeclFromUser; 1035 1036 template <class D> class DeclFromParser : public TaggedASTDecl<D> { 1037 public: 1038 DeclFromParser() : TaggedASTDecl<D>() {} 1039 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {} 1040 1041 DeclFromUser<D> GetOrigin(ClangASTSource &source); 1042 }; 1043 1044 template <class D> class DeclFromUser : public TaggedASTDecl<D> { 1045 public: 1046 DeclFromUser() : TaggedASTDecl<D>() {} 1047 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {} 1048 1049 DeclFromParser<D> Import(ClangASTSource &source); 1050 }; 1051 1052 template <class D> 1053 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) { 1054 DeclFromUser<> origin_decl; 1055 source.ResolveDeclOrigin(this->decl, &origin_decl.decl, nullptr); 1056 if (origin_decl.IsInvalid()) 1057 return DeclFromUser<D>(); 1058 return DeclFromUser<D>(dyn_cast<D>(origin_decl.decl)); 1059 } 1060 1061 template <class D> 1062 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) { 1063 DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl)); 1064 if (parser_generic_decl.IsInvalid()) 1065 return DeclFromParser<D>(); 1066 return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl)); 1067 } 1068 1069 bool ClangASTSource::FindObjCMethodDeclsWithOrigin( 1070 unsigned int current_id, NameSearchContext &context, 1071 ObjCInterfaceDecl *original_interface_decl, const char *log_info) { 1072 const DeclarationName &decl_name(context.m_decl_name); 1073 clang::ASTContext *original_ctx = &original_interface_decl->getASTContext(); 1074 1075 Selector original_selector; 1076 1077 if (decl_name.isObjCZeroArgSelector()) { 1078 IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString()); 1079 original_selector = original_ctx->Selectors.getSelector(0, &ident); 1080 } else if (decl_name.isObjCOneArgSelector()) { 1081 const std::string &decl_name_string = decl_name.getAsString(); 1082 std::string decl_name_string_without_colon(decl_name_string.c_str(), 1083 decl_name_string.length() - 1); 1084 IdentifierInfo *ident = 1085 &original_ctx->Idents.get(decl_name_string_without_colon); 1086 original_selector = original_ctx->Selectors.getSelector(1, &ident); 1087 } else { 1088 SmallVector<IdentifierInfo *, 4> idents; 1089 1090 clang::Selector sel = decl_name.getObjCSelector(); 1091 1092 unsigned num_args = sel.getNumArgs(); 1093 1094 for (unsigned i = 0; i != num_args; ++i) { 1095 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i))); 1096 } 1097 1098 original_selector = 1099 original_ctx->Selectors.getSelector(num_args, idents.data()); 1100 } 1101 1102 DeclarationName original_decl_name(original_selector); 1103 1104 llvm::SmallVector<NamedDecl *, 1> methods; 1105 1106 ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl); 1107 1108 if (ObjCMethodDecl *instance_method_decl = 1109 original_interface_decl->lookupInstanceMethod(original_selector)) { 1110 methods.push_back(instance_method_decl); 1111 } else if (ObjCMethodDecl *class_method_decl = 1112 original_interface_decl->lookupClassMethod( 1113 original_selector)) { 1114 methods.push_back(class_method_decl); 1115 } 1116 1117 if (methods.empty()) { 1118 return false; 1119 } 1120 1121 for (NamedDecl *named_decl : methods) { 1122 if (!named_decl) 1123 continue; 1124 1125 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl); 1126 1127 if (!result_method) 1128 continue; 1129 1130 Decl *copied_decl = CopyDecl(result_method); 1131 1132 if (!copied_decl) 1133 continue; 1134 1135 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl); 1136 1137 if (!copied_method_decl) 1138 continue; 1139 1140 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1141 1142 if (log) { 1143 ASTDumper dumper((Decl *)copied_method_decl); 1144 LLDB_LOGF(log, " CAS::FOMD[%d] found (%s) %s", current_id, log_info, 1145 dumper.GetCString()); 1146 } 1147 1148 context.AddNamedDecl(copied_method_decl); 1149 } 1150 1151 return true; 1152 } 1153 1154 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) { 1155 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1156 1157 if (HasMerger()) { 1158 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) { 1159 ObjCInterfaceDecl *complete_iface_decl = 1160 GetCompleteObjCInterface(interface_decl); 1161 1162 if (complete_iface_decl && (complete_iface_decl != context.m_decl_context)) { 1163 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()}); 1164 } 1165 } 1166 1167 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context, 1168 context.m_decl_name); 1169 return; 1170 } 1171 1172 static unsigned int invocation_id = 0; 1173 unsigned int current_id = invocation_id++; 1174 1175 const DeclarationName &decl_name(context.m_decl_name); 1176 const DeclContext *decl_ctx(context.m_decl_context); 1177 1178 const ObjCInterfaceDecl *interface_decl = 1179 dyn_cast<ObjCInterfaceDecl>(decl_ctx); 1180 1181 if (!interface_decl) 1182 return; 1183 1184 do { 1185 Decl *original_decl = nullptr; 1186 ASTContext *original_ctx = nullptr; 1187 1188 m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl, 1189 &original_ctx); 1190 1191 if (!original_decl) 1192 break; 1193 1194 ObjCInterfaceDecl *original_interface_decl = 1195 dyn_cast<ObjCInterfaceDecl>(original_decl); 1196 1197 if (FindObjCMethodDeclsWithOrigin(current_id, context, 1198 original_interface_decl, "at origin")) 1199 return; // found it, no need to look any further 1200 } while (false); 1201 1202 StreamString ss; 1203 1204 if (decl_name.isObjCZeroArgSelector()) { 1205 ss.Printf("%s", decl_name.getAsString().c_str()); 1206 } else if (decl_name.isObjCOneArgSelector()) { 1207 ss.Printf("%s", decl_name.getAsString().c_str()); 1208 } else { 1209 clang::Selector sel = decl_name.getObjCSelector(); 1210 1211 for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) { 1212 llvm::StringRef r = sel.getNameForSlot(i); 1213 ss.Printf("%s:", r.str().c_str()); 1214 } 1215 } 1216 ss.Flush(); 1217 1218 if (ss.GetString().contains("$__lldb")) 1219 return; // we don't need any results 1220 1221 ConstString selector_name(ss.GetString()); 1222 1223 LLDB_LOGF(log, 1224 "ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p " 1225 "for selector [%s %s]", 1226 current_id, static_cast<void *>(m_ast_context), 1227 interface_decl->getNameAsString().c_str(), 1228 selector_name.AsCString()); 1229 SymbolContextList sc_list; 1230 1231 const bool include_symbols = false; 1232 const bool include_inlines = false; 1233 const bool append = false; 1234 1235 std::string interface_name = interface_decl->getNameAsString(); 1236 1237 do { 1238 StreamString ms; 1239 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString()); 1240 ms.Flush(); 1241 ConstString instance_method_name(ms.GetString()); 1242 1243 m_target->GetImages().FindFunctions( 1244 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols, 1245 include_inlines, append, sc_list); 1246 1247 if (sc_list.GetSize()) 1248 break; 1249 1250 ms.Clear(); 1251 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString()); 1252 ms.Flush(); 1253 ConstString class_method_name(ms.GetString()); 1254 1255 m_target->GetImages().FindFunctions( 1256 class_method_name, lldb::eFunctionNameTypeFull, include_symbols, 1257 include_inlines, append, sc_list); 1258 1259 if (sc_list.GetSize()) 1260 break; 1261 1262 // Fall back and check for methods in categories. If we find methods this 1263 // way, we need to check that they're actually in categories on the desired 1264 // class. 1265 1266 SymbolContextList candidate_sc_list; 1267 1268 m_target->GetImages().FindFunctions( 1269 selector_name, lldb::eFunctionNameTypeSelector, include_symbols, 1270 include_inlines, append, candidate_sc_list); 1271 1272 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) { 1273 SymbolContext candidate_sc; 1274 1275 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc)) 1276 continue; 1277 1278 if (!candidate_sc.function) 1279 continue; 1280 1281 const char *candidate_name = candidate_sc.function->GetName().AsCString(); 1282 1283 const char *cursor = candidate_name; 1284 1285 if (*cursor != '+' && *cursor != '-') 1286 continue; 1287 1288 ++cursor; 1289 1290 if (*cursor != '[') 1291 continue; 1292 1293 ++cursor; 1294 1295 size_t interface_len = interface_name.length(); 1296 1297 if (strncmp(cursor, interface_name.c_str(), interface_len)) 1298 continue; 1299 1300 cursor += interface_len; 1301 1302 if (*cursor == ' ' || *cursor == '(') 1303 sc_list.Append(candidate_sc); 1304 } 1305 } while (false); 1306 1307 if (sc_list.GetSize()) { 1308 // We found a good function symbol. Use that. 1309 1310 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) { 1311 SymbolContext sc; 1312 1313 if (!sc_list.GetContextAtIndex(i, sc)) 1314 continue; 1315 1316 if (!sc.function) 1317 continue; 1318 1319 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext(); 1320 if (!function_decl_ctx) 1321 continue; 1322 1323 ObjCMethodDecl *method_decl = 1324 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx); 1325 1326 if (!method_decl) 1327 continue; 1328 1329 ObjCInterfaceDecl *found_interface_decl = 1330 method_decl->getClassInterface(); 1331 1332 if (!found_interface_decl) 1333 continue; 1334 1335 if (found_interface_decl->getName() == interface_decl->getName()) { 1336 Decl *copied_decl = CopyDecl(method_decl); 1337 1338 if (!copied_decl) 1339 continue; 1340 1341 ObjCMethodDecl *copied_method_decl = 1342 dyn_cast<ObjCMethodDecl>(copied_decl); 1343 1344 if (!copied_method_decl) 1345 continue; 1346 1347 if (log) { 1348 ASTDumper dumper((Decl *)copied_method_decl); 1349 LLDB_LOGF(log, " CAS::FOMD[%d] found (in symbols) %s", current_id, 1350 dumper.GetCString()); 1351 } 1352 1353 context.AddNamedDecl(copied_method_decl); 1354 } 1355 } 1356 1357 return; 1358 } 1359 1360 // Try the debug information. 1361 1362 do { 1363 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( 1364 const_cast<ObjCInterfaceDecl *>(interface_decl)); 1365 1366 if (!complete_interface_decl) 1367 break; 1368 1369 // We found the complete interface. The runtime never needs to be queried 1370 // in this scenario. 1371 1372 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl( 1373 complete_interface_decl); 1374 1375 if (complete_interface_decl == interface_decl) 1376 break; // already checked this one 1377 1378 LLDB_LOGF(log, 1379 "CAS::FOPD[%d] trying origin " 1380 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1381 current_id, static_cast<void *>(complete_interface_decl), 1382 static_cast<void *>(&complete_iface_decl->getASTContext())); 1383 1384 FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl, 1385 "in debug info"); 1386 1387 return; 1388 } while (false); 1389 1390 do { 1391 // Check the modules only if the debug information didn't have a complete 1392 // interface. 1393 1394 if (ClangModulesDeclVendor *modules_decl_vendor = 1395 m_target->GetClangModulesDeclVendor()) { 1396 ConstString interface_name(interface_decl->getNameAsString().c_str()); 1397 bool append = false; 1398 uint32_t max_matches = 1; 1399 std::vector<clang::NamedDecl *> decls; 1400 1401 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches, 1402 decls)) 1403 break; 1404 1405 ObjCInterfaceDecl *interface_decl_from_modules = 1406 dyn_cast<ObjCInterfaceDecl>(decls[0]); 1407 1408 if (!interface_decl_from_modules) 1409 break; 1410 1411 if (FindObjCMethodDeclsWithOrigin( 1412 current_id, context, interface_decl_from_modules, "in modules")) 1413 return; 1414 } 1415 } while (false); 1416 1417 do { 1418 // Check the runtime only if the debug information didn't have a complete 1419 // interface and the modules don't get us anywhere. 1420 1421 lldb::ProcessSP process(m_target->GetProcessSP()); 1422 1423 if (!process) 1424 break; 1425 1426 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 1427 1428 if (!language_runtime) 1429 break; 1430 1431 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 1432 1433 if (!decl_vendor) 1434 break; 1435 1436 ConstString interface_name(interface_decl->getNameAsString().c_str()); 1437 bool append = false; 1438 uint32_t max_matches = 1; 1439 std::vector<clang::NamedDecl *> decls; 1440 1441 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 1442 if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches, 1443 decls)) 1444 break; 1445 1446 ObjCInterfaceDecl *runtime_interface_decl = 1447 dyn_cast<ObjCInterfaceDecl>(decls[0]); 1448 1449 if (!runtime_interface_decl) 1450 break; 1451 1452 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl, 1453 "in runtime"); 1454 } while (false); 1455 } 1456 1457 static bool FindObjCPropertyAndIvarDeclsWithOrigin( 1458 unsigned int current_id, NameSearchContext &context, ClangASTSource &source, 1459 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) { 1460 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1461 1462 if (origin_iface_decl.IsInvalid()) 1463 return false; 1464 1465 std::string name_str = context.m_decl_name.getAsString(); 1466 StringRef name(name_str); 1467 IdentifierInfo &name_identifier( 1468 origin_iface_decl->getASTContext().Idents.get(name)); 1469 1470 DeclFromUser<ObjCPropertyDecl> origin_property_decl( 1471 origin_iface_decl->FindPropertyDeclaration( 1472 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance)); 1473 1474 bool found = false; 1475 1476 if (origin_property_decl.IsValid()) { 1477 DeclFromParser<ObjCPropertyDecl> parser_property_decl( 1478 origin_property_decl.Import(source)); 1479 if (parser_property_decl.IsValid()) { 1480 if (log) { 1481 ASTDumper dumper((Decl *)parser_property_decl.decl); 1482 LLDB_LOGF(log, " CAS::FOPD[%d] found %s", current_id, 1483 dumper.GetCString()); 1484 } 1485 1486 context.AddNamedDecl(parser_property_decl.decl); 1487 found = true; 1488 } 1489 } 1490 1491 DeclFromUser<ObjCIvarDecl> origin_ivar_decl( 1492 origin_iface_decl->getIvarDecl(&name_identifier)); 1493 1494 if (origin_ivar_decl.IsValid()) { 1495 DeclFromParser<ObjCIvarDecl> parser_ivar_decl( 1496 origin_ivar_decl.Import(source)); 1497 if (parser_ivar_decl.IsValid()) { 1498 if (log) { 1499 ASTDumper dumper((Decl *)parser_ivar_decl.decl); 1500 LLDB_LOGF(log, " CAS::FOPD[%d] found %s", current_id, 1501 dumper.GetCString()); 1502 } 1503 1504 context.AddNamedDecl(parser_ivar_decl.decl); 1505 found = true; 1506 } 1507 } 1508 1509 return found; 1510 } 1511 1512 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) { 1513 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1514 1515 static unsigned int invocation_id = 0; 1516 unsigned int current_id = invocation_id++; 1517 1518 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl( 1519 cast<ObjCInterfaceDecl>(context.m_decl_context)); 1520 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl( 1521 parser_iface_decl.GetOrigin(*this)); 1522 1523 ConstString class_name(parser_iface_decl->getNameAsString().c_str()); 1524 1525 LLDB_LOGF(log, 1526 "ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on " 1527 "(ASTContext*)%p for '%s.%s'", 1528 current_id, static_cast<void *>(m_ast_context), 1529 parser_iface_decl->getNameAsString().c_str(), 1530 context.m_decl_name.getAsString().c_str()); 1531 1532 if (FindObjCPropertyAndIvarDeclsWithOrigin( 1533 current_id, context, *this, origin_iface_decl)) 1534 return; 1535 1536 LLDB_LOGF(log, 1537 "CAS::FOPD[%d] couldn't find the property on origin " 1538 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching " 1539 "elsewhere...", 1540 current_id, static_cast<const void *>(origin_iface_decl.decl), 1541 static_cast<void *>(&origin_iface_decl->getASTContext())); 1542 1543 SymbolContext null_sc; 1544 TypeList type_list; 1545 1546 do { 1547 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface( 1548 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl)); 1549 1550 if (!complete_interface_decl) 1551 break; 1552 1553 // We found the complete interface. The runtime never needs to be queried 1554 // in this scenario. 1555 1556 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl( 1557 complete_interface_decl); 1558 1559 if (complete_iface_decl.decl == origin_iface_decl.decl) 1560 break; // already checked this one 1561 1562 LLDB_LOGF(log, 1563 "CAS::FOPD[%d] trying origin " 1564 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1565 current_id, static_cast<const void *>(complete_iface_decl.decl), 1566 static_cast<void *>(&complete_iface_decl->getASTContext())); 1567 1568 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, 1569 complete_iface_decl); 1570 1571 return; 1572 } while (false); 1573 1574 do { 1575 // Check the modules only if the debug information didn't have a complete 1576 // interface. 1577 1578 ClangModulesDeclVendor *modules_decl_vendor = 1579 m_target->GetClangModulesDeclVendor(); 1580 1581 if (!modules_decl_vendor) 1582 break; 1583 1584 bool append = false; 1585 uint32_t max_matches = 1; 1586 std::vector<clang::NamedDecl *> decls; 1587 1588 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1589 break; 1590 1591 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules( 1592 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1593 1594 if (!interface_decl_from_modules.IsValid()) 1595 break; 1596 1597 LLDB_LOGF( 1598 log, 1599 "CAS::FOPD[%d] trying module " 1600 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1601 current_id, static_cast<const void *>(interface_decl_from_modules.decl), 1602 static_cast<void *>(&interface_decl_from_modules->getASTContext())); 1603 1604 if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this, 1605 interface_decl_from_modules)) 1606 return; 1607 } while (false); 1608 1609 do { 1610 // Check the runtime only if the debug information didn't have a complete 1611 // interface and nothing was in the modules. 1612 1613 lldb::ProcessSP process(m_target->GetProcessSP()); 1614 1615 if (!process) 1616 return; 1617 1618 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process)); 1619 1620 if (!language_runtime) 1621 return; 1622 1623 DeclVendor *decl_vendor = language_runtime->GetDeclVendor(); 1624 1625 if (!decl_vendor) 1626 break; 1627 1628 bool append = false; 1629 uint32_t max_matches = 1; 1630 std::vector<clang::NamedDecl *> decls; 1631 1632 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor); 1633 if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls)) 1634 break; 1635 1636 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime( 1637 dyn_cast<ObjCInterfaceDecl>(decls[0])); 1638 1639 if (!interface_decl_from_runtime.IsValid()) 1640 break; 1641 1642 LLDB_LOGF( 1643 log, 1644 "CAS::FOPD[%d] trying runtime " 1645 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...", 1646 current_id, static_cast<const void *>(interface_decl_from_runtime.decl), 1647 static_cast<void *>(&interface_decl_from_runtime->getASTContext())); 1648 1649 if (FindObjCPropertyAndIvarDeclsWithOrigin( 1650 current_id, context, *this, interface_decl_from_runtime)) 1651 return; 1652 } while (false); 1653 } 1654 1655 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap; 1656 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap; 1657 1658 template <class D, class O> 1659 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map, 1660 llvm::DenseMap<const D *, O> &source_map, 1661 ClangASTSource &source) { 1662 // When importing fields into a new record, clang has a hard requirement that 1663 // fields be imported in field offset order. Since they are stored in a 1664 // DenseMap with a pointer as the key type, this means we cannot simply 1665 // iterate over the map, as the order will be non-deterministic. Instead we 1666 // have to sort by the offset and then insert in sorted order. 1667 typedef llvm::DenseMap<const D *, O> MapType; 1668 typedef typename MapType::value_type PairType; 1669 std::vector<PairType> sorted_items; 1670 sorted_items.reserve(source_map.size()); 1671 sorted_items.assign(source_map.begin(), source_map.end()); 1672 llvm::sort(sorted_items.begin(), sorted_items.end(), 1673 [](const PairType &lhs, const PairType &rhs) { 1674 return lhs.second < rhs.second; 1675 }); 1676 1677 for (const auto &item : sorted_items) { 1678 DeclFromUser<D> user_decl(const_cast<D *>(item.first)); 1679 DeclFromParser<D> parser_decl(user_decl.Import(source)); 1680 if (parser_decl.IsInvalid()) 1681 return false; 1682 destination_map.insert( 1683 std::pair<const D *, O>(parser_decl.decl, item.second)); 1684 } 1685 1686 return true; 1687 } 1688 1689 template <bool IsVirtual> 1690 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout, 1691 DeclFromUser<const CXXRecordDecl> &record, 1692 BaseOffsetMap &base_offsets) { 1693 for (CXXRecordDecl::base_class_const_iterator 1694 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()), 1695 be = (IsVirtual ? record->vbases_end() : record->bases_end()); 1696 bi != be; ++bi) { 1697 if (!IsVirtual && bi->isVirtual()) 1698 continue; 1699 1700 const clang::Type *origin_base_type = bi->getType().getTypePtr(); 1701 const clang::RecordType *origin_base_record_type = 1702 origin_base_type->getAs<RecordType>(); 1703 1704 if (!origin_base_record_type) 1705 return false; 1706 1707 DeclFromUser<RecordDecl> origin_base_record( 1708 origin_base_record_type->getDecl()); 1709 1710 if (origin_base_record.IsInvalid()) 1711 return false; 1712 1713 DeclFromUser<CXXRecordDecl> origin_base_cxx_record( 1714 DynCast<CXXRecordDecl>(origin_base_record)); 1715 1716 if (origin_base_cxx_record.IsInvalid()) 1717 return false; 1718 1719 CharUnits base_offset; 1720 1721 if (IsVirtual) 1722 base_offset = 1723 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl); 1724 else 1725 base_offset = 1726 record_layout.getBaseClassOffset(origin_base_cxx_record.decl); 1727 1728 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>( 1729 origin_base_cxx_record.decl, base_offset)); 1730 } 1731 1732 return true; 1733 } 1734 1735 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size, 1736 uint64_t &alignment, 1737 FieldOffsetMap &field_offsets, 1738 BaseOffsetMap &base_offsets, 1739 BaseOffsetMap &virtual_base_offsets) { 1740 ClangASTMetrics::RegisterRecordLayout(); 1741 1742 static unsigned int invocation_id = 0; 1743 unsigned int current_id = invocation_id++; 1744 1745 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1746 1747 LLDB_LOGF(log, 1748 "LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p " 1749 "[name = '%s']", 1750 current_id, static_cast<void *>(m_ast_context), 1751 static_cast<const void *>(record), 1752 record->getNameAsString().c_str()); 1753 1754 DeclFromParser<const RecordDecl> parser_record(record); 1755 DeclFromUser<const RecordDecl> origin_record( 1756 parser_record.GetOrigin(*this)); 1757 1758 if (origin_record.IsInvalid()) 1759 return false; 1760 1761 FieldOffsetMap origin_field_offsets; 1762 BaseOffsetMap origin_base_offsets; 1763 BaseOffsetMap origin_virtual_base_offsets; 1764 1765 ClangASTContext::GetCompleteDecl( 1766 &origin_record->getASTContext(), 1767 const_cast<RecordDecl *>(origin_record.decl)); 1768 1769 clang::RecordDecl *definition = origin_record.decl->getDefinition(); 1770 if (!definition || !definition->isCompleteDefinition()) 1771 return false; 1772 1773 const ASTRecordLayout &record_layout( 1774 origin_record->getASTContext().getASTRecordLayout(origin_record.decl)); 1775 1776 int field_idx = 0, field_count = record_layout.getFieldCount(); 1777 1778 for (RecordDecl::field_iterator fi = origin_record->field_begin(), 1779 fe = origin_record->field_end(); 1780 fi != fe; ++fi) { 1781 if (field_idx >= field_count) 1782 return false; // Layout didn't go well. Bail out. 1783 1784 uint64_t field_offset = record_layout.getFieldOffset(field_idx); 1785 1786 origin_field_offsets.insert( 1787 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset)); 1788 1789 field_idx++; 1790 } 1791 1792 lldbassert(&record->getASTContext() == m_ast_context); 1793 1794 DeclFromUser<const CXXRecordDecl> origin_cxx_record( 1795 DynCast<const CXXRecordDecl>(origin_record)); 1796 1797 if (origin_cxx_record.IsValid()) { 1798 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record, 1799 origin_base_offsets) || 1800 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record, 1801 origin_virtual_base_offsets)) 1802 return false; 1803 } 1804 1805 if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) || 1806 !ImportOffsetMap(base_offsets, origin_base_offsets, *this) || 1807 !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets, 1808 *this)) 1809 return false; 1810 1811 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth(); 1812 alignment = record_layout.getAlignment().getQuantity() * 1813 m_ast_context->getCharWidth(); 1814 1815 if (log) { 1816 LLDB_LOGF(log, "LRT[%u] returned:", current_id); 1817 LLDB_LOGF(log, "LRT[%u] Original = (RecordDecl*)%p", current_id, 1818 static_cast<const void *>(origin_record.decl)); 1819 LLDB_LOGF(log, "LRT[%u] Size = %" PRId64, current_id, size); 1820 LLDB_LOGF(log, "LRT[%u] Alignment = %" PRId64, current_id, alignment); 1821 LLDB_LOGF(log, "LRT[%u] Fields:", current_id); 1822 for (RecordDecl::field_iterator fi = record->field_begin(), 1823 fe = record->field_end(); 1824 fi != fe; ++fi) { 1825 LLDB_LOGF(log, 1826 "LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %" PRId64 1827 " bits", 1828 current_id, static_cast<void *>(*fi), 1829 fi->getNameAsString().c_str(), field_offsets[*fi]); 1830 } 1831 DeclFromParser<const CXXRecordDecl> parser_cxx_record = 1832 DynCast<const CXXRecordDecl>(parser_record); 1833 if (parser_cxx_record.IsValid()) { 1834 LLDB_LOGF(log, "LRT[%u] Bases:", current_id); 1835 for (CXXRecordDecl::base_class_const_iterator 1836 bi = parser_cxx_record->bases_begin(), 1837 be = parser_cxx_record->bases_end(); 1838 bi != be; ++bi) { 1839 bool is_virtual = bi->isVirtual(); 1840 1841 QualType base_type = bi->getType(); 1842 const RecordType *base_record_type = base_type->getAs<RecordType>(); 1843 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl()); 1844 DeclFromParser<CXXRecordDecl> base_cxx_record = 1845 DynCast<CXXRecordDecl>(base_record); 1846 1847 LLDB_LOGF( 1848 log, 1849 "LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64 1850 " chars", 1851 current_id, (is_virtual ? "Virtual " : ""), 1852 static_cast<void *>(base_cxx_record.decl), 1853 base_cxx_record.decl->getNameAsString().c_str(), 1854 (is_virtual 1855 ? virtual_base_offsets[base_cxx_record.decl].getQuantity() 1856 : base_offsets[base_cxx_record.decl].getQuantity())); 1857 } 1858 } else { 1859 LLDB_LOGF(log, "LRD[%u] Not a CXXRecord, so no bases", current_id); 1860 } 1861 } 1862 1863 return true; 1864 } 1865 1866 void ClangASTSource::CompleteNamespaceMap( 1867 ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name, 1868 ClangASTImporter::NamespaceMapSP &parent_map) const { 1869 static unsigned int invocation_id = 0; 1870 unsigned int current_id = invocation_id++; 1871 1872 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 1873 1874 if (log) { 1875 if (parent_map && parent_map->size()) 1876 LLDB_LOGF(log, 1877 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for " 1878 "namespace %s in namespace %s", 1879 current_id, static_cast<void *>(m_ast_context), 1880 name.GetCString(), 1881 parent_map->begin()->second.GetName().AsCString()); 1882 else 1883 LLDB_LOGF(log, 1884 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for " 1885 "namespace %s", 1886 current_id, static_cast<void *>(m_ast_context), 1887 name.GetCString()); 1888 } 1889 1890 if (parent_map) { 1891 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(), 1892 e = parent_map->end(); 1893 i != e; ++i) { 1894 CompilerDeclContext found_namespace_decl; 1895 1896 lldb::ModuleSP module_sp = i->first; 1897 CompilerDeclContext module_parent_namespace_decl = i->second; 1898 1899 SymbolFile *symbol_file = module_sp->GetSymbolFile(); 1900 1901 if (!symbol_file) 1902 continue; 1903 1904 found_namespace_decl = 1905 symbol_file->FindNamespace(name, &module_parent_namespace_decl); 1906 1907 if (!found_namespace_decl) 1908 continue; 1909 1910 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>( 1911 module_sp, found_namespace_decl)); 1912 1913 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id, 1914 name.GetCString(), 1915 module_sp->GetFileSpec().GetFilename().GetCString()); 1916 } 1917 } else { 1918 const ModuleList &target_images = m_target->GetImages(); 1919 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex()); 1920 1921 CompilerDeclContext null_namespace_decl; 1922 1923 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) { 1924 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i); 1925 1926 if (!image) 1927 continue; 1928 1929 CompilerDeclContext found_namespace_decl; 1930 1931 SymbolFile *symbol_file = image->GetSymbolFile(); 1932 1933 if (!symbol_file) 1934 continue; 1935 1936 found_namespace_decl = 1937 symbol_file->FindNamespace(name, &null_namespace_decl); 1938 1939 if (!found_namespace_decl) 1940 continue; 1941 1942 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>( 1943 image, found_namespace_decl)); 1944 1945 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id, 1946 name.GetCString(), 1947 image->GetFileSpec().GetFilename().GetCString()); 1948 } 1949 } 1950 } 1951 1952 NamespaceDecl *ClangASTSource::AddNamespace( 1953 NameSearchContext &context, 1954 ClangASTImporter::NamespaceMapSP &namespace_decls) { 1955 if (!namespace_decls) 1956 return nullptr; 1957 1958 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second; 1959 1960 clang::ASTContext *src_ast = 1961 ClangASTContext::DeclContextGetClangASTContext(namespace_decl); 1962 if (!src_ast) 1963 return nullptr; 1964 clang::NamespaceDecl *src_namespace_decl = 1965 ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl); 1966 1967 if (!src_namespace_decl) 1968 return nullptr; 1969 1970 Decl *copied_decl = CopyDecl(src_namespace_decl); 1971 1972 if (!copied_decl) 1973 return nullptr; 1974 1975 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl); 1976 1977 if (!copied_namespace_decl) 1978 return nullptr; 1979 1980 context.m_decls.push_back(copied_namespace_decl); 1981 1982 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl, 1983 namespace_decls); 1984 1985 return dyn_cast<NamespaceDecl>(copied_decl); 1986 } 1987 1988 clang::QualType ClangASTSource::CopyTypeWithMerger( 1989 clang::ASTContext &from_context, 1990 clang::ExternalASTMerger &merger, 1991 clang::QualType type) { 1992 if (!merger.HasImporterForOrigin(from_context)) { 1993 lldbassert(0 && "Couldn't find the importer for a source context!"); 1994 return QualType(); 1995 } 1996 1997 if (llvm::Expected<QualType> type_or_error = 1998 merger.ImporterForOrigin(from_context).Import(type)) { 1999 return *type_or_error; 2000 } else { 2001 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 2002 LLDB_LOG_ERROR(log, type_or_error.takeError(), "Couldn't import type: {0}"); 2003 return QualType(); 2004 } 2005 } 2006 2007 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) { 2008 clang::ASTContext &from_context = src_decl->getASTContext(); 2009 if (m_ast_importer_sp) { 2010 return m_ast_importer_sp->CopyDecl(m_ast_context, &from_context, src_decl); 2011 } else if (m_merger_up) { 2012 if (!m_merger_up->HasImporterForOrigin(from_context)) { 2013 lldbassert(0 && "Couldn't find the importer for a source context!"); 2014 return nullptr; 2015 } 2016 2017 if (llvm::Expected<Decl *> decl_or_error = 2018 m_merger_up->ImporterForOrigin(from_context).Import(src_decl)) { 2019 return *decl_or_error; 2020 } else { 2021 Log *log = 2022 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 2023 LLDB_LOG_ERROR(log, decl_or_error.takeError(), 2024 "Couldn't import decl: {0}"); 2025 return nullptr; 2026 } 2027 } else { 2028 lldbassert(0 && "No mechanism for copying a decl!"); 2029 return nullptr; 2030 } 2031 } 2032 2033 bool ClangASTSource::ResolveDeclOrigin(const clang::Decl *decl, 2034 clang::Decl **original_decl, 2035 clang::ASTContext **original_ctx) { 2036 if (m_ast_importer_sp) { 2037 return m_ast_importer_sp->ResolveDeclOrigin(decl, original_decl, 2038 original_ctx); 2039 } else if (m_merger_up) { 2040 return false; // Implement this correctly in ExternalASTMerger 2041 } else { 2042 // this can happen early enough that no ExternalASTSource is installed. 2043 return false; 2044 } 2045 } 2046 2047 clang::ExternalASTMerger &ClangASTSource::GetMergerUnchecked() { 2048 lldbassert(m_merger_up != nullptr); 2049 return *m_merger_up; 2050 } 2051 2052 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) { 2053 ClangASTContext *src_ast = 2054 llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem()); 2055 if (src_ast == nullptr) 2056 return CompilerType(); 2057 2058 ClangASTMetrics::RegisterLLDBImport(); 2059 2060 SetImportInProgress(true); 2061 2062 QualType copied_qual_type; 2063 2064 if (m_ast_importer_sp) { 2065 copied_qual_type = 2066 m_ast_importer_sp->CopyType(m_ast_context, src_ast->getASTContext(), 2067 ClangUtil::GetQualType(src_type)); 2068 } else if (m_merger_up) { 2069 copied_qual_type = 2070 CopyTypeWithMerger(*src_ast->getASTContext(), *m_merger_up, 2071 ClangUtil::GetQualType(src_type)); 2072 } else { 2073 lldbassert(0 && "No mechanism for copying a type!"); 2074 return CompilerType(); 2075 } 2076 2077 SetImportInProgress(false); 2078 2079 if (copied_qual_type.getAsOpaquePtr() && 2080 copied_qual_type->getCanonicalTypeInternal().isNull()) 2081 // this shouldn't happen, but we're hardening because the AST importer 2082 // seems to be generating bad types on occasion. 2083 return CompilerType(); 2084 2085 return CompilerType(ClangASTContext::GetASTContext(m_ast_context), 2086 copied_qual_type.getAsOpaquePtr()); 2087 } 2088 2089 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) { 2090 assert(type && "Type for variable must be valid!"); 2091 2092 if (!type.IsValid()) 2093 return nullptr; 2094 2095 ClangASTContext *lldb_ast = 2096 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2097 if (!lldb_ast) 2098 return nullptr; 2099 2100 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo(); 2101 2102 clang::ASTContext *ast = lldb_ast->getASTContext(); 2103 2104 clang::NamedDecl *Decl = VarDecl::Create( 2105 *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(), 2106 SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static); 2107 m_decls.push_back(Decl); 2108 2109 return Decl; 2110 } 2111 2112 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type, 2113 bool extern_c) { 2114 assert(type && "Type for variable must be valid!"); 2115 2116 if (!type.IsValid()) 2117 return nullptr; 2118 2119 if (m_function_types.count(type)) 2120 return nullptr; 2121 2122 ClangASTContext *lldb_ast = 2123 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem()); 2124 if (!lldb_ast) 2125 return nullptr; 2126 2127 m_function_types.insert(type); 2128 2129 QualType qual_type(ClangUtil::GetQualType(type)); 2130 2131 clang::ASTContext *ast = lldb_ast->getASTContext(); 2132 2133 const bool isInlineSpecified = false; 2134 const bool hasWrittenPrototype = true; 2135 const bool isConstexprSpecified = false; 2136 2137 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context); 2138 2139 if (extern_c) { 2140 context = LinkageSpecDecl::Create( 2141 *ast, context, SourceLocation(), SourceLocation(), 2142 clang::LinkageSpecDecl::LanguageIDs::lang_c, false); 2143 } 2144 2145 // Pass the identifier info for functions the decl_name is needed for 2146 // operators 2147 clang::DeclarationName decl_name = 2148 m_decl_name.getNameKind() == DeclarationName::Identifier 2149 ? m_decl_name.getAsIdentifierInfo() 2150 : m_decl_name; 2151 2152 clang::FunctionDecl *func_decl = FunctionDecl::Create( 2153 *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type, 2154 nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype, 2155 isConstexprSpecified ? CSK_constexpr : CSK_unspecified); 2156 2157 // We have to do more than just synthesize the FunctionDecl. We have to 2158 // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do 2159 // this, we raid the function's FunctionProtoType for types. 2160 2161 const FunctionProtoType *func_proto_type = 2162 qual_type.getTypePtr()->getAs<FunctionProtoType>(); 2163 2164 if (func_proto_type) { 2165 unsigned NumArgs = func_proto_type->getNumParams(); 2166 unsigned ArgIndex; 2167 2168 SmallVector<ParmVarDecl *, 5> parm_var_decls; 2169 2170 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) { 2171 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex)); 2172 2173 parm_var_decls.push_back( 2174 ParmVarDecl::Create(*ast, const_cast<DeclContext *>(context), 2175 SourceLocation(), SourceLocation(), nullptr, 2176 arg_qual_type, nullptr, SC_Static, nullptr)); 2177 } 2178 2179 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls)); 2180 } else { 2181 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 2182 2183 LLDB_LOGF(log, "Function type wasn't a FunctionProtoType"); 2184 } 2185 2186 // If this is an operator (e.g. operator new or operator==), only insert the 2187 // declaration we inferred from the symbol if we can provide the correct 2188 // number of arguments. We shouldn't really inject random decl(s) for 2189 // functions that are analyzed semantically in a special way, otherwise we 2190 // will crash in clang. 2191 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; 2192 if (func_proto_type && 2193 ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) { 2194 if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount( 2195 false, op_kind, func_proto_type->getNumParams())) 2196 return nullptr; 2197 } 2198 m_decls.push_back(func_decl); 2199 2200 return func_decl; 2201 } 2202 2203 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() { 2204 FunctionProtoType::ExtProtoInfo proto_info; 2205 2206 proto_info.Variadic = true; 2207 2208 QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType( 2209 m_ast_source.m_ast_context->UnknownAnyTy, // result 2210 ArrayRef<QualType>(), // argument types 2211 proto_info)); 2212 2213 return AddFunDecl( 2214 CompilerType(ClangASTContext::GetASTContext(m_ast_source.m_ast_context), 2215 generic_function_type.getAsOpaquePtr()), 2216 true); 2217 } 2218 2219 clang::NamedDecl * 2220 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) { 2221 if (ClangUtil::IsClangType(clang_type)) { 2222 QualType qual_type = ClangUtil::GetQualType(clang_type); 2223 2224 if (const TypedefType *typedef_type = 2225 llvm::dyn_cast<TypedefType>(qual_type)) { 2226 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl(); 2227 2228 m_decls.push_back(typedef_name_decl); 2229 2230 return (NamedDecl *)typedef_name_decl; 2231 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) { 2232 TagDecl *tag_decl = tag_type->getDecl(); 2233 2234 m_decls.push_back(tag_decl); 2235 2236 return tag_decl; 2237 } else if (const ObjCObjectType *objc_object_type = 2238 qual_type->getAs<ObjCObjectType>()) { 2239 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface(); 2240 2241 m_decls.push_back((NamedDecl *)interface_decl); 2242 2243 return (NamedDecl *)interface_decl; 2244 } 2245 } 2246 return nullptr; 2247 } 2248 2249 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) { 2250 for (clang::NamedDecl *decl : result) 2251 m_decls.push_back(decl); 2252 } 2253 2254 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) { 2255 m_decls.push_back(decl); 2256 } 2257