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