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