1 //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "ClangExpressionDeclMap.h"
11 #include "ClangASTSource.h"
12 #include "ClangModulesDeclVendor.h"
13 #include "ClangPersistentVariables.h"
15 #include "lldb/Core/Address.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleSpec.h"
18 #include "lldb/Core/ValueObjectConstResult.h"
19 #include "lldb/Core/ValueObjectVariable.h"
20 #include "lldb/Expression/Materializer.h"
21 #include "lldb/Symbol/ClangASTContext.h"
22 #include "lldb/Symbol/ClangUtil.h"
23 #include "lldb/Symbol/CompileUnit.h"
24 #include "lldb/Symbol/CompilerDecl.h"
25 #include "lldb/Symbol/CompilerDeclContext.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolFile.h"
30 #include "lldb/Symbol/SymbolVendor.h"
31 #include "lldb/Symbol/Type.h"
32 #include "lldb/Symbol/TypeList.h"
33 #include "lldb/Symbol/Variable.h"
34 #include "lldb/Symbol/VariableList.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/RegisterContext.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Utility/Endian.h"
42 #include "lldb/Utility/Log.h"
43 #include "lldb/Utility/RegisterValue.h"
44 #include "lldb/Utility/Status.h"
45 #include "lldb/lldb-private.h"
46 #include "clang/AST/ASTConsumer.h"
47 #include "clang/AST/ASTContext.h"
48 #include "clang/AST/ASTImporter.h"
49 #include "clang/AST/Decl.h"
50 #include "clang/AST/DeclarationName.h"
51 #include "clang/AST/RecursiveASTVisitor.h"
53 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
54 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
55 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
58 using namespace lldb_private;
59 using namespace clang;
62 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars";
63 } // anonymous namespace
65 ClangExpressionDeclMap::ClangExpressionDeclMap(
66 bool keep_result_in_memory,
67 Materializer::PersistentVariableDelegate *result_delegate,
68 const lldb::TargetSP &target, const lldb::ClangASTImporterSP &importer,
70 : ClangASTSource(target, importer), m_found_entities(), m_struct_members(),
71 m_keep_result_in_memory(keep_result_in_memory),
72 m_result_delegate(result_delegate), m_ctx_obj(ctx_obj), m_parser_vars(),
77 ClangExpressionDeclMap::~ClangExpressionDeclMap() {
78 // Note: The model is now that the parser's AST context and all associated
79 // data does not vanish until the expression has been executed. This means
80 // that valuable lookup data (like namespaces) doesn't vanish, but
86 bool ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
87 Materializer *materializer) {
89 m_parser_vars->m_exe_ctx = exe_ctx;
91 Target *target = exe_ctx.GetTargetPtr();
92 if (exe_ctx.GetFramePtr())
93 m_parser_vars->m_sym_ctx =
94 exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
95 else if (exe_ctx.GetThreadPtr() &&
96 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
97 m_parser_vars->m_sym_ctx =
98 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(
99 lldb::eSymbolContextEverything);
100 else if (exe_ctx.GetProcessPtr()) {
101 m_parser_vars->m_sym_ctx.Clear(true);
102 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
104 m_parser_vars->m_sym_ctx.Clear(true);
105 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
109 m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(
110 target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
112 if (!ClangASTContext::GetScratch(*target))
116 m_parser_vars->m_target_info = GetTargetInfo();
117 m_parser_vars->m_materializer = materializer;
122 void ClangExpressionDeclMap::InstallCodeGenerator(
123 clang::ASTConsumer *code_gen) {
124 assert(m_parser_vars);
125 m_parser_vars->m_code_gen = code_gen;
128 void ClangExpressionDeclMap::DidParse() {
129 if (m_parser_vars && m_parser_vars->m_persistent_vars) {
130 for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
131 entity_index < num_entities; ++entity_index) {
132 ExpressionVariableSP var_sp(
133 m_found_entities.GetVariableAtIndex(entity_index));
135 llvm::cast<ClangExpressionVariable>(var_sp.get())
136 ->DisableParserVars(GetParserID());
139 for (size_t pvar_index = 0,
140 num_pvars = m_parser_vars->m_persistent_vars->GetSize();
141 pvar_index < num_pvars; ++pvar_index) {
142 ExpressionVariableSP pvar_sp(
143 m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
144 if (ClangExpressionVariable *clang_var =
145 llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
146 clang_var->DisableParserVars(GetParserID());
153 // Interface for IRForTarget
155 ClangExpressionDeclMap::TargetInfo ClangExpressionDeclMap::GetTargetInfo() {
156 assert(m_parser_vars.get());
160 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
162 Process *process = exe_ctx.GetProcessPtr();
164 ret.byte_order = process->GetByteOrder();
165 ret.address_byte_size = process->GetAddressByteSize();
167 Target *target = exe_ctx.GetTargetPtr();
169 ret.byte_order = target->GetArchitecture().GetByteOrder();
170 ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
177 TypeFromUser ClangExpressionDeclMap::DeportType(ClangASTContext &target,
178 ClangASTContext &source,
179 TypeFromParser parser_type) {
180 assert(&target == ClangASTContext::GetScratch(*m_target));
181 assert((TypeSystem *)&source == parser_type.GetTypeSystem());
182 assert(&source.getASTContext() == m_ast_context);
184 if (m_ast_importer_sp) {
185 return TypeFromUser(m_ast_importer_sp->DeportType(target, parser_type));
187 lldbassert(0 && "No mechanism for deporting a type!");
188 return TypeFromUser();
192 bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl,
194 TypeFromParser parser_type,
197 assert(m_parser_vars.get());
199 ClangASTContext *ast =
200 llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem());
204 if (m_parser_vars->m_materializer && is_result) {
207 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
208 Target *target = exe_ctx.GetTargetPtr();
209 if (target == nullptr)
212 auto *clang_ast_context = ClangASTContext::GetScratch(*target);
213 if (!clang_ast_context)
216 TypeFromUser user_type = DeportType(*clang_ast_context, *ast, parser_type);
218 uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(
219 user_type, is_lvalue, m_keep_result_in_memory, m_result_delegate, err);
221 ClangExpressionVariable *var = new ClangExpressionVariable(
222 exe_ctx.GetBestExecutionContextScope(), name, user_type,
223 m_parser_vars->m_target_info.byte_order,
224 m_parser_vars->m_target_info.address_byte_size);
226 m_found_entities.AddNewlyConstructedVariable(var);
228 var->EnableParserVars(GetParserID());
230 ClangExpressionVariable::ParserVars *parser_vars =
231 var->GetParserVars(GetParserID());
233 parser_vars->m_named_decl = decl;
234 parser_vars->m_parser_type = parser_type;
236 var->EnableJITVars(GetParserID());
238 ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
240 jit_vars->m_offset = offset;
245 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
246 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
247 Target *target = exe_ctx.GetTargetPtr();
248 if (target == nullptr)
251 ClangASTContext *context = ClangASTContext::GetScratch(*target);
255 TypeFromUser user_type = DeportType(*context, *ast, parser_type);
257 if (!user_type.GetOpaqueQualType()) {
258 LLDB_LOGF(log, "Persistent variable's type wasn't copied successfully");
262 if (!m_parser_vars->m_target_info.IsValid())
265 if (!m_parser_vars->m_persistent_vars)
268 ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(
269 m_parser_vars->m_persistent_vars
270 ->CreatePersistentVariable(
271 exe_ctx.GetBestExecutionContextScope(), name, user_type,
272 m_parser_vars->m_target_info.byte_order,
273 m_parser_vars->m_target_info.address_byte_size)
279 var->m_frozen_sp->SetHasCompleteType();
282 var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
285 ClangExpressionVariable::EVKeepInTarget; // explicitly-declared
286 // persistent variables should
290 var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
292 var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
293 var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
296 if (m_keep_result_in_memory) {
297 var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
300 LLDB_LOGF(log, "Created persistent variable with flags 0x%hx", var->m_flags);
302 var->EnableParserVars(GetParserID());
304 ClangExpressionVariable::ParserVars *parser_vars =
305 var->GetParserVars(GetParserID());
307 parser_vars->m_named_decl = decl;
308 parser_vars->m_parser_type = parser_type;
313 bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl,
315 llvm::Value *value, size_t size,
316 lldb::offset_t alignment) {
317 assert(m_struct_vars.get());
318 assert(m_parser_vars.get());
320 bool is_persistent_variable = false;
322 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
324 m_struct_vars->m_struct_laid_out = false;
326 if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl,
330 ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(
331 m_found_entities, decl, GetParserID()));
333 if (!var && m_parser_vars->m_persistent_vars) {
334 var = ClangExpressionVariable::FindVariableInList(
335 *m_parser_vars->m_persistent_vars, decl, GetParserID());
336 is_persistent_variable = true;
342 LLDB_LOGF(log, "Adding value for (NamedDecl*)%p [%s - %s] to the structure",
343 static_cast<const void *>(decl), name.GetCString(),
344 var->GetName().GetCString());
346 // We know entity->m_parser_vars is valid because we used a parser variable
349 ClangExpressionVariable::ParserVars *parser_vars =
350 llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
352 parser_vars->m_llvm_value = value;
354 if (ClangExpressionVariable::JITVars *jit_vars =
355 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID())) {
356 // We already laid this out; do not touch
358 LLDB_LOGF(log, "Already placed at 0x%llx",
359 (unsigned long long)jit_vars->m_offset);
362 llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
364 ClangExpressionVariable::JITVars *jit_vars =
365 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
367 jit_vars->m_alignment = alignment;
368 jit_vars->m_size = size;
370 m_struct_members.AddVariable(var->shared_from_this());
372 if (m_parser_vars->m_materializer) {
377 if (is_persistent_variable) {
378 ExpressionVariableSP var_sp(var->shared_from_this());
379 offset = m_parser_vars->m_materializer->AddPersistentVariable(
380 var_sp, nullptr, err);
382 if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
383 offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
384 else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
385 offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
386 else if (parser_vars->m_lldb_var)
387 offset = m_parser_vars->m_materializer->AddVariable(
388 parser_vars->m_lldb_var, err);
394 LLDB_LOGF(log, "Placed at 0x%llx", (unsigned long long)offset);
397 offset; // TODO DoStructLayout() should not change this.
403 bool ClangExpressionDeclMap::DoStructLayout() {
404 assert(m_struct_vars.get());
406 if (m_struct_vars->m_struct_laid_out)
409 if (!m_parser_vars->m_materializer)
412 m_struct_vars->m_struct_alignment =
413 m_parser_vars->m_materializer->GetStructAlignment();
414 m_struct_vars->m_struct_size =
415 m_parser_vars->m_materializer->GetStructByteSize();
416 m_struct_vars->m_struct_laid_out = true;
420 bool ClangExpressionDeclMap::GetStructInfo(uint32_t &num_elements, size_t &size,
421 lldb::offset_t &alignment) {
422 assert(m_struct_vars.get());
424 if (!m_struct_vars->m_struct_laid_out)
427 num_elements = m_struct_members.GetSize();
428 size = m_struct_vars->m_struct_size;
429 alignment = m_struct_vars->m_struct_alignment;
434 bool ClangExpressionDeclMap::GetStructElement(const NamedDecl *&decl,
436 lldb::offset_t &offset,
439 assert(m_struct_vars.get());
441 if (!m_struct_vars->m_struct_laid_out)
444 if (index >= m_struct_members.GetSize())
447 ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
452 ClangExpressionVariable::ParserVars *parser_vars =
453 llvm::cast<ClangExpressionVariable>(member_sp.get())
454 ->GetParserVars(GetParserID());
455 ClangExpressionVariable::JITVars *jit_vars =
456 llvm::cast<ClangExpressionVariable>(member_sp.get())
457 ->GetJITVars(GetParserID());
459 if (!parser_vars || !jit_vars || !member_sp->GetValueObject())
462 decl = parser_vars->m_named_decl;
463 value = parser_vars->m_llvm_value;
464 offset = jit_vars->m_offset;
465 name = member_sp->GetName();
470 bool ClangExpressionDeclMap::GetFunctionInfo(const NamedDecl *decl,
472 ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(
473 m_found_entities, decl, GetParserID()));
478 // We know m_parser_vars is valid since we searched for the variable by its
481 ClangExpressionVariable::ParserVars *parser_vars =
482 entity->GetParserVars(GetParserID());
484 ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
489 addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target,
492 lldb::SymbolType symbol_type,
493 lldb_private::Module *module) {
494 SymbolContextList sc_list;
497 module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
499 target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
501 const uint32_t num_matches = sc_list.GetSize();
502 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
506 (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS);
508 SymbolContext sym_ctx;
509 sc_list.GetContextAtIndex(i, sym_ctx);
511 const Address sym_address = sym_ctx.symbol->GetAddress();
513 if (!sym_address.IsValid())
516 switch (sym_ctx.symbol->GetType()) {
517 case eSymbolTypeCode:
518 case eSymbolTypeTrampoline:
519 symbol_load_addr = sym_address.GetCallableLoadAddress(&target);
522 case eSymbolTypeResolver:
523 symbol_load_addr = sym_address.GetCallableLoadAddress(&target, true);
526 case eSymbolTypeReExported: {
527 ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
529 ModuleSP reexport_module_sp;
530 ModuleSpec reexport_module_spec;
531 reexport_module_spec.GetPlatformFileSpec() =
532 sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
533 if (reexport_module_spec.GetPlatformFileSpec()) {
535 target.GetImages().FindFirstModule(reexport_module_spec);
536 if (!reexport_module_sp) {
537 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
539 target.GetImages().FindFirstModule(reexport_module_spec);
542 symbol_load_addr = GetSymbolAddress(
543 target, process, sym_ctx.symbol->GetReExportedSymbolName(),
544 symbol_type, reexport_module_sp.get());
548 case eSymbolTypeData:
549 case eSymbolTypeRuntime:
550 case eSymbolTypeVariable:
551 case eSymbolTypeLocal:
552 case eSymbolTypeParam:
553 case eSymbolTypeInvalid:
554 case eSymbolTypeAbsolute:
555 case eSymbolTypeException:
556 case eSymbolTypeSourceFile:
557 case eSymbolTypeHeaderFile:
558 case eSymbolTypeObjectFile:
559 case eSymbolTypeCommonBlock:
560 case eSymbolTypeBlock:
561 case eSymbolTypeVariableType:
562 case eSymbolTypeLineEntry:
563 case eSymbolTypeLineHeader:
564 case eSymbolTypeScopeBegin:
565 case eSymbolTypeScopeEnd:
566 case eSymbolTypeAdditional:
567 case eSymbolTypeCompiler:
568 case eSymbolTypeInstrumentation:
569 case eSymbolTypeUndefined:
570 case eSymbolTypeObjCClass:
571 case eSymbolTypeObjCMetaClass:
572 case eSymbolTypeObjCIVar:
573 symbol_load_addr = sym_address.GetLoadAddress(&target);
578 if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) {
579 ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process);
582 symbol_load_addr = runtime->LookupRuntimeSymbol(name);
586 return symbol_load_addr;
589 addr_t ClangExpressionDeclMap::GetSymbolAddress(ConstString name,
590 lldb::SymbolType symbol_type) {
591 assert(m_parser_vars.get());
593 if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
596 return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(),
597 m_parser_vars->m_exe_ctx.GetProcessPtr(), name,
601 lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable(
602 Target &target, ModuleSP &module, ConstString name,
603 CompilerDeclContext *namespace_decl) {
606 if (module && namespace_decl)
607 module->FindGlobalVariables(name, namespace_decl, -1, vars);
609 target.GetImages().FindGlobalVariables(name, -1, vars);
611 if (vars.GetSize() == 0)
613 return vars.GetVariableAtIndex(0);
616 ClangASTContext *ClangExpressionDeclMap::GetClangASTContext() {
617 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
618 if (frame == nullptr)
621 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
622 lldb::eSymbolContextBlock);
623 if (sym_ctx.block == nullptr)
626 CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
627 if (!frame_decl_context)
630 return llvm::dyn_cast_or_null<ClangASTContext>(
631 frame_decl_context.GetTypeSystem());
634 // Interface for ClangASTSource
636 void ClangExpressionDeclMap::FindExternalVisibleDecls(
637 NameSearchContext &context) {
638 assert(m_ast_context);
640 const ConstString name(context.m_decl_name.getAsString().c_str());
642 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
644 if (GetImportInProgress()) {
645 if (log && log->GetVerbose())
646 LLDB_LOGF(log, "Ignoring a query during an import");
650 static unsigned int invocation_id = 0;
651 unsigned int current_id = invocation_id++;
654 if (!context.m_decl_context)
656 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
657 "'%s' in a NULL DeclContext",
658 current_id, name.GetCString());
659 else if (const NamedDecl *context_named_decl =
660 dyn_cast<NamedDecl>(context.m_decl_context))
662 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
664 current_id, name.GetCString(),
665 context_named_decl->getNameAsString().c_str());
668 "ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
670 current_id, name.GetCString(),
671 context.m_decl_context->getDeclKindName());
674 if (const NamespaceDecl *namespace_context =
675 dyn_cast<NamespaceDecl>(context.m_decl_context)) {
676 if (namespace_context->getName().str() ==
677 std::string(g_lldb_local_vars_namespace_cstr)) {
678 CompilerDeclContext compiler_decl_ctx =
679 m_clang_ast_context->CreateDeclContext(
680 const_cast<clang::DeclContext *>(context.m_decl_context));
681 FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx,
686 ClangASTImporter::NamespaceMapSP namespace_map =
688 ? m_ast_importer_sp->GetNamespaceMap(namespace_context)
689 : ClangASTImporter::NamespaceMapSP();
694 if (log && log->GetVerbose())
695 log->Printf(" CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)",
696 current_id, static_cast<void *>(namespace_map.get()),
697 (int)namespace_map->size());
699 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
700 e = namespace_map->end();
703 log->Printf(" CEDM::FEVD[%u] Searching namespace %s in module %s",
704 current_id, i->second.GetName().AsCString(),
705 i->first->GetFileSpec().GetFilename().GetCString());
707 FindExternalVisibleDecls(context, i->first, i->second, current_id);
709 } else if (isa<TranslationUnitDecl>(context.m_decl_context)) {
710 CompilerDeclContext namespace_decl;
713 log->Printf(" CEDM::FEVD[%u] Searching the root namespace", current_id);
715 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
719 ClangASTSource::FindExternalVisibleDecls(context);
722 void ClangExpressionDeclMap::MaybeRegisterFunctionBody(
723 FunctionDecl *copied_function_decl) {
724 if (copied_function_decl->getBody() && m_parser_vars->m_code_gen) {
725 clang::DeclGroupRef decl_group_ref(copied_function_decl);
726 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
730 clang::NamedDecl *ClangExpressionDeclMap::GetPersistentDecl(ConstString name) {
733 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
737 ClangASTContext::GetScratch(*target);
739 if (!m_parser_vars->m_persistent_vars)
741 return m_parser_vars->m_persistent_vars->GetPersistentDecl(name);
744 void ClangExpressionDeclMap::SearchPersistenDecls(NameSearchContext &context,
745 const ConstString name,
746 unsigned int current_id) {
747 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
749 NamedDecl *persistent_decl = GetPersistentDecl(name);
751 if (!persistent_decl)
754 Decl *parser_persistent_decl = CopyDecl(persistent_decl);
756 if (!parser_persistent_decl)
759 NamedDecl *parser_named_decl = dyn_cast<NamedDecl>(parser_persistent_decl);
761 if (!parser_named_decl)
764 if (clang::FunctionDecl *parser_function_decl =
765 llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl)) {
766 MaybeRegisterFunctionBody(parser_function_decl);
769 LLDB_LOGF(log, " CEDM::FEVD[%u] Found persistent decl %s", current_id,
772 context.AddNamedDecl(parser_named_decl);
775 void ClangExpressionDeclMap::LookUpLldbClass(NameSearchContext &context,
776 unsigned int current_id) {
777 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
779 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
780 SymbolContext sym_ctx;
781 if (frame != nullptr)
782 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
783 lldb::eSymbolContextBlock);
787 lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
788 if (!ctx_obj_ptr || status.Fail())
791 AddThisType(context, TypeFromUser(m_ctx_obj->GetCompilerType()),
794 m_struct_vars->m_object_pointer_type =
795 TypeFromUser(ctx_obj_ptr->GetCompilerType());
800 // Clang is looking for the type of "this"
802 if (frame == nullptr)
805 // Find the block that defines the function represented by "sym_ctx"
806 Block *function_block = sym_ctx.GetFunctionBlock();
811 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
813 if (!function_decl_ctx)
816 clang::CXXMethodDecl *method_decl =
817 ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
820 clang::CXXRecordDecl *class_decl = method_decl->getParent();
822 QualType class_qual_type(class_decl->getTypeForDecl(), 0);
824 TypeFromUser class_user_type(class_qual_type.getAsOpaquePtr(),
825 function_decl_ctx.GetTypeSystem());
827 LLDB_LOG(log, " CEDM::FEVD[{0}] Adding type for $__lldb_class: {1}",
828 current_id, class_qual_type.getAsString());
830 AddThisType(context, class_user_type, current_id);
832 if (method_decl->isInstance()) {
833 // self is a pointer to the object
835 QualType class_pointer_type =
836 method_decl->getASTContext().getPointerType(class_qual_type);
838 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
839 function_decl_ctx.GetTypeSystem());
841 m_struct_vars->m_object_pointer_type = self_user_type;
846 // This branch will get hit if we are executing code in the context of
847 // a function that claims to have an object pointer (through
848 // DW_AT_object_pointer?) but is not formally a method of the class.
849 // In that case, just look up the "this" variable in the current scope
851 // FIXME: This code is formally correct, but clang doesn't currently
852 // emit DW_AT_object_pointer
853 // for C++ so it hasn't actually been tested.
855 VariableList *vars = frame->GetVariableList(false);
857 lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
859 if (this_var && this_var->IsInScope(frame) &&
860 this_var->LocationIsValidForFrame(frame)) {
861 Type *this_type = this_var->GetType();
866 TypeFromUser pointee_type =
867 this_type->GetForwardCompilerType().GetPointeeType();
869 LLDB_LOG(log, " FEVD[{0}] Adding type for $__lldb_class: {1}", current_id,
870 ClangUtil::GetQualType(pointee_type).getAsString());
872 AddThisType(context, pointee_type, current_id);
873 TypeFromUser this_user_type(this_type->GetFullCompilerType());
874 m_struct_vars->m_object_pointer_type = this_user_type;
878 void ClangExpressionDeclMap::LookUpLldbObjCClass(NameSearchContext &context,
879 unsigned int current_id) {
880 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
882 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
886 lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
887 if (!ctx_obj_ptr || status.Fail())
890 AddOneType(context, TypeFromUser(m_ctx_obj->GetCompilerType()), current_id);
892 m_struct_vars->m_object_pointer_type =
893 TypeFromUser(ctx_obj_ptr->GetCompilerType());
898 // Clang is looking for the type of "*self"
903 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
904 lldb::eSymbolContextBlock);
906 // Find the block that defines the function represented by "sym_ctx"
907 Block *function_block = sym_ctx.GetFunctionBlock();
912 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
914 if (!function_decl_ctx)
917 clang::ObjCMethodDecl *method_decl =
918 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
921 ObjCInterfaceDecl *self_interface = method_decl->getClassInterface();
926 const clang::Type *interface_type = self_interface->getTypeForDecl();
929 return; // This is unlikely, but we have seen crashes where this
932 TypeFromUser class_user_type(QualType(interface_type, 0).getAsOpaquePtr(),
933 function_decl_ctx.GetTypeSystem());
935 LLDB_LOG(log, " FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
936 current_id, ClangUtil::ToString(interface_type));
938 AddOneType(context, class_user_type, current_id);
940 if (method_decl->isInstanceMethod()) {
941 // self is a pointer to the object
943 QualType class_pointer_type =
944 method_decl->getASTContext().getObjCObjectPointerType(
945 QualType(interface_type, 0));
947 TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
948 function_decl_ctx.GetTypeSystem());
950 m_struct_vars->m_object_pointer_type = self_user_type;
952 // self is a Class pointer
953 QualType class_type = method_decl->getASTContext().getObjCClassType();
955 TypeFromUser self_user_type(class_type.getAsOpaquePtr(),
956 function_decl_ctx.GetTypeSystem());
958 m_struct_vars->m_object_pointer_type = self_user_type;
963 // This branch will get hit if we are executing code in the context of
964 // a function that claims to have an object pointer (through
965 // DW_AT_object_pointer?) but is not formally a method of the class.
966 // In that case, just look up the "self" variable in the current scope
969 VariableList *vars = frame->GetVariableList(false);
971 lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
975 if (!self_var->IsInScope(frame))
977 if (!self_var->LocationIsValidForFrame(frame))
980 Type *self_type = self_var->GetType();
985 CompilerType self_clang_type = self_type->GetFullCompilerType();
987 if (ClangASTContext::IsObjCClassType(self_clang_type)) {
990 if (!ClangASTContext::IsObjCObjectPointerType(self_clang_type))
992 self_clang_type = self_clang_type.GetPointeeType();
994 if (!self_clang_type)
997 LLDB_LOG(log, " FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
998 current_id, ClangUtil::ToString(self_type->GetFullCompilerType()));
1000 TypeFromUser class_user_type(self_clang_type);
1002 AddOneType(context, class_user_type, current_id);
1004 TypeFromUser self_user_type(self_type->GetFullCompilerType());
1006 m_struct_vars->m_object_pointer_type = self_user_type;
1009 void ClangExpressionDeclMap::LookupLocalVarNamespace(
1010 SymbolContext &sym_ctx, NameSearchContext &name_context) {
1011 if (sym_ctx.block == nullptr)
1014 CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
1015 if (!frame_decl_context)
1018 ClangASTContext *frame_ast = llvm::dyn_cast_or_null<ClangASTContext>(
1019 frame_decl_context.GetTypeSystem());
1023 clang::NamespaceDecl *namespace_decl =
1024 m_clang_ast_context->GetUniqueNamespaceDeclaration(
1025 g_lldb_local_vars_namespace_cstr, nullptr);
1026 if (!namespace_decl)
1029 name_context.AddNamedDecl(namespace_decl);
1030 clang::DeclContext *ctxt = clang::Decl::castToDeclContext(namespace_decl);
1031 ctxt->setHasExternalVisibleStorage(true);
1032 name_context.m_found.local_vars_nsp = true;
1035 void ClangExpressionDeclMap::LookupInModulesDeclVendor(
1036 NameSearchContext &context, ConstString name, unsigned current_id) {
1037 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1042 auto *modules_decl_vendor = m_target->GetClangModulesDeclVendor();
1043 if (!modules_decl_vendor)
1046 bool append = false;
1047 uint32_t max_matches = 1;
1048 std::vector<clang::NamedDecl *> decls;
1050 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
1053 assert(!decls.empty() && "FindDecls returned true but no decls?");
1054 clang::NamedDecl *const decl_from_modules = decls[0];
1057 " CAS::FEVD[{0}] Matching decl found for "
1058 "\"{1}\" in the modules",
1061 clang::Decl *copied_decl = CopyDecl(decl_from_modules);
1064 " CAS::FEVD[{0}] - Couldn't export a "
1065 "declaration from the modules",
1070 if (auto copied_function = dyn_cast<clang::FunctionDecl>(copied_decl)) {
1071 MaybeRegisterFunctionBody(copied_function);
1073 context.AddNamedDecl(copied_function);
1075 context.m_found.function_with_type_info = true;
1076 context.m_found.function = true;
1077 } else if (auto copied_var = dyn_cast<clang::VarDecl>(copied_decl)) {
1078 context.AddNamedDecl(copied_var);
1079 context.m_found.variable = true;
1083 bool ClangExpressionDeclMap::LookupLocalVariable(
1084 NameSearchContext &context, ConstString name, unsigned current_id,
1085 SymbolContext &sym_ctx, CompilerDeclContext &namespace_decl) {
1086 if (sym_ctx.block == nullptr)
1089 CompilerDeclContext decl_context = sym_ctx.block->GetDeclContext();
1093 // Make sure that the variables are parsed so that we have the
1095 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1096 VariableListSP vars = frame->GetInScopeVariableList(true);
1097 for (size_t i = 0; i < vars->GetSize(); i++)
1098 vars->GetVariableAtIndex(i)->GetDecl();
1100 // Search for declarations matching the name. Do not include imported
1101 // decls in the search if we are looking for decls in the artificial
1102 // namespace $__lldb_local_vars.
1103 std::vector<CompilerDecl> found_decls =
1104 decl_context.FindDeclByName(name, namespace_decl.IsValid());
1107 bool variable_found = false;
1108 for (CompilerDecl decl : found_decls) {
1109 for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi) {
1110 VariableSP candidate_var = vars->GetVariableAtIndex(vi);
1111 if (candidate_var->GetDecl() == decl) {
1112 var = candidate_var;
1117 if (var && !variable_found) {
1118 variable_found = true;
1119 ValueObjectSP valobj = ValueObjectVariable::Create(frame, var);
1120 AddOneVariable(context, var, valobj, current_id);
1121 context.m_found.variable = true;
1124 return variable_found;
1127 /// Structure to hold the info needed when comparing function
1130 struct FuncDeclInfo {
1132 CompilerType m_copied_type;
1133 uint32_t m_decl_lvl;
1134 SymbolContext m_sym_ctx;
1138 SymbolContextList ClangExpressionDeclMap::SearchFunctionsInSymbolContexts(
1139 const SymbolContextList &sc_list,
1140 const CompilerDeclContext &frame_decl_context) {
1141 // First, symplify things by looping through the symbol contexts to
1142 // remove unwanted functions and separate out the functions we want to
1143 // compare and prune into a separate list. Cache the info needed about
1144 // the function declarations in a vector for efficiency.
1145 uint32_t num_indices = sc_list.GetSize();
1146 SymbolContextList sc_sym_list;
1147 std::vector<FuncDeclInfo> decl_infos;
1148 decl_infos.reserve(num_indices);
1149 clang::DeclContext *frame_decl_ctx =
1150 (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1151 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(
1152 frame_decl_context.GetTypeSystem());
1154 for (uint32_t index = 0; index < num_indices; ++index) {
1156 SymbolContext sym_ctx;
1157 sc_list.GetContextAtIndex(index, sym_ctx);
1159 // We don't know enough about symbols to compare them, but we should
1160 // keep them in the list.
1161 Function *function = sym_ctx.function;
1163 sc_sym_list.Append(sym_ctx);
1166 // Filter out functions without declaration contexts, as well as
1167 // class/instance methods, since they'll be skipped in the code that
1169 CompilerDeclContext func_decl_context = function->GetDeclContext();
1170 if (!func_decl_context ||
1171 func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1173 // We can only prune functions for which we can copy the type.
1174 CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1175 CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1176 if (!copied_func_type) {
1177 sc_sym_list.Append(sym_ctx);
1181 fdi.m_sym_ctx = sym_ctx;
1182 fdi.m_name = function->GetName();
1183 fdi.m_copied_type = copied_func_type;
1184 fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1185 if (fdi.m_copied_type && func_decl_context) {
1186 // Call CountDeclLevels to get the number of parent scopes we have
1187 // to look through before we find the function declaration. When
1188 // comparing functions of the same type, the one with a lower count
1189 // will be closer to us in the lookup scope and shadows the other.
1190 clang::DeclContext *func_decl_ctx =
1191 (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1192 fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx, func_decl_ctx,
1193 &fdi.m_name, &fdi.m_copied_type);
1195 decl_infos.emplace_back(fdi);
1198 // Loop through the functions in our cache looking for matching types,
1199 // then compare their scope levels to see which is closer.
1200 std::multimap<CompilerType, const FuncDeclInfo *> matches;
1201 for (const FuncDeclInfo &fdi : decl_infos) {
1202 const CompilerType t = fdi.m_copied_type;
1203 auto q = matches.find(t);
1204 if (q != matches.end()) {
1205 if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1206 // This function is closer; remove the old set.
1208 else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1209 // The functions in our set are closer - skip this one.
1212 matches.insert(std::make_pair(t, &fdi));
1215 // Loop through our matches and add their symbol contexts to our list.
1216 SymbolContextList sc_func_list;
1217 for (const auto &q : matches)
1218 sc_func_list.Append(q.second->m_sym_ctx);
1220 // Rejoin the lists with the functions in front.
1221 sc_func_list.Append(sc_sym_list);
1222 return sc_func_list;
1225 void ClangExpressionDeclMap::LookupFunction(NameSearchContext &context,
1226 lldb::ModuleSP module_sp,
1228 CompilerDeclContext &namespace_decl,
1229 unsigned current_id) {
1233 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1235 std::vector<clang::NamedDecl *> decls_from_modules;
1238 if (ClangModulesDeclVendor *decl_vendor =
1239 target->GetClangModulesDeclVendor()) {
1240 decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1244 const bool include_inlines = false;
1245 SymbolContextList sc_list;
1246 if (namespace_decl && module_sp) {
1247 const bool include_symbols = false;
1249 module_sp->FindFunctions(name, &namespace_decl, eFunctionNameTypeBase,
1250 include_symbols, include_inlines, sc_list);
1251 } else if (target && !namespace_decl) {
1252 const bool include_symbols = true;
1254 // TODO Fix FindFunctions so that it doesn't return
1255 // instance methods for eFunctionNameTypeBase.
1257 target->GetImages().FindFunctions(
1258 name, eFunctionNameTypeFull | eFunctionNameTypeBase, include_symbols,
1259 include_inlines, sc_list);
1262 // If we found more than one function, see if we can use the frame's decl
1263 // context to remove functions that are shadowed by other functions which
1264 // match in type but are nearer in scope.
1266 // AddOneFunction will not add a function whose type has already been
1267 // added, so if there's another function in the list with a matching type,
1268 // check to see if their decl context is a parent of the current frame's or
1269 // was imported via a and using statement, and pick the best match
1270 // according to lookup rules.
1271 if (sc_list.GetSize() > 1) {
1272 // Collect some info about our frame's context.
1273 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1274 SymbolContext frame_sym_ctx;
1275 if (frame != nullptr)
1276 frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1277 lldb::eSymbolContextBlock);
1278 CompilerDeclContext frame_decl_context =
1279 frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext()
1280 : CompilerDeclContext();
1282 // We can't do this without a compiler decl context for our frame.
1283 if (frame_decl_context) {
1284 sc_list = SearchFunctionsInSymbolContexts(sc_list, frame_decl_context);
1288 if (sc_list.GetSize()) {
1289 Symbol *extern_symbol = nullptr;
1290 Symbol *non_extern_symbol = nullptr;
1292 for (uint32_t index = 0, num_indices = sc_list.GetSize();
1293 index < num_indices; ++index) {
1294 SymbolContext sym_ctx;
1295 sc_list.GetContextAtIndex(index, sym_ctx);
1297 if (sym_ctx.function) {
1298 CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1303 // Filter out class/instance methods.
1304 if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1307 AddOneFunction(context, sym_ctx.function, nullptr, current_id);
1308 context.m_found.function_with_type_info = true;
1309 context.m_found.function = true;
1310 } else if (sym_ctx.symbol) {
1311 if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) {
1312 sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1313 if (sym_ctx.symbol == nullptr)
1317 if (sym_ctx.symbol->IsExternal())
1318 extern_symbol = sym_ctx.symbol;
1320 non_extern_symbol = sym_ctx.symbol;
1324 if (!context.m_found.function_with_type_info) {
1325 for (clang::NamedDecl *decl : decls_from_modules) {
1326 if (llvm::isa<clang::FunctionDecl>(decl)) {
1327 clang::NamedDecl *copied_decl =
1328 llvm::cast_or_null<FunctionDecl>(CopyDecl(decl));
1330 context.AddNamedDecl(copied_decl);
1331 context.m_found.function_with_type_info = true;
1337 if (!context.m_found.function_with_type_info) {
1338 if (extern_symbol) {
1339 AddOneFunction(context, nullptr, extern_symbol, current_id);
1340 context.m_found.function = true;
1341 } else if (non_extern_symbol) {
1342 AddOneFunction(context, nullptr, non_extern_symbol, current_id);
1343 context.m_found.function = true;
1349 void ClangExpressionDeclMap::FindExternalVisibleDecls(
1350 NameSearchContext &context, lldb::ModuleSP module_sp,
1351 CompilerDeclContext &namespace_decl, unsigned int current_id) {
1352 assert(m_ast_context);
1354 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1356 const ConstString name(context.m_decl_name.getAsString().c_str());
1357 if (IgnoreName(name, false))
1360 // Only look for functions by name out in our symbols if the function doesn't
1361 // start with our phony prefix of '$'
1363 Target *target = nullptr;
1364 StackFrame *frame = nullptr;
1365 SymbolContext sym_ctx;
1366 if (m_parser_vars) {
1367 target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1368 frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1370 if (frame != nullptr)
1371 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1372 lldb::eSymbolContextBlock);
1374 // Try the persistent decls, which take precedence over all else.
1375 if (!namespace_decl)
1376 SearchPersistenDecls(context, name, current_id);
1378 if (name.GetStringRef().startswith("$") && !namespace_decl) {
1379 if (name == "$__lldb_class") {
1380 LookUpLldbClass(context, current_id);
1384 if (name == "$__lldb_objc_class") {
1385 LookUpLldbObjCClass(context, current_id);
1388 if (name == g_lldb_local_vars_namespace_cstr) {
1389 LookupLocalVarNamespace(sym_ctx, context);
1393 // any other $__lldb names should be weeded out now
1394 if (name.GetStringRef().startswith("$__lldb"))
1397 // No ParserVars means we can't do register or variable lookup.
1398 if (!m_parser_vars || !m_parser_vars->m_persistent_vars)
1401 ExpressionVariableSP pvar_sp(
1402 m_parser_vars->m_persistent_vars->GetVariable(name));
1405 AddOneVariable(context, pvar_sp, current_id);
1409 assert(name.GetStringRef().startswith("$"));
1410 llvm::StringRef reg_name = name.GetStringRef().substr(1);
1412 if (m_parser_vars->m_exe_ctx.GetRegisterContext()) {
1413 const RegisterInfo *reg_info(
1414 m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(
1418 LLDB_LOGF(log, " CEDM::FEVD[%u] Found register %s", current_id,
1421 AddOneRegister(context, reg_info, current_id);
1427 bool local_var_lookup = !namespace_decl || (namespace_decl.GetName() ==
1428 g_lldb_local_vars_namespace_cstr);
1429 if (frame && local_var_lookup)
1430 if (LookupLocalVariable(context, name, current_id, sym_ctx, namespace_decl))
1434 ValueObjectSP valobj;
1436 var = FindGlobalVariable(*target, module_sp, name, &namespace_decl);
1439 valobj = ValueObjectVariable::Create(target, var);
1440 AddOneVariable(context, var, valobj, current_id);
1441 context.m_found.variable = true;
1446 LookupFunction(context, module_sp, name, namespace_decl, current_id);
1448 // Try the modules next.
1449 if (!context.m_found.function_with_type_info)
1450 LookupInModulesDeclVendor(context, name, current_id);
1452 if (target && !context.m_found.variable && !namespace_decl) {
1453 // We couldn't find a non-symbol variable for this. Now we'll hunt for a
1454 // generic data symbol, and -- if it is found -- treat it as a variable.
1457 const Symbol *data_symbol =
1458 m_parser_vars->m_sym_ctx.FindBestGlobalDataSymbol(name, error);
1460 if (!error.Success()) {
1461 const unsigned diag_id =
1462 m_ast_context->getDiagnostics().getCustomDiagID(
1463 clang::DiagnosticsEngine::Level::Error, "%0");
1464 m_ast_context->getDiagnostics().Report(diag_id) << error.AsCString();
1468 std::string warning("got name from symbols: ");
1469 warning.append(name.AsCString());
1470 const unsigned diag_id =
1471 m_ast_context->getDiagnostics().getCustomDiagID(
1472 clang::DiagnosticsEngine::Level::Warning, "%0");
1473 m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1474 AddOneGenericVariable(context, *data_symbol, current_id);
1475 context.m_found.variable = true;
1480 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var,
1481 lldb_private::Value &var_location,
1482 TypeFromUser *user_type,
1483 TypeFromParser *parser_type) {
1484 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1486 Type *var_type = var->GetType();
1490 log->PutCString("Skipped a definition because it has no type");
1494 CompilerType var_clang_type = var_type->GetFullCompilerType();
1496 if (!var_clang_type) {
1498 log->PutCString("Skipped a definition because it has no Clang type");
1502 ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(
1503 var_type->GetForwardCompilerType().GetTypeSystem());
1507 log->PutCString("Skipped a definition because it has no Clang AST");
1511 DWARFExpression &var_location_expr = var->LocationExpression();
1513 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1516 if (var->GetLocationIsConstantValueData()) {
1517 DataExtractor const_value_extractor;
1519 if (var_location_expr.GetExpressionData(const_value_extractor)) {
1520 var_location = Value(const_value_extractor.GetDataStart(),
1521 const_value_extractor.GetByteSize());
1522 var_location.SetValueType(Value::eValueTypeHostAddress);
1524 LLDB_LOGF(log, "Error evaluating constant variable: %s", err.AsCString());
1529 CompilerType type_to_use = GuardedCopyType(var_clang_type);
1533 "Couldn't copy a variable's type into the parser's AST context");
1539 *parser_type = TypeFromParser(type_to_use);
1541 if (var_location.GetContextType() == Value::eContextTypeInvalid)
1542 var_location.SetCompilerType(type_to_use);
1544 if (var_location.GetValueType() == Value::eValueTypeFileAddress) {
1545 SymbolContext var_sc;
1546 var->CalculateSymbolContext(&var_sc);
1548 if (!var_sc.module_sp)
1551 Address so_addr(var_location.GetScalar().ULongLong(),
1552 var_sc.module_sp->GetSectionList());
1554 lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1556 if (load_addr != LLDB_INVALID_ADDRESS) {
1557 var_location.GetScalar() = load_addr;
1558 var_location.SetValueType(Value::eValueTypeLoadAddress);
1563 *user_type = TypeFromUser(var_clang_type);
1568 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1570 ValueObjectSP valobj,
1571 unsigned int current_id) {
1572 assert(m_parser_vars.get());
1574 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1580 if (!GetVariableValue(var, var_location, &ut, &pt))
1583 clang::QualType parser_opaque_type =
1584 QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1586 if (parser_opaque_type.isNull())
1589 if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) {
1590 if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1591 CompleteType(tag_type->getDecl());
1592 if (const ObjCObjectPointerType *objc_object_ptr_type =
1593 dyn_cast<ObjCObjectPointerType>(parser_type))
1594 CompleteType(objc_object_ptr_type->getInterfaceDecl());
1597 bool is_reference = pt.IsReferenceType();
1599 NamedDecl *var_decl = nullptr;
1601 var_decl = context.AddVarDecl(pt);
1603 var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1605 std::string decl_name(context.m_decl_name.getAsString());
1606 ConstString entity_name(decl_name.c_str());
1607 ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1608 m_found_entities.AddNewlyConstructedVariable(entity);
1611 entity->EnableParserVars(GetParserID());
1612 ClangExpressionVariable::ParserVars *parser_vars =
1613 entity->GetParserVars(GetParserID());
1614 parser_vars->m_parser_type = pt;
1615 parser_vars->m_named_decl = var_decl;
1616 parser_vars->m_llvm_value = nullptr;
1617 parser_vars->m_lldb_value = var_location;
1618 parser_vars->m_lldb_var = var;
1621 entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1624 " CEDM::FEVD[{0}] Found variable {1}, returned\n{2} (original {3})",
1625 current_id, decl_name, ClangUtil::DumpDecl(var_decl),
1626 ClangUtil::ToString(ut));
1629 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1630 ExpressionVariableSP &pvar_sp,
1631 unsigned int current_id) {
1632 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1634 TypeFromUser user_type(
1635 llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1637 TypeFromParser parser_type(GuardedCopyType(user_type));
1639 if (!parser_type.GetOpaqueQualType()) {
1640 LLDB_LOGF(log, " CEDM::FEVD[%u] Couldn't import type for pvar %s",
1641 current_id, pvar_sp->GetName().GetCString());
1645 NamedDecl *var_decl =
1646 context.AddVarDecl(parser_type.GetLValueReferenceType());
1648 llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1649 ->EnableParserVars(GetParserID());
1650 ClangExpressionVariable::ParserVars *parser_vars =
1651 llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1652 ->GetParserVars(GetParserID());
1653 parser_vars->m_parser_type = parser_type;
1654 parser_vars->m_named_decl = var_decl;
1655 parser_vars->m_llvm_value = nullptr;
1656 parser_vars->m_lldb_value.Clear();
1658 LLDB_LOG(log, " CEDM::FEVD[{0}] Added pvar {1}, returned\n{2}", current_id,
1659 pvar_sp->GetName(), ClangUtil::DumpDecl(var_decl));
1662 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1663 const Symbol &symbol,
1664 unsigned int current_id) {
1665 assert(m_parser_vars.get());
1667 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1669 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1671 if (target == nullptr)
1674 ClangASTContext *scratch_ast_context = ClangASTContext::GetScratch(*target);
1675 if (!scratch_ast_context)
1678 TypeFromUser user_type(scratch_ast_context->GetBasicType(eBasicTypeVoid)
1680 .GetLValueReferenceType());
1681 TypeFromParser parser_type(m_clang_ast_context->GetBasicType(eBasicTypeVoid)
1683 .GetLValueReferenceType());
1684 NamedDecl *var_decl = context.AddVarDecl(parser_type);
1686 std::string decl_name(context.m_decl_name.getAsString());
1687 ConstString entity_name(decl_name.c_str());
1688 ClangExpressionVariable *entity(new ClangExpressionVariable(
1689 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name,
1690 user_type, m_parser_vars->m_target_info.byte_order,
1691 m_parser_vars->m_target_info.address_byte_size));
1692 m_found_entities.AddNewlyConstructedVariable(entity);
1694 entity->EnableParserVars(GetParserID());
1695 ClangExpressionVariable::ParserVars *parser_vars =
1696 entity->GetParserVars(GetParserID());
1698 const Address symbol_address = symbol.GetAddress();
1699 lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1701 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType,
1702 // user_type.GetOpaqueQualType());
1703 parser_vars->m_lldb_value.SetCompilerType(user_type);
1704 parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1705 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1707 parser_vars->m_parser_type = parser_type;
1708 parser_vars->m_named_decl = var_decl;
1709 parser_vars->m_llvm_value = nullptr;
1710 parser_vars->m_lldb_sym = &symbol;
1712 LLDB_LOG(log, " CEDM::FEVD[{0}] Found variable {1}, returned\n{2}",
1713 current_id, decl_name, ClangUtil::DumpDecl(var_decl));
1716 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context,
1717 const RegisterInfo *reg_info,
1718 unsigned int current_id) {
1719 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1721 CompilerType clang_type =
1722 m_clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1723 reg_info->encoding, reg_info->byte_size * 8);
1726 LLDB_LOGF(log, " Tried to add a type for %s, but couldn't get one",
1727 context.m_decl_name.getAsString().c_str());
1731 TypeFromParser parser_clang_type(clang_type);
1733 NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
1735 ClangExpressionVariable *entity(new ClangExpressionVariable(
1736 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1737 m_parser_vars->m_target_info.byte_order,
1738 m_parser_vars->m_target_info.address_byte_size));
1739 m_found_entities.AddNewlyConstructedVariable(entity);
1741 std::string decl_name(context.m_decl_name.getAsString());
1742 entity->SetName(ConstString(decl_name.c_str()));
1743 entity->SetRegisterInfo(reg_info);
1744 entity->EnableParserVars(GetParserID());
1745 ClangExpressionVariable::ParserVars *parser_vars =
1746 entity->GetParserVars(GetParserID());
1747 parser_vars->m_parser_type = parser_clang_type;
1748 parser_vars->m_named_decl = var_decl;
1749 parser_vars->m_llvm_value = nullptr;
1750 parser_vars->m_lldb_value.Clear();
1751 entity->m_flags |= ClangExpressionVariable::EVBareRegister;
1753 LLDB_LOG(log, " CEDM::FEVD[{0}] Added register {1}, returned\n{2}",
1754 current_id, context.m_decl_name.getAsString(),
1755 ClangUtil::DumpDecl(var_decl));
1758 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context,
1759 Function *function, Symbol *symbol,
1760 unsigned int current_id) {
1761 assert(m_parser_vars.get());
1763 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1765 NamedDecl *function_decl = nullptr;
1766 Address fun_address;
1767 CompilerType function_clang_type;
1769 bool is_indirect_function = false;
1772 Type *function_type = function->GetType();
1774 const auto lang = function->GetCompileUnit()->GetLanguage();
1775 const auto name = function->GetMangled().GetMangledName().AsCString();
1776 const bool extern_c = (Language::LanguageIsC(lang) &&
1777 !CPlusPlusLanguage::IsCPPMangledName(name)) ||
1778 (Language::LanguageIsObjC(lang) &&
1779 !Language::LanguageIsCPlusPlus(lang));
1782 TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
1783 if (llvm::isa<ClangASTContext>(type_system)) {
1784 clang::DeclContext *src_decl_context =
1785 (clang::DeclContext *)function->GetDeclContext()
1786 .GetOpaqueDeclContext();
1787 clang::FunctionDecl *src_function_decl =
1788 llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
1789 if (src_function_decl &&
1790 src_function_decl->getTemplateSpecializationInfo()) {
1791 clang::FunctionTemplateDecl *function_template =
1792 src_function_decl->getTemplateSpecializationInfo()->getTemplate();
1793 clang::FunctionTemplateDecl *copied_function_template =
1794 llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(
1795 CopyDecl(function_template));
1796 if (copied_function_template) {
1800 function->DumpSymbolContext(&ss);
1803 " CEDM::FEVD[{0}] Imported decl for function template"
1804 " {1} (description {2}), returned\n{3}",
1805 current_id, copied_function_template->getNameAsString(),
1807 ClangUtil::DumpDecl(copied_function_template));
1810 context.AddNamedDecl(copied_function_template);
1812 } else if (src_function_decl) {
1813 if (clang::FunctionDecl *copied_function_decl =
1814 llvm::dyn_cast_or_null<clang::FunctionDecl>(
1815 CopyDecl(src_function_decl))) {
1819 function->DumpSymbolContext(&ss);
1822 " CEDM::FEVD[{0}]] Imported decl for function {1} "
1823 "(description {2}), returned\n{3}",
1824 current_id, copied_function_decl->getNameAsString(),
1825 ss.GetData(), ClangUtil::DumpDecl(copied_function_decl));
1828 context.AddNamedDecl(copied_function_decl);
1832 LLDB_LOGF(log, " Failed to import the function decl for '%s'",
1833 src_function_decl->getName().str().c_str());
1840 if (!function_type) {
1842 log->PutCString(" Skipped a function because it has no type");
1846 function_clang_type = function_type->GetFullCompilerType();
1848 if (!function_clang_type) {
1850 log->PutCString(" Skipped a function because it has no Clang type");
1854 fun_address = function->GetAddressRange().GetBaseAddress();
1856 CompilerType copied_function_type = GuardedCopyType(function_clang_type);
1857 if (copied_function_type) {
1858 function_decl = context.AddFunDecl(copied_function_type, extern_c);
1860 if (!function_decl) {
1864 " Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
1865 function_type->GetName().GetCString(), function_type->GetID());
1871 // We failed to copy the type we found
1874 " Failed to import the function type '%s' {0x%8.8" PRIx64
1875 "} into the expression parser AST contenxt",
1876 function_type->GetName().GetCString(),
1877 function_type->GetID());
1882 } else if (symbol) {
1883 fun_address = symbol->GetAddress();
1884 function_decl = context.AddGenericFunDecl();
1885 is_indirect_function = symbol->IsIndirect();
1888 log->PutCString(" AddOneFunction called with no function and no symbol");
1892 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1894 lldb::addr_t load_addr =
1895 fun_address.GetCallableLoadAddress(target, is_indirect_function);
1897 ClangExpressionVariable *entity(new ClangExpressionVariable(
1898 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1899 m_parser_vars->m_target_info.byte_order,
1900 m_parser_vars->m_target_info.address_byte_size));
1901 m_found_entities.AddNewlyConstructedVariable(entity);
1903 std::string decl_name(context.m_decl_name.getAsString());
1904 entity->SetName(ConstString(decl_name.c_str()));
1905 entity->SetCompilerType(function_clang_type);
1906 entity->EnableParserVars(GetParserID());
1908 ClangExpressionVariable::ParserVars *parser_vars =
1909 entity->GetParserVars(GetParserID());
1911 if (load_addr != LLDB_INVALID_ADDRESS) {
1912 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1913 parser_vars->m_lldb_value.GetScalar() = load_addr;
1915 // We have to try finding a file address.
1917 lldb::addr_t file_addr = fun_address.GetFileAddress();
1919 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
1920 parser_vars->m_lldb_value.GetScalar() = file_addr;
1923 parser_vars->m_named_decl = function_decl;
1924 parser_vars->m_llvm_value = nullptr;
1929 fun_address.Dump(&ss,
1930 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1931 Address::DumpStyleResolvedDescription);
1934 " CEDM::FEVD[{0}] Found {1} function {2} (description {3}), "
1936 current_id, (function ? "specific" : "generic"), decl_name,
1937 ss.GetData(), ClangUtil::DumpDecl(function_decl));
1941 void ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
1942 const TypeFromUser &ut,
1943 unsigned int current_id) {
1944 CompilerType copied_clang_type = GuardedCopyType(ut);
1946 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1948 if (!copied_clang_type) {
1952 "ClangExpressionDeclMap::AddThisType - Couldn't import the type");
1957 if (copied_clang_type.IsAggregateType() &&
1958 copied_clang_type.GetCompleteType()) {
1959 CompilerType void_clang_type =
1960 m_clang_ast_context->GetBasicType(eBasicTypeVoid);
1961 CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
1963 CompilerType method_type = m_clang_ast_context->CreateFunctionType(
1964 void_clang_type, &void_ptr_clang_type, 1, false, 0);
1966 const bool is_virtual = false;
1967 const bool is_static = false;
1968 const bool is_inline = false;
1969 const bool is_explicit = false;
1970 const bool is_attr_used = true;
1971 const bool is_artificial = false;
1973 CXXMethodDecl *method_decl = m_clang_ast_context->AddMethodToCXXRecordType(
1974 copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr,
1975 method_type, lldb::eAccessPublic, is_virtual, is_static, is_inline,
1976 is_explicit, is_attr_used, is_artificial);
1979 " CEDM::AddThisType Added function $__lldb_expr "
1980 "(description {0}) for this type\n{1}",
1981 ClangUtil::ToString(copied_clang_type),
1982 ClangUtil::DumpDecl(method_decl));
1985 if (!copied_clang_type.IsValid())
1988 TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(
1989 QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
1991 if (!type_source_info)
1994 // Construct a typedef type because if "*this" is a templated type we can't
1995 // just return ClassTemplateSpecializationDecls in response to name queries.
1996 // Using a typedef makes this much more robust.
1998 TypedefDecl *typedef_decl = TypedefDecl::Create(
1999 *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(),
2000 SourceLocation(), context.m_decl_name.getAsIdentifierInfo(),
2006 context.AddNamedDecl(typedef_decl);
2011 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2012 const TypeFromUser &ut,
2013 unsigned int current_id) {
2014 CompilerType copied_clang_type = GuardedCopyType(ut);
2016 if (!copied_clang_type) {
2017 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2021 log, "ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2026 context.AddTypeDecl(copied_clang_type);