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