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