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