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