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