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