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