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_import_in_progress(false), m_lookups_enabled(false), m_target(target),
57       m_ast_context(nullptr), m_ast_importer_sp(importer),
58       m_active_lexical_decls(), 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   // We are in the process of destruction, don't create clang ast context on
75   // demand by passing false to
76   // Target::GetScratchTypeSystemClang(create_on_demand).
77   TypeSystemClang *scratch_clang_ast_context =
78       TypeSystemClang::GetScratch(*m_target, false);
79 
80   if (!scratch_clang_ast_context)
81     return;
82 
83   clang::ASTContext &scratch_ast_context =
84       scratch_clang_ast_context->getASTContext();
85 
86   if (m_ast_context != &scratch_ast_context && m_ast_importer_sp)
87     m_ast_importer_sp->ForgetSource(&scratch_ast_context, m_ast_context);
88 }
89 
90 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
91   if (!m_ast_context)
92     return;
93 
94   m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
95   m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
96 }
97 
98 // The core lookup interface.
99 bool ClangASTSource::FindExternalVisibleDeclsByName(
100     const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
101   if (!m_ast_context) {
102     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
103     return false;
104   }
105 
106   if (GetImportInProgress()) {
107     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
108     return false;
109   }
110 
111   std::string decl_name(clang_decl_name.getAsString());
112 
113   switch (clang_decl_name.getNameKind()) {
114   // Normal identifiers.
115   case DeclarationName::Identifier: {
116     clang::IdentifierInfo *identifier_info =
117         clang_decl_name.getAsIdentifierInfo();
118 
119     if (!identifier_info || identifier_info->getBuiltinID() != 0) {
120       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
121       return false;
122     }
123   } break;
124 
125   // Operator names.
126   case DeclarationName::CXXOperatorName:
127   case DeclarationName::CXXLiteralOperatorName:
128     break;
129 
130   // Using directives found in this context.
131   // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
132   case DeclarationName::CXXUsingDirective:
133     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
134     return false;
135 
136   case DeclarationName::ObjCZeroArgSelector:
137   case DeclarationName::ObjCOneArgSelector:
138   case DeclarationName::ObjCMultiArgSelector: {
139     llvm::SmallVector<NamedDecl *, 1> method_decls;
140 
141     NameSearchContext method_search_context(*m_clang_ast_context, method_decls,
142                                             clang_decl_name, decl_ctx);
143 
144     FindObjCMethodDecls(method_search_context);
145 
146     SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
147     return (method_decls.size() > 0);
148   }
149   // These aren't possible in the global context.
150   case DeclarationName::CXXConstructorName:
151   case DeclarationName::CXXDestructorName:
152   case DeclarationName::CXXConversionFunctionName:
153   case DeclarationName::CXXDeductionGuideName:
154     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
155     return false;
156   }
157 
158   if (!GetLookupsEnabled()) {
159     // Wait until we see a '$' at the start of a name before we start doing any
160     // lookups so we can avoid lookup up all of the builtin types.
161     if (!decl_name.empty() && decl_name[0] == '$') {
162       SetLookupsEnabled(true);
163     } else {
164       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
165       return false;
166     }
167   }
168 
169   ConstString const_decl_name(decl_name.c_str());
170 
171   const char *uniqued_const_decl_name = const_decl_name.GetCString();
172   if (m_active_lookups.find(uniqued_const_decl_name) !=
173       m_active_lookups.end()) {
174     // We are currently looking up this name...
175     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
176     return false;
177   }
178   m_active_lookups.insert(uniqued_const_decl_name);
179   llvm::SmallVector<NamedDecl *, 4> name_decls;
180   NameSearchContext name_search_context(*m_clang_ast_context, name_decls,
181                                         clang_decl_name, decl_ctx);
182   FindExternalVisibleDecls(name_search_context);
183   SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
184   m_active_lookups.erase(uniqued_const_decl_name);
185   return (name_decls.size() != 0);
186 }
187 
188 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
189   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
190 
191   if (log) {
192     LLDB_LOG(log,
193              "    CompleteTagDecl on (ASTContext*){0} Completing "
194              "(TagDecl*){1} named {2}",
195              m_clang_ast_context->getDisplayName(), tag_decl,
196              tag_decl->getName());
197 
198     LLDB_LOG(log, "      CTD Before:\n{0}", ClangUtil::DumpDecl(tag_decl));
199   }
200 
201   auto iter = m_active_lexical_decls.find(tag_decl);
202   if (iter != m_active_lexical_decls.end())
203     return;
204   m_active_lexical_decls.insert(tag_decl);
205   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
206 
207   if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
208     // We couldn't complete the type.  Maybe there's a definition somewhere
209     // else that can be completed.
210 
211     LLDB_LOG(log, "      CTD Type could not be completed in the module in "
212                   "which it was first found.");
213 
214     bool found = false;
215 
216     DeclContext *decl_ctx = tag_decl->getDeclContext();
217 
218     if (const NamespaceDecl *namespace_context =
219             dyn_cast<NamespaceDecl>(decl_ctx)) {
220       ClangASTImporter::NamespaceMapSP namespace_map =
221           m_ast_importer_sp->GetNamespaceMap(namespace_context);
222 
223       LLDB_LOGV(log, "      CTD Inspecting namespace map{0} ({1} entries)",
224                 namespace_map.get(), namespace_map->size());
225 
226       if (!namespace_map)
227         return;
228 
229       for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
230                                                     e = namespace_map->end();
231            i != e && !found; ++i) {
232         LLDB_LOG(log, "      CTD Searching namespace {0} in module {1}",
233                  i->second.GetName(), i->first->GetFileSpec().GetFilename());
234 
235         TypeList types;
236 
237         ConstString name(tag_decl->getName().str().c_str());
238 
239         i->first->FindTypesInNamespace(name, i->second, UINT32_MAX, types);
240 
241         for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
242           lldb::TypeSP type = types.GetTypeAtIndex(ti);
243 
244           if (!type)
245             continue;
246 
247           CompilerType clang_type(type->GetFullCompilerType());
248 
249           if (!ClangUtil::IsClangType(clang_type))
250             continue;
251 
252           const TagType *tag_type =
253               ClangUtil::GetQualType(clang_type)->getAs<TagType>();
254 
255           if (!tag_type)
256             continue;
257 
258           TagDecl *candidate_tag_decl =
259               const_cast<TagDecl *>(tag_type->getDecl());
260 
261           if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
262                                                            candidate_tag_decl))
263             found = true;
264         }
265       }
266     } else {
267       TypeList types;
268 
269       ConstString name(tag_decl->getName().str().c_str());
270 
271       const ModuleList &module_list = m_target->GetImages();
272 
273       bool exact_match = false;
274       llvm::DenseSet<SymbolFile *> searched_symbol_files;
275       module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
276                             searched_symbol_files, types);
277 
278       for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
279         lldb::TypeSP type = types.GetTypeAtIndex(ti);
280 
281         if (!type)
282           continue;
283 
284         CompilerType clang_type(type->GetFullCompilerType());
285 
286         if (!ClangUtil::IsClangType(clang_type))
287           continue;
288 
289         const TagType *tag_type =
290             ClangUtil::GetQualType(clang_type)->getAs<TagType>();
291 
292         if (!tag_type)
293           continue;
294 
295         TagDecl *candidate_tag_decl =
296             const_cast<TagDecl *>(tag_type->getDecl());
297 
298         // We have found a type by basename and we need to make sure the decl
299         // contexts are the same before we can try to complete this type with
300         // another
301         if (!TypeSystemClang::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
302           continue;
303 
304         if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
305                                                          candidate_tag_decl))
306           found = true;
307       }
308     }
309   }
310 
311   LLDB_LOG(log, "      [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
312 }
313 
314 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
315   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
316 
317   LLDB_LOG(log,
318            "    [CompleteObjCInterfaceDecl] on (ASTContext*){0} '{1}' "
319            "Completing an ObjCInterfaceDecl named {1}",
320            m_ast_context, m_clang_ast_context->getDisplayName(),
321            interface_decl->getName());
322   LLDB_LOG(log, "      [COID] Before:\n{0}",
323            ClangUtil::DumpDecl(interface_decl));
324 
325   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
326 
327   if (original.Valid()) {
328     if (ObjCInterfaceDecl *original_iface_decl =
329             dyn_cast<ObjCInterfaceDecl>(original.decl)) {
330       ObjCInterfaceDecl *complete_iface_decl =
331           GetCompleteObjCInterface(original_iface_decl);
332 
333       if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
334         m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
335       }
336     }
337   }
338 
339   m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
340 
341   if (interface_decl->getSuperClass() &&
342       interface_decl->getSuperClass() != interface_decl)
343     CompleteType(interface_decl->getSuperClass());
344 
345   LLDB_LOG(log, "      [COID] After:");
346   LLDB_LOG(log, "      [COID] {0}", ClangUtil::DumpDecl(interface_decl));
347 }
348 
349 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
350     const clang::ObjCInterfaceDecl *interface_decl) {
351   lldb::ProcessSP process(m_target->GetProcessSP());
352 
353   if (!process)
354     return nullptr;
355 
356   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
357 
358   if (!language_runtime)
359     return nullptr;
360 
361   ConstString class_name(interface_decl->getNameAsString().c_str());
362 
363   lldb::TypeSP complete_type_sp(
364       language_runtime->LookupInCompleteClassCache(class_name));
365 
366   if (!complete_type_sp)
367     return nullptr;
368 
369   TypeFromUser complete_type =
370       TypeFromUser(complete_type_sp->GetFullCompilerType());
371   lldb::opaque_compiler_type_t complete_opaque_type =
372       complete_type.GetOpaqueQualType();
373 
374   if (!complete_opaque_type)
375     return nullptr;
376 
377   const clang::Type *complete_clang_type =
378       QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
379   const ObjCInterfaceType *complete_interface_type =
380       dyn_cast<ObjCInterfaceType>(complete_clang_type);
381 
382   if (!complete_interface_type)
383     return nullptr;
384 
385   ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
386 
387   return complete_iface_decl;
388 }
389 
390 void ClangASTSource::FindExternalLexicalDecls(
391     const DeclContext *decl_context,
392     llvm::function_ref<bool(Decl::Kind)> predicate,
393     llvm::SmallVectorImpl<Decl *> &decls) {
394 
395   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
396 
397   const Decl *context_decl = dyn_cast<Decl>(decl_context);
398 
399   if (!context_decl)
400     return;
401 
402   auto iter = m_active_lexical_decls.find(context_decl);
403   if (iter != m_active_lexical_decls.end())
404     return;
405   m_active_lexical_decls.insert(context_decl);
406   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
407 
408   if (log) {
409     if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
410       LLDB_LOG(log,
411                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
412                "'{2}' (%sDecl*){3}",
413                m_ast_context, m_clang_ast_context->getDisplayName(),
414                context_named_decl->getNameAsString().c_str(),
415                context_decl->getDeclKindName(),
416                static_cast<const void *>(context_decl));
417     else if (context_decl)
418       LLDB_LOG(log,
419                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
420                "({2}Decl*){3}",
421                m_ast_context, m_clang_ast_context->getDisplayName(),
422                context_decl->getDeclKindName(),
423                static_cast<const void *>(context_decl));
424     else
425       LLDB_LOG(log,
426                "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in a "
427                "NULL context",
428                m_ast_context, m_clang_ast_context->getDisplayName());
429   }
430 
431   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
432 
433   if (!original.Valid())
434     return;
435 
436   LLDB_LOG(log, "  FELD Original decl {0} (Decl*){1:x}:\n{2}",
437            static_cast<void *>(original.ctx),
438            static_cast<void *>(original.decl),
439            ClangUtil::DumpDecl(original.decl));
440 
441   if (ObjCInterfaceDecl *original_iface_decl =
442           dyn_cast<ObjCInterfaceDecl>(original.decl)) {
443     ObjCInterfaceDecl *complete_iface_decl =
444         GetCompleteObjCInterface(original_iface_decl);
445 
446     if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
447       original.decl = complete_iface_decl;
448       original.ctx = &complete_iface_decl->getASTContext();
449 
450       m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
451     }
452   }
453 
454   if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
455     ExternalASTSource *external_source = original.ctx->getExternalSource();
456 
457     if (external_source)
458       external_source->CompleteType(original_tag_decl);
459   }
460 
461   const DeclContext *original_decl_context =
462       dyn_cast<DeclContext>(original.decl);
463 
464   if (!original_decl_context)
465     return;
466 
467   // Indicates whether we skipped any Decls of the original DeclContext.
468   bool SkippedDecls = false;
469   for (Decl *decl : original_decl_context->decls()) {
470     // The predicate function returns true if the passed declaration kind is
471     // the one we are looking for.
472     // See clang::ExternalASTSource::FindExternalLexicalDecls()
473     if (predicate(decl->getKind())) {
474       if (log) {
475         std::string ast_dump = ClangUtil::DumpDecl(decl);
476         if (const NamedDecl *context_named_decl =
477                 dyn_cast<NamedDecl>(context_decl))
478           LLDB_LOG(log, "  FELD Adding [to {0}Decl {1}] lexical {2}Decl {3}",
479                    context_named_decl->getDeclKindName(),
480                    context_named_decl->getName(), decl->getDeclKindName(),
481                    ast_dump);
482         else
483           LLDB_LOG(log, "  FELD Adding lexical {0}Decl {1}",
484                    decl->getDeclKindName(), ast_dump);
485       }
486 
487       Decl *copied_decl = CopyDecl(decl);
488 
489       if (!copied_decl)
490         continue;
491 
492       if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
493         QualType copied_field_type = copied_field->getType();
494 
495         m_ast_importer_sp->RequireCompleteType(copied_field_type);
496       }
497     } else {
498       SkippedDecls = true;
499     }
500   }
501 
502   // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
503   // to false.  However, since we skipped some of the external Decls we must
504   // set it back!
505   if (SkippedDecls) {
506     decl_context->setHasExternalLexicalStorage(true);
507     // This sets HasLazyExternalLexicalLookups to true.  By setting this bit we
508     // ensure that the lookup table is rebuilt, which means the external source
509     // is consulted again when a clang::DeclContext::lookup is called.
510     const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
511   }
512 
513   return;
514 }
515 
516 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
517   assert(m_ast_context);
518 
519   const ConstString name(context.m_decl_name.getAsString().c_str());
520 
521   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
522 
523   if (log) {
524     if (!context.m_decl_context)
525       LLDB_LOG(log,
526                "ClangASTSource::FindExternalVisibleDecls on "
527                "(ASTContext*){0} '{1}' for '{2}' in a NULL DeclContext",
528                m_ast_context, m_clang_ast_context->getDisplayName(), name);
529     else if (const NamedDecl *context_named_decl =
530                  dyn_cast<NamedDecl>(context.m_decl_context))
531       LLDB_LOG(log,
532                "ClangASTSource::FindExternalVisibleDecls on "
533                "(ASTContext*){0} '{1}' for '{2}' in '{3}'",
534                m_ast_context, m_clang_ast_context->getDisplayName(), name,
535                context_named_decl->getName());
536     else
537       LLDB_LOG(log,
538                "ClangASTSource::FindExternalVisibleDecls on "
539                "(ASTContext*){0} '{1}' for '{2}' in a '{3}'",
540                m_ast_context, m_clang_ast_context->getDisplayName(), name,
541                context.m_decl_context->getDeclKindName());
542   }
543 
544   if (isa<NamespaceDecl>(context.m_decl_context)) {
545     LookupInNamespace(context);
546   } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
547     FindObjCPropertyAndIvarDecls(context);
548   } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
549     // we shouldn't be getting FindExternalVisibleDecls calls for these
550     return;
551   } else {
552     CompilerDeclContext namespace_decl;
553 
554     LLDB_LOG(log, "  CAS::FEVD Searching the root namespace");
555 
556     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl);
557   }
558 
559   if (!context.m_namespace_map->empty()) {
560     if (log && log->GetVerbose())
561       LLDB_LOG(log, "  CAS::FEVD Registering namespace map {0} ({1} entries)",
562                context.m_namespace_map.get(), context.m_namespace_map->size());
563 
564     NamespaceDecl *clang_namespace_decl =
565         AddNamespace(context, context.m_namespace_map);
566 
567     if (clang_namespace_decl)
568       clang_namespace_decl->setHasExternalVisibleStorage();
569   }
570 }
571 
572 clang::Sema *ClangASTSource::getSema() {
573   return m_clang_ast_context->getSema();
574 }
575 
576 bool ClangASTSource::IgnoreName(const ConstString name,
577                                 bool ignore_all_dollar_names) {
578   static const ConstString id_name("id");
579   static const ConstString Class_name("Class");
580 
581   if (m_ast_context->getLangOpts().ObjC)
582     if (name == id_name || name == Class_name)
583       return true;
584 
585   StringRef name_string_ref = name.GetStringRef();
586 
587   // The ClangASTSource is not responsible for finding $-names.
588   return name_string_ref.empty() ||
589          (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
590          name_string_ref.startswith("_$");
591 }
592 
593 void ClangASTSource::FindExternalVisibleDecls(
594     NameSearchContext &context, lldb::ModuleSP module_sp,
595     CompilerDeclContext &namespace_decl) {
596   assert(m_ast_context);
597 
598   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
599 
600   SymbolContextList sc_list;
601 
602   const ConstString name(context.m_decl_name.getAsString().c_str());
603   if (IgnoreName(name, true))
604     return;
605 
606   if (!m_target)
607     return;
608 
609   FillNamespaceMap(context, module_sp, namespace_decl);
610 
611   if (context.m_found_type)
612     return;
613 
614   TypeList types;
615   const bool exact_match = true;
616   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
617   if (module_sp && namespace_decl)
618     module_sp->FindTypesInNamespace(name, namespace_decl, 1, types);
619   else {
620     m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
621                                     searched_symbol_files, types);
622   }
623 
624   if (size_t num_types = types.GetSize()) {
625     for (size_t ti = 0; ti < num_types; ++ti) {
626       lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
627 
628       if (log) {
629         const char *name_string = type_sp->GetName().GetCString();
630 
631         LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{0}\": {1}", name,
632                  (name_string ? name_string : "<anonymous>"));
633       }
634 
635       CompilerType full_type = type_sp->GetFullCompilerType();
636 
637       CompilerType copied_clang_type(GuardedCopyType(full_type));
638 
639       if (!copied_clang_type) {
640         LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type");
641 
642         continue;
643       }
644 
645       context.AddTypeDecl(copied_clang_type);
646 
647       context.m_found_type = true;
648       break;
649     }
650   }
651 
652   if (!context.m_found_type) {
653     // Try the modules next.
654     FindDeclInModules(context, name);
655   }
656 
657   if (!context.m_found_type) {
658     FindDeclInObjCRuntime(context, name);
659   }
660 }
661 
662 void ClangASTSource::FillNamespaceMap(
663     NameSearchContext &context, lldb::ModuleSP module_sp,
664     const CompilerDeclContext &namespace_decl) {
665   const ConstString name(context.m_decl_name.getAsString().c_str());
666   if (IgnoreName(name, true))
667     return;
668 
669   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
670 
671   if (module_sp && namespace_decl) {
672     CompilerDeclContext found_namespace_decl;
673 
674     if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
675       found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
676 
677       if (found_namespace_decl) {
678         context.m_namespace_map->push_back(
679             std::pair<lldb::ModuleSP, CompilerDeclContext>(
680                 module_sp, found_namespace_decl));
681 
682         LLDB_LOG(log, "  CAS::FEVD Found namespace {0} in module {1}", name,
683                  module_sp->GetFileSpec().GetFilename());
684       }
685     }
686     return;
687   }
688 
689   const ModuleList &target_images = m_target->GetImages();
690   std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
691 
692   for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
693     lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
694 
695     if (!image)
696       continue;
697 
698     CompilerDeclContext found_namespace_decl;
699 
700     SymbolFile *symbol_file = image->GetSymbolFile();
701 
702     if (!symbol_file)
703       continue;
704 
705     found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
706 
707     if (found_namespace_decl) {
708       context.m_namespace_map->push_back(
709           std::pair<lldb::ModuleSP, CompilerDeclContext>(image,
710                                                          found_namespace_decl));
711 
712       LLDB_LOG(log, "  CAS::FEVD Found namespace {0} in module {1}", name,
713                image->GetFileSpec().GetFilename());
714     }
715   }
716 }
717 
718 template <class D> class TaggedASTDecl {
719 public:
720   TaggedASTDecl() : decl(nullptr) {}
721   TaggedASTDecl(D *_decl) : decl(_decl) {}
722   bool IsValid() const { return (decl != nullptr); }
723   bool IsInvalid() const { return !IsValid(); }
724   D *operator->() const { return decl; }
725   D *decl;
726 };
727 
728 template <class D2, template <class D> class TD, class D1>
729 TD<D2> DynCast(TD<D1> source) {
730   return TD<D2>(dyn_cast<D2>(source.decl));
731 }
732 
733 template <class D = Decl> class DeclFromParser;
734 template <class D = Decl> class DeclFromUser;
735 
736 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
737 public:
738   DeclFromParser() : TaggedASTDecl<D>() {}
739   DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
740 
741   DeclFromUser<D> GetOrigin(ClangASTSource &source);
742 };
743 
744 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
745 public:
746   DeclFromUser() : TaggedASTDecl<D>() {}
747   DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
748 
749   DeclFromParser<D> Import(ClangASTSource &source);
750 };
751 
752 template <class D>
753 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
754   ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
755   if (!origin.Valid())
756     return DeclFromUser<D>();
757   return DeclFromUser<D>(dyn_cast<D>(origin.decl));
758 }
759 
760 template <class D>
761 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
762   DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
763   if (parser_generic_decl.IsInvalid())
764     return DeclFromParser<D>();
765   return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
766 }
767 
768 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
769     NameSearchContext &context, ObjCInterfaceDecl *original_interface_decl,
770     const char *log_info) {
771   const DeclarationName &decl_name(context.m_decl_name);
772   clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
773 
774   Selector original_selector;
775 
776   if (decl_name.isObjCZeroArgSelector()) {
777     IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
778     original_selector = original_ctx->Selectors.getSelector(0, &ident);
779   } else if (decl_name.isObjCOneArgSelector()) {
780     const std::string &decl_name_string = decl_name.getAsString();
781     std::string decl_name_string_without_colon(decl_name_string.c_str(),
782                                                decl_name_string.length() - 1);
783     IdentifierInfo *ident =
784         &original_ctx->Idents.get(decl_name_string_without_colon);
785     original_selector = original_ctx->Selectors.getSelector(1, &ident);
786   } else {
787     SmallVector<IdentifierInfo *, 4> idents;
788 
789     clang::Selector sel = decl_name.getObjCSelector();
790 
791     unsigned num_args = sel.getNumArgs();
792 
793     for (unsigned i = 0; i != num_args; ++i) {
794       idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
795     }
796 
797     original_selector =
798         original_ctx->Selectors.getSelector(num_args, idents.data());
799   }
800 
801   DeclarationName original_decl_name(original_selector);
802 
803   llvm::SmallVector<NamedDecl *, 1> methods;
804 
805   TypeSystemClang::GetCompleteDecl(original_ctx, original_interface_decl);
806 
807   if (ObjCMethodDecl *instance_method_decl =
808           original_interface_decl->lookupInstanceMethod(original_selector)) {
809     methods.push_back(instance_method_decl);
810   } else if (ObjCMethodDecl *class_method_decl =
811                  original_interface_decl->lookupClassMethod(
812                      original_selector)) {
813     methods.push_back(class_method_decl);
814   }
815 
816   if (methods.empty()) {
817     return false;
818   }
819 
820   for (NamedDecl *named_decl : methods) {
821     if (!named_decl)
822       continue;
823 
824     ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
825 
826     if (!result_method)
827       continue;
828 
829     Decl *copied_decl = CopyDecl(result_method);
830 
831     if (!copied_decl)
832       continue;
833 
834     ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
835 
836     if (!copied_method_decl)
837       continue;
838 
839     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
840 
841     LLDB_LOG(log, "  CAS::FOMD found ({0}) {1}", log_info,
842              ClangUtil::DumpDecl(copied_method_decl));
843 
844     context.AddNamedDecl(copied_method_decl);
845   }
846 
847   return true;
848 }
849 
850 void ClangASTSource::FindDeclInModules(NameSearchContext &context,
851                                        ConstString name) {
852   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
853 
854   ClangModulesDeclVendor *modules_decl_vendor =
855       m_target->GetClangModulesDeclVendor();
856   if (!modules_decl_vendor)
857     return;
858 
859   bool append = false;
860   uint32_t max_matches = 1;
861   std::vector<clang::NamedDecl *> decls;
862 
863   if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
864     return;
865 
866   LLDB_LOG(log, "  CAS::FEVD Matching entity found for \"{0}\" in the modules",
867            name);
868 
869   clang::NamedDecl *const decl_from_modules = decls[0];
870 
871   if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
872       llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
873       llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
874     clang::Decl *copied_decl = CopyDecl(decl_from_modules);
875     clang::NamedDecl *copied_named_decl =
876         copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
877 
878     if (!copied_named_decl) {
879       LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the modules");
880 
881       return;
882     }
883 
884     context.AddNamedDecl(copied_named_decl);
885 
886     context.m_found_type = true;
887   }
888 }
889 
890 void ClangASTSource::FindDeclInObjCRuntime(NameSearchContext &context,
891                                            ConstString name) {
892   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
893 
894   lldb::ProcessSP process(m_target->GetProcessSP());
895 
896   if (!process)
897     return;
898 
899   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
900 
901   if (!language_runtime)
902     return;
903 
904   DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
905 
906   if (!decl_vendor)
907     return;
908 
909   bool append = false;
910   uint32_t max_matches = 1;
911   std::vector<clang::NamedDecl *> decls;
912 
913   auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
914   if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
915     return;
916 
917   LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{0}\" in the runtime",
918            name);
919 
920   clang::Decl *copied_decl = CopyDecl(decls[0]);
921   clang::NamedDecl *copied_named_decl =
922       copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
923 
924   if (!copied_named_decl) {
925     LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the runtime");
926 
927     return;
928   }
929 
930   context.AddNamedDecl(copied_named_decl);
931 }
932 
933 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
934   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
935 
936   const DeclarationName &decl_name(context.m_decl_name);
937   const DeclContext *decl_ctx(context.m_decl_context);
938 
939   const ObjCInterfaceDecl *interface_decl =
940       dyn_cast<ObjCInterfaceDecl>(decl_ctx);
941 
942   if (!interface_decl)
943     return;
944 
945   do {
946     ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
947 
948     if (!original.Valid())
949       break;
950 
951     ObjCInterfaceDecl *original_interface_decl =
952         dyn_cast<ObjCInterfaceDecl>(original.decl);
953 
954     if (FindObjCMethodDeclsWithOrigin(context, original_interface_decl,
955                                       "at origin"))
956       return; // found it, no need to look any further
957   } while (false);
958 
959   StreamString ss;
960 
961   if (decl_name.isObjCZeroArgSelector()) {
962     ss.Printf("%s", decl_name.getAsString().c_str());
963   } else if (decl_name.isObjCOneArgSelector()) {
964     ss.Printf("%s", decl_name.getAsString().c_str());
965   } else {
966     clang::Selector sel = decl_name.getObjCSelector();
967 
968     for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
969       llvm::StringRef r = sel.getNameForSlot(i);
970       ss.Printf("%s:", r.str().c_str());
971     }
972   }
973   ss.Flush();
974 
975   if (ss.GetString().contains("$__lldb"))
976     return; // we don't need any results
977 
978   ConstString selector_name(ss.GetString());
979 
980   LLDB_LOG(log,
981            "ClangASTSource::FindObjCMethodDecls on (ASTContext*){0} '{1}' "
982            "for selector [{2} {3}]",
983            m_ast_context, m_clang_ast_context->getDisplayName(),
984            interface_decl->getName(), selector_name);
985   SymbolContextList sc_list;
986 
987   const bool include_symbols = false;
988   const bool 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(
1000         instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1001         include_inlines, 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(
1013         class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1014         include_inlines, 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(
1026         selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1027         include_inlines, 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 (ClangModulesDeclVendor *modules_decl_vendor =
1148             m_target->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     ClangModulesDeclVendor *modules_decl_vendor =
1318         m_target->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            "{3} [name = '{4}']",
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*)%p",
1575              static_cast<const void *>(origin_record.decl));
1576     LLDB_LOG(log, "LRT   Size = %" PRId64, size);
1577     LLDB_LOG(log, "LRT   Alignment = %" PRId64, 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}', Offset = {2} bits",
1584                *fi, fi->getName(), field_offsets[*fi]);
1585     }
1586     DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1587         DynCast<const CXXRecordDecl>(parser_record);
1588     if (parser_cxx_record.IsValid()) {
1589       LLDB_LOG(log, "LRT   Bases:");
1590       for (CXXRecordDecl::base_class_const_iterator
1591                bi = parser_cxx_record->bases_begin(),
1592                be = parser_cxx_record->bases_end();
1593            bi != be; ++bi) {
1594         bool is_virtual = bi->isVirtual();
1595 
1596         QualType base_type = bi->getType();
1597         const RecordType *base_record_type = base_type->getAs<RecordType>();
1598         DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1599         DeclFromParser<CXXRecordDecl> base_cxx_record =
1600             DynCast<CXXRecordDecl>(base_record);
1601 
1602         LLDB_LOG(log,
1603                  "LRT     {0}(CXXRecordDecl*){1}, Name = '{2}', Offset = "
1604                  "{3} chars",
1605                  (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
1606                  base_cxx_record.decl->getName(),
1607                  (is_virtual
1608                       ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1609                       : base_offsets[base_cxx_record.decl].getQuantity()));
1610       }
1611     } else {
1612       LLDB_LOG(log, "LRD   Not a CXXRecord, so no bases");
1613     }
1614   }
1615 
1616   return true;
1617 }
1618 
1619 void ClangASTSource::CompleteNamespaceMap(
1620     ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1621     ClangASTImporter::NamespaceMapSP &parent_map) const {
1622 
1623   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1624 
1625   if (log) {
1626     if (parent_map && parent_map->size())
1627       LLDB_LOG(log,
1628                "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1629                "for namespace {2} in namespace {3}",
1630                m_ast_context, m_clang_ast_context->getDisplayName(), name,
1631                parent_map->begin()->second.GetName());
1632     else
1633       LLDB_LOG(log,
1634                "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1635                "for namespace {2}",
1636                m_ast_context, m_clang_ast_context->getDisplayName(), name);
1637   }
1638 
1639   if (parent_map) {
1640     for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1641                                                   e = parent_map->end();
1642          i != e; ++i) {
1643       CompilerDeclContext found_namespace_decl;
1644 
1645       lldb::ModuleSP module_sp = i->first;
1646       CompilerDeclContext module_parent_namespace_decl = i->second;
1647 
1648       SymbolFile *symbol_file = module_sp->GetSymbolFile();
1649 
1650       if (!symbol_file)
1651         continue;
1652 
1653       found_namespace_decl =
1654           symbol_file->FindNamespace(name, module_parent_namespace_decl);
1655 
1656       if (!found_namespace_decl)
1657         continue;
1658 
1659       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1660           module_sp, found_namespace_decl));
1661 
1662       LLDB_LOG(log, "  CMN Found namespace {0} in module {1}", name,
1663                module_sp->GetFileSpec().GetFilename());
1664     }
1665   } else {
1666     const ModuleList &target_images = m_target->GetImages();
1667     std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1668 
1669     CompilerDeclContext null_namespace_decl;
1670 
1671     for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1672       lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1673 
1674       if (!image)
1675         continue;
1676 
1677       CompilerDeclContext found_namespace_decl;
1678 
1679       SymbolFile *symbol_file = image->GetSymbolFile();
1680 
1681       if (!symbol_file)
1682         continue;
1683 
1684       found_namespace_decl =
1685           symbol_file->FindNamespace(name, null_namespace_decl);
1686 
1687       if (!found_namespace_decl)
1688         continue;
1689 
1690       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1691           image, found_namespace_decl));
1692 
1693       LLDB_LOG(log, "  CMN[{0}] Found namespace {0} in module {1}", name,
1694                image->GetFileSpec().GetFilename());
1695     }
1696   }
1697 }
1698 
1699 NamespaceDecl *ClangASTSource::AddNamespace(
1700     NameSearchContext &context,
1701     ClangASTImporter::NamespaceMapSP &namespace_decls) {
1702   if (!namespace_decls)
1703     return nullptr;
1704 
1705   const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1706 
1707   clang::ASTContext *src_ast =
1708       TypeSystemClang::DeclContextGetTypeSystemClang(namespace_decl);
1709   if (!src_ast)
1710     return nullptr;
1711   clang::NamespaceDecl *src_namespace_decl =
1712       TypeSystemClang::DeclContextGetAsNamespaceDecl(namespace_decl);
1713 
1714   if (!src_namespace_decl)
1715     return nullptr;
1716 
1717   Decl *copied_decl = CopyDecl(src_namespace_decl);
1718 
1719   if (!copied_decl)
1720     return nullptr;
1721 
1722   NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1723 
1724   if (!copied_namespace_decl)
1725     return nullptr;
1726 
1727   context.m_decls.push_back(copied_namespace_decl);
1728 
1729   m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1730                                           namespace_decls);
1731 
1732   return dyn_cast<NamespaceDecl>(copied_decl);
1733 }
1734 
1735 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1736   return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1737 }
1738 
1739 ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1740   return m_ast_importer_sp->GetDeclOrigin(decl);
1741 }
1742 
1743 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1744   TypeSystemClang *src_ast =
1745       llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
1746   if (src_ast == nullptr)
1747     return CompilerType();
1748 
1749   SetImportInProgress(true);
1750 
1751   QualType copied_qual_type = ClangUtil::GetQualType(
1752       m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1753 
1754   SetImportInProgress(false);
1755 
1756   if (copied_qual_type.getAsOpaquePtr() &&
1757       copied_qual_type->getCanonicalTypeInternal().isNull())
1758     // this shouldn't happen, but we're hardening because the AST importer
1759     // seems to be generating bad types on occasion.
1760     return CompilerType();
1761 
1762   return m_clang_ast_context->GetType(copied_qual_type);
1763 }
1764