xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===-- ClangASTSource.cpp ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangASTSource.h"
10 
11 #include "ClangDeclVendor.h"
12 #include "ClangModulesDeclVendor.h"
13 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Symbol/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/Log.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 
26 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
27 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
28 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
29 
30 #include <memory>
31 #include <vector>
32 
33 using namespace clang;
34 using namespace lldb_private;
35 
36 // Scoped class that will remove an active lexical decl from the set when it
37 // goes out of scope.
38 namespace {
39 class ScopedLexicalDeclEraser {
40 public:
41   ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
42                           const clang::Decl *decl)
43       : m_active_lexical_decls(decls), m_decl(decl) {}
44 
45   ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
46 
47 private:
48   std::set<const clang::Decl *> &m_active_lexical_decls;
49   const clang::Decl *m_decl;
50 };
51 }
52 
53 ClangASTSource::ClangASTSource(
54     const lldb::TargetSP &target,
55     const std::shared_ptr<ClangASTImporter> &importer)
56     : m_lookups_enabled(false), m_target(target), m_ast_context(nullptr),
57       m_ast_importer_sp(importer), m_active_lexical_decls(),
58       m_active_lookups() {
59   assert(m_ast_importer_sp && "No ClangASTImporter passed to ClangASTSource?");
60 }
61 
62 void ClangASTSource::InstallASTContext(TypeSystemClang &clang_ast_context) {
63   m_ast_context = &clang_ast_context.getASTContext();
64   m_clang_ast_context = &clang_ast_context;
65   m_file_manager = &m_ast_context->getSourceManager().getFileManager();
66   m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
67 }
68 
69 ClangASTSource::~ClangASTSource() {
70   m_ast_importer_sp->ForgetDestination(m_ast_context);
71 
72   if (!m_target)
73     return;
74 
75   // Unregister the current ASTContext as a source for all scratch
76   // ASTContexts in the ClangASTImporter. Without this the scratch AST might
77   // query the deleted ASTContext for additional type information.
78   // We unregister from *all* scratch ASTContexts in case a type got exported
79   // to a scratch AST that isn't the best fitting scratch ASTContext.
80   TypeSystemClang *scratch_ast = ScratchTypeSystemClang::GetForTarget(
81       *m_target, ScratchTypeSystemClang::DefaultAST, false);
82 
83   if (!scratch_ast)
84     return;
85 
86   ScratchTypeSystemClang *default_scratch_ast =
87       llvm::cast<ScratchTypeSystemClang>(scratch_ast);
88   // Unregister from the default scratch AST (and all sub-ASTs).
89   default_scratch_ast->ForgetSource(m_ast_context, *m_ast_importer_sp);
90 }
91 
92 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
93   if (!m_ast_context)
94     return;
95 
96   m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
97   m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
98 }
99 
100 // The core lookup interface.
101 bool ClangASTSource::FindExternalVisibleDeclsByName(
102     const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
103   if (!m_ast_context) {
104     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
105     return false;
106   }
107 
108   std::string decl_name(clang_decl_name.getAsString());
109 
110   switch (clang_decl_name.getNameKind()) {
111   // Normal identifiers.
112   case DeclarationName::Identifier: {
113     clang::IdentifierInfo *identifier_info =
114         clang_decl_name.getAsIdentifierInfo();
115 
116     if (!identifier_info || identifier_info->getBuiltinID() != 0) {
117       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
118       return false;
119     }
120   } break;
121 
122   // Operator names.
123   case DeclarationName::CXXOperatorName:
124   case DeclarationName::CXXLiteralOperatorName:
125     break;
126 
127   // Using directives found in this context.
128   // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
129   case DeclarationName::CXXUsingDirective:
130     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
131     return false;
132 
133   case DeclarationName::ObjCZeroArgSelector:
134   case DeclarationName::ObjCOneArgSelector:
135   case DeclarationName::ObjCMultiArgSelector: {
136     llvm::SmallVector<NamedDecl *, 1> method_decls;
137 
138     NameSearchContext method_search_context(*m_clang_ast_context, method_decls,
139                                             clang_decl_name, decl_ctx);
140 
141     FindObjCMethodDecls(method_search_context);
142 
143     SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
144     return (method_decls.size() > 0);
145   }
146   // These aren't possible in the global context.
147   case DeclarationName::CXXConstructorName:
148   case DeclarationName::CXXDestructorName:
149   case DeclarationName::CXXConversionFunctionName:
150   case DeclarationName::CXXDeductionGuideName:
151     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
152     return false;
153   }
154 
155   if (!GetLookupsEnabled()) {
156     // Wait until we see a '$' at the start of a name before we start doing any
157     // lookups so we can avoid lookup up all of the builtin types.
158     if (!decl_name.empty() && decl_name[0] == '$') {
159       SetLookupsEnabled(true);
160     } else {
161       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
162       return false;
163     }
164   }
165 
166   ConstString const_decl_name(decl_name.c_str());
167 
168   const char *uniqued_const_decl_name = const_decl_name.GetCString();
169   if (m_active_lookups.find(uniqued_const_decl_name) !=
170       m_active_lookups.end()) {
171     // We are currently looking up this name...
172     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
173     return false;
174   }
175   m_active_lookups.insert(uniqued_const_decl_name);
176   llvm::SmallVector<NamedDecl *, 4> name_decls;
177   NameSearchContext name_search_context(*m_clang_ast_context, name_decls,
178                                         clang_decl_name, decl_ctx);
179   FindExternalVisibleDecls(name_search_context);
180   SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
181   m_active_lookups.erase(uniqued_const_decl_name);
182   return (name_decls.size() != 0);
183 }
184 
185 TagDecl *ClangASTSource::FindCompleteType(const TagDecl *decl) {
186   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
187 
188   if (const NamespaceDecl *namespace_context =
189           dyn_cast<NamespaceDecl>(decl->getDeclContext())) {
190     ClangASTImporter::NamespaceMapSP namespace_map =
191         m_ast_importer_sp->GetNamespaceMap(namespace_context);
192 
193     LLDB_LOGV(log, "      CTD Inspecting namespace map{0} ({1} entries)",
194               namespace_map.get(), namespace_map->size());
195 
196     if (!namespace_map)
197       return nullptr;
198 
199     for (const ClangASTImporter::NamespaceMapItem &item : *namespace_map) {
200       LLDB_LOG(log, "      CTD Searching namespace {0} in module {1}",
201                item.second.GetName(), item.first->GetFileSpec().GetFilename());
202 
203       TypeList types;
204 
205       ConstString name(decl->getName());
206 
207       item.first->FindTypesInNamespace(name, item.second, UINT32_MAX, types);
208 
209       for (uint32_t ti = 0, te = types.GetSize(); ti != te; ++ti) {
210         lldb::TypeSP type = types.GetTypeAtIndex(ti);
211 
212         if (!type)
213           continue;
214 
215         CompilerType clang_type(type->GetFullCompilerType());
216 
217         if (!ClangUtil::IsClangType(clang_type))
218           continue;
219 
220         const TagType *tag_type =
221             ClangUtil::GetQualType(clang_type)->getAs<TagType>();
222 
223         if (!tag_type)
224           continue;
225 
226         TagDecl *candidate_tag_decl =
227             const_cast<TagDecl *>(tag_type->getDecl());
228 
229         if (TypeSystemClang::GetCompleteDecl(
230                 &candidate_tag_decl->getASTContext(), candidate_tag_decl))
231           return candidate_tag_decl;
232       }
233     }
234   } else {
235     TypeList types;
236 
237     ConstString name(decl->getName());
238 
239     const ModuleList &module_list = m_target->GetImages();
240 
241     bool exact_match = false;
242     llvm::DenseSet<SymbolFile *> searched_symbol_files;
243     module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
244                           searched_symbol_files, types);
245 
246     for (uint32_t ti = 0, te = types.GetSize(); ti != te; ++ti) {
247       lldb::TypeSP type = types.GetTypeAtIndex(ti);
248 
249       if (!type)
250         continue;
251 
252       CompilerType clang_type(type->GetFullCompilerType());
253 
254       if (!ClangUtil::IsClangType(clang_type))
255         continue;
256 
257       const TagType *tag_type =
258           ClangUtil::GetQualType(clang_type)->getAs<TagType>();
259 
260       if (!tag_type)
261         continue;
262 
263       TagDecl *candidate_tag_decl = const_cast<TagDecl *>(tag_type->getDecl());
264 
265       // We have found a type by basename and we need to make sure the decl
266       // contexts are the same before we can try to complete this type with
267       // another
268       if (!TypeSystemClang::DeclsAreEquivalent(const_cast<TagDecl *>(decl),
269                                                candidate_tag_decl))
270         continue;
271 
272       if (TypeSystemClang::GetCompleteDecl(&candidate_tag_decl->getASTContext(),
273                                            candidate_tag_decl))
274         return candidate_tag_decl;
275     }
276   }
277   return nullptr;
278 }
279 
280 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
281   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
282 
283   if (log) {
284     LLDB_LOG(log,
285              "    CompleteTagDecl on (ASTContext*){0} Completing "
286              "(TagDecl*){1} named {2}",
287              m_clang_ast_context->getDisplayName(), tag_decl,
288              tag_decl->getName());
289 
290     LLDB_LOG(log, "      CTD Before:\n{0}", ClangUtil::DumpDecl(tag_decl));
291   }
292 
293   auto iter = m_active_lexical_decls.find(tag_decl);
294   if (iter != m_active_lexical_decls.end())
295     return;
296   m_active_lexical_decls.insert(tag_decl);
297   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
298 
299   if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
300     // We couldn't complete the type.  Maybe there's a definition somewhere
301     // else that can be completed.
302     if (TagDecl *alternate = FindCompleteType(tag_decl))
303       m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, alternate);
304   }
305 
306   LLDB_LOG(log, "      [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
307 }
308 
309 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
310   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
311 
312   LLDB_LOG(log,
313            "    [CompleteObjCInterfaceDecl] on (ASTContext*){0} '{1}' "
314            "Completing an ObjCInterfaceDecl named {1}",
315            m_ast_context, m_clang_ast_context->getDisplayName(),
316            interface_decl->getName());
317   LLDB_LOG(log, "      [COID] Before:\n{0}",
318            ClangUtil::DumpDecl(interface_decl));
319 
320   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
321 
322   if (original.Valid()) {
323     if (ObjCInterfaceDecl *original_iface_decl =
324             dyn_cast<ObjCInterfaceDecl>(original.decl)) {
325       ObjCInterfaceDecl *complete_iface_decl =
326           GetCompleteObjCInterface(original_iface_decl);
327 
328       if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
329         m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
330       }
331     }
332   }
333 
334   m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
335 
336   if (interface_decl->getSuperClass() &&
337       interface_decl->getSuperClass() != interface_decl)
338     CompleteType(interface_decl->getSuperClass());
339 
340   LLDB_LOG(log, "      [COID] After:");
341   LLDB_LOG(log, "      [COID] {0}", ClangUtil::DumpDecl(interface_decl));
342 }
343 
344 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
345     const clang::ObjCInterfaceDecl *interface_decl) {
346   lldb::ProcessSP process(m_target->GetProcessSP());
347 
348   if (!process)
349     return nullptr;
350 
351   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
352 
353   if (!language_runtime)
354     return nullptr;
355 
356   ConstString class_name(interface_decl->getNameAsString().c_str());
357 
358   lldb::TypeSP complete_type_sp(
359       language_runtime->LookupInCompleteClassCache(class_name));
360 
361   if (!complete_type_sp)
362     return nullptr;
363 
364   TypeFromUser complete_type =
365       TypeFromUser(complete_type_sp->GetFullCompilerType());
366   lldb::opaque_compiler_type_t complete_opaque_type =
367       complete_type.GetOpaqueQualType();
368 
369   if (!complete_opaque_type)
370     return nullptr;
371 
372   const clang::Type *complete_clang_type =
373       QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
374   const ObjCInterfaceType *complete_interface_type =
375       dyn_cast<ObjCInterfaceType>(complete_clang_type);
376 
377   if (!complete_interface_type)
378     return nullptr;
379 
380   ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
381 
382   return complete_iface_decl;
383 }
384 
385 void ClangASTSource::FindExternalLexicalDecls(
386     const DeclContext *decl_context,
387     llvm::function_ref<bool(Decl::Kind)> predicate,
388     llvm::SmallVectorImpl<Decl *> &decls) {
389 
390   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
391 
392   const Decl *context_decl = dyn_cast<Decl>(decl_context);
393 
394   if (!context_decl)
395     return;
396 
397   auto iter = m_active_lexical_decls.find(context_decl);
398   if (iter != m_active_lexical_decls.end())
399     return;
400   m_active_lexical_decls.insert(context_decl);
401   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
402 
403   if (log) {
404     if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
405       LLDB_LOG(log,
406                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
407                "'{2}' (%sDecl*){3}",
408                m_ast_context, m_clang_ast_context->getDisplayName(),
409                context_named_decl->getNameAsString().c_str(),
410                context_decl->getDeclKindName(),
411                static_cast<const void *>(context_decl));
412     else if (context_decl)
413       LLDB_LOG(log,
414                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
415                "({2}Decl*){3}",
416                m_ast_context, m_clang_ast_context->getDisplayName(),
417                context_decl->getDeclKindName(),
418                static_cast<const void *>(context_decl));
419     else
420       LLDB_LOG(log,
421                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in a "
422                "NULL context",
423                m_ast_context, m_clang_ast_context->getDisplayName());
424   }
425 
426   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
427 
428   if (!original.Valid())
429     return;
430 
431   LLDB_LOG(log, "  FELD Original decl {0} (Decl*){1:x}:\n{2}",
432            static_cast<void *>(original.ctx),
433            static_cast<void *>(original.decl),
434            ClangUtil::DumpDecl(original.decl));
435 
436   if (ObjCInterfaceDecl *original_iface_decl =
437           dyn_cast<ObjCInterfaceDecl>(original.decl)) {
438     ObjCInterfaceDecl *complete_iface_decl =
439         GetCompleteObjCInterface(original_iface_decl);
440 
441     if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
442       original.decl = complete_iface_decl;
443       original.ctx = &complete_iface_decl->getASTContext();
444 
445       m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
446     }
447   }
448 
449   if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
450     ExternalASTSource *external_source = original.ctx->getExternalSource();
451 
452     if (external_source)
453       external_source->CompleteType(original_tag_decl);
454   }
455 
456   const DeclContext *original_decl_context =
457       dyn_cast<DeclContext>(original.decl);
458 
459   if (!original_decl_context)
460     return;
461 
462   // Indicates whether we skipped any Decls of the original DeclContext.
463   bool SkippedDecls = false;
464   for (Decl *decl : original_decl_context->decls()) {
465     // The predicate function returns true if the passed declaration kind is
466     // the one we are looking for.
467     // See clang::ExternalASTSource::FindExternalLexicalDecls()
468     if (predicate(decl->getKind())) {
469       if (log) {
470         std::string ast_dump = ClangUtil::DumpDecl(decl);
471         if (const NamedDecl *context_named_decl =
472                 dyn_cast<NamedDecl>(context_decl))
473           LLDB_LOG(log, "  FELD Adding [to {0}Decl {1}] lexical {2}Decl {3}",
474                    context_named_decl->getDeclKindName(),
475                    context_named_decl->getName(), decl->getDeclKindName(),
476                    ast_dump);
477         else
478           LLDB_LOG(log, "  FELD Adding lexical {0}Decl {1}",
479                    decl->getDeclKindName(), ast_dump);
480       }
481 
482       Decl *copied_decl = CopyDecl(decl);
483 
484       if (!copied_decl)
485         continue;
486 
487       // FIXME: We should add the copied decl to the 'decls' list. This would
488       // add the copied Decl into the DeclContext and make sure that we
489       // correctly propagate that we added some Decls back to Clang.
490       // By leaving 'decls' empty we incorrectly return false from
491       // DeclContext::LoadLexicalDeclsFromExternalStorage which might cause
492       // lookup issues later on.
493       // We can't just add them for now as the ASTImporter already added the
494       // decl into the DeclContext and this would add it twice.
495 
496       if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
497         QualType copied_field_type = copied_field->getType();
498 
499         m_ast_importer_sp->RequireCompleteType(copied_field_type);
500       }
501     } else {
502       SkippedDecls = true;
503     }
504   }
505 
506   // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
507   // to false.  However, since we skipped some of the external Decls we must
508   // set it back!
509   if (SkippedDecls) {
510     decl_context->setHasExternalLexicalStorage(true);
511     // This sets HasLazyExternalLexicalLookups to true.  By setting this bit we
512     // ensure that the lookup table is rebuilt, which means the external source
513     // is consulted again when a clang::DeclContext::lookup is called.
514     const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
515   }
516 
517   return;
518 }
519 
520 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
521   assert(m_ast_context);
522 
523   const ConstString name(context.m_decl_name.getAsString().c_str());
524 
525   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
526 
527   if (log) {
528     if (!context.m_decl_context)
529       LLDB_LOG(log,
530                "ClangASTSource::FindExternalVisibleDecls on "
531                "(ASTContext*){0} '{1}' for '{2}' in a NULL DeclContext",
532                m_ast_context, m_clang_ast_context->getDisplayName(), name);
533     else if (const NamedDecl *context_named_decl =
534                  dyn_cast<NamedDecl>(context.m_decl_context))
535       LLDB_LOG(log,
536                "ClangASTSource::FindExternalVisibleDecls on "
537                "(ASTContext*){0} '{1}' for '{2}' in '{3}'",
538                m_ast_context, m_clang_ast_context->getDisplayName(), name,
539                context_named_decl->getName());
540     else
541       LLDB_LOG(log,
542                "ClangASTSource::FindExternalVisibleDecls on "
543                "(ASTContext*){0} '{1}' for '{2}' in a '{3}'",
544                m_ast_context, m_clang_ast_context->getDisplayName(), name,
545                context.m_decl_context->getDeclKindName());
546   }
547 
548   if (isa<NamespaceDecl>(context.m_decl_context)) {
549     LookupInNamespace(context);
550   } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
551     FindObjCPropertyAndIvarDecls(context);
552   } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
553     // we shouldn't be getting FindExternalVisibleDecls calls for these
554     return;
555   } else {
556     CompilerDeclContext namespace_decl;
557 
558     LLDB_LOG(log, "  CAS::FEVD Searching the root namespace");
559 
560     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl);
561   }
562 
563   if (!context.m_namespace_map->empty()) {
564     if (log && log->GetVerbose())
565       LLDB_LOG(log, "  CAS::FEVD Registering namespace map {0} ({1} entries)",
566                context.m_namespace_map.get(), context.m_namespace_map->size());
567 
568     NamespaceDecl *clang_namespace_decl =
569         AddNamespace(context, context.m_namespace_map);
570 
571     if (clang_namespace_decl)
572       clang_namespace_decl->setHasExternalVisibleStorage();
573   }
574 }
575 
576 clang::Sema *ClangASTSource::getSema() {
577   return m_clang_ast_context->getSema();
578 }
579 
580 bool ClangASTSource::IgnoreName(const ConstString name,
581                                 bool ignore_all_dollar_names) {
582   static const ConstString id_name("id");
583   static const ConstString Class_name("Class");
584 
585   if (m_ast_context->getLangOpts().ObjC)
586     if (name == id_name || name == Class_name)
587       return true;
588 
589   StringRef name_string_ref = name.GetStringRef();
590 
591   // The ClangASTSource is not responsible for finding $-names.
592   return name_string_ref.empty() ||
593          (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
594          name_string_ref.startswith("_$");
595 }
596 
597 void ClangASTSource::FindExternalVisibleDecls(
598     NameSearchContext &context, lldb::ModuleSP module_sp,
599     CompilerDeclContext &namespace_decl) {
600   assert(m_ast_context);
601 
602   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
603 
604   SymbolContextList sc_list;
605 
606   const ConstString name(context.m_decl_name.getAsString().c_str());
607   if (IgnoreName(name, true))
608     return;
609 
610   if (!m_target)
611     return;
612 
613   FillNamespaceMap(context, module_sp, namespace_decl);
614 
615   if (context.m_found_type)
616     return;
617 
618   TypeList types;
619   const bool exact_match = true;
620   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
621   if (module_sp && namespace_decl)
622     module_sp->FindTypesInNamespace(name, namespace_decl, 1, types);
623   else {
624     m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
625                                     searched_symbol_files, types);
626   }
627 
628   if (size_t num_types = types.GetSize()) {
629     for (size_t ti = 0; ti < num_types; ++ti) {
630       lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
631 
632       if (log) {
633         const char *name_string = type_sp->GetName().GetCString();
634 
635         LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{0}\": {1}", name,
636                  (name_string ? name_string : "<anonymous>"));
637       }
638 
639       CompilerType full_type = type_sp->GetFullCompilerType();
640 
641       CompilerType copied_clang_type(GuardedCopyType(full_type));
642 
643       if (!copied_clang_type) {
644         LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type");
645 
646         continue;
647       }
648 
649       context.AddTypeDecl(copied_clang_type);
650 
651       context.m_found_type = true;
652       break;
653     }
654   }
655 
656   if (!context.m_found_type) {
657     // Try the modules next.
658     FindDeclInModules(context, name);
659   }
660 
661   if (!context.m_found_type) {
662     FindDeclInObjCRuntime(context, name);
663   }
664 }
665 
666 void ClangASTSource::FillNamespaceMap(
667     NameSearchContext &context, lldb::ModuleSP module_sp,
668     const CompilerDeclContext &namespace_decl) {
669   const ConstString name(context.m_decl_name.getAsString().c_str());
670   if (IgnoreName(name, true))
671     return;
672 
673   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
674 
675   if (module_sp && namespace_decl) {
676     CompilerDeclContext found_namespace_decl;
677 
678     if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
679       found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
680 
681       if (found_namespace_decl) {
682         context.m_namespace_map->push_back(
683             std::pair<lldb::ModuleSP, CompilerDeclContext>(
684                 module_sp, found_namespace_decl));
685 
686         LLDB_LOG(log, "  CAS::FEVD Found namespace {0} in module {1}", name,
687                  module_sp->GetFileSpec().GetFilename());
688       }
689     }
690     return;
691   }
692 
693   for (lldb::ModuleSP image : m_target->GetImages().Modules()) {
694     if (!image)
695       continue;
696 
697     CompilerDeclContext found_namespace_decl;
698 
699     SymbolFile *symbol_file = image->GetSymbolFile();
700 
701     if (!symbol_file)
702       continue;
703 
704     found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
705 
706     if (found_namespace_decl) {
707       context.m_namespace_map->push_back(
708           std::pair<lldb::ModuleSP, CompilerDeclContext>(image,
709                                                          found_namespace_decl));
710 
711       LLDB_LOG(log, "  CAS::FEVD Found namespace {0} in module {1}", name,
712                image->GetFileSpec().GetFilename());
713     }
714   }
715 }
716 
717 template <class D> class TaggedASTDecl {
718 public:
719   TaggedASTDecl() : decl(nullptr) {}
720   TaggedASTDecl(D *_decl) : decl(_decl) {}
721   bool IsValid() const { return (decl != nullptr); }
722   bool IsInvalid() const { return !IsValid(); }
723   D *operator->() const { return decl; }
724   D *decl;
725 };
726 
727 template <class D2, template <class D> class TD, class D1>
728 TD<D2> DynCast(TD<D1> source) {
729   return TD<D2>(dyn_cast<D2>(source.decl));
730 }
731 
732 template <class D = Decl> class DeclFromParser;
733 template <class D = Decl> class DeclFromUser;
734 
735 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
736 public:
737   DeclFromParser() : TaggedASTDecl<D>() {}
738   DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
739 
740   DeclFromUser<D> GetOrigin(ClangASTSource &source);
741 };
742 
743 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
744 public:
745   DeclFromUser() : TaggedASTDecl<D>() {}
746   DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
747 
748   DeclFromParser<D> Import(ClangASTSource &source);
749 };
750 
751 template <class D>
752 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
753   ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
754   if (!origin.Valid())
755     return DeclFromUser<D>();
756   return DeclFromUser<D>(dyn_cast<D>(origin.decl));
757 }
758 
759 template <class D>
760 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
761   DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
762   if (parser_generic_decl.IsInvalid())
763     return DeclFromParser<D>();
764   return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
765 }
766 
767 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
768     NameSearchContext &context, ObjCInterfaceDecl *original_interface_decl,
769     const char *log_info) {
770   const DeclarationName &decl_name(context.m_decl_name);
771   clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
772 
773   Selector original_selector;
774 
775   if (decl_name.isObjCZeroArgSelector()) {
776     IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
777     original_selector = original_ctx->Selectors.getSelector(0, &ident);
778   } else if (decl_name.isObjCOneArgSelector()) {
779     const std::string &decl_name_string = decl_name.getAsString();
780     std::string decl_name_string_without_colon(decl_name_string.c_str(),
781                                                decl_name_string.length() - 1);
782     IdentifierInfo *ident =
783         &original_ctx->Idents.get(decl_name_string_without_colon);
784     original_selector = original_ctx->Selectors.getSelector(1, &ident);
785   } else {
786     SmallVector<IdentifierInfo *, 4> idents;
787 
788     clang::Selector sel = decl_name.getObjCSelector();
789 
790     unsigned num_args = sel.getNumArgs();
791 
792     for (unsigned i = 0; i != num_args; ++i) {
793       idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
794     }
795 
796     original_selector =
797         original_ctx->Selectors.getSelector(num_args, idents.data());
798   }
799 
800   DeclarationName original_decl_name(original_selector);
801 
802   llvm::SmallVector<NamedDecl *, 1> methods;
803 
804   TypeSystemClang::GetCompleteDecl(original_ctx, original_interface_decl);
805 
806   if (ObjCMethodDecl *instance_method_decl =
807           original_interface_decl->lookupInstanceMethod(original_selector)) {
808     methods.push_back(instance_method_decl);
809   } else if (ObjCMethodDecl *class_method_decl =
810                  original_interface_decl->lookupClassMethod(
811                      original_selector)) {
812     methods.push_back(class_method_decl);
813   }
814 
815   if (methods.empty()) {
816     return false;
817   }
818 
819   for (NamedDecl *named_decl : methods) {
820     if (!named_decl)
821       continue;
822 
823     ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
824 
825     if (!result_method)
826       continue;
827 
828     Decl *copied_decl = CopyDecl(result_method);
829 
830     if (!copied_decl)
831       continue;
832 
833     ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
834 
835     if (!copied_method_decl)
836       continue;
837 
838     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
839 
840     LLDB_LOG(log, "  CAS::FOMD found ({0}) {1}", log_info,
841              ClangUtil::DumpDecl(copied_method_decl));
842 
843     context.AddNamedDecl(copied_method_decl);
844   }
845 
846   return true;
847 }
848 
849 void ClangASTSource::FindDeclInModules(NameSearchContext &context,
850                                        ConstString name) {
851   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
852 
853   std::shared_ptr<ClangModulesDeclVendor> modules_decl_vendor =
854       GetClangModulesDeclVendor();
855   if (!modules_decl_vendor)
856     return;
857 
858   bool append = false;
859   uint32_t max_matches = 1;
860   std::vector<clang::NamedDecl *> decls;
861 
862   if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
863     return;
864 
865   LLDB_LOG(log, "  CAS::FEVD Matching entity found for \"{0}\" in the modules",
866            name);
867 
868   clang::NamedDecl *const decl_from_modules = decls[0];
869 
870   if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
871       llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
872       llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
873     clang::Decl *copied_decl = CopyDecl(decl_from_modules);
874     clang::NamedDecl *copied_named_decl =
875         copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
876 
877     if (!copied_named_decl) {
878       LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the modules");
879 
880       return;
881     }
882 
883     context.AddNamedDecl(copied_named_decl);
884 
885     context.m_found_type = true;
886   }
887 }
888 
889 void ClangASTSource::FindDeclInObjCRuntime(NameSearchContext &context,
890                                            ConstString name) {
891   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
892 
893   lldb::ProcessSP process(m_target->GetProcessSP());
894 
895   if (!process)
896     return;
897 
898   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
899 
900   if (!language_runtime)
901     return;
902 
903   DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
904 
905   if (!decl_vendor)
906     return;
907 
908   bool append = false;
909   uint32_t max_matches = 1;
910   std::vector<clang::NamedDecl *> decls;
911 
912   auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
913   if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
914     return;
915 
916   LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{0}\" in the runtime",
917            name);
918 
919   clang::Decl *copied_decl = CopyDecl(decls[0]);
920   clang::NamedDecl *copied_named_decl =
921       copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
922 
923   if (!copied_named_decl) {
924     LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the runtime");
925 
926     return;
927   }
928 
929   context.AddNamedDecl(copied_named_decl);
930 }
931 
932 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
933   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
934 
935   const DeclarationName &decl_name(context.m_decl_name);
936   const DeclContext *decl_ctx(context.m_decl_context);
937 
938   const ObjCInterfaceDecl *interface_decl =
939       dyn_cast<ObjCInterfaceDecl>(decl_ctx);
940 
941   if (!interface_decl)
942     return;
943 
944   do {
945     ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
946 
947     if (!original.Valid())
948       break;
949 
950     ObjCInterfaceDecl *original_interface_decl =
951         dyn_cast<ObjCInterfaceDecl>(original.decl);
952 
953     if (FindObjCMethodDeclsWithOrigin(context, original_interface_decl,
954                                       "at origin"))
955       return; // found it, no need to look any further
956   } while (false);
957 
958   StreamString ss;
959 
960   if (decl_name.isObjCZeroArgSelector()) {
961     ss.Printf("%s", decl_name.getAsString().c_str());
962   } else if (decl_name.isObjCOneArgSelector()) {
963     ss.Printf("%s", decl_name.getAsString().c_str());
964   } else {
965     clang::Selector sel = decl_name.getObjCSelector();
966 
967     for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
968       llvm::StringRef r = sel.getNameForSlot(i);
969       ss.Printf("%s:", r.str().c_str());
970     }
971   }
972   ss.Flush();
973 
974   if (ss.GetString().contains("$__lldb"))
975     return; // we don't need any results
976 
977   ConstString selector_name(ss.GetString());
978 
979   LLDB_LOG(log,
980            "ClangASTSource::FindObjCMethodDecls on (ASTContext*){0} '{1}' "
981            "for selector [{2} {3}]",
982            m_ast_context, m_clang_ast_context->getDisplayName(),
983            interface_decl->getName(), selector_name);
984   SymbolContextList sc_list;
985 
986   ModuleFunctionSearchOptions function_options;
987   function_options.include_symbols = false;
988   function_options.include_inlines = false;
989 
990   std::string interface_name = interface_decl->getNameAsString();
991 
992   do {
993     StreamString ms;
994     ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
995     ms.Flush();
996     ConstString instance_method_name(ms.GetString());
997 
998     sc_list.Clear();
999     m_target->GetImages().FindFunctions(instance_method_name,
1000                                         lldb::eFunctionNameTypeFull,
1001                                         function_options, sc_list);
1002 
1003     if (sc_list.GetSize())
1004       break;
1005 
1006     ms.Clear();
1007     ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1008     ms.Flush();
1009     ConstString class_method_name(ms.GetString());
1010 
1011     sc_list.Clear();
1012     m_target->GetImages().FindFunctions(class_method_name,
1013                                         lldb::eFunctionNameTypeFull,
1014                                         function_options, sc_list);
1015 
1016     if (sc_list.GetSize())
1017       break;
1018 
1019     // Fall back and check for methods in categories.  If we find methods this
1020     // way, we need to check that they're actually in categories on the desired
1021     // class.
1022 
1023     SymbolContextList candidate_sc_list;
1024 
1025     m_target->GetImages().FindFunctions(selector_name,
1026                                         lldb::eFunctionNameTypeSelector,
1027                                         function_options, candidate_sc_list);
1028 
1029     for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1030       SymbolContext candidate_sc;
1031 
1032       if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1033         continue;
1034 
1035       if (!candidate_sc.function)
1036         continue;
1037 
1038       const char *candidate_name = candidate_sc.function->GetName().AsCString();
1039 
1040       const char *cursor = candidate_name;
1041 
1042       if (*cursor != '+' && *cursor != '-')
1043         continue;
1044 
1045       ++cursor;
1046 
1047       if (*cursor != '[')
1048         continue;
1049 
1050       ++cursor;
1051 
1052       size_t interface_len = interface_name.length();
1053 
1054       if (strncmp(cursor, interface_name.c_str(), interface_len))
1055         continue;
1056 
1057       cursor += interface_len;
1058 
1059       if (*cursor == ' ' || *cursor == '(')
1060         sc_list.Append(candidate_sc);
1061     }
1062   } while (false);
1063 
1064   if (sc_list.GetSize()) {
1065     // We found a good function symbol.  Use that.
1066 
1067     for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1068       SymbolContext sc;
1069 
1070       if (!sc_list.GetContextAtIndex(i, sc))
1071         continue;
1072 
1073       if (!sc.function)
1074         continue;
1075 
1076       CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1077       if (!function_decl_ctx)
1078         continue;
1079 
1080       ObjCMethodDecl *method_decl =
1081           TypeSystemClang::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1082 
1083       if (!method_decl)
1084         continue;
1085 
1086       ObjCInterfaceDecl *found_interface_decl =
1087           method_decl->getClassInterface();
1088 
1089       if (!found_interface_decl)
1090         continue;
1091 
1092       if (found_interface_decl->getName() == interface_decl->getName()) {
1093         Decl *copied_decl = CopyDecl(method_decl);
1094 
1095         if (!copied_decl)
1096           continue;
1097 
1098         ObjCMethodDecl *copied_method_decl =
1099             dyn_cast<ObjCMethodDecl>(copied_decl);
1100 
1101         if (!copied_method_decl)
1102           continue;
1103 
1104         LLDB_LOG(log, "  CAS::FOMD found (in symbols)\n{0}",
1105                  ClangUtil::DumpDecl(copied_method_decl));
1106 
1107         context.AddNamedDecl(copied_method_decl);
1108       }
1109     }
1110 
1111     return;
1112   }
1113 
1114   // Try the debug information.
1115 
1116   do {
1117     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1118         const_cast<ObjCInterfaceDecl *>(interface_decl));
1119 
1120     if (!complete_interface_decl)
1121       break;
1122 
1123     // We found the complete interface.  The runtime never needs to be queried
1124     // in this scenario.
1125 
1126     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1127         complete_interface_decl);
1128 
1129     if (complete_interface_decl == interface_decl)
1130       break; // already checked this one
1131 
1132     LLDB_LOG(log,
1133              "CAS::FOPD trying origin "
1134              "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1135              complete_interface_decl, &complete_iface_decl->getASTContext());
1136 
1137     FindObjCMethodDeclsWithOrigin(context, complete_interface_decl,
1138                                   "in debug info");
1139 
1140     return;
1141   } while (false);
1142 
1143   do {
1144     // Check the modules only if the debug information didn't have a complete
1145     // interface.
1146 
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;
1153 
1154       if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1155                                           decls))
1156         break;
1157 
1158       ObjCInterfaceDecl *interface_decl_from_modules =
1159           dyn_cast<ObjCInterfaceDecl>(decls[0]);
1160 
1161       if (!interface_decl_from_modules)
1162         break;
1163 
1164       if (FindObjCMethodDeclsWithOrigin(context, interface_decl_from_modules,
1165                                         "in modules"))
1166         return;
1167     }
1168   } while (false);
1169 
1170   do {
1171     // Check the runtime only if the debug information didn't have a complete
1172     // interface and the modules don't get us anywhere.
1173 
1174     lldb::ProcessSP process(m_target->GetProcessSP());
1175 
1176     if (!process)
1177       break;
1178 
1179     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1180 
1181     if (!language_runtime)
1182       break;
1183 
1184     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1185 
1186     if (!decl_vendor)
1187       break;
1188 
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;
1193 
1194     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1195     if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1196                                       decls))
1197       break;
1198 
1199     ObjCInterfaceDecl *runtime_interface_decl =
1200         dyn_cast<ObjCInterfaceDecl>(decls[0]);
1201 
1202     if (!runtime_interface_decl)
1203       break;
1204 
1205     FindObjCMethodDeclsWithOrigin(context, runtime_interface_decl,
1206                                   "in runtime");
1207   } while (false);
1208 }
1209 
1210 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1211     NameSearchContext &context, ClangASTSource &source,
1212     DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1213   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1214 
1215   if (origin_iface_decl.IsInvalid())
1216     return false;
1217 
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));
1222 
1223   DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1224       origin_iface_decl->FindPropertyDeclaration(
1225           &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1226 
1227   bool found = false;
1228 
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));
1235 
1236       context.AddNamedDecl(parser_property_decl.decl);
1237       found = true;
1238     }
1239   }
1240 
1241   DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1242       origin_iface_decl->getIvarDecl(&name_identifier));
1243 
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));
1250 
1251       context.AddNamedDecl(parser_ivar_decl.decl);
1252       found = true;
1253     }
1254   }
1255 
1256   return found;
1257 }
1258 
1259 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1260   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1261 
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));
1266 
1267   ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1268 
1269   LLDB_LOG(log,
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());
1274 
1275   if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, origin_iface_decl))
1276     return;
1277 
1278   LLDB_LOG(log,
1279            "CAS::FOPD couldn't find the property on origin "
1280            "(ObjCInterfaceDecl*){0}/(ASTContext*){1}, searching "
1281            "elsewhere...",
1282            origin_iface_decl.decl, &origin_iface_decl->getASTContext());
1283 
1284   SymbolContext null_sc;
1285   TypeList type_list;
1286 
1287   do {
1288     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1289         const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1290 
1291     if (!complete_interface_decl)
1292       break;
1293 
1294     // We found the complete interface.  The runtime never needs to be queried
1295     // in this scenario.
1296 
1297     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1298         complete_interface_decl);
1299 
1300     if (complete_iface_decl.decl == origin_iface_decl.decl)
1301       break; // already checked this one
1302 
1303     LLDB_LOG(log,
1304              "CAS::FOPD trying origin "
1305              "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1306              complete_iface_decl.decl, &complete_iface_decl->getASTContext());
1307 
1308     FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, complete_iface_decl);
1309 
1310     return;
1311   } while (false);
1312 
1313   do {
1314     // Check the modules only if the debug information didn't have a complete
1315     // interface.
1316 
1317     std::shared_ptr<ClangModulesDeclVendor> modules_decl_vendor =
1318         GetClangModulesDeclVendor();
1319 
1320     if (!modules_decl_vendor)
1321       break;
1322 
1323     bool append = false;
1324     uint32_t max_matches = 1;
1325     std::vector<clang::NamedDecl *> decls;
1326 
1327     if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1328       break;
1329 
1330     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1331         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1332 
1333     if (!interface_decl_from_modules.IsValid())
1334       break;
1335 
1336     LLDB_LOG(log,
1337              "CAS::FOPD[{0}] trying module "
1338              "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1339              interface_decl_from_modules.decl,
1340              &interface_decl_from_modules->getASTContext());
1341 
1342     if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1343                                                interface_decl_from_modules))
1344       return;
1345   } while (false);
1346 
1347   do {
1348     // Check the runtime only if the debug information didn't have a complete
1349     // interface and nothing was in the modules.
1350 
1351     lldb::ProcessSP process(m_target->GetProcessSP());
1352 
1353     if (!process)
1354       return;
1355 
1356     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1357 
1358     if (!language_runtime)
1359       return;
1360 
1361     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1362 
1363     if (!decl_vendor)
1364       break;
1365 
1366     bool append = false;
1367     uint32_t max_matches = 1;
1368     std::vector<clang::NamedDecl *> decls;
1369 
1370     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1371     if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1372       break;
1373 
1374     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1375         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1376 
1377     if (!interface_decl_from_runtime.IsValid())
1378       break;
1379 
1380     LLDB_LOG(log,
1381              "CAS::FOPD[{0}] trying runtime "
1382              "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1383              interface_decl_from_runtime.decl,
1384              &interface_decl_from_runtime->getASTContext());
1385 
1386     if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1387                                                interface_decl_from_runtime))
1388       return;
1389   } while (false);
1390 }
1391 
1392 void ClangASTSource::LookupInNamespace(NameSearchContext &context) {
1393   const NamespaceDecl *namespace_context =
1394       dyn_cast<NamespaceDecl>(context.m_decl_context);
1395 
1396   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1397 
1398   ClangASTImporter::NamespaceMapSP namespace_map =
1399       m_ast_importer_sp->GetNamespaceMap(namespace_context);
1400 
1401   LLDB_LOGV(log, "  CAS::FEVD Inspecting namespace map {0} ({1} entries)",
1402             namespace_map.get(), namespace_map->size());
1403 
1404   if (!namespace_map)
1405     return;
1406 
1407   for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
1408                                                 e = namespace_map->end();
1409        i != e; ++i) {
1410     LLDB_LOG(log, "  CAS::FEVD Searching namespace {0} in module {1}",
1411              i->second.GetName(), i->first->GetFileSpec().GetFilename());
1412 
1413     FindExternalVisibleDecls(context, i->first, i->second);
1414   }
1415 }
1416 
1417 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1418 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1419 
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.begin(), sorted_items.end(),
1435              [](const PairType &lhs, const PairType &rhs) {
1436                return lhs.second < rhs.second;
1437              });
1438 
1439   for (const auto &item : sorted_items) {
1440     DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1441     DeclFromParser<D> parser_decl(user_decl.Import(source));
1442     if (parser_decl.IsInvalid())
1443       return false;
1444     destination_map.insert(
1445         std::pair<const D *, O>(parser_decl.decl, item.second));
1446   }
1447 
1448   return true;
1449 }
1450 
1451 template <bool IsVirtual>
1452 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1453                         DeclFromUser<const CXXRecordDecl> &record,
1454                         BaseOffsetMap &base_offsets) {
1455   for (CXXRecordDecl::base_class_const_iterator
1456            bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1457            be = (IsVirtual ? record->vbases_end() : record->bases_end());
1458        bi != be; ++bi) {
1459     if (!IsVirtual && bi->isVirtual())
1460       continue;
1461 
1462     const clang::Type *origin_base_type = bi->getType().getTypePtr();
1463     const clang::RecordType *origin_base_record_type =
1464         origin_base_type->getAs<RecordType>();
1465 
1466     if (!origin_base_record_type)
1467       return false;
1468 
1469     DeclFromUser<RecordDecl> origin_base_record(
1470         origin_base_record_type->getDecl());
1471 
1472     if (origin_base_record.IsInvalid())
1473       return false;
1474 
1475     DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1476         DynCast<CXXRecordDecl>(origin_base_record));
1477 
1478     if (origin_base_cxx_record.IsInvalid())
1479       return false;
1480 
1481     CharUnits base_offset;
1482 
1483     if (IsVirtual)
1484       base_offset =
1485           record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1486     else
1487       base_offset =
1488           record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1489 
1490     base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1491         origin_base_cxx_record.decl, base_offset));
1492   }
1493 
1494   return true;
1495 }
1496 
1497 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1498                                       uint64_t &alignment,
1499                                       FieldOffsetMap &field_offsets,
1500                                       BaseOffsetMap &base_offsets,
1501                                       BaseOffsetMap &virtual_base_offsets) {
1502 
1503   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1504 
1505   LLDB_LOG(log,
1506            "LayoutRecordType on (ASTContext*){0} '{1}' for (RecordDecl*)"
1507            "{2} [name = '{3}']",
1508            m_ast_context, m_clang_ast_context->getDisplayName(), record,
1509            record->getName());
1510 
1511   DeclFromParser<const RecordDecl> parser_record(record);
1512   DeclFromUser<const RecordDecl> origin_record(
1513       parser_record.GetOrigin(*this));
1514 
1515   if (origin_record.IsInvalid())
1516     return false;
1517 
1518   FieldOffsetMap origin_field_offsets;
1519   BaseOffsetMap origin_base_offsets;
1520   BaseOffsetMap origin_virtual_base_offsets;
1521 
1522   TypeSystemClang::GetCompleteDecl(
1523       &origin_record->getASTContext(),
1524       const_cast<RecordDecl *>(origin_record.decl));
1525 
1526   clang::RecordDecl *definition = origin_record.decl->getDefinition();
1527   if (!definition || !definition->isCompleteDefinition())
1528     return false;
1529 
1530   const ASTRecordLayout &record_layout(
1531       origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1532 
1533   int field_idx = 0, field_count = record_layout.getFieldCount();
1534 
1535   for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1536                                   fe = origin_record->field_end();
1537        fi != fe; ++fi) {
1538     if (field_idx >= field_count)
1539       return false; // Layout didn't go well.  Bail out.
1540 
1541     uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1542 
1543     origin_field_offsets.insert(
1544         std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1545 
1546     field_idx++;
1547   }
1548 
1549   lldbassert(&record->getASTContext() == m_ast_context);
1550 
1551   DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1552       DynCast<const CXXRecordDecl>(origin_record));
1553 
1554   if (origin_cxx_record.IsValid()) {
1555     if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1556                                    origin_base_offsets) ||
1557         !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1558                                   origin_virtual_base_offsets))
1559       return false;
1560   }
1561 
1562   if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1563       !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1564       !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1565                        *this))
1566     return false;
1567 
1568   size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1569   alignment = record_layout.getAlignment().getQuantity() *
1570               m_ast_context->getCharWidth();
1571 
1572   if (log) {
1573     LLDB_LOG(log, "LRT returned:");
1574     LLDB_LOG(log, "LRT   Original = (RecordDecl*){0}",
1575              static_cast<const void *>(origin_record.decl));
1576     LLDB_LOG(log, "LRT   Size = {0}", size);
1577     LLDB_LOG(log, "LRT   Alignment = {0}", alignment);
1578     LLDB_LOG(log, "LRT   Fields:");
1579     for (RecordDecl::field_iterator fi = record->field_begin(),
1580                                     fe = record->field_end();
1581          fi != fe; ++fi) {
1582       LLDB_LOG(log,
1583                "LRT     (FieldDecl*){0}, Name = '{1}', Type = '{2}', Offset = "
1584                "{3} bits",
1585                *fi, fi->getName(), fi->getType().getAsString(),
1586                field_offsets[*fi]);
1587     }
1588     DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1589         DynCast<const CXXRecordDecl>(parser_record);
1590     if (parser_cxx_record.IsValid()) {
1591       LLDB_LOG(log, "LRT   Bases:");
1592       for (CXXRecordDecl::base_class_const_iterator
1593                bi = parser_cxx_record->bases_begin(),
1594                be = parser_cxx_record->bases_end();
1595            bi != be; ++bi) {
1596         bool is_virtual = bi->isVirtual();
1597 
1598         QualType base_type = bi->getType();
1599         const RecordType *base_record_type = base_type->getAs<RecordType>();
1600         DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1601         DeclFromParser<CXXRecordDecl> base_cxx_record =
1602             DynCast<CXXRecordDecl>(base_record);
1603 
1604         LLDB_LOG(log,
1605                  "LRT     {0}(CXXRecordDecl*){1}, Name = '{2}', Offset = "
1606                  "{3} chars",
1607                  (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
1608                  base_cxx_record.decl->getName(),
1609                  (is_virtual
1610                       ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1611                       : base_offsets[base_cxx_record.decl].getQuantity()));
1612       }
1613     } else {
1614       LLDB_LOG(log, "LRD   Not a CXXRecord, so no bases");
1615     }
1616   }
1617 
1618   return true;
1619 }
1620 
1621 void ClangASTSource::CompleteNamespaceMap(
1622     ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1623     ClangASTImporter::NamespaceMapSP &parent_map) const {
1624 
1625   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1626 
1627   if (log) {
1628     if (parent_map && parent_map->size())
1629       LLDB_LOG(log,
1630                "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1631                "for namespace {2} in namespace {3}",
1632                m_ast_context, m_clang_ast_context->getDisplayName(), name,
1633                parent_map->begin()->second.GetName());
1634     else
1635       LLDB_LOG(log,
1636                "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1637                "for namespace {2}",
1638                m_ast_context, m_clang_ast_context->getDisplayName(), name);
1639   }
1640 
1641   if (parent_map) {
1642     for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1643                                                   e = parent_map->end();
1644          i != e; ++i) {
1645       CompilerDeclContext found_namespace_decl;
1646 
1647       lldb::ModuleSP module_sp = i->first;
1648       CompilerDeclContext module_parent_namespace_decl = i->second;
1649 
1650       SymbolFile *symbol_file = module_sp->GetSymbolFile();
1651 
1652       if (!symbol_file)
1653         continue;
1654 
1655       found_namespace_decl =
1656           symbol_file->FindNamespace(name, module_parent_namespace_decl);
1657 
1658       if (!found_namespace_decl)
1659         continue;
1660 
1661       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1662           module_sp, found_namespace_decl));
1663 
1664       LLDB_LOG(log, "  CMN Found namespace {0} in module {1}", name,
1665                module_sp->GetFileSpec().GetFilename());
1666     }
1667   } else {
1668     CompilerDeclContext null_namespace_decl;
1669     for (lldb::ModuleSP image : m_target->GetImages().Modules()) {
1670       if (!image)
1671         continue;
1672 
1673       CompilerDeclContext found_namespace_decl;
1674 
1675       SymbolFile *symbol_file = image->GetSymbolFile();
1676 
1677       if (!symbol_file)
1678         continue;
1679 
1680       found_namespace_decl =
1681           symbol_file->FindNamespace(name, null_namespace_decl);
1682 
1683       if (!found_namespace_decl)
1684         continue;
1685 
1686       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1687           image, found_namespace_decl));
1688 
1689       LLDB_LOG(log, "  CMN[{0}] Found namespace {0} in module {1}", name,
1690                image->GetFileSpec().GetFilename());
1691     }
1692   }
1693 }
1694 
1695 NamespaceDecl *ClangASTSource::AddNamespace(
1696     NameSearchContext &context,
1697     ClangASTImporter::NamespaceMapSP &namespace_decls) {
1698   if (!namespace_decls)
1699     return nullptr;
1700 
1701   const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1702 
1703   clang::ASTContext *src_ast =
1704       TypeSystemClang::DeclContextGetTypeSystemClang(namespace_decl);
1705   if (!src_ast)
1706     return nullptr;
1707   clang::NamespaceDecl *src_namespace_decl =
1708       TypeSystemClang::DeclContextGetAsNamespaceDecl(namespace_decl);
1709 
1710   if (!src_namespace_decl)
1711     return nullptr;
1712 
1713   Decl *copied_decl = CopyDecl(src_namespace_decl);
1714 
1715   if (!copied_decl)
1716     return nullptr;
1717 
1718   NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1719 
1720   if (!copied_namespace_decl)
1721     return nullptr;
1722 
1723   context.m_decls.push_back(copied_namespace_decl);
1724 
1725   m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1726                                           namespace_decls);
1727 
1728   return dyn_cast<NamespaceDecl>(copied_decl);
1729 }
1730 
1731 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1732   return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1733 }
1734 
1735 ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1736   return m_ast_importer_sp->GetDeclOrigin(decl);
1737 }
1738 
1739 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1740   TypeSystemClang *src_ast =
1741       llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
1742   if (src_ast == nullptr)
1743     return CompilerType();
1744 
1745   QualType copied_qual_type = ClangUtil::GetQualType(
1746       m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1747 
1748   if (copied_qual_type.getAsOpaquePtr() &&
1749       copied_qual_type->getCanonicalTypeInternal().isNull())
1750     // this shouldn't happen, but we're hardening because the AST importer
1751     // seems to be generating bad types on occasion.
1752     return CompilerType();
1753 
1754   return m_clang_ast_context->GetType(copied_qual_type);
1755 }
1756 
1757 std::shared_ptr<ClangModulesDeclVendor>
1758 ClangASTSource::GetClangModulesDeclVendor() {
1759   auto persistent_vars = llvm::cast<ClangPersistentVariables>(
1760       m_target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
1761   return persistent_vars->GetClangModulesDeclVendor();
1762 }
1763