1 //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ClangASTSource.h"
12 #include "ASTDumper.h"
13 #include "ClangModulesDeclVendor.h"
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"
32 using namespace clang;
33 using namespace lldb_private;
35 //------------------------------------------------------------------
36 // Scoped class that will remove an active lexical decl from the set when it
38 //------------------------------------------------------------------
40 class ScopedLexicalDeclEraser {
42 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
43 const clang::Decl *decl)
44 : m_active_lexical_decls(decls), m_decl(decl) {}
46 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
49 std::set<const clang::Decl *> &m_active_lexical_decls;
50 const clang::Decl *m_decl;
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();
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
73 lldbassert(!m_merger_up);
74 clang::ExternalASTMerger::ImporterTarget target = {ast_context,
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()
90 lldb::ProcessSP process(m_target->GetProcessSP());
95 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
97 if (!language_runtime)
100 DeclVendor *runtime_decl_vendor = language_runtime->GetDeclVendor();
102 if (!runtime_decl_vendor)
105 sources.push_back(runtime_decl_vendor->GetImporterSource());
109 DeclVendor *modules_decl_vendor =
110 m_target->GetClangModulesDeclVendor();
112 if (!modules_decl_vendor)
115 sources.push_back(modules_decl_vendor->GetImporterSource());
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.
122 auto scratch_ast_context = static_cast<ClangASTContextForExpressions*>(
123 m_target->GetScratchClangASTContext());
125 scratch_ast_context->GetMergerUnchecked().AddSources(sources);
127 sources.push_back({*scratch_ast_context->getASTContext(),
128 *scratch_ast_context->getFileManager(),
129 scratch_ast_context->GetOriginMap()});
133 llvm::make_unique<clang::ExternalASTMerger>(target, sources);
135 m_ast_importer_sp->InstallMapCompleter(&ast_context, *this);
139 ClangASTSource::~ClangASTSource() {
140 if (m_ast_importer_sp)
141 m_ast_importer_sp->ForgetDestination(m_ast_context);
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);
149 if (!scratch_clang_ast_context)
152 clang::ASTContext *scratch_ast_context =
153 scratch_clang_ast_context->getASTContext();
155 if (!scratch_ast_context)
158 if (m_ast_context != scratch_ast_context && m_ast_importer_sp)
159 m_ast_importer_sp->ForgetSource(scratch_ast_context, m_ast_context);
162 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
166 m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
167 m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
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);
178 if (GetImportInProgress()) {
179 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
183 std::string decl_name(clang_decl_name.getAsString());
185 // if (m_decl_map.DoingASTImport ())
186 // return DeclContext::lookup_result();
188 switch (clang_decl_name.getNameKind()) {
189 // Normal identifiers.
190 case DeclarationName::Identifier: {
191 clang::IdentifierInfo *identifier_info =
192 clang_decl_name.getAsIdentifierInfo();
194 if (!identifier_info || identifier_info->getBuiltinID() != 0) {
195 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
201 case DeclarationName::CXXOperatorName:
202 case DeclarationName::CXXLiteralOperatorName:
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);
211 case DeclarationName::ObjCZeroArgSelector:
212 case DeclarationName::ObjCOneArgSelector:
213 case DeclarationName::ObjCMultiArgSelector: {
214 llvm::SmallVector<NamedDecl *, 1> method_decls;
216 NameSearchContext method_search_context(*this, method_decls,
217 clang_decl_name, decl_ctx);
219 FindObjCMethodDecls(method_search_context);
221 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
222 return (method_decls.size() > 0);
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);
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);
239 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
244 ConstString const_decl_name(decl_name.c_str());
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);
253 m_active_lookups.insert(uniqued_const_decl_name);
254 // static uint32_t g_depth = 0;
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,
261 FindExternalVisibleDecls(name_search_context);
262 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
264 m_active_lookups.erase(uniqued_const_decl_name);
265 return (name_decls.size() != 0);
268 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
269 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
271 static unsigned int invocation_id = 0;
272 unsigned int current_id = invocation_id++;
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());
281 log->Printf(" CTD[%u] Before:", current_id);
282 ASTDumper dumper((Decl *)tag_decl);
283 dumper.ToLog(log, " [CTD] ");
286 auto iter = m_active_lexical_decls.find(tag_decl);
287 if (iter != m_active_lexical_decls.end())
289 m_active_lexical_decls.insert(tag_decl);
290 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
292 if (!m_ast_importer_sp) {
294 GetMergerUnchecked().CompleteType(tag_decl);
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.
304 log->Printf(" CTD[%u] Type could not be completed in the module in "
305 "which it was first found.",
310 DeclContext *decl_ctx = tag_decl->getDeclContext();
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);
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()));
325 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
326 e = namespace_map->end();
327 i != e && !found; ++i) {
329 log->Printf(" CTD[%u] Searching namespace %s in module %s",
330 current_id, i->second.GetName().AsCString(),
331 i->first->GetFileSpec().GetFilename().GetCString());
335 SymbolContext null_sc;
336 ConstString name(tag_decl->getName().str().c_str());
338 i->first->FindTypesInNamespace(null_sc, name, &i->second, UINT32_MAX,
341 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
342 lldb::TypeSP type = types.GetTypeAtIndex(ti);
347 CompilerType clang_type(type->GetFullCompilerType());
349 if (!ClangUtil::IsClangType(clang_type))
352 const TagType *tag_type =
353 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
358 TagDecl *candidate_tag_decl =
359 const_cast<TagDecl *>(tag_type->getDecl());
361 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
369 SymbolContext null_sc;
370 ConstString name(tag_decl->getName().str().c_str());
371 CompilerDeclContext namespace_decl;
373 const ModuleList &module_list = m_target->GetImages();
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);
380 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
381 lldb::TypeSP type = types.GetTypeAtIndex(ti);
386 CompilerType clang_type(type->GetFullCompilerType());
388 if (!ClangUtil::IsClangType(clang_type))
391 const TagType *tag_type =
392 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
397 TagDecl *candidate_tag_decl =
398 const_cast<TagDecl *>(tag_type->getDecl());
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
403 if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
406 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
414 log->Printf(" [CTD] After:");
415 ASTDumper dumper((Decl *)tag_decl);
416 dumper.ToLog(log, " [CTD] ");
420 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
421 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
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] ");
433 if (!m_ast_importer_sp) {
435 ObjCInterfaceDecl *complete_iface_decl =
436 GetCompleteObjCInterface(interface_decl);
438 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
439 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
442 GetMergerUnchecked().CompleteType(interface_decl);
444 lldbassert(0 && "No mechanism for completing a type!");
449 Decl *original_decl = NULL;
450 ASTContext *original_ctx = NULL;
452 if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
454 if (ObjCInterfaceDecl *original_iface_decl =
455 dyn_cast<ObjCInterfaceDecl>(original_decl)) {
456 ObjCInterfaceDecl *complete_iface_decl =
457 GetCompleteObjCInterface(original_iface_decl);
459 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
460 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
465 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
467 if (interface_decl->getSuperClass() &&
468 interface_decl->getSuperClass() != interface_decl)
469 CompleteType(interface_decl->getSuperClass());
472 log->Printf(" [COID] After:");
473 ASTDumper dumper((Decl *)interface_decl);
474 dumper.ToLog(log, " [COID] ");
478 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
479 const clang::ObjCInterfaceDecl *interface_decl) {
480 lldb::ProcessSP process(m_target->GetProcessSP());
485 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
487 if (!language_runtime)
490 ConstString class_name(interface_decl->getNameAsString().c_str());
492 lldb::TypeSP complete_type_sp(
493 language_runtime->LookupInCompleteClassCache(class_name));
495 if (!complete_type_sp)
498 TypeFromUser complete_type =
499 TypeFromUser(complete_type_sp->GetFullCompilerType());
500 lldb::opaque_compiler_type_t complete_opaque_type =
501 complete_type.GetOpaqueQualType();
503 if (!complete_opaque_type)
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);
511 if (!complete_interface_type)
514 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
516 return complete_iface_decl;
519 void ClangASTSource::FindExternalLexicalDecls(
520 const DeclContext *decl_context,
521 llvm::function_ref<bool(Decl::Kind)> predicate,
522 llvm::SmallVectorImpl<Decl *> &decls) {
525 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl_context)) {
526 ObjCInterfaceDecl *complete_iface_decl =
527 GetCompleteObjCInterface(interface_decl);
529 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
530 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
533 return GetMergerUnchecked().FindExternalLexicalDecls(decl_context,
536 } else if (!m_ast_importer_sp)
539 ClangASTMetrics::RegisterLexicalQuery();
541 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
543 const Decl *context_decl = dyn_cast<Decl>(decl_context);
548 auto iter = m_active_lexical_decls.find(context_decl);
549 if (iter != m_active_lexical_decls.end())
551 m_active_lexical_decls.insert(context_decl);
552 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
554 static unsigned int invocation_id = 0;
555 unsigned int current_id = invocation_id++;
558 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
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)
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));
573 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context",
574 current_id, static_cast<const void *>(m_ast_context));
577 Decl *original_decl = NULL;
578 ASTContext *original_ctx = NULL;
580 if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl,
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, " ");
591 if (ObjCInterfaceDecl *original_iface_decl =
592 dyn_cast<ObjCInterfaceDecl>(original_decl)) {
593 ObjCInterfaceDecl *complete_iface_decl =
594 GetCompleteObjCInterface(original_iface_decl);
596 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
597 original_decl = complete_iface_decl;
598 original_ctx = &complete_iface_decl->getASTContext();
600 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
604 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
605 ExternalASTSource *external_source = original_ctx->getExternalSource();
608 external_source->CompleteType(original_tag_decl);
611 const DeclContext *original_decl_context =
612 dyn_cast<DeclContext>(original_decl);
614 if (!original_decl_context)
617 for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
618 iter != original_decl_context->decls_end(); ++iter) {
621 if (predicate(decl->getKind())) {
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());
631 log->Printf(" FELD[%d] Adding lexical %sDecl %s", current_id,
632 decl->getDeclKindName(), ast_dumper.GetCString());
635 Decl *copied_decl = CopyDecl(decl);
640 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
641 QualType copied_field_type = copied_field->getType();
643 m_ast_importer_sp->RequireCompleteType(copied_field_type);
646 DeclContext *decl_context_non_const =
647 const_cast<DeclContext *>(decl_context);
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);
655 if (!decl_context_non_const->containsDecl(copied_decl))
656 decl_context_non_const->addDeclInternal(copied_decl);
663 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
664 assert(m_ast_context);
666 ClangASTMetrics::RegisterVisibleQuery();
668 const ConstString name(context.m_decl_name.getAsString().c_str());
670 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
672 static unsigned int invocation_id = 0;
673 unsigned int current_id = invocation_id++;
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),
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),
687 context_named_decl->getNameAsString().c_str());
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());
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);
702 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
703 GetMergerUnchecked().ForceRecordOrigin(
705 {complete_iface_decl, &complete_iface_decl->getASTContext()});
709 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
710 context.m_decl_name);
711 return; // otherwise we may need to fall back
714 context.m_namespace_map.reset(new ClangASTImporter::NamespaceMap);
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;
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()));
729 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
730 e = namespace_map->end();
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());
737 FindExternalVisibleDecls(context, i->first, i->second, current_id);
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
745 CompilerDeclContext namespace_decl;
748 log->Printf(" CAS::FEVD[%u] Searching the root namespace", current_id);
750 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
754 if (!context.m_namespace_map->empty()) {
755 if (log && log->GetVerbose())
756 log->Printf(" CAS::FEVD[%u] Registering namespace map %p (%d entries)",
758 static_cast<void *>(context.m_namespace_map.get()),
759 static_cast<int>(context.m_namespace_map->size()));
761 NamespaceDecl *clang_namespace_decl =
762 AddNamespace(context, context.m_namespace_map);
764 if (clang_namespace_decl)
765 clang_namespace_decl->setHasExternalVisibleStorage();
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");
774 if (name == id_name || name == Class_name)
777 StringRef name_string_ref = name.GetStringRef();
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("_$"))
788 void ClangASTSource::FindExternalVisibleDecls(
789 NameSearchContext &context, lldb::ModuleSP module_sp,
790 CompilerDeclContext &namespace_decl, unsigned int current_id) {
791 assert(m_ast_context);
793 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
795 SymbolContextList sc_list;
797 const ConstString name(context.m_decl_name.getAsString().c_str());
798 if (IgnoreName(name, true))
801 if (module_sp && namespace_decl) {
802 CompilerDeclContext found_namespace_decl;
804 SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
807 SymbolContext null_sc;
809 found_namespace_decl =
810 symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
812 if (found_namespace_decl) {
813 context.m_namespace_map->push_back(
814 std::pair<lldb::ModuleSP, CompilerDeclContext>(
815 module_sp, found_namespace_decl));
818 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
819 current_id, name.GetCString(),
820 module_sp->GetFileSpec().GetFilename().GetCString());
823 } else if (!HasMerger()) {
824 const ModuleList &target_images = m_target->GetImages();
825 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
827 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
828 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
833 CompilerDeclContext found_namespace_decl;
835 SymbolVendor *symbol_vendor = image->GetSymbolVendor();
840 SymbolContext null_sc;
842 found_namespace_decl =
843 symbol_vendor->FindNamespace(null_sc, name, &namespace_decl);
845 if (found_namespace_decl) {
846 context.m_namespace_map->push_back(
847 std::pair<lldb::ModuleSP, CompilerDeclContext>(
848 image, found_namespace_decl));
851 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
852 current_id, name.GetCString(),
853 image->GetFileSpec().GetFilename().GetCString());
859 if (context.m_found.type)
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);
870 sc.module_sp = module_sp;
871 m_target->GetImages().FindTypes(sc, name, exact_match, 1,
872 searched_symbol_files, types);
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);
880 const char *name_string = type_sp->GetName().GetCString();
882 log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\": %s",
883 current_id, name.GetCString(),
884 (name_string ? name_string : "<anonymous>"));
887 CompilerType full_type = type_sp->GetFullCompilerType();
889 CompilerType copied_clang_type(GuardedCopyType(full_type));
891 if (!copied_clang_type) {
893 log->Printf(" CAS::FEVD[%u] - Couldn't export a type", current_id);
898 context.AddTypeDecl(copied_clang_type);
900 context.m_found.type = true;
905 if (!context.m_found.type) {
906 // Try the modules next.
909 if (ClangModulesDeclVendor *modules_decl_vendor =
910 m_target->GetClangModulesDeclVendor()) {
912 uint32_t max_matches = 1;
913 std::vector<clang::NamedDecl *> decls;
915 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
919 log->Printf(" CAS::FEVD[%u] Matching entity found for \"%s\" in "
921 current_id, name.GetCString());
924 clang::NamedDecl *const decl_from_modules = decls[0];
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;
933 if (!copied_named_decl) {
936 " CAS::FEVD[%u] - Couldn't export a type from the modules",
942 context.AddNamedDecl(copied_named_decl);
944 context.m_found.type = true;
950 if (!context.m_found.type) {
952 // Couldn't find any types elsewhere. Try the Objective-C runtime if
955 lldb::ProcessSP process(m_target->GetProcessSP());
960 ObjCLanguageRuntime *language_runtime(
961 process->GetObjCLanguageRuntime());
963 if (!language_runtime)
966 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
972 uint32_t max_matches = 1;
973 std::vector<clang::NamedDecl *> decls;
975 if (!decl_vendor->FindDecls(name, append, max_matches, decls))
980 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
981 current_id, name.GetCString());
984 clang::Decl *copied_decl = CopyDecl(decls[0]);
985 clang::NamedDecl *copied_named_decl =
986 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
988 if (!copied_named_decl) {
991 " CAS::FEVD[%u] - Couldn't export a type from the runtime",
997 context.AddNamedDecl(copied_named_decl);
1004 template <class D> class TaggedASTDecl {
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; }
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));
1019 template <class D = Decl> class DeclFromParser;
1020 template <class D = Decl> class DeclFromUser;
1022 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
1024 DeclFromParser() : TaggedASTDecl<D>() {}
1025 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1027 DeclFromUser<D> GetOrigin(ClangASTSource &source);
1030 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
1032 DeclFromUser() : TaggedASTDecl<D>() {}
1033 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1035 DeclFromParser<D> Import(ClangASTSource &source);
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));
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));
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();
1061 Selector original_selector;
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);
1074 SmallVector<IdentifierInfo *, 4> idents;
1076 clang::Selector sel = decl_name.getObjCSelector();
1078 unsigned num_args = sel.getNumArgs();
1080 for (unsigned i = 0; i != num_args; ++i) {
1081 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
1085 original_ctx->Selectors.getSelector(num_args, idents.data());
1088 DeclarationName original_decl_name(original_selector);
1090 llvm::SmallVector<NamedDecl *, 1> methods;
1092 ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl);
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);
1103 if (methods.empty()) {
1107 for (NamedDecl *named_decl : methods) {
1111 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
1116 Decl *copied_decl = CopyDecl(result_method);
1121 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
1123 if (!copied_method_decl)
1126 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1129 ASTDumper dumper((Decl *)copied_method_decl);
1130 log->Printf(" CAS::FOMD[%d] found (%s) %s", current_id, log_info,
1131 dumper.GetCString());
1134 context.AddNamedDecl(copied_method_decl);
1140 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
1141 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1144 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) {
1145 ObjCInterfaceDecl *complete_iface_decl =
1146 GetCompleteObjCInterface(interface_decl);
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()});
1153 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
1154 context.m_decl_name);
1158 static unsigned int invocation_id = 0;
1159 unsigned int current_id = invocation_id++;
1161 const DeclarationName &decl_name(context.m_decl_name);
1162 const DeclContext *decl_ctx(context.m_decl_context);
1164 const ObjCInterfaceDecl *interface_decl =
1165 dyn_cast<ObjCInterfaceDecl>(decl_ctx);
1167 if (!interface_decl)
1171 Decl *original_decl = NULL;
1172 ASTContext *original_ctx = NULL;
1174 m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
1180 ObjCInterfaceDecl *original_interface_decl =
1181 dyn_cast<ObjCInterfaceDecl>(original_decl);
1183 if (FindObjCMethodDeclsWithOrigin(current_id, context,
1184 original_interface_decl, "at origin"))
1185 return; // found it, no need to look any further
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());
1195 clang::Selector sel = decl_name.getObjCSelector();
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());
1204 if (ss.GetString().contains("$__lldb"))
1205 return; // we don't need any results
1207 ConstString selector_name(ss.GetString());
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;
1217 const bool include_symbols = false;
1218 const bool include_inlines = false;
1219 const bool append = false;
1221 std::string interface_name = interface_decl->getNameAsString();
1225 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1227 ConstString instance_method_name(ms.GetString());
1229 m_target->GetImages().FindFunctions(
1230 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1231 include_inlines, append, sc_list);
1233 if (sc_list.GetSize())
1237 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1239 ConstString class_method_name(ms.GetString());
1241 m_target->GetImages().FindFunctions(
1242 class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1243 include_inlines, append, sc_list);
1245 if (sc_list.GetSize())
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
1252 SymbolContextList candidate_sc_list;
1254 m_target->GetImages().FindFunctions(
1255 selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1256 include_inlines, append, candidate_sc_list);
1258 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1259 SymbolContext candidate_sc;
1261 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1264 if (!candidate_sc.function)
1267 const char *candidate_name = candidate_sc.function->GetName().AsCString();
1269 const char *cursor = candidate_name;
1271 if (*cursor != '+' && *cursor != '-')
1281 size_t interface_len = interface_name.length();
1283 if (strncmp(cursor, interface_name.c_str(), interface_len))
1286 cursor += interface_len;
1288 if (*cursor == ' ' || *cursor == '(')
1289 sc_list.Append(candidate_sc);
1293 if (sc_list.GetSize()) {
1294 // We found a good function symbol. Use that.
1296 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1299 if (!sc_list.GetContextAtIndex(i, sc))
1305 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1306 if (!function_decl_ctx)
1309 ObjCMethodDecl *method_decl =
1310 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1315 ObjCInterfaceDecl *found_interface_decl =
1316 method_decl->getClassInterface();
1318 if (!found_interface_decl)
1321 if (found_interface_decl->getName() == interface_decl->getName()) {
1322 Decl *copied_decl = CopyDecl(method_decl);
1327 ObjCMethodDecl *copied_method_decl =
1328 dyn_cast<ObjCMethodDecl>(copied_decl);
1330 if (!copied_method_decl)
1334 ASTDumper dumper((Decl *)copied_method_decl);
1335 log->Printf(" CAS::FOMD[%d] found (in symbols) %s", current_id,
1336 dumper.GetCString());
1339 context.AddNamedDecl(copied_method_decl);
1346 // Try the debug information.
1349 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1350 const_cast<ObjCInterfaceDecl *>(interface_decl));
1352 if (!complete_interface_decl)
1355 // We found the complete interface. The runtime never needs to be queried
1356 // in this scenario.
1358 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1359 complete_interface_decl);
1361 if (complete_interface_decl == interface_decl)
1362 break; // already checked this one
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()));
1370 FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl,
1377 // Check the modules only if the debug information didn't have a complete
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;
1387 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1391 ObjCInterfaceDecl *interface_decl_from_modules =
1392 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1394 if (!interface_decl_from_modules)
1397 if (FindObjCMethodDeclsWithOrigin(
1398 current_id, context, interface_decl_from_modules, "in modules"))
1404 // Check the runtime only if the debug information didn't have a complete
1405 // interface and the modules don't get us anywhere.
1407 lldb::ProcessSP process(m_target->GetProcessSP());
1412 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
1414 if (!language_runtime)
1417 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
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;
1427 if (!decl_vendor->FindDecls(interface_name, append, max_matches, decls))
1430 ObjCInterfaceDecl *runtime_interface_decl =
1431 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1433 if (!runtime_interface_decl)
1436 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl,
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));
1446 if (origin_iface_decl.IsInvalid())
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));
1454 DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1455 origin_iface_decl->FindPropertyDeclaration(
1456 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1460 if (origin_property_decl.IsValid()) {
1461 DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1462 origin_property_decl.Import(source));
1463 if (parser_property_decl.IsValid()) {
1465 ASTDumper dumper((Decl *)parser_property_decl.decl);
1466 log->Printf(" CAS::FOPD[%d] found %s", current_id,
1467 dumper.GetCString());
1470 context.AddNamedDecl(parser_property_decl.decl);
1475 DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1476 origin_iface_decl->getIvarDecl(&name_identifier));
1478 if (origin_ivar_decl.IsValid()) {
1479 DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1480 origin_ivar_decl.Import(source));
1481 if (parser_ivar_decl.IsValid()) {
1483 ASTDumper dumper((Decl *)parser_ivar_decl.decl);
1484 log->Printf(" CAS::FOPD[%d] found %s", current_id,
1485 dumper.GetCString());
1488 context.AddNamedDecl(parser_ivar_decl.decl);
1496 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1497 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1499 static unsigned int invocation_id = 0;
1500 unsigned int current_id = invocation_id++;
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));
1507 ConstString class_name(parser_iface_decl->getNameAsString().c_str());
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());
1516 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1517 current_id, context, *this, origin_iface_decl))
1521 log->Printf("CAS::FOPD[%d] couldn't find the property on origin "
1522 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "
1524 current_id, static_cast<const void *>(origin_iface_decl.decl),
1525 static_cast<void *>(&origin_iface_decl->getASTContext()));
1527 SymbolContext null_sc;
1531 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1532 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1534 if (!complete_interface_decl)
1537 // We found the complete interface. The runtime never needs to be queried
1538 // in this scenario.
1540 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1541 complete_interface_decl);
1543 if (complete_iface_decl.decl == origin_iface_decl.decl)
1544 break; // already checked this one
1547 log->Printf("CAS::FOPD[%d] trying origin "
1548 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1550 static_cast<const void *>(complete_iface_decl.decl),
1551 static_cast<void *>(&complete_iface_decl->getASTContext()));
1553 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1554 complete_iface_decl);
1560 // Check the modules only if the debug information didn't have a complete
1563 ClangModulesDeclVendor *modules_decl_vendor =
1564 m_target->GetClangModulesDeclVendor();
1566 if (!modules_decl_vendor)
1569 bool append = false;
1570 uint32_t max_matches = 1;
1571 std::vector<clang::NamedDecl *> decls;
1573 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1576 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1577 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1579 if (!interface_decl_from_modules.IsValid())
1584 "CAS::FOPD[%d] trying module "
1585 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1587 static_cast<const void *>(interface_decl_from_modules.decl),
1588 static_cast<void *>(&interface_decl_from_modules->getASTContext()));
1590 if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1591 interface_decl_from_modules))
1596 // Check the runtime only if the debug information didn't have a complete
1597 // interface and nothing was in the modules.
1599 lldb::ProcessSP process(m_target->GetProcessSP());
1604 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
1606 if (!language_runtime)
1609 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1614 bool append = false;
1615 uint32_t max_matches = 1;
1616 std::vector<clang::NamedDecl *> decls;
1618 if (!decl_vendor->FindDecls(class_name, append, max_matches, decls))
1621 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1622 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1624 if (!interface_decl_from_runtime.IsValid())
1629 "CAS::FOPD[%d] trying runtime "
1630 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1632 static_cast<const void *>(interface_decl_from_runtime.decl),
1633 static_cast<void *>(&interface_decl_from_runtime->getASTContext()));
1635 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1636 current_id, context, *this, interface_decl_from_runtime))
1641 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1642 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
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;
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())
1668 destination_map.insert(
1669 std::pair<const D *, O>(parser_decl.decl, item.second));
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());
1683 if (!IsVirtual && bi->isVirtual())
1686 const clang::Type *origin_base_type = bi->getType().getTypePtr();
1687 const clang::RecordType *origin_base_record_type =
1688 origin_base_type->getAs<RecordType>();
1690 if (!origin_base_record_type)
1693 DeclFromUser<RecordDecl> origin_base_record(
1694 origin_base_record_type->getDecl());
1696 if (origin_base_record.IsInvalid())
1699 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1700 DynCast<CXXRecordDecl>(origin_base_record));
1702 if (origin_base_cxx_record.IsInvalid())
1705 CharUnits base_offset;
1709 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1712 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1714 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1715 origin_base_cxx_record.decl, base_offset));
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();
1728 static unsigned int invocation_id = 0;
1729 unsigned int current_id = invocation_id++;
1731 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1734 log->Printf("LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "
1736 current_id, static_cast<void *>(m_ast_context),
1737 static_cast<const void *>(record),
1738 record->getNameAsString().c_str());
1740 DeclFromParser<const RecordDecl> parser_record(record);
1741 DeclFromUser<const RecordDecl> origin_record(
1742 parser_record.GetOrigin(*this));
1744 if (origin_record.IsInvalid())
1747 FieldOffsetMap origin_field_offsets;
1748 BaseOffsetMap origin_base_offsets;
1749 BaseOffsetMap origin_virtual_base_offsets;
1751 ClangASTContext::GetCompleteDecl(
1752 &origin_record->getASTContext(),
1753 const_cast<RecordDecl *>(origin_record.decl));
1755 clang::RecordDecl *definition = origin_record.decl->getDefinition();
1756 if (!definition || !definition->isCompleteDefinition())
1759 const ASTRecordLayout &record_layout(
1760 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1762 int field_idx = 0, field_count = record_layout.getFieldCount();
1764 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1765 fe = origin_record->field_end();
1767 if (field_idx >= field_count)
1768 return false; // Layout didn't go well. Bail out.
1770 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1772 origin_field_offsets.insert(
1773 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1778 lldbassert(&record->getASTContext() == m_ast_context);
1780 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1781 DynCast<const CXXRecordDecl>(origin_record));
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))
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,
1797 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1798 alignment = record_layout.getAlignment().getQuantity() *
1799 m_ast_context->getCharWidth();
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();
1811 log->Printf("LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %" PRId64
1813 current_id, static_cast<void *>(*fi),
1814 fi->getNameAsString().c_str(), field_offsets[*fi]);
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();
1824 bool is_virtual = bi->isVirtual();
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);
1833 "LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64
1835 current_id, (is_virtual ? "Virtual " : ""),
1836 static_cast<void *>(base_cxx_record.decl),
1837 base_cxx_record.decl->getNameAsString().c_str(),
1839 ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1840 : base_offsets[base_cxx_record.decl].getQuantity()));
1843 log->Printf("LRD[%u] Not a CXXRecord, so no bases", current_id);
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++;
1856 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
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),
1864 parent_map->begin()->second.GetName().AsCString());
1866 log->Printf("CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1868 current_id, static_cast<void *>(m_ast_context),
1873 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1874 e = parent_map->end();
1876 CompilerDeclContext found_namespace_decl;
1878 lldb::ModuleSP module_sp = i->first;
1879 CompilerDeclContext module_parent_namespace_decl = i->second;
1881 SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
1886 SymbolContext null_sc;
1888 found_namespace_decl = symbol_vendor->FindNamespace(
1889 null_sc, name, &module_parent_namespace_decl);
1891 if (!found_namespace_decl)
1894 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1895 module_sp, found_namespace_decl));
1898 log->Printf(" CMN[%u] Found namespace %s in module %s", current_id,
1900 module_sp->GetFileSpec().GetFilename().GetCString());
1903 const ModuleList &target_images = m_target->GetImages();
1904 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1906 CompilerDeclContext null_namespace_decl;
1908 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1909 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1914 CompilerDeclContext found_namespace_decl;
1916 SymbolVendor *symbol_vendor = image->GetSymbolVendor();
1921 SymbolContext null_sc;
1923 found_namespace_decl =
1924 symbol_vendor->FindNamespace(null_sc, name, &null_namespace_decl);
1926 if (!found_namespace_decl)
1929 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1930 image, found_namespace_decl));
1933 log->Printf(" CMN[%u] Found namespace %s in module %s", current_id,
1935 image->GetFileSpec().GetFilename().GetCString());
1940 NamespaceDecl *ClangASTSource::AddNamespace(
1941 NameSearchContext &context,
1942 ClangASTImporter::NamespaceMapSP &namespace_decls) {
1943 if (!namespace_decls)
1946 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1948 clang::ASTContext *src_ast =
1949 ClangASTContext::DeclContextGetClangASTContext(namespace_decl);
1952 clang::NamespaceDecl *src_namespace_decl =
1953 ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl);
1955 if (!src_namespace_decl)
1958 Decl *copied_decl = CopyDecl(src_namespace_decl);
1963 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1965 if (!copied_namespace_decl)
1968 context.m_decls.push_back(copied_namespace_decl);
1970 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1973 return dyn_cast<NamespaceDecl>(copied_decl);
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!");
1985 return merger.ImporterForOrigin(from_context).Import(type);
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!");
1998 return m_merger_up->ImporterForOrigin(from_context).Import(src_decl);
2000 lldbassert(0 && "No mechanism for copying a decl!");
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,
2011 } else if (m_merger_up) {
2012 return false; // Implement this correctly in ExternalASTMerger
2014 // this can happen early enough that no ExternalASTSource is installed.
2019 clang::ExternalASTMerger &ClangASTSource::GetMergerUnchecked() {
2020 lldbassert(m_merger_up != nullptr);
2021 return *m_merger_up;
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();
2030 ClangASTMetrics::RegisterLLDBImport();
2032 SetImportInProgress(true);
2034 QualType copied_qual_type;
2036 if (m_ast_importer_sp) {
2038 m_ast_importer_sp->CopyType(m_ast_context, src_ast->getASTContext(),
2039 ClangUtil::GetQualType(src_type));
2040 } else if (m_merger_up) {
2042 CopyTypeWithMerger(*src_ast->getASTContext(), *m_merger_up,
2043 ClangUtil::GetQualType(src_type));
2045 lldbassert(0 && "No mechanism for copying a type!");
2046 return CompilerType();
2049 SetImportInProgress(false);
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();
2057 return CompilerType(m_ast_context, copied_qual_type);
2060 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) {
2061 assert(type && "Type for variable must be valid!");
2063 if (!type.IsValid())
2066 ClangASTContext *lldb_ast =
2067 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2071 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
2073 clang::ASTContext *ast = lldb_ast->getASTContext();
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);
2083 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type,
2085 assert(type && "Type for variable must be valid!");
2087 if (!type.IsValid())
2090 if (m_function_types.count(type))
2093 ClangASTContext *lldb_ast =
2094 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2098 m_function_types.insert(type);
2100 QualType qual_type(ClangUtil::GetQualType(type));
2102 clang::ASTContext *ast = lldb_ast->getASTContext();
2104 const bool isInlineSpecified = false;
2105 const bool hasWrittenPrototype = true;
2106 const bool isConstexprSpecified = false;
2108 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context);
2111 context = LinkageSpecDecl::Create(
2112 *ast, context, SourceLocation(), SourceLocation(),
2113 clang::LinkageSpecDecl::LanguageIDs::lang_c, false);
2116 // Pass the identifier info for functions the decl_name is needed for
2118 clang::DeclarationName decl_name =
2119 m_decl_name.getNameKind() == DeclarationName::Identifier
2120 ? m_decl_name.getAsIdentifierInfo()
2123 clang::FunctionDecl *func_decl = FunctionDecl::Create(
2124 *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type,
2125 NULL, SC_Extern, isInlineSpecified, hasWrittenPrototype,
2126 isConstexprSpecified);
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.
2132 const FunctionProtoType *func_proto_type =
2133 qual_type.getTypePtr()->getAs<FunctionProtoType>();
2135 if (func_proto_type) {
2136 unsigned NumArgs = func_proto_type->getNumParams();
2139 SmallVector<ParmVarDecl *, 5> parm_var_decls;
2141 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) {
2142 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex));
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));
2149 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls));
2151 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2154 log->Printf("Function type wasn't a FunctionProtoType");
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()))
2169 m_decls.push_back(func_decl);
2174 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() {
2175 FunctionProtoType::ExtProtoInfo proto_info;
2177 proto_info.Variadic = true;
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
2185 CompilerType(m_ast_source.m_ast_context, generic_function_type), true);
2189 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) {
2190 if (ClangUtil::IsClangType(clang_type)) {
2191 QualType qual_type = ClangUtil::GetQualType(clang_type);
2193 if (const TypedefType *typedef_type =
2194 llvm::dyn_cast<TypedefType>(qual_type)) {
2195 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
2197 m_decls.push_back(typedef_name_decl);
2199 return (NamedDecl *)typedef_name_decl;
2200 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) {
2201 TagDecl *tag_decl = tag_type->getDecl();
2203 m_decls.push_back(tag_decl);
2206 } else if (const ObjCObjectType *objc_object_type =
2207 qual_type->getAs<ObjCObjectType>()) {
2208 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
2210 m_decls.push_back((NamedDecl *)interface_decl);
2212 return (NamedDecl *)interface_decl;
2218 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
2219 for (clang::NamedDecl *decl : result)
2220 m_decls.push_back(decl);
2223 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) {
2224 m_decls.push_back(decl);