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