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