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