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