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