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