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