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