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