1 //===-- ClangASTSource.cpp ------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "ClangASTSource.h"
11 #include "ClangDeclVendor.h"
12 #include "ClangModulesDeclVendor.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Symbol/CompilerDeclContext.h"
17 #include "lldb/Symbol/Function.h"
18 #include "lldb/Symbol/SymbolFile.h"
19 #include "lldb/Symbol/TaggedASTType.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Utility/LLDBLog.h"
22 #include "lldb/Utility/Log.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/Basic/SourceManager.h"
27 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
28 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
29 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
34 using namespace clang
;
35 using namespace lldb_private
;
37 // Scoped class that will remove an active lexical decl from the set when it
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(
55 const lldb::TargetSP
&target
,
56 const std::shared_ptr
<ClangASTImporter
> &importer
)
57 : m_lookups_enabled(false), m_target(target
), m_ast_context(nullptr),
58 m_ast_importer_sp(importer
), m_active_lexical_decls(),
60 assert(m_ast_importer_sp
&& "No ClangASTImporter passed to ClangASTSource?");
63 void ClangASTSource::InstallASTContext(TypeSystemClang
&clang_ast_context
) {
64 m_ast_context
= &clang_ast_context
.getASTContext();
65 m_clang_ast_context
= &clang_ast_context
;
66 m_file_manager
= &m_ast_context
->getSourceManager().getFileManager();
67 m_ast_importer_sp
->InstallMapCompleter(m_ast_context
, *this);
70 ClangASTSource::~ClangASTSource() {
71 m_ast_importer_sp
->ForgetDestination(m_ast_context
);
76 // Unregister the current ASTContext as a source for all scratch
77 // ASTContexts in the ClangASTImporter. Without this the scratch AST might
78 // query the deleted ASTContext for additional type information.
79 // We unregister from *all* scratch ASTContexts in case a type got exported
80 // to a scratch AST that isn't the best fitting scratch ASTContext.
81 lldb::TypeSystemClangSP scratch_ts_sp
= ScratchTypeSystemClang::GetForTarget(
82 *m_target
, ScratchTypeSystemClang::DefaultAST
, false);
87 ScratchTypeSystemClang
*default_scratch_ast
=
88 llvm::cast
<ScratchTypeSystemClang
>(scratch_ts_sp
.get());
89 // Unregister from the default scratch AST (and all sub-ASTs).
90 default_scratch_ast
->ForgetSource(m_ast_context
, *m_ast_importer_sp
);
93 void ClangASTSource::StartTranslationUnit(ASTConsumer
*Consumer
) {
97 m_ast_context
->getTranslationUnitDecl()->setHasExternalVisibleStorage();
98 m_ast_context
->getTranslationUnitDecl()->setHasExternalLexicalStorage();
101 // The core lookup interface.
102 bool ClangASTSource::FindExternalVisibleDeclsByName(
103 const DeclContext
*decl_ctx
, DeclarationName clang_decl_name
) {
104 if (!m_ast_context
) {
105 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
109 std::string
decl_name(clang_decl_name
.getAsString());
111 switch (clang_decl_name
.getNameKind()) {
112 // Normal identifiers.
113 case DeclarationName::Identifier
: {
114 clang::IdentifierInfo
*identifier_info
=
115 clang_decl_name
.getAsIdentifierInfo();
117 if (!identifier_info
|| identifier_info
->getBuiltinID() != 0) {
118 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
124 case DeclarationName::CXXOperatorName
:
125 case DeclarationName::CXXLiteralOperatorName
:
128 // Using directives found in this context.
129 // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
130 case DeclarationName::CXXUsingDirective
:
131 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
134 case DeclarationName::ObjCZeroArgSelector
:
135 case DeclarationName::ObjCOneArgSelector
:
136 case DeclarationName::ObjCMultiArgSelector
: {
137 llvm::SmallVector
<NamedDecl
*, 1> method_decls
;
139 NameSearchContext
method_search_context(*m_clang_ast_context
, method_decls
,
140 clang_decl_name
, decl_ctx
);
142 FindObjCMethodDecls(method_search_context
);
144 SetExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
, method_decls
);
145 return (method_decls
.size() > 0);
147 // These aren't possible in the global context.
148 case DeclarationName::CXXConstructorName
:
149 case DeclarationName::CXXDestructorName
:
150 case DeclarationName::CXXConversionFunctionName
:
151 case DeclarationName::CXXDeductionGuideName
:
152 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
156 if (!GetLookupsEnabled()) {
157 // Wait until we see a '$' at the start of a name before we start doing any
158 // lookups so we can avoid lookup up all of the builtin types.
159 if (!decl_name
.empty() && decl_name
[0] == '$') {
160 SetLookupsEnabled(true);
162 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
167 ConstString
const_decl_name(decl_name
.c_str());
169 const char *uniqued_const_decl_name
= const_decl_name
.GetCString();
170 if (m_active_lookups
.find(uniqued_const_decl_name
) !=
171 m_active_lookups
.end()) {
172 // We are currently looking up this name...
173 SetNoExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
);
176 m_active_lookups
.insert(uniqued_const_decl_name
);
177 llvm::SmallVector
<NamedDecl
*, 4> name_decls
;
178 NameSearchContext
name_search_context(*m_clang_ast_context
, name_decls
,
179 clang_decl_name
, decl_ctx
);
180 FindExternalVisibleDecls(name_search_context
);
181 SetExternalVisibleDeclsForName(decl_ctx
, clang_decl_name
, name_decls
);
182 m_active_lookups
.erase(uniqued_const_decl_name
);
183 return (name_decls
.size() != 0);
186 TagDecl
*ClangASTSource::FindCompleteType(const TagDecl
*decl
) {
187 Log
*log
= GetLog(LLDBLog::Expressions
);
189 if (const NamespaceDecl
*namespace_context
=
190 dyn_cast
<NamespaceDecl
>(decl
->getDeclContext())) {
191 ClangASTImporter::NamespaceMapSP namespace_map
=
192 m_ast_importer_sp
->GetNamespaceMap(namespace_context
);
197 LLDB_LOGV(log
, " CTD Inspecting namespace map{0} ({1} entries)",
198 namespace_map
.get(), namespace_map
->size());
200 for (const ClangASTImporter::NamespaceMapItem
&item
: *namespace_map
) {
201 LLDB_LOG(log
, " CTD Searching namespace {0} in module {1}",
202 item
.second
.GetName(), item
.first
->GetFileSpec().GetFilename());
206 ConstString
name(decl
->getName());
208 item
.first
->FindTypesInNamespace(name
, item
.second
, UINT32_MAX
, types
);
210 for (uint32_t ti
= 0, te
= types
.GetSize(); ti
!= te
; ++ti
) {
211 lldb::TypeSP type
= types
.GetTypeAtIndex(ti
);
216 CompilerType
clang_type(type
->GetFullCompilerType());
218 if (!ClangUtil::IsClangType(clang_type
))
221 const TagType
*tag_type
=
222 ClangUtil::GetQualType(clang_type
)->getAs
<TagType
>();
227 TagDecl
*candidate_tag_decl
=
228 const_cast<TagDecl
*>(tag_type
->getDecl());
230 if (TypeSystemClang::GetCompleteDecl(
231 &candidate_tag_decl
->getASTContext(), candidate_tag_decl
))
232 return candidate_tag_decl
;
238 ConstString
name(decl
->getName());
240 const ModuleList
&module_list
= m_target
->GetImages();
242 bool exact_match
= false;
243 llvm::DenseSet
<SymbolFile
*> searched_symbol_files
;
244 module_list
.FindTypes(nullptr, name
, exact_match
, UINT32_MAX
,
245 searched_symbol_files
, types
);
247 for (uint32_t ti
= 0, te
= types
.GetSize(); ti
!= te
; ++ti
) {
248 lldb::TypeSP type
= types
.GetTypeAtIndex(ti
);
253 CompilerType
clang_type(type
->GetFullCompilerType());
255 if (!ClangUtil::IsClangType(clang_type
))
258 const TagType
*tag_type
=
259 ClangUtil::GetQualType(clang_type
)->getAs
<TagType
>();
264 TagDecl
*candidate_tag_decl
= const_cast<TagDecl
*>(tag_type
->getDecl());
266 // We have found a type by basename and we need to make sure the decl
267 // contexts are the same before we can try to complete this type with
269 if (!TypeSystemClang::DeclsAreEquivalent(const_cast<TagDecl
*>(decl
),
273 if (TypeSystemClang::GetCompleteDecl(&candidate_tag_decl
->getASTContext(),
275 return candidate_tag_decl
;
281 void ClangASTSource::CompleteType(TagDecl
*tag_decl
) {
282 Log
*log
= GetLog(LLDBLog::Expressions
);
286 " CompleteTagDecl on (ASTContext*){0} Completing "
287 "(TagDecl*){1} named {2}",
288 m_clang_ast_context
->getDisplayName(), tag_decl
,
289 tag_decl
->getName());
291 LLDB_LOG(log
, " CTD Before:\n{0}", ClangUtil::DumpDecl(tag_decl
));
294 auto iter
= m_active_lexical_decls
.find(tag_decl
);
295 if (iter
!= m_active_lexical_decls
.end())
297 m_active_lexical_decls
.insert(tag_decl
);
298 ScopedLexicalDeclEraser
eraser(m_active_lexical_decls
, tag_decl
);
300 if (!m_ast_importer_sp
->CompleteTagDecl(tag_decl
)) {
301 // We couldn't complete the type. Maybe there's a definition somewhere
302 // else that can be completed.
303 if (TagDecl
*alternate
= FindCompleteType(tag_decl
))
304 m_ast_importer_sp
->CompleteTagDeclWithOrigin(tag_decl
, alternate
);
307 LLDB_LOG(log
, " [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl
));
310 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl
*interface_decl
) {
311 Log
*log
= GetLog(LLDBLog::Expressions
);
314 " [CompleteObjCInterfaceDecl] on (ASTContext*){0} '{1}' "
315 "Completing an ObjCInterfaceDecl named {1}",
316 m_ast_context
, m_clang_ast_context
->getDisplayName(),
317 interface_decl
->getName());
318 LLDB_LOG(log
, " [COID] Before:\n{0}",
319 ClangUtil::DumpDecl(interface_decl
));
321 ClangASTImporter::DeclOrigin original
= m_ast_importer_sp
->GetDeclOrigin(interface_decl
);
323 if (original
.Valid()) {
324 if (ObjCInterfaceDecl
*original_iface_decl
=
325 dyn_cast
<ObjCInterfaceDecl
>(original
.decl
)) {
326 ObjCInterfaceDecl
*complete_iface_decl
=
327 GetCompleteObjCInterface(original_iface_decl
);
329 if (complete_iface_decl
&& (complete_iface_decl
!= original_iface_decl
)) {
330 m_ast_importer_sp
->SetDeclOrigin(interface_decl
, complete_iface_decl
);
335 m_ast_importer_sp
->CompleteObjCInterfaceDecl(interface_decl
);
337 if (interface_decl
->getSuperClass() &&
338 interface_decl
->getSuperClass() != interface_decl
)
339 CompleteType(interface_decl
->getSuperClass());
341 LLDB_LOG(log
, " [COID] After:");
342 LLDB_LOG(log
, " [COID] {0}", ClangUtil::DumpDecl(interface_decl
));
345 clang::ObjCInterfaceDecl
*ClangASTSource::GetCompleteObjCInterface(
346 const clang::ObjCInterfaceDecl
*interface_decl
) {
347 lldb::ProcessSP
process(m_target
->GetProcessSP());
352 ObjCLanguageRuntime
*language_runtime(ObjCLanguageRuntime::Get(*process
));
354 if (!language_runtime
)
357 ConstString
class_name(interface_decl
->getNameAsString().c_str());
359 lldb::TypeSP
complete_type_sp(
360 language_runtime
->LookupInCompleteClassCache(class_name
));
362 if (!complete_type_sp
)
365 TypeFromUser complete_type
=
366 TypeFromUser(complete_type_sp
->GetFullCompilerType());
367 lldb::opaque_compiler_type_t complete_opaque_type
=
368 complete_type
.GetOpaqueQualType();
370 if (!complete_opaque_type
)
373 const clang::Type
*complete_clang_type
=
374 QualType::getFromOpaquePtr(complete_opaque_type
).getTypePtr();
375 const ObjCInterfaceType
*complete_interface_type
=
376 dyn_cast
<ObjCInterfaceType
>(complete_clang_type
);
378 if (!complete_interface_type
)
381 ObjCInterfaceDecl
*complete_iface_decl(complete_interface_type
->getDecl());
383 return complete_iface_decl
;
386 void ClangASTSource::FindExternalLexicalDecls(
387 const DeclContext
*decl_context
,
388 llvm::function_ref
<bool(Decl::Kind
)> predicate
,
389 llvm::SmallVectorImpl
<Decl
*> &decls
) {
391 Log
*log
= GetLog(LLDBLog::Expressions
);
393 const Decl
*context_decl
= dyn_cast
<Decl
>(decl_context
);
398 auto iter
= m_active_lexical_decls
.find(context_decl
);
399 if (iter
!= m_active_lexical_decls
.end())
401 m_active_lexical_decls
.insert(context_decl
);
402 ScopedLexicalDeclEraser
eraser(m_active_lexical_decls
, context_decl
);
405 if (const NamedDecl
*context_named_decl
= dyn_cast
<NamedDecl
>(context_decl
))
407 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
408 "'{2}' ({3}Decl*){4}",
409 m_ast_context
, m_clang_ast_context
->getDisplayName(),
410 context_named_decl
->getNameAsString().c_str(),
411 context_decl
->getDeclKindName(),
412 static_cast<const void *>(context_decl
));
413 else if (context_decl
)
415 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
417 m_ast_context
, m_clang_ast_context
->getDisplayName(),
418 context_decl
->getDeclKindName(),
419 static_cast<const void *>(context_decl
));
422 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in a "
424 m_ast_context
, m_clang_ast_context
->getDisplayName());
427 ClangASTImporter::DeclOrigin original
= m_ast_importer_sp
->GetDeclOrigin(context_decl
);
429 if (!original
.Valid())
432 LLDB_LOG(log
, " FELD Original decl {0} (Decl*){1:x}:\n{2}",
433 static_cast<void *>(original
.ctx
),
434 static_cast<void *>(original
.decl
),
435 ClangUtil::DumpDecl(original
.decl
));
437 if (ObjCInterfaceDecl
*original_iface_decl
=
438 dyn_cast
<ObjCInterfaceDecl
>(original
.decl
)) {
439 ObjCInterfaceDecl
*complete_iface_decl
=
440 GetCompleteObjCInterface(original_iface_decl
);
442 if (complete_iface_decl
&& (complete_iface_decl
!= original_iface_decl
)) {
443 original
.decl
= complete_iface_decl
;
444 original
.ctx
= &complete_iface_decl
->getASTContext();
446 m_ast_importer_sp
->SetDeclOrigin(context_decl
, complete_iface_decl
);
450 if (TagDecl
*original_tag_decl
= dyn_cast
<TagDecl
>(original
.decl
)) {
451 ExternalASTSource
*external_source
= original
.ctx
->getExternalSource();
454 external_source
->CompleteType(original_tag_decl
);
457 const DeclContext
*original_decl_context
=
458 dyn_cast
<DeclContext
>(original
.decl
);
460 if (!original_decl_context
)
463 // Indicates whether we skipped any Decls of the original DeclContext.
464 bool SkippedDecls
= false;
465 for (Decl
*decl
: original_decl_context
->decls()) {
466 // The predicate function returns true if the passed declaration kind is
467 // the one we are looking for.
468 // See clang::ExternalASTSource::FindExternalLexicalDecls()
469 if (predicate(decl
->getKind())) {
471 std::string ast_dump
= ClangUtil::DumpDecl(decl
);
472 if (const NamedDecl
*context_named_decl
=
473 dyn_cast
<NamedDecl
>(context_decl
))
474 LLDB_LOG(log
, " FELD Adding [to {0}Decl {1}] lexical {2}Decl {3}",
475 context_named_decl
->getDeclKindName(),
476 context_named_decl
->getName(), decl
->getDeclKindName(),
479 LLDB_LOG(log
, " FELD Adding lexical {0}Decl {1}",
480 decl
->getDeclKindName(), ast_dump
);
483 Decl
*copied_decl
= CopyDecl(decl
);
488 // FIXME: We should add the copied decl to the 'decls' list. This would
489 // add the copied Decl into the DeclContext and make sure that we
490 // correctly propagate that we added some Decls back to Clang.
491 // By leaving 'decls' empty we incorrectly return false from
492 // DeclContext::LoadLexicalDeclsFromExternalStorage which might cause
493 // lookup issues later on.
494 // We can't just add them for now as the ASTImporter already added the
495 // decl into the DeclContext and this would add it twice.
497 if (FieldDecl
*copied_field
= dyn_cast
<FieldDecl
>(copied_decl
)) {
498 QualType copied_field_type
= copied_field
->getType();
500 m_ast_importer_sp
->RequireCompleteType(copied_field_type
);
507 // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
508 // to false. However, since we skipped some of the external Decls we must
511 decl_context
->setHasExternalLexicalStorage(true);
512 // This sets HasLazyExternalLexicalLookups to true. By setting this bit we
513 // ensure that the lookup table is rebuilt, which means the external source
514 // is consulted again when a clang::DeclContext::lookup is called.
515 const_cast<DeclContext
*>(decl_context
)->setMustBuildLookupTable();
519 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext
&context
) {
520 assert(m_ast_context
);
522 const ConstString
name(context
.m_decl_name
.getAsString().c_str());
524 Log
*log
= GetLog(LLDBLog::Expressions
);
527 if (!context
.m_decl_context
)
529 "ClangASTSource::FindExternalVisibleDecls on "
530 "(ASTContext*){0} '{1}' for '{2}' in a NULL DeclContext",
531 m_ast_context
, m_clang_ast_context
->getDisplayName(), name
);
532 else if (const NamedDecl
*context_named_decl
=
533 dyn_cast
<NamedDecl
>(context
.m_decl_context
))
535 "ClangASTSource::FindExternalVisibleDecls on "
536 "(ASTContext*){0} '{1}' for '{2}' in '{3}'",
537 m_ast_context
, m_clang_ast_context
->getDisplayName(), name
,
538 context_named_decl
->getName());
541 "ClangASTSource::FindExternalVisibleDecls on "
542 "(ASTContext*){0} '{1}' for '{2}' in a '{3}'",
543 m_ast_context
, m_clang_ast_context
->getDisplayName(), name
,
544 context
.m_decl_context
->getDeclKindName());
547 if (isa
<NamespaceDecl
>(context
.m_decl_context
)) {
548 LookupInNamespace(context
);
549 } else if (isa
<ObjCInterfaceDecl
>(context
.m_decl_context
)) {
550 FindObjCPropertyAndIvarDecls(context
);
551 } else if (!isa
<TranslationUnitDecl
>(context
.m_decl_context
)) {
552 // we shouldn't be getting FindExternalVisibleDecls calls for these
555 CompilerDeclContext namespace_decl
;
557 LLDB_LOG(log
, " CAS::FEVD Searching the root namespace");
559 FindExternalVisibleDecls(context
, lldb::ModuleSP(), namespace_decl
);
562 if (!context
.m_namespace_map
->empty()) {
563 if (log
&& log
->GetVerbose())
564 LLDB_LOG(log
, " CAS::FEVD Registering namespace map {0} ({1} entries)",
565 context
.m_namespace_map
.get(), context
.m_namespace_map
->size());
567 NamespaceDecl
*clang_namespace_decl
=
568 AddNamespace(context
, context
.m_namespace_map
);
570 if (clang_namespace_decl
)
571 clang_namespace_decl
->setHasExternalVisibleStorage();
575 clang::Sema
*ClangASTSource::getSema() {
576 return m_clang_ast_context
->getSema();
579 bool ClangASTSource::IgnoreName(const ConstString name
,
580 bool ignore_all_dollar_names
) {
581 static const ConstString
id_name("id");
582 static const ConstString
Class_name("Class");
584 if (m_ast_context
->getLangOpts().ObjC
)
585 if (name
== id_name
|| name
== Class_name
)
588 StringRef name_string_ref
= name
.GetStringRef();
590 // The ClangASTSource is not responsible for finding $-names.
591 return name_string_ref
.empty() ||
592 (ignore_all_dollar_names
&& name_string_ref
.startswith("$")) ||
593 name_string_ref
.startswith("_$");
596 void ClangASTSource::FindExternalVisibleDecls(
597 NameSearchContext
&context
, lldb::ModuleSP module_sp
,
598 CompilerDeclContext
&namespace_decl
) {
599 assert(m_ast_context
);
601 Log
*log
= GetLog(LLDBLog::Expressions
);
603 SymbolContextList sc_list
;
605 const ConstString
name(context
.m_decl_name
.getAsString().c_str());
606 if (IgnoreName(name
, true))
612 FillNamespaceMap(context
, module_sp
, namespace_decl
);
614 if (context
.m_found_type
)
618 const bool exact_match
= true;
619 llvm::DenseSet
<lldb_private::SymbolFile
*> searched_symbol_files
;
620 if (module_sp
&& namespace_decl
)
621 module_sp
->FindTypesInNamespace(name
, namespace_decl
, 1, types
);
623 m_target
->GetImages().FindTypes(module_sp
.get(), name
, exact_match
, 1,
624 searched_symbol_files
, types
);
627 if (size_t num_types
= types
.GetSize()) {
628 for (size_t ti
= 0; ti
< num_types
; ++ti
) {
629 lldb::TypeSP type_sp
= types
.GetTypeAtIndex(ti
);
632 const char *name_string
= type_sp
->GetName().GetCString();
634 LLDB_LOG(log
, " CAS::FEVD Matching type found for \"{0}\": {1}", name
,
635 (name_string
? name_string
: "<anonymous>"));
638 CompilerType full_type
= type_sp
->GetFullCompilerType();
640 CompilerType
copied_clang_type(GuardedCopyType(full_type
));
642 if (!copied_clang_type
) {
643 LLDB_LOG(log
, " CAS::FEVD - Couldn't export a type");
648 context
.AddTypeDecl(copied_clang_type
);
650 context
.m_found_type
= true;
655 if (!context
.m_found_type
) {
656 // Try the modules next.
657 FindDeclInModules(context
, name
);
660 if (!context
.m_found_type
) {
661 FindDeclInObjCRuntime(context
, name
);
665 void ClangASTSource::FillNamespaceMap(
666 NameSearchContext
&context
, lldb::ModuleSP module_sp
,
667 const CompilerDeclContext
&namespace_decl
) {
668 const ConstString
name(context
.m_decl_name
.getAsString().c_str());
669 if (IgnoreName(name
, true))
672 Log
*log
= GetLog(LLDBLog::Expressions
);
674 if (module_sp
&& namespace_decl
) {
675 CompilerDeclContext found_namespace_decl
;
677 if (SymbolFile
*symbol_file
= module_sp
->GetSymbolFile()) {
678 found_namespace_decl
= symbol_file
->FindNamespace(name
, namespace_decl
);
680 if (found_namespace_decl
) {
681 context
.m_namespace_map
->push_back(
682 std::pair
<lldb::ModuleSP
, CompilerDeclContext
>(
683 module_sp
, found_namespace_decl
));
685 LLDB_LOG(log
, " CAS::FEVD Found namespace {0} in module {1}", name
,
686 module_sp
->GetFileSpec().GetFilename());
692 for (lldb::ModuleSP image
: m_target
->GetImages().Modules()) {
696 CompilerDeclContext found_namespace_decl
;
698 SymbolFile
*symbol_file
= image
->GetSymbolFile();
703 // If namespace_decl is not valid, 'FindNamespace' would look for
704 // any namespace called 'name' (ignoring parent contexts) and return
705 // the first one it finds. Thus if we're doing a qualified lookup only
706 // consider root namespaces. E.g., in an expression ::A::B::Foo, the
707 // lookup of ::A will result in a qualified lookup. Note, namespace
708 // disambiguation for function calls are handled separately in
709 // SearchFunctionsInSymbolContexts.
710 const bool find_root_namespaces
=
711 context
.m_decl_context
&&
712 context
.m_decl_context
->shouldUseQualifiedLookup();
713 found_namespace_decl
= symbol_file
->FindNamespace(
714 name
, namespace_decl
, /* only root namespaces */ find_root_namespaces
);
716 if (found_namespace_decl
) {
717 context
.m_namespace_map
->push_back(
718 std::pair
<lldb::ModuleSP
, CompilerDeclContext
>(image
,
719 found_namespace_decl
));
721 LLDB_LOG(log
, " CAS::FEVD Found namespace {0} in module {1}", name
,
722 image
->GetFileSpec().GetFilename());
727 template <class D
> class TaggedASTDecl
{
729 TaggedASTDecl() : decl(nullptr) {}
730 TaggedASTDecl(D
*_decl
) : decl(_decl
) {}
731 bool IsValid() const { return (decl
!= nullptr); }
732 bool IsInvalid() const { return !IsValid(); }
733 D
*operator->() const { return decl
; }
737 template <class D2
, template <class D
> class TD
, class D1
>
738 TD
<D2
> DynCast(TD
<D1
> source
) {
739 return TD
<D2
>(dyn_cast
<D2
>(source
.decl
));
742 template <class D
= Decl
> class DeclFromParser
;
743 template <class D
= Decl
> class DeclFromUser
;
745 template <class D
> class DeclFromParser
: public TaggedASTDecl
<D
> {
747 DeclFromParser() : TaggedASTDecl
<D
>() {}
748 DeclFromParser(D
*_decl
) : TaggedASTDecl
<D
>(_decl
) {}
750 DeclFromUser
<D
> GetOrigin(ClangASTSource
&source
);
753 template <class D
> class DeclFromUser
: public TaggedASTDecl
<D
> {
755 DeclFromUser() : TaggedASTDecl
<D
>() {}
756 DeclFromUser(D
*_decl
) : TaggedASTDecl
<D
>(_decl
) {}
758 DeclFromParser
<D
> Import(ClangASTSource
&source
);
762 DeclFromUser
<D
> DeclFromParser
<D
>::GetOrigin(ClangASTSource
&source
) {
763 ClangASTImporter::DeclOrigin origin
= source
.GetDeclOrigin(this->decl
);
765 return DeclFromUser
<D
>();
766 return DeclFromUser
<D
>(dyn_cast
<D
>(origin
.decl
));
770 DeclFromParser
<D
> DeclFromUser
<D
>::Import(ClangASTSource
&source
) {
771 DeclFromParser
<> parser_generic_decl(source
.CopyDecl(this->decl
));
772 if (parser_generic_decl
.IsInvalid())
773 return DeclFromParser
<D
>();
774 return DeclFromParser
<D
>(dyn_cast
<D
>(parser_generic_decl
.decl
));
777 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
778 NameSearchContext
&context
, ObjCInterfaceDecl
*original_interface_decl
,
779 const char *log_info
) {
780 const DeclarationName
&decl_name(context
.m_decl_name
);
781 clang::ASTContext
*original_ctx
= &original_interface_decl
->getASTContext();
783 Selector original_selector
;
785 if (decl_name
.isObjCZeroArgSelector()) {
786 IdentifierInfo
*ident
= &original_ctx
->Idents
.get(decl_name
.getAsString());
787 original_selector
= original_ctx
->Selectors
.getSelector(0, &ident
);
788 } else if (decl_name
.isObjCOneArgSelector()) {
789 const std::string
&decl_name_string
= decl_name
.getAsString();
790 std::string
decl_name_string_without_colon(decl_name_string
.c_str(),
791 decl_name_string
.length() - 1);
792 IdentifierInfo
*ident
=
793 &original_ctx
->Idents
.get(decl_name_string_without_colon
);
794 original_selector
= original_ctx
->Selectors
.getSelector(1, &ident
);
796 SmallVector
<IdentifierInfo
*, 4> idents
;
798 clang::Selector sel
= decl_name
.getObjCSelector();
800 unsigned num_args
= sel
.getNumArgs();
802 for (unsigned i
= 0; i
!= num_args
; ++i
) {
803 idents
.push_back(&original_ctx
->Idents
.get(sel
.getNameForSlot(i
)));
807 original_ctx
->Selectors
.getSelector(num_args
, idents
.data());
810 DeclarationName
original_decl_name(original_selector
);
812 llvm::SmallVector
<NamedDecl
*, 1> methods
;
814 TypeSystemClang::GetCompleteDecl(original_ctx
, original_interface_decl
);
816 if (ObjCMethodDecl
*instance_method_decl
=
817 original_interface_decl
->lookupInstanceMethod(original_selector
)) {
818 methods
.push_back(instance_method_decl
);
819 } else if (ObjCMethodDecl
*class_method_decl
=
820 original_interface_decl
->lookupClassMethod(
821 original_selector
)) {
822 methods
.push_back(class_method_decl
);
825 if (methods
.empty()) {
829 for (NamedDecl
*named_decl
: methods
) {
833 ObjCMethodDecl
*result_method
= dyn_cast
<ObjCMethodDecl
>(named_decl
);
838 Decl
*copied_decl
= CopyDecl(result_method
);
843 ObjCMethodDecl
*copied_method_decl
= dyn_cast
<ObjCMethodDecl
>(copied_decl
);
845 if (!copied_method_decl
)
848 Log
*log
= GetLog(LLDBLog::Expressions
);
850 LLDB_LOG(log
, " CAS::FOMD found ({0}) {1}", log_info
,
851 ClangUtil::DumpDecl(copied_method_decl
));
853 context
.AddNamedDecl(copied_method_decl
);
859 void ClangASTSource::FindDeclInModules(NameSearchContext
&context
,
861 Log
*log
= GetLog(LLDBLog::Expressions
);
863 std::shared_ptr
<ClangModulesDeclVendor
> modules_decl_vendor
=
864 GetClangModulesDeclVendor();
865 if (!modules_decl_vendor
)
869 uint32_t max_matches
= 1;
870 std::vector
<clang::NamedDecl
*> decls
;
872 if (!modules_decl_vendor
->FindDecls(name
, append
, max_matches
, decls
))
875 LLDB_LOG(log
, " CAS::FEVD Matching entity found for \"{0}\" in the modules",
878 clang::NamedDecl
*const decl_from_modules
= decls
[0];
880 if (llvm::isa
<clang::TypeDecl
>(decl_from_modules
) ||
881 llvm::isa
<clang::ObjCContainerDecl
>(decl_from_modules
) ||
882 llvm::isa
<clang::EnumConstantDecl
>(decl_from_modules
)) {
883 clang::Decl
*copied_decl
= CopyDecl(decl_from_modules
);
884 clang::NamedDecl
*copied_named_decl
=
885 copied_decl
? dyn_cast
<clang::NamedDecl
>(copied_decl
) : nullptr;
887 if (!copied_named_decl
) {
888 LLDB_LOG(log
, " CAS::FEVD - Couldn't export a type from the modules");
893 context
.AddNamedDecl(copied_named_decl
);
895 context
.m_found_type
= true;
899 void ClangASTSource::FindDeclInObjCRuntime(NameSearchContext
&context
,
901 Log
*log
= GetLog(LLDBLog::Expressions
);
903 lldb::ProcessSP
process(m_target
->GetProcessSP());
908 ObjCLanguageRuntime
*language_runtime(ObjCLanguageRuntime::Get(*process
));
910 if (!language_runtime
)
913 DeclVendor
*decl_vendor
= language_runtime
->GetDeclVendor();
919 uint32_t max_matches
= 1;
920 std::vector
<clang::NamedDecl
*> decls
;
922 auto *clang_decl_vendor
= llvm::cast
<ClangDeclVendor
>(decl_vendor
);
923 if (!clang_decl_vendor
->FindDecls(name
, append
, max_matches
, decls
))
926 LLDB_LOG(log
, " CAS::FEVD Matching type found for \"{0}\" in the runtime",
929 clang::Decl
*copied_decl
= CopyDecl(decls
[0]);
930 clang::NamedDecl
*copied_named_decl
=
931 copied_decl
? dyn_cast
<clang::NamedDecl
>(copied_decl
) : nullptr;
933 if (!copied_named_decl
) {
934 LLDB_LOG(log
, " CAS::FEVD - Couldn't export a type from the runtime");
939 context
.AddNamedDecl(copied_named_decl
);
942 void ClangASTSource::FindObjCMethodDecls(NameSearchContext
&context
) {
943 Log
*log
= GetLog(LLDBLog::Expressions
);
945 const DeclarationName
&decl_name(context
.m_decl_name
);
946 const DeclContext
*decl_ctx(context
.m_decl_context
);
948 const ObjCInterfaceDecl
*interface_decl
=
949 dyn_cast
<ObjCInterfaceDecl
>(decl_ctx
);
955 ClangASTImporter::DeclOrigin original
= m_ast_importer_sp
->GetDeclOrigin(interface_decl
);
957 if (!original
.Valid())
960 ObjCInterfaceDecl
*original_interface_decl
=
961 dyn_cast
<ObjCInterfaceDecl
>(original
.decl
);
963 if (FindObjCMethodDeclsWithOrigin(context
, original_interface_decl
,
965 return; // found it, no need to look any further
970 if (decl_name
.isObjCZeroArgSelector()) {
971 ss
.Printf("%s", decl_name
.getAsString().c_str());
972 } else if (decl_name
.isObjCOneArgSelector()) {
973 ss
.Printf("%s", decl_name
.getAsString().c_str());
975 clang::Selector sel
= decl_name
.getObjCSelector();
977 for (unsigned i
= 0, e
= sel
.getNumArgs(); i
!= e
; ++i
) {
978 llvm::StringRef r
= sel
.getNameForSlot(i
);
979 ss
.Printf("%s:", r
.str().c_str());
984 if (ss
.GetString().contains("$__lldb"))
985 return; // we don't need any results
987 ConstString
selector_name(ss
.GetString());
990 "ClangASTSource::FindObjCMethodDecls on (ASTContext*){0} '{1}' "
991 "for selector [{2} {3}]",
992 m_ast_context
, m_clang_ast_context
->getDisplayName(),
993 interface_decl
->getName(), selector_name
);
994 SymbolContextList sc_list
;
996 ModuleFunctionSearchOptions function_options
;
997 function_options
.include_symbols
= false;
998 function_options
.include_inlines
= false;
1000 std::string interface_name
= interface_decl
->getNameAsString();
1004 ms
.Printf("-[%s %s]", interface_name
.c_str(), selector_name
.AsCString());
1006 ConstString
instance_method_name(ms
.GetString());
1009 m_target
->GetImages().FindFunctions(instance_method_name
,
1010 lldb::eFunctionNameTypeFull
,
1011 function_options
, sc_list
);
1013 if (sc_list
.GetSize())
1017 ms
.Printf("+[%s %s]", interface_name
.c_str(), selector_name
.AsCString());
1019 ConstString
class_method_name(ms
.GetString());
1022 m_target
->GetImages().FindFunctions(class_method_name
,
1023 lldb::eFunctionNameTypeFull
,
1024 function_options
, sc_list
);
1026 if (sc_list
.GetSize())
1029 // Fall back and check for methods in categories. If we find methods this
1030 // way, we need to check that they're actually in categories on the desired
1033 SymbolContextList candidate_sc_list
;
1035 m_target
->GetImages().FindFunctions(selector_name
,
1036 lldb::eFunctionNameTypeSelector
,
1037 function_options
, candidate_sc_list
);
1039 for (const SymbolContext
&candidate_sc
: candidate_sc_list
) {
1040 if (!candidate_sc
.function
)
1043 const char *candidate_name
= candidate_sc
.function
->GetName().AsCString();
1045 const char *cursor
= candidate_name
;
1047 if (*cursor
!= '+' && *cursor
!= '-')
1057 size_t interface_len
= interface_name
.length();
1059 if (strncmp(cursor
, interface_name
.c_str(), interface_len
))
1062 cursor
+= interface_len
;
1064 if (*cursor
== ' ' || *cursor
== '(')
1065 sc_list
.Append(candidate_sc
);
1069 if (sc_list
.GetSize()) {
1070 // We found a good function symbol. Use that.
1072 for (const SymbolContext
&sc
: sc_list
) {
1076 CompilerDeclContext function_decl_ctx
= sc
.function
->GetDeclContext();
1077 if (!function_decl_ctx
)
1080 ObjCMethodDecl
*method_decl
=
1081 TypeSystemClang::DeclContextGetAsObjCMethodDecl(function_decl_ctx
);
1086 ObjCInterfaceDecl
*found_interface_decl
=
1087 method_decl
->getClassInterface();
1089 if (!found_interface_decl
)
1092 if (found_interface_decl
->getName() == interface_decl
->getName()) {
1093 Decl
*copied_decl
= CopyDecl(method_decl
);
1098 ObjCMethodDecl
*copied_method_decl
=
1099 dyn_cast
<ObjCMethodDecl
>(copied_decl
);
1101 if (!copied_method_decl
)
1104 LLDB_LOG(log
, " CAS::FOMD found (in symbols)\n{0}",
1105 ClangUtil::DumpDecl(copied_method_decl
));
1107 context
.AddNamedDecl(copied_method_decl
);
1114 // Try the debug information.
1117 ObjCInterfaceDecl
*complete_interface_decl
= GetCompleteObjCInterface(
1118 const_cast<ObjCInterfaceDecl
*>(interface_decl
));
1120 if (!complete_interface_decl
)
1123 // We found the complete interface. The runtime never needs to be queried
1124 // in this scenario.
1126 DeclFromUser
<const ObjCInterfaceDecl
> complete_iface_decl(
1127 complete_interface_decl
);
1129 if (complete_interface_decl
== interface_decl
)
1130 break; // already checked this one
1133 "CAS::FOPD trying origin "
1134 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1135 complete_interface_decl
, &complete_iface_decl
->getASTContext());
1137 FindObjCMethodDeclsWithOrigin(context
, complete_interface_decl
,
1144 // Check the modules only if the debug information didn't have a complete
1147 if (std::shared_ptr
<ClangModulesDeclVendor
> modules_decl_vendor
=
1148 GetClangModulesDeclVendor()) {
1149 ConstString
interface_name(interface_decl
->getNameAsString().c_str());
1150 bool append
= false;
1151 uint32_t max_matches
= 1;
1152 std::vector
<clang::NamedDecl
*> decls
;
1154 if (!modules_decl_vendor
->FindDecls(interface_name
, append
, max_matches
,
1158 ObjCInterfaceDecl
*interface_decl_from_modules
=
1159 dyn_cast
<ObjCInterfaceDecl
>(decls
[0]);
1161 if (!interface_decl_from_modules
)
1164 if (FindObjCMethodDeclsWithOrigin(context
, interface_decl_from_modules
,
1171 // Check the runtime only if the debug information didn't have a complete
1172 // interface and the modules don't get us anywhere.
1174 lldb::ProcessSP
process(m_target
->GetProcessSP());
1179 ObjCLanguageRuntime
*language_runtime(ObjCLanguageRuntime::Get(*process
));
1181 if (!language_runtime
)
1184 DeclVendor
*decl_vendor
= language_runtime
->GetDeclVendor();
1189 ConstString
interface_name(interface_decl
->getNameAsString().c_str());
1190 bool append
= false;
1191 uint32_t max_matches
= 1;
1192 std::vector
<clang::NamedDecl
*> decls
;
1194 auto *clang_decl_vendor
= llvm::cast
<ClangDeclVendor
>(decl_vendor
);
1195 if (!clang_decl_vendor
->FindDecls(interface_name
, append
, max_matches
,
1199 ObjCInterfaceDecl
*runtime_interface_decl
=
1200 dyn_cast
<ObjCInterfaceDecl
>(decls
[0]);
1202 if (!runtime_interface_decl
)
1205 FindObjCMethodDeclsWithOrigin(context
, runtime_interface_decl
,
1210 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1211 NameSearchContext
&context
, ClangASTSource
&source
,
1212 DeclFromUser
<const ObjCInterfaceDecl
> &origin_iface_decl
) {
1213 Log
*log
= GetLog(LLDBLog::Expressions
);
1215 if (origin_iface_decl
.IsInvalid())
1218 std::string name_str
= context
.m_decl_name
.getAsString();
1219 StringRef
name(name_str
);
1220 IdentifierInfo
&name_identifier(
1221 origin_iface_decl
->getASTContext().Idents
.get(name
));
1223 DeclFromUser
<ObjCPropertyDecl
> origin_property_decl(
1224 origin_iface_decl
->FindPropertyDeclaration(
1225 &name_identifier
, ObjCPropertyQueryKind::OBJC_PR_query_instance
));
1229 if (origin_property_decl
.IsValid()) {
1230 DeclFromParser
<ObjCPropertyDecl
> parser_property_decl(
1231 origin_property_decl
.Import(source
));
1232 if (parser_property_decl
.IsValid()) {
1233 LLDB_LOG(log
, " CAS::FOPD found\n{0}",
1234 ClangUtil::DumpDecl(parser_property_decl
.decl
));
1236 context
.AddNamedDecl(parser_property_decl
.decl
);
1241 DeclFromUser
<ObjCIvarDecl
> origin_ivar_decl(
1242 origin_iface_decl
->getIvarDecl(&name_identifier
));
1244 if (origin_ivar_decl
.IsValid()) {
1245 DeclFromParser
<ObjCIvarDecl
> parser_ivar_decl(
1246 origin_ivar_decl
.Import(source
));
1247 if (parser_ivar_decl
.IsValid()) {
1248 LLDB_LOG(log
, " CAS::FOPD found\n{0}",
1249 ClangUtil::DumpDecl(parser_ivar_decl
.decl
));
1251 context
.AddNamedDecl(parser_ivar_decl
.decl
);
1259 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext
&context
) {
1260 Log
*log
= GetLog(LLDBLog::Expressions
);
1262 DeclFromParser
<const ObjCInterfaceDecl
> parser_iface_decl(
1263 cast
<ObjCInterfaceDecl
>(context
.m_decl_context
));
1264 DeclFromUser
<const ObjCInterfaceDecl
> origin_iface_decl(
1265 parser_iface_decl
.GetOrigin(*this));
1267 ConstString
class_name(parser_iface_decl
->getNameAsString().c_str());
1270 "ClangASTSource::FindObjCPropertyAndIvarDecls on "
1271 "(ASTContext*){0} '{1}' for '{2}.{3}'",
1272 m_ast_context
, m_clang_ast_context
->getDisplayName(),
1273 parser_iface_decl
->getName(), context
.m_decl_name
.getAsString());
1275 if (FindObjCPropertyAndIvarDeclsWithOrigin(context
, *this, origin_iface_decl
))
1279 "CAS::FOPD couldn't find the property on origin "
1280 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}, searching "
1282 origin_iface_decl
.decl
, &origin_iface_decl
->getASTContext());
1284 SymbolContext null_sc
;
1288 ObjCInterfaceDecl
*complete_interface_decl
= GetCompleteObjCInterface(
1289 const_cast<ObjCInterfaceDecl
*>(parser_iface_decl
.decl
));
1291 if (!complete_interface_decl
)
1294 // We found the complete interface. The runtime never needs to be queried
1295 // in this scenario.
1297 DeclFromUser
<const ObjCInterfaceDecl
> complete_iface_decl(
1298 complete_interface_decl
);
1300 if (complete_iface_decl
.decl
== origin_iface_decl
.decl
)
1301 break; // already checked this one
1304 "CAS::FOPD trying origin "
1305 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1306 complete_iface_decl
.decl
, &complete_iface_decl
->getASTContext());
1308 FindObjCPropertyAndIvarDeclsWithOrigin(context
, *this, complete_iface_decl
);
1314 // Check the modules only if the debug information didn't have a complete
1317 std::shared_ptr
<ClangModulesDeclVendor
> modules_decl_vendor
=
1318 GetClangModulesDeclVendor();
1320 if (!modules_decl_vendor
)
1323 bool append
= false;
1324 uint32_t max_matches
= 1;
1325 std::vector
<clang::NamedDecl
*> decls
;
1327 if (!modules_decl_vendor
->FindDecls(class_name
, append
, max_matches
, decls
))
1330 DeclFromUser
<const ObjCInterfaceDecl
> interface_decl_from_modules(
1331 dyn_cast
<ObjCInterfaceDecl
>(decls
[0]));
1333 if (!interface_decl_from_modules
.IsValid())
1337 "CAS::FOPD[{0}] trying module "
1338 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1339 interface_decl_from_modules
.decl
,
1340 &interface_decl_from_modules
->getASTContext());
1342 if (FindObjCPropertyAndIvarDeclsWithOrigin(context
, *this,
1343 interface_decl_from_modules
))
1348 // Check the runtime only if the debug information didn't have a complete
1349 // interface and nothing was in the modules.
1351 lldb::ProcessSP
process(m_target
->GetProcessSP());
1356 ObjCLanguageRuntime
*language_runtime(ObjCLanguageRuntime::Get(*process
));
1358 if (!language_runtime
)
1361 DeclVendor
*decl_vendor
= language_runtime
->GetDeclVendor();
1366 bool append
= false;
1367 uint32_t max_matches
= 1;
1368 std::vector
<clang::NamedDecl
*> decls
;
1370 auto *clang_decl_vendor
= llvm::cast
<ClangDeclVendor
>(decl_vendor
);
1371 if (!clang_decl_vendor
->FindDecls(class_name
, append
, max_matches
, decls
))
1374 DeclFromUser
<const ObjCInterfaceDecl
> interface_decl_from_runtime(
1375 dyn_cast
<ObjCInterfaceDecl
>(decls
[0]));
1377 if (!interface_decl_from_runtime
.IsValid())
1381 "CAS::FOPD[{0}] trying runtime "
1382 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1383 interface_decl_from_runtime
.decl
,
1384 &interface_decl_from_runtime
->getASTContext());
1386 if (FindObjCPropertyAndIvarDeclsWithOrigin(context
, *this,
1387 interface_decl_from_runtime
))
1392 void ClangASTSource::LookupInNamespace(NameSearchContext
&context
) {
1393 const NamespaceDecl
*namespace_context
=
1394 dyn_cast
<NamespaceDecl
>(context
.m_decl_context
);
1396 Log
*log
= GetLog(LLDBLog::Expressions
);
1398 ClangASTImporter::NamespaceMapSP namespace_map
=
1399 m_ast_importer_sp
->GetNamespaceMap(namespace_context
);
1401 LLDB_LOGV(log
, " CAS::FEVD Inspecting namespace map {0} ({1} entries)",
1402 namespace_map
.get(), namespace_map
->size());
1407 for (ClangASTImporter::NamespaceMap::iterator i
= namespace_map
->begin(),
1408 e
= namespace_map
->end();
1410 LLDB_LOG(log
, " CAS::FEVD Searching namespace {0} in module {1}",
1411 i
->second
.GetName(), i
->first
->GetFileSpec().GetFilename());
1413 FindExternalVisibleDecls(context
, i
->first
, i
->second
);
1417 typedef llvm::DenseMap
<const FieldDecl
*, uint64_t> FieldOffsetMap
;
1418 typedef llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
> BaseOffsetMap
;
1420 template <class D
, class O
>
1421 static bool ImportOffsetMap(llvm::DenseMap
<const D
*, O
> &destination_map
,
1422 llvm::DenseMap
<const D
*, O
> &source_map
,
1423 ClangASTSource
&source
) {
1424 // When importing fields into a new record, clang has a hard requirement that
1425 // fields be imported in field offset order. Since they are stored in a
1426 // DenseMap with a pointer as the key type, this means we cannot simply
1427 // iterate over the map, as the order will be non-deterministic. Instead we
1428 // have to sort by the offset and then insert in sorted order.
1429 typedef llvm::DenseMap
<const D
*, O
> MapType
;
1430 typedef typename
MapType::value_type PairType
;
1431 std::vector
<PairType
> sorted_items
;
1432 sorted_items
.reserve(source_map
.size());
1433 sorted_items
.assign(source_map
.begin(), source_map
.end());
1434 llvm::sort(sorted_items
, llvm::less_second());
1436 for (const auto &item
: sorted_items
) {
1437 DeclFromUser
<D
> user_decl(const_cast<D
*>(item
.first
));
1438 DeclFromParser
<D
> parser_decl(user_decl
.Import(source
));
1439 if (parser_decl
.IsInvalid())
1441 destination_map
.insert(
1442 std::pair
<const D
*, O
>(parser_decl
.decl
, item
.second
));
1448 template <bool IsVirtual
>
1449 bool ExtractBaseOffsets(const ASTRecordLayout
&record_layout
,
1450 DeclFromUser
<const CXXRecordDecl
> &record
,
1451 BaseOffsetMap
&base_offsets
) {
1452 for (CXXRecordDecl::base_class_const_iterator
1453 bi
= (IsVirtual
? record
->vbases_begin() : record
->bases_begin()),
1454 be
= (IsVirtual
? record
->vbases_end() : record
->bases_end());
1456 if (!IsVirtual
&& bi
->isVirtual())
1459 const clang::Type
*origin_base_type
= bi
->getType().getTypePtr();
1460 const clang::RecordType
*origin_base_record_type
=
1461 origin_base_type
->getAs
<RecordType
>();
1463 if (!origin_base_record_type
)
1466 DeclFromUser
<RecordDecl
> origin_base_record(
1467 origin_base_record_type
->getDecl());
1469 if (origin_base_record
.IsInvalid())
1472 DeclFromUser
<CXXRecordDecl
> origin_base_cxx_record(
1473 DynCast
<CXXRecordDecl
>(origin_base_record
));
1475 if (origin_base_cxx_record
.IsInvalid())
1478 CharUnits base_offset
;
1482 record_layout
.getVBaseClassOffset(origin_base_cxx_record
.decl
);
1485 record_layout
.getBaseClassOffset(origin_base_cxx_record
.decl
);
1487 base_offsets
.insert(std::pair
<const CXXRecordDecl
*, CharUnits
>(
1488 origin_base_cxx_record
.decl
, base_offset
));
1494 bool ClangASTSource::layoutRecordType(const RecordDecl
*record
, uint64_t &size
,
1495 uint64_t &alignment
,
1496 FieldOffsetMap
&field_offsets
,
1497 BaseOffsetMap
&base_offsets
,
1498 BaseOffsetMap
&virtual_base_offsets
) {
1500 Log
*log
= GetLog(LLDBLog::Expressions
);
1503 "LayoutRecordType on (ASTContext*){0} '{1}' for (RecordDecl*)"
1504 "{2} [name = '{3}']",
1505 m_ast_context
, m_clang_ast_context
->getDisplayName(), record
,
1508 DeclFromParser
<const RecordDecl
> parser_record(record
);
1509 DeclFromUser
<const RecordDecl
> origin_record(
1510 parser_record
.GetOrigin(*this));
1512 if (origin_record
.IsInvalid())
1515 FieldOffsetMap origin_field_offsets
;
1516 BaseOffsetMap origin_base_offsets
;
1517 BaseOffsetMap origin_virtual_base_offsets
;
1519 TypeSystemClang::GetCompleteDecl(
1520 &origin_record
->getASTContext(),
1521 const_cast<RecordDecl
*>(origin_record
.decl
));
1523 clang::RecordDecl
*definition
= origin_record
.decl
->getDefinition();
1524 if (!definition
|| !definition
->isCompleteDefinition())
1527 const ASTRecordLayout
&record_layout(
1528 origin_record
->getASTContext().getASTRecordLayout(origin_record
.decl
));
1530 int field_idx
= 0, field_count
= record_layout
.getFieldCount();
1532 for (RecordDecl::field_iterator fi
= origin_record
->field_begin(),
1533 fe
= origin_record
->field_end();
1535 if (field_idx
>= field_count
)
1536 return false; // Layout didn't go well. Bail out.
1538 uint64_t field_offset
= record_layout
.getFieldOffset(field_idx
);
1540 origin_field_offsets
.insert(
1541 std::pair
<const FieldDecl
*, uint64_t>(*fi
, field_offset
));
1546 lldbassert(&record
->getASTContext() == m_ast_context
);
1548 DeclFromUser
<const CXXRecordDecl
> origin_cxx_record(
1549 DynCast
<const CXXRecordDecl
>(origin_record
));
1551 if (origin_cxx_record
.IsValid()) {
1552 if (!ExtractBaseOffsets
<false>(record_layout
, origin_cxx_record
,
1553 origin_base_offsets
) ||
1554 !ExtractBaseOffsets
<true>(record_layout
, origin_cxx_record
,
1555 origin_virtual_base_offsets
))
1559 if (!ImportOffsetMap(field_offsets
, origin_field_offsets
, *this) ||
1560 !ImportOffsetMap(base_offsets
, origin_base_offsets
, *this) ||
1561 !ImportOffsetMap(virtual_base_offsets
, origin_virtual_base_offsets
,
1565 size
= record_layout
.getSize().getQuantity() * m_ast_context
->getCharWidth();
1566 alignment
= record_layout
.getAlignment().getQuantity() *
1567 m_ast_context
->getCharWidth();
1570 LLDB_LOG(log
, "LRT returned:");
1571 LLDB_LOG(log
, "LRT Original = (RecordDecl*){0}",
1572 static_cast<const void *>(origin_record
.decl
));
1573 LLDB_LOG(log
, "LRT Size = {0}", size
);
1574 LLDB_LOG(log
, "LRT Alignment = {0}", alignment
);
1575 LLDB_LOG(log
, "LRT Fields:");
1576 for (RecordDecl::field_iterator fi
= record
->field_begin(),
1577 fe
= record
->field_end();
1580 "LRT (FieldDecl*){0}, Name = '{1}', Type = '{2}', Offset = "
1582 *fi
, fi
->getName(), fi
->getType().getAsString(),
1583 field_offsets
[*fi
]);
1585 DeclFromParser
<const CXXRecordDecl
> parser_cxx_record
=
1586 DynCast
<const CXXRecordDecl
>(parser_record
);
1587 if (parser_cxx_record
.IsValid()) {
1588 LLDB_LOG(log
, "LRT Bases:");
1589 for (CXXRecordDecl::base_class_const_iterator
1590 bi
= parser_cxx_record
->bases_begin(),
1591 be
= parser_cxx_record
->bases_end();
1593 bool is_virtual
= bi
->isVirtual();
1595 QualType base_type
= bi
->getType();
1596 const RecordType
*base_record_type
= base_type
->getAs
<RecordType
>();
1597 DeclFromParser
<RecordDecl
> base_record(base_record_type
->getDecl());
1598 DeclFromParser
<CXXRecordDecl
> base_cxx_record
=
1599 DynCast
<CXXRecordDecl
>(base_record
);
1602 "LRT {0}(CXXRecordDecl*){1}, Name = '{2}', Offset = "
1604 (is_virtual
? "Virtual " : ""), base_cxx_record
.decl
,
1605 base_cxx_record
.decl
->getName(),
1607 ? virtual_base_offsets
[base_cxx_record
.decl
].getQuantity()
1608 : base_offsets
[base_cxx_record
.decl
].getQuantity()));
1611 LLDB_LOG(log
, "LRD Not a CXXRecord, so no bases");
1618 void ClangASTSource::CompleteNamespaceMap(
1619 ClangASTImporter::NamespaceMapSP
&namespace_map
, ConstString name
,
1620 ClangASTImporter::NamespaceMapSP
&parent_map
) const {
1622 Log
*log
= GetLog(LLDBLog::Expressions
);
1625 if (parent_map
&& parent_map
->size())
1627 "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1628 "for namespace {2} in namespace {3}",
1629 m_ast_context
, m_clang_ast_context
->getDisplayName(), name
,
1630 parent_map
->begin()->second
.GetName());
1633 "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1634 "for namespace {2}",
1635 m_ast_context
, m_clang_ast_context
->getDisplayName(), name
);
1639 for (ClangASTImporter::NamespaceMap::iterator i
= parent_map
->begin(),
1640 e
= parent_map
->end();
1642 CompilerDeclContext found_namespace_decl
;
1644 lldb::ModuleSP module_sp
= i
->first
;
1645 CompilerDeclContext module_parent_namespace_decl
= i
->second
;
1647 SymbolFile
*symbol_file
= module_sp
->GetSymbolFile();
1652 found_namespace_decl
=
1653 symbol_file
->FindNamespace(name
, module_parent_namespace_decl
);
1655 if (!found_namespace_decl
)
1658 namespace_map
->push_back(std::pair
<lldb::ModuleSP
, CompilerDeclContext
>(
1659 module_sp
, found_namespace_decl
));
1661 LLDB_LOG(log
, " CMN Found namespace {0} in module {1}", name
,
1662 module_sp
->GetFileSpec().GetFilename());
1665 CompilerDeclContext null_namespace_decl
;
1666 for (lldb::ModuleSP image
: m_target
->GetImages().Modules()) {
1670 CompilerDeclContext found_namespace_decl
;
1672 SymbolFile
*symbol_file
= image
->GetSymbolFile();
1677 found_namespace_decl
=
1678 symbol_file
->FindNamespace(name
, null_namespace_decl
);
1680 if (!found_namespace_decl
)
1683 namespace_map
->push_back(std::pair
<lldb::ModuleSP
, CompilerDeclContext
>(
1684 image
, found_namespace_decl
));
1686 LLDB_LOG(log
, " CMN[{0}] Found namespace {0} in module {1}", name
,
1687 image
->GetFileSpec().GetFilename());
1692 NamespaceDecl
*ClangASTSource::AddNamespace(
1693 NameSearchContext
&context
,
1694 ClangASTImporter::NamespaceMapSP
&namespace_decls
) {
1695 if (!namespace_decls
)
1698 const CompilerDeclContext
&namespace_decl
= namespace_decls
->begin()->second
;
1700 clang::ASTContext
*src_ast
=
1701 TypeSystemClang::DeclContextGetTypeSystemClang(namespace_decl
);
1704 clang::NamespaceDecl
*src_namespace_decl
=
1705 TypeSystemClang::DeclContextGetAsNamespaceDecl(namespace_decl
);
1707 if (!src_namespace_decl
)
1710 Decl
*copied_decl
= CopyDecl(src_namespace_decl
);
1715 NamespaceDecl
*copied_namespace_decl
= dyn_cast
<NamespaceDecl
>(copied_decl
);
1717 if (!copied_namespace_decl
)
1720 context
.m_decls
.push_back(copied_namespace_decl
);
1722 m_ast_importer_sp
->RegisterNamespaceMap(copied_namespace_decl
,
1725 return dyn_cast
<NamespaceDecl
>(copied_decl
);
1728 clang::Decl
*ClangASTSource::CopyDecl(Decl
*src_decl
) {
1729 return m_ast_importer_sp
->CopyDecl(m_ast_context
, src_decl
);
1732 ClangASTImporter::DeclOrigin
ClangASTSource::GetDeclOrigin(const clang::Decl
*decl
) {
1733 return m_ast_importer_sp
->GetDeclOrigin(decl
);
1736 CompilerType
ClangASTSource::GuardedCopyType(const CompilerType
&src_type
) {
1737 auto ts
= src_type
.GetTypeSystem();
1738 auto src_ast
= ts
.dyn_cast_or_null
<TypeSystemClang
>();
1742 QualType copied_qual_type
= ClangUtil::GetQualType(
1743 m_ast_importer_sp
->CopyType(*m_clang_ast_context
, src_type
));
1745 if (copied_qual_type
.getAsOpaquePtr() &&
1746 copied_qual_type
->getCanonicalTypeInternal().isNull())
1747 // this shouldn't happen, but we're hardening because the AST importer
1748 // seems to be generating bad types on occasion.
1751 return m_clang_ast_context
->GetType(copied_qual_type
);
1754 std::shared_ptr
<ClangModulesDeclVendor
>
1755 ClangASTSource::GetClangModulesDeclVendor() {
1756 auto persistent_vars
= llvm::cast
<ClangPersistentVariables
>(
1757 m_target
->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC
));
1758 return persistent_vars
->GetClangModulesDeclVendor();