1 //===-- ClangExpressionDeclMap.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ClangExpressionDeclMap.h"
12 #include "ASTDumper.h"
13 #include "ClangASTSource.h"
14 #include "ClangModulesDeclVendor.h"
15 #include "ClangPersistentVariables.h"
17 #include "lldb/Core/Address.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/RegisterValue.h"
21 #include "lldb/Core/ValueObjectConstResult.h"
22 #include "lldb/Core/ValueObjectVariable.h"
23 #include "lldb/Expression/Materializer.h"
24 #include "lldb/Symbol/ClangASTContext.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/CompilerDecl.h"
27 #include "lldb/Symbol/CompilerDeclContext.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Symbol/SymbolContext.h"
31 #include "lldb/Symbol/SymbolFile.h"
32 #include "lldb/Symbol/SymbolVendor.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/TypeList.h"
35 #include "lldb/Symbol/Variable.h"
36 #include "lldb/Symbol/VariableList.h"
37 #include "lldb/Target/CPPLanguageRuntime.h"
38 #include "lldb/Target/ExecutionContext.h"
39 #include "lldb/Target/ObjCLanguageRuntime.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Target/RegisterContext.h"
42 #include "lldb/Target/StackFrame.h"
43 #include "lldb/Target/Target.h"
44 #include "lldb/Target/Thread.h"
45 #include "lldb/Utility/Endian.h"
46 #include "lldb/Utility/Error.h"
47 #include "lldb/Utility/Log.h"
48 #include "lldb/lldb-private.h"
49 #include "clang/AST/ASTConsumer.h"
50 #include "clang/AST/ASTContext.h"
51 #include "clang/AST/Decl.h"
52 #include "clang/AST/DeclarationName.h"
54 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
57 using namespace lldb_private;
58 using namespace clang;
61 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars";
62 } // anonymous namespace
64 ClangExpressionDeclMap::ClangExpressionDeclMap(
65 bool keep_result_in_memory,
66 Materializer::PersistentVariableDelegate *result_delegate,
67 ExecutionContext &exe_ctx)
68 : ClangASTSource(exe_ctx.GetTargetSP()), m_found_entities(),
69 m_struct_members(), m_keep_result_in_memory(keep_result_in_memory),
70 m_result_delegate(result_delegate), m_parser_vars(), m_struct_vars() {
74 ClangExpressionDeclMap::~ClangExpressionDeclMap() {
75 // Note: The model is now that the parser's AST context and all associated
76 // data does not vanish until the expression has been executed. This means
77 // that valuable lookup data (like namespaces) doesn't vanish, but
83 bool ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
84 Materializer *materializer) {
85 ClangASTMetrics::ClearLocalCounters();
88 m_parser_vars->m_exe_ctx = exe_ctx;
90 Target *target = exe_ctx.GetTargetPtr();
91 if (exe_ctx.GetFramePtr())
92 m_parser_vars->m_sym_ctx =
93 exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
94 else if (exe_ctx.GetThreadPtr() &&
95 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
96 m_parser_vars->m_sym_ctx =
97 exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(
98 lldb::eSymbolContextEverything);
99 else if (exe_ctx.GetProcessPtr()) {
100 m_parser_vars->m_sym_ctx.Clear(true);
101 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
103 m_parser_vars->m_sym_ctx.Clear(true);
104 m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
108 m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(
109 target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
111 if (!target->GetScratchClangASTContext())
115 m_parser_vars->m_target_info = GetTargetInfo();
116 m_parser_vars->m_materializer = materializer;
121 void ClangExpressionDeclMap::InstallCodeGenerator(
122 clang::ASTConsumer *code_gen) {
123 assert(m_parser_vars);
124 m_parser_vars->m_code_gen = code_gen;
127 void ClangExpressionDeclMap::DidParse() {
128 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
131 ClangASTMetrics::DumpCounters(log);
133 if (m_parser_vars.get()) {
134 for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
135 entity_index < num_entities; ++entity_index) {
136 ExpressionVariableSP var_sp(
137 m_found_entities.GetVariableAtIndex(entity_index));
139 llvm::cast<ClangExpressionVariable>(var_sp.get())
140 ->DisableParserVars(GetParserID());
143 for (size_t pvar_index = 0,
144 num_pvars = m_parser_vars->m_persistent_vars->GetSize();
145 pvar_index < num_pvars; ++pvar_index) {
146 ExpressionVariableSP pvar_sp(
147 m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
148 if (ClangExpressionVariable *clang_var =
149 llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
150 clang_var->DisableParserVars(GetParserID());
157 // Interface for IRForTarget
159 ClangExpressionDeclMap::TargetInfo ClangExpressionDeclMap::GetTargetInfo() {
160 assert(m_parser_vars.get());
164 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
166 Process *process = exe_ctx.GetProcessPtr();
168 ret.byte_order = process->GetByteOrder();
169 ret.address_byte_size = process->GetAddressByteSize();
171 Target *target = exe_ctx.GetTargetPtr();
173 ret.byte_order = target->GetArchitecture().GetByteOrder();
174 ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
181 bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl,
182 const ConstString &name,
183 TypeFromParser parser_type,
186 assert(m_parser_vars.get());
188 ClangASTContext *ast =
189 llvm::dyn_cast_or_null<ClangASTContext>(parser_type.GetTypeSystem());
193 if (m_parser_vars->m_materializer && is_result) {
196 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
197 Target *target = exe_ctx.GetTargetPtr();
198 if (target == nullptr)
201 ClangASTContext *context(target->GetScratchClangASTContext());
203 TypeFromUser user_type(m_ast_importer_sp->DeportType(
204 context->getASTContext(), ast->getASTContext(),
205 parser_type.GetOpaqueQualType()),
208 uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(
209 user_type, is_lvalue, m_keep_result_in_memory, m_result_delegate, err);
211 ClangExpressionVariable *var = new ClangExpressionVariable(
212 exe_ctx.GetBestExecutionContextScope(), name, user_type,
213 m_parser_vars->m_target_info.byte_order,
214 m_parser_vars->m_target_info.address_byte_size);
216 m_found_entities.AddNewlyConstructedVariable(var);
218 var->EnableParserVars(GetParserID());
220 ClangExpressionVariable::ParserVars *parser_vars =
221 var->GetParserVars(GetParserID());
223 parser_vars->m_named_decl = decl;
224 parser_vars->m_parser_type = parser_type;
226 var->EnableJITVars(GetParserID());
228 ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
230 jit_vars->m_offset = offset;
235 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
236 ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
237 Target *target = exe_ctx.GetTargetPtr();
241 ClangASTContext *context(target->GetScratchClangASTContext());
243 TypeFromUser user_type(m_ast_importer_sp->DeportType(
244 context->getASTContext(), ast->getASTContext(),
245 parser_type.GetOpaqueQualType()),
248 if (!user_type.GetOpaqueQualType()) {
250 log->Printf("Persistent variable's type wasn't copied successfully");
254 if (!m_parser_vars->m_target_info.IsValid())
257 ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(
258 m_parser_vars->m_persistent_vars
259 ->CreatePersistentVariable(
260 exe_ctx.GetBestExecutionContextScope(), name, user_type,
261 m_parser_vars->m_target_info.byte_order,
262 m_parser_vars->m_target_info.address_byte_size)
268 var->m_frozen_sp->SetHasCompleteType();
271 var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
274 ClangExpressionVariable::EVKeepInTarget; // explicitly-declared
275 // persistent variables should
279 var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
281 var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
282 var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
285 if (m_keep_result_in_memory) {
286 var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
290 log->Printf("Created persistent variable with flags 0x%hx", var->m_flags);
292 var->EnableParserVars(GetParserID());
294 ClangExpressionVariable::ParserVars *parser_vars =
295 var->GetParserVars(GetParserID());
297 parser_vars->m_named_decl = decl;
298 parser_vars->m_parser_type = parser_type;
303 bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl,
304 const ConstString &name,
305 llvm::Value *value, size_t size,
306 lldb::offset_t alignment) {
307 assert(m_struct_vars.get());
308 assert(m_parser_vars.get());
310 bool is_persistent_variable = false;
312 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
314 m_struct_vars->m_struct_laid_out = false;
316 if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl,
320 ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(
321 m_found_entities, decl, GetParserID()));
324 var = ClangExpressionVariable::FindVariableInList(
325 *m_parser_vars->m_persistent_vars, decl, GetParserID());
326 is_persistent_variable = true;
333 log->Printf("Adding value for (NamedDecl*)%p [%s - %s] to the structure",
334 static_cast<const void *>(decl), name.GetCString(),
335 var->GetName().GetCString());
337 // We know entity->m_parser_vars is valid because we used a parser variable
340 ClangExpressionVariable::ParserVars *parser_vars =
341 llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
343 parser_vars->m_llvm_value = value;
345 if (ClangExpressionVariable::JITVars *jit_vars =
346 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID())) {
347 // We already laid this out; do not touch
350 log->Printf("Already placed at 0x%llx",
351 (unsigned long long)jit_vars->m_offset);
354 llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
356 ClangExpressionVariable::JITVars *jit_vars =
357 llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
359 jit_vars->m_alignment = alignment;
360 jit_vars->m_size = size;
362 m_struct_members.AddVariable(var->shared_from_this());
364 if (m_parser_vars->m_materializer) {
369 if (is_persistent_variable) {
370 ExpressionVariableSP var_sp(var->shared_from_this());
371 offset = m_parser_vars->m_materializer->AddPersistentVariable(
372 var_sp, nullptr, err);
374 if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
375 offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
376 else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
377 offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
378 else if (parser_vars->m_lldb_var)
379 offset = m_parser_vars->m_materializer->AddVariable(
380 parser_vars->m_lldb_var, err);
387 log->Printf("Placed at 0x%llx", (unsigned long long)offset);
390 offset; // TODO DoStructLayout() should not change this.
396 bool ClangExpressionDeclMap::DoStructLayout() {
397 assert(m_struct_vars.get());
399 if (m_struct_vars->m_struct_laid_out)
402 if (!m_parser_vars->m_materializer)
405 m_struct_vars->m_struct_alignment =
406 m_parser_vars->m_materializer->GetStructAlignment();
407 m_struct_vars->m_struct_size =
408 m_parser_vars->m_materializer->GetStructByteSize();
409 m_struct_vars->m_struct_laid_out = true;
413 bool ClangExpressionDeclMap::GetStructInfo(uint32_t &num_elements, size_t &size,
414 lldb::offset_t &alignment) {
415 assert(m_struct_vars.get());
417 if (!m_struct_vars->m_struct_laid_out)
420 num_elements = m_struct_members.GetSize();
421 size = m_struct_vars->m_struct_size;
422 alignment = m_struct_vars->m_struct_alignment;
427 bool ClangExpressionDeclMap::GetStructElement(const NamedDecl *&decl,
429 lldb::offset_t &offset,
432 assert(m_struct_vars.get());
434 if (!m_struct_vars->m_struct_laid_out)
437 if (index >= m_struct_members.GetSize())
440 ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
445 ClangExpressionVariable::ParserVars *parser_vars =
446 llvm::cast<ClangExpressionVariable>(member_sp.get())
447 ->GetParserVars(GetParserID());
448 ClangExpressionVariable::JITVars *jit_vars =
449 llvm::cast<ClangExpressionVariable>(member_sp.get())
450 ->GetJITVars(GetParserID());
452 if (!parser_vars || !jit_vars || !member_sp->GetValueObject())
455 decl = parser_vars->m_named_decl;
456 value = parser_vars->m_llvm_value;
457 offset = jit_vars->m_offset;
458 name = member_sp->GetName();
463 bool ClangExpressionDeclMap::GetFunctionInfo(const NamedDecl *decl,
465 ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(
466 m_found_entities, decl, GetParserID()));
471 // We know m_parser_vars is valid since we searched for the variable by
474 ClangExpressionVariable::ParserVars *parser_vars =
475 entity->GetParserVars(GetParserID());
477 ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
482 addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target,
484 const ConstString &name,
485 lldb::SymbolType symbol_type,
486 lldb_private::Module *module) {
487 SymbolContextList sc_list;
490 module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
492 target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
494 const uint32_t num_matches = sc_list.GetSize();
495 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
499 (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS);
501 SymbolContext sym_ctx;
502 sc_list.GetContextAtIndex(i, sym_ctx);
504 const Address sym_address = sym_ctx.symbol->GetAddress();
506 if (!sym_address.IsValid())
509 switch (sym_ctx.symbol->GetType()) {
510 case eSymbolTypeCode:
511 case eSymbolTypeTrampoline:
512 symbol_load_addr = sym_address.GetCallableLoadAddress(&target);
515 case eSymbolTypeResolver:
516 symbol_load_addr = sym_address.GetCallableLoadAddress(&target, true);
519 case eSymbolTypeReExported: {
520 ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
522 ModuleSP reexport_module_sp;
523 ModuleSpec reexport_module_spec;
524 reexport_module_spec.GetPlatformFileSpec() =
525 sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
526 if (reexport_module_spec.GetPlatformFileSpec()) {
528 target.GetImages().FindFirstModule(reexport_module_spec);
529 if (!reexport_module_sp) {
530 reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
532 target.GetImages().FindFirstModule(reexport_module_spec);
535 symbol_load_addr = GetSymbolAddress(
536 target, process, sym_ctx.symbol->GetReExportedSymbolName(),
537 symbol_type, reexport_module_sp.get());
541 case eSymbolTypeData:
542 case eSymbolTypeRuntime:
543 case eSymbolTypeVariable:
544 case eSymbolTypeLocal:
545 case eSymbolTypeParam:
546 case eSymbolTypeInvalid:
547 case eSymbolTypeAbsolute:
548 case eSymbolTypeException:
549 case eSymbolTypeSourceFile:
550 case eSymbolTypeHeaderFile:
551 case eSymbolTypeObjectFile:
552 case eSymbolTypeCommonBlock:
553 case eSymbolTypeBlock:
554 case eSymbolTypeVariableType:
555 case eSymbolTypeLineEntry:
556 case eSymbolTypeLineHeader:
557 case eSymbolTypeScopeBegin:
558 case eSymbolTypeScopeEnd:
559 case eSymbolTypeAdditional:
560 case eSymbolTypeCompiler:
561 case eSymbolTypeInstrumentation:
562 case eSymbolTypeUndefined:
563 case eSymbolTypeObjCClass:
564 case eSymbolTypeObjCMetaClass:
565 case eSymbolTypeObjCIVar:
566 symbol_load_addr = sym_address.GetLoadAddress(&target);
571 if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) {
572 ObjCLanguageRuntime *runtime = process->GetObjCLanguageRuntime();
575 symbol_load_addr = runtime->LookupRuntimeSymbol(name);
579 return symbol_load_addr;
582 addr_t ClangExpressionDeclMap::GetSymbolAddress(const ConstString &name,
583 lldb::SymbolType symbol_type) {
584 assert(m_parser_vars.get());
586 if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
589 return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(),
590 m_parser_vars->m_exe_ctx.GetProcessPtr(), name,
594 const Symbol *ClangExpressionDeclMap::FindGlobalDataSymbol(
595 Target &target, const ConstString &name, lldb_private::Module *module) {
596 SymbolContextList sc_list;
599 module->FindSymbolsWithNameAndType(name, eSymbolTypeAny, sc_list);
601 target.GetImages().FindSymbolsWithNameAndType(name, eSymbolTypeAny,
604 const uint32_t matches = sc_list.GetSize();
605 for (uint32_t i = 0; i < matches; ++i) {
606 SymbolContext sym_ctx;
607 sc_list.GetContextAtIndex(i, sym_ctx);
608 if (sym_ctx.symbol) {
609 const Symbol *symbol = sym_ctx.symbol;
610 const Address sym_address = symbol->GetAddress();
612 if (sym_address.IsValid()) {
613 switch (symbol->GetType()) {
614 case eSymbolTypeData:
615 case eSymbolTypeRuntime:
616 case eSymbolTypeAbsolute:
617 case eSymbolTypeObjCClass:
618 case eSymbolTypeObjCMetaClass:
619 case eSymbolTypeObjCIVar:
620 if (symbol->GetDemangledNameIsSynthesized()) {
621 // If the demangled name was synthesized, then don't use it
622 // for expressions. Only let the symbol match if the mangled
623 // named matches for these symbols.
624 if (symbol->GetMangled().GetMangledName() != name)
629 case eSymbolTypeReExported: {
630 ConstString reexport_name = symbol->GetReExportedSymbolName();
632 ModuleSP reexport_module_sp;
633 ModuleSpec reexport_module_spec;
634 reexport_module_spec.GetPlatformFileSpec() =
635 symbol->GetReExportedSymbolSharedLibrary();
636 if (reexport_module_spec.GetPlatformFileSpec()) {
638 target.GetImages().FindFirstModule(reexport_module_spec);
639 if (!reexport_module_sp) {
640 reexport_module_spec.GetPlatformFileSpec()
644 target.GetImages().FindFirstModule(reexport_module_spec);
647 // Don't allow us to try and resolve a re-exported symbol if it is
649 // as the current symbol
650 if (name == symbol->GetReExportedSymbolName() &&
651 module == reexport_module_sp.get())
654 return FindGlobalDataSymbol(target,
655 symbol->GetReExportedSymbolName(),
656 reexport_module_sp.get());
660 case eSymbolTypeCode: // We already lookup functions elsewhere
661 case eSymbolTypeVariable:
662 case eSymbolTypeLocal:
663 case eSymbolTypeParam:
664 case eSymbolTypeTrampoline:
665 case eSymbolTypeInvalid:
666 case eSymbolTypeException:
667 case eSymbolTypeSourceFile:
668 case eSymbolTypeHeaderFile:
669 case eSymbolTypeObjectFile:
670 case eSymbolTypeCommonBlock:
671 case eSymbolTypeBlock:
672 case eSymbolTypeVariableType:
673 case eSymbolTypeLineEntry:
674 case eSymbolTypeLineHeader:
675 case eSymbolTypeScopeBegin:
676 case eSymbolTypeScopeEnd:
677 case eSymbolTypeAdditional:
678 case eSymbolTypeCompiler:
679 case eSymbolTypeInstrumentation:
680 case eSymbolTypeUndefined:
681 case eSymbolTypeResolver:
691 lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable(
692 Target &target, ModuleSP &module, const ConstString &name,
693 CompilerDeclContext *namespace_decl, TypeFromUser *type) {
696 if (module && namespace_decl)
697 module->FindGlobalVariables(name, namespace_decl, true, -1, vars);
699 target.GetImages().FindGlobalVariables(name, true, -1, vars);
701 if (vars.GetSize()) {
703 for (size_t i = 0; i < vars.GetSize(); ++i) {
704 VariableSP var_sp = vars.GetVariableAtIndex(i);
706 if (ClangASTContext::AreTypesSame(
707 *type, var_sp->GetType()->GetFullCompilerType()))
711 return vars.GetVariableAtIndex(0);
718 ClangASTContext *ClangExpressionDeclMap::GetClangASTContext() {
719 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
720 if (frame == nullptr)
723 SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
724 lldb::eSymbolContextBlock);
725 if (sym_ctx.block == nullptr)
728 CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
729 if (!frame_decl_context)
732 return llvm::dyn_cast_or_null<ClangASTContext>(
733 frame_decl_context.GetTypeSystem());
736 // Interface for ClangASTSource
738 void ClangExpressionDeclMap::FindExternalVisibleDecls(
739 NameSearchContext &context) {
740 assert(m_ast_context);
742 ClangASTMetrics::RegisterVisibleQuery();
744 const ConstString name(context.m_decl_name.getAsString().c_str());
746 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
748 if (GetImportInProgress()) {
749 if (log && log->GetVerbose())
750 log->Printf("Ignoring a query during an import");
754 static unsigned int invocation_id = 0;
755 unsigned int current_id = invocation_id++;
758 if (!context.m_decl_context)
759 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
760 "'%s' in a NULL DeclContext",
761 current_id, name.GetCString());
762 else if (const NamedDecl *context_named_decl =
763 dyn_cast<NamedDecl>(context.m_decl_context))
764 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
766 current_id, name.GetCString(),
767 context_named_decl->getNameAsString().c_str());
769 log->Printf("ClangExpressionDeclMap::FindExternalVisibleDecls[%u] for "
771 current_id, name.GetCString(),
772 context.m_decl_context->getDeclKindName());
775 if (const NamespaceDecl *namespace_context =
776 dyn_cast<NamespaceDecl>(context.m_decl_context)) {
777 if (namespace_context->getName().str() ==
778 std::string(g_lldb_local_vars_namespace_cstr)) {
779 CompilerDeclContext compiler_decl_ctx(
780 GetClangASTContext(), const_cast<void *>(static_cast<const void *>(
781 context.m_decl_context)));
782 FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx,
787 ClangASTImporter::NamespaceMapSP namespace_map =
788 m_ast_importer_sp->GetNamespaceMap(namespace_context);
790 if (log && log->GetVerbose())
791 log->Printf(" CEDM::FEVD[%u] Inspecting (NamespaceMap*)%p (%d entries)",
792 current_id, static_cast<void *>(namespace_map.get()),
793 (int)namespace_map->size());
798 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
799 e = namespace_map->end();
802 log->Printf(" CEDM::FEVD[%u] Searching namespace %s in module %s",
803 current_id, i->second.GetName().AsCString(),
804 i->first->GetFileSpec().GetFilename().GetCString());
806 FindExternalVisibleDecls(context, i->first, i->second, current_id);
808 } else if (isa<TranslationUnitDecl>(context.m_decl_context)) {
809 CompilerDeclContext namespace_decl;
812 log->Printf(" CEDM::FEVD[%u] Searching the root namespace", current_id);
814 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
818 ClangASTSource::FindExternalVisibleDecls(context);
821 void ClangExpressionDeclMap::FindExternalVisibleDecls(
822 NameSearchContext &context, lldb::ModuleSP module_sp,
823 CompilerDeclContext &namespace_decl, unsigned int current_id) {
824 assert(m_ast_context);
826 std::function<void(clang::FunctionDecl *)> MaybeRegisterFunctionBody =
827 [this](clang::FunctionDecl *copied_function_decl) {
828 if (copied_function_decl->getBody() && m_parser_vars->m_code_gen) {
829 DeclGroupRef decl_group_ref(copied_function_decl);
830 m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
834 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
836 SymbolContextList sc_list;
838 const ConstString name(context.m_decl_name.getAsString().c_str());
840 const char *name_unique_cstr = name.GetCString();
842 if (name_unique_cstr == NULL)
845 static ConstString id_name("id");
846 static ConstString Class_name("Class");
848 if (name == id_name || name == Class_name)
851 // Only look for functions by name out in our symbols if the function
852 // doesn't start with our phony prefix of '$'
853 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
854 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
855 SymbolContext sym_ctx;
856 if (frame != nullptr)
857 sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
858 lldb::eSymbolContextBlock);
860 // Try the persistent decls, which take precedence over all else.
861 if (!namespace_decl) {
866 ClangASTContext *scratch_clang_ast_context =
867 target->GetScratchClangASTContext();
869 if (!scratch_clang_ast_context)
872 ASTContext *scratch_ast_context =
873 scratch_clang_ast_context->getASTContext();
875 if (!scratch_ast_context)
878 NamedDecl *persistent_decl =
879 m_parser_vars->m_persistent_vars->GetPersistentDecl(name);
881 if (!persistent_decl)
884 Decl *parser_persistent_decl = m_ast_importer_sp->CopyDecl(
885 m_ast_context, scratch_ast_context, persistent_decl);
887 if (!parser_persistent_decl)
890 NamedDecl *parser_named_decl =
891 dyn_cast<NamedDecl>(parser_persistent_decl);
893 if (!parser_named_decl)
896 if (clang::FunctionDecl *parser_function_decl =
897 llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl)) {
898 MaybeRegisterFunctionBody(parser_function_decl);
902 log->Printf(" CEDM::FEVD[%u] Found persistent decl %s", current_id,
905 context.AddNamedDecl(parser_named_decl);
909 if (name_unique_cstr[0] == '$' && !namespace_decl) {
910 static ConstString g_lldb_class_name("$__lldb_class");
912 if (name == g_lldb_class_name) {
913 // Clang is looking for the type of "this"
918 // Find the block that defines the function represented by "sym_ctx"
919 Block *function_block = sym_ctx.GetFunctionBlock();
924 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
926 if (!function_decl_ctx)
929 clang::CXXMethodDecl *method_decl =
930 ClangASTContext::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
933 clang::CXXRecordDecl *class_decl = method_decl->getParent();
935 QualType class_qual_type(class_decl->getTypeForDecl(), 0);
937 TypeFromUser class_user_type(
938 class_qual_type.getAsOpaquePtr(),
939 ClangASTContext::GetASTContext(&class_decl->getASTContext()));
942 ASTDumper ast_dumper(class_qual_type);
943 log->Printf(" CEDM::FEVD[%u] Adding type for $__lldb_class: %s",
944 current_id, ast_dumper.GetCString());
947 AddThisType(context, class_user_type, current_id);
949 if (method_decl->isInstance()) {
950 // self is a pointer to the object
952 QualType class_pointer_type =
953 method_decl->getASTContext().getPointerType(class_qual_type);
955 TypeFromUser self_user_type(
956 class_pointer_type.getAsOpaquePtr(),
957 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
959 m_struct_vars->m_object_pointer_type = self_user_type;
962 // This branch will get hit if we are executing code in the context of a
964 // claims to have an object pointer (through DW_AT_object_pointer?) but
966 // method of the class. In that case, just look up the "this" variable
968 // scope and use its type.
969 // FIXME: This code is formally correct, but clang doesn't currently
970 // emit DW_AT_object_pointer
971 // for C++ so it hasn't actually been tested.
973 VariableList *vars = frame->GetVariableList(false);
975 lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
977 if (this_var && this_var->IsInScope(frame) &&
978 this_var->LocationIsValidForFrame(frame)) {
979 Type *this_type = this_var->GetType();
984 TypeFromUser pointee_type =
985 this_type->GetForwardCompilerType().GetPointeeType();
987 if (pointee_type.IsValid()) {
989 ASTDumper ast_dumper(pointee_type);
990 log->Printf(" FEVD[%u] Adding type for $__lldb_class: %s",
991 current_id, ast_dumper.GetCString());
994 AddThisType(context, pointee_type, current_id);
995 TypeFromUser this_user_type(this_type->GetFullCompilerType());
996 m_struct_vars->m_object_pointer_type = this_user_type;
1005 static ConstString g_lldb_objc_class_name("$__lldb_objc_class");
1006 if (name == g_lldb_objc_class_name) {
1007 // Clang is looking for the type of "*self"
1012 SymbolContext sym_ctx = frame->GetSymbolContext(
1013 lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
1015 // Find the block that defines the function represented by "sym_ctx"
1016 Block *function_block = sym_ctx.GetFunctionBlock();
1018 if (!function_block)
1021 CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
1023 if (!function_decl_ctx)
1026 clang::ObjCMethodDecl *method_decl =
1027 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1030 ObjCInterfaceDecl *self_interface = method_decl->getClassInterface();
1032 if (!self_interface)
1035 const clang::Type *interface_type = self_interface->getTypeForDecl();
1037 if (!interface_type)
1038 return; // This is unlikely, but we have seen crashes where this
1041 TypeFromUser class_user_type(
1042 QualType(interface_type, 0).getAsOpaquePtr(),
1043 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1046 ASTDumper ast_dumper(interface_type);
1047 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s",
1048 current_id, ast_dumper.GetCString());
1051 AddOneType(context, class_user_type, current_id);
1053 if (method_decl->isInstanceMethod()) {
1054 // self is a pointer to the object
1056 QualType class_pointer_type =
1057 method_decl->getASTContext().getObjCObjectPointerType(
1058 QualType(interface_type, 0));
1060 TypeFromUser self_user_type(
1061 class_pointer_type.getAsOpaquePtr(),
1062 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1064 m_struct_vars->m_object_pointer_type = self_user_type;
1066 // self is a Class pointer
1067 QualType class_type = method_decl->getASTContext().getObjCClassType();
1069 TypeFromUser self_user_type(
1070 class_type.getAsOpaquePtr(),
1071 ClangASTContext::GetASTContext(&method_decl->getASTContext()));
1073 m_struct_vars->m_object_pointer_type = self_user_type;
1078 // This branch will get hit if we are executing code in the context of a
1080 // claims to have an object pointer (through DW_AT_object_pointer?) but
1081 // is not formally a
1082 // method of the class. In that case, just look up the "self" variable
1084 // scope and use its type.
1086 VariableList *vars = frame->GetVariableList(false);
1088 lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
1090 if (self_var && self_var->IsInScope(frame) &&
1091 self_var->LocationIsValidForFrame(frame)) {
1092 Type *self_type = self_var->GetType();
1097 CompilerType self_clang_type = self_type->GetFullCompilerType();
1099 if (ClangASTContext::IsObjCClassType(self_clang_type)) {
1101 } else if (ClangASTContext::IsObjCObjectPointerType(
1103 self_clang_type = self_clang_type.GetPointeeType();
1105 if (!self_clang_type)
1109 ASTDumper ast_dumper(self_type->GetFullCompilerType());
1110 log->Printf(" FEVD[%u] Adding type for $__lldb_objc_class: %s",
1111 current_id, ast_dumper.GetCString());
1114 TypeFromUser class_user_type(self_clang_type);
1116 AddOneType(context, class_user_type, current_id);
1118 TypeFromUser self_user_type(self_type->GetFullCompilerType());
1120 m_struct_vars->m_object_pointer_type = self_user_type;
1129 if (name == ConstString(g_lldb_local_vars_namespace_cstr)) {
1130 CompilerDeclContext frame_decl_context =
1131 sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext()
1132 : CompilerDeclContext();
1134 if (frame_decl_context) {
1135 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(
1136 frame_decl_context.GetTypeSystem());
1139 clang::NamespaceDecl *namespace_decl =
1140 ClangASTContext::GetUniqueNamespaceDeclaration(
1141 m_ast_context, name_unique_cstr, nullptr);
1142 if (namespace_decl) {
1143 context.AddNamedDecl(namespace_decl);
1144 clang::DeclContext *clang_decl_ctx =
1145 clang::Decl::castToDeclContext(namespace_decl);
1146 clang_decl_ctx->setHasExternalVisibleStorage(true);
1147 context.m_found.local_vars_nsp = true;
1155 // any other $__lldb names should be weeded out now
1156 if (!::strncmp(name_unique_cstr, "$__lldb", sizeof("$__lldb") - 1))
1159 ExpressionVariableSP pvar_sp(
1160 m_parser_vars->m_persistent_vars->GetVariable(name));
1163 AddOneVariable(context, pvar_sp, current_id);
1167 const char *reg_name(&name.GetCString()[1]);
1169 if (m_parser_vars->m_exe_ctx.GetRegisterContext()) {
1170 const RegisterInfo *reg_info(
1171 m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(
1176 log->Printf(" CEDM::FEVD[%u] Found register %s", current_id,
1179 AddOneRegister(context, reg_info, current_id);
1183 ValueObjectSP valobj;
1186 bool local_var_lookup =
1187 !namespace_decl || (namespace_decl.GetName() ==
1188 ConstString(g_lldb_local_vars_namespace_cstr));
1189 if (frame && local_var_lookup) {
1190 CompilerDeclContext compiler_decl_context =
1191 sym_ctx.block != nullptr ? sym_ctx.block->GetDeclContext()
1192 : CompilerDeclContext();
1194 if (compiler_decl_context) {
1195 // Make sure that the variables are parsed so that we have the
1197 VariableListSP vars = frame->GetInScopeVariableList(true);
1198 for (size_t i = 0; i < vars->GetSize(); i++)
1199 vars->GetVariableAtIndex(i)->GetDecl();
1201 // Search for declarations matching the name. Do not include imported
1203 // in the search if we are looking for decls in the artificial namespace
1204 // $__lldb_local_vars.
1205 std::vector<CompilerDecl> found_decls =
1206 compiler_decl_context.FindDeclByName(name,
1207 namespace_decl.IsValid());
1209 bool variable_found = false;
1210 for (CompilerDecl decl : found_decls) {
1211 for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi) {
1212 VariableSP candidate_var = vars->GetVariableAtIndex(vi);
1213 if (candidate_var->GetDecl() == decl) {
1214 var = candidate_var;
1219 if (var && !variable_found) {
1220 variable_found = true;
1221 valobj = ValueObjectVariable::Create(frame, var);
1222 AddOneVariable(context, var, valobj, current_id);
1223 context.m_found.variable = true;
1231 var = FindGlobalVariable(*target, module_sp, name, &namespace_decl, NULL);
1234 valobj = ValueObjectVariable::Create(target, var);
1235 AddOneVariable(context, var, valobj, current_id);
1236 context.m_found.variable = true;
1241 std::vector<clang::NamedDecl *> decls_from_modules;
1244 if (ClangModulesDeclVendor *decl_vendor =
1245 target->GetClangModulesDeclVendor()) {
1246 decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1250 const bool include_inlines = false;
1251 const bool append = false;
1253 if (namespace_decl && module_sp) {
1254 const bool include_symbols = false;
1256 module_sp->FindFunctions(name, &namespace_decl, eFunctionNameTypeBase,
1257 include_symbols, include_inlines, append,
1259 } else if (target && !namespace_decl) {
1260 const bool include_symbols = true;
1262 // TODO Fix FindFunctions so that it doesn't return
1263 // instance methods for eFunctionNameTypeBase.
1265 target->GetImages().FindFunctions(name, eFunctionNameTypeFull,
1266 include_symbols, include_inlines,
1270 // If we found more than one function, see if we can use the
1271 // frame's decl context to remove functions that are shadowed
1272 // by other functions which match in type but are nearer in scope.
1274 // AddOneFunction will not add a function whose type has already been
1275 // added, so if there's another function in the list with a matching
1276 // type, check to see if their decl context is a parent of the current
1277 // frame's or was imported via a and using statement, and pick the
1278 // best match according to lookup rules.
1279 if (sc_list.GetSize() > 1) {
1280 // Collect some info about our frame's context.
1281 StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1282 SymbolContext frame_sym_ctx;
1283 if (frame != nullptr)
1284 frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1285 lldb::eSymbolContextBlock);
1286 CompilerDeclContext frame_decl_context =
1287 frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext()
1288 : CompilerDeclContext();
1290 // We can't do this without a compiler decl context for our frame.
1291 if (frame_decl_context) {
1292 clang::DeclContext *frame_decl_ctx =
1293 (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1294 ClangASTContext *ast = llvm::dyn_cast_or_null<ClangASTContext>(
1295 frame_decl_context.GetTypeSystem());
1297 // Structure to hold the info needed when comparing function
1299 struct FuncDeclInfo {
1301 CompilerType m_copied_type;
1302 uint32_t m_decl_lvl;
1303 SymbolContext m_sym_ctx;
1306 // First, symplify things by looping through the symbol contexts
1307 // to remove unwanted functions and separate out the functions we
1308 // want to compare and prune into a separate list.
1309 // Cache the info needed about the function declarations in a
1310 // vector for efficiency.
1311 SymbolContextList sc_sym_list;
1312 uint32_t num_indices = sc_list.GetSize();
1313 std::vector<FuncDeclInfo> fdi_cache;
1314 fdi_cache.reserve(num_indices);
1315 for (uint32_t index = 0; index < num_indices; ++index) {
1317 SymbolContext sym_ctx;
1318 sc_list.GetContextAtIndex(index, sym_ctx);
1320 // We don't know enough about symbols to compare them,
1321 // but we should keep them in the list.
1322 Function *function = sym_ctx.function;
1324 sc_sym_list.Append(sym_ctx);
1327 // Filter out functions without declaration contexts, as well as
1328 // class/instance methods, since they'll be skipped in the
1329 // code that follows anyway.
1330 CompilerDeclContext func_decl_context = function->GetDeclContext();
1331 if (!func_decl_context ||
1332 func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1334 // We can only prune functions for which we can copy the type.
1335 CompilerType func_clang_type =
1336 function->GetType()->GetFullCompilerType();
1337 CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1338 if (!copied_func_type) {
1339 sc_sym_list.Append(sym_ctx);
1343 fdi.m_sym_ctx = sym_ctx;
1344 fdi.m_name = function->GetName();
1345 fdi.m_copied_type = copied_func_type;
1346 fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1347 if (fdi.m_copied_type && func_decl_context) {
1348 // Call CountDeclLevels to get the number of parent scopes we
1349 // have to look through before we find the function declaration.
1350 // When comparing functions of the same type, the one with a
1351 // lower count will be closer to us in the lookup scope and
1352 // shadows the other.
1353 clang::DeclContext *func_decl_ctx =
1354 (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1355 fdi.m_decl_lvl = ast->CountDeclLevels(
1356 frame_decl_ctx, func_decl_ctx, &fdi.m_name, &fdi.m_copied_type);
1358 fdi_cache.emplace_back(fdi);
1361 // Loop through the functions in our cache looking for matching types,
1362 // then compare their scope levels to see which is closer.
1363 std::multimap<CompilerType, const FuncDeclInfo *> matches;
1364 for (const FuncDeclInfo &fdi : fdi_cache) {
1365 const CompilerType t = fdi.m_copied_type;
1366 auto q = matches.find(t);
1367 if (q != matches.end()) {
1368 if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1369 // This function is closer; remove the old set.
1371 else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1372 // The functions in our set are closer - skip this one.
1375 matches.insert(std::make_pair(t, &fdi));
1378 // Loop through our matches and add their symbol contexts to our list.
1379 SymbolContextList sc_func_list;
1380 for (const auto &q : matches)
1381 sc_func_list.Append(q.second->m_sym_ctx);
1383 // Rejoin the lists with the functions in front.
1384 sc_list = sc_func_list;
1385 sc_list.Append(sc_sym_list);
1389 if (sc_list.GetSize()) {
1390 Symbol *extern_symbol = NULL;
1391 Symbol *non_extern_symbol = NULL;
1393 for (uint32_t index = 0, num_indices = sc_list.GetSize();
1394 index < num_indices; ++index) {
1395 SymbolContext sym_ctx;
1396 sc_list.GetContextAtIndex(index, sym_ctx);
1398 if (sym_ctx.function) {
1399 CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1404 // Filter out class/instance methods.
1405 if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1408 AddOneFunction(context, sym_ctx.function, NULL, current_id);
1409 context.m_found.function_with_type_info = true;
1410 context.m_found.function = true;
1411 } else if (sym_ctx.symbol) {
1412 if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) {
1413 sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1414 if (sym_ctx.symbol == NULL)
1418 if (sym_ctx.symbol->IsExternal())
1419 extern_symbol = sym_ctx.symbol;
1421 non_extern_symbol = sym_ctx.symbol;
1425 if (!context.m_found.function_with_type_info) {
1426 for (clang::NamedDecl *decl : decls_from_modules) {
1427 if (llvm::isa<clang::FunctionDecl>(decl)) {
1428 clang::NamedDecl *copied_decl =
1429 llvm::cast_or_null<FunctionDecl>(m_ast_importer_sp->CopyDecl(
1430 m_ast_context, &decl->getASTContext(), decl));
1432 context.AddNamedDecl(copied_decl);
1433 context.m_found.function_with_type_info = true;
1439 if (!context.m_found.function_with_type_info) {
1440 if (extern_symbol) {
1441 AddOneFunction(context, NULL, extern_symbol, current_id);
1442 context.m_found.function = true;
1443 } else if (non_extern_symbol) {
1444 AddOneFunction(context, NULL, non_extern_symbol, current_id);
1445 context.m_found.function = true;
1450 if (!context.m_found.function_with_type_info) {
1451 // Try the modules next.
1454 if (ClangModulesDeclVendor *modules_decl_vendor =
1455 m_target->GetClangModulesDeclVendor()) {
1456 bool append = false;
1457 uint32_t max_matches = 1;
1458 std::vector<clang::NamedDecl *> decls;
1460 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
1463 clang::NamedDecl *const decl_from_modules = decls[0];
1465 if (llvm::isa<clang::FunctionDecl>(decl_from_modules)) {
1467 log->Printf(" CAS::FEVD[%u] Matching function found for "
1468 "\"%s\" in the modules",
1469 current_id, name.GetCString());
1472 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(
1473 m_ast_context, &decl_from_modules->getASTContext(),
1475 clang::FunctionDecl *copied_function_decl =
1476 copied_decl ? dyn_cast<clang::FunctionDecl>(copied_decl)
1479 if (!copied_function_decl) {
1481 log->Printf(" CAS::FEVD[%u] - Couldn't export a function "
1482 "declaration from the modules",
1488 MaybeRegisterFunctionBody(copied_function_decl);
1490 context.AddNamedDecl(copied_function_decl);
1492 context.m_found.function_with_type_info = true;
1493 context.m_found.function = true;
1494 } else if (llvm::isa<clang::VarDecl>(decl_from_modules)) {
1496 log->Printf(" CAS::FEVD[%u] Matching variable found for "
1497 "\"%s\" in the modules",
1498 current_id, name.GetCString());
1501 clang::Decl *copied_decl = m_ast_importer_sp->CopyDecl(
1502 m_ast_context, &decl_from_modules->getASTContext(),
1504 clang::VarDecl *copied_var_decl =
1505 copied_decl ? dyn_cast_or_null<clang::VarDecl>(copied_decl)
1508 if (!copied_var_decl) {
1510 log->Printf(" CAS::FEVD[%u] - Couldn't export a variable "
1511 "declaration from the modules",
1517 context.AddNamedDecl(copied_var_decl);
1519 context.m_found.variable = true;
1525 if (target && !context.m_found.variable && !namespace_decl) {
1526 // We couldn't find a non-symbol variable for this. Now we'll hunt for
1528 // data symbol, and -- if it is found -- treat it as a variable.
1530 const Symbol *data_symbol = FindGlobalDataSymbol(*target, name);
1533 std::string warning("got name from symbols: ");
1534 warning.append(name.AsCString());
1535 const unsigned diag_id =
1536 m_ast_context->getDiagnostics().getCustomDiagID(
1537 clang::DiagnosticsEngine::Level::Warning, "%0");
1538 m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1539 AddOneGenericVariable(context, *data_symbol, current_id);
1540 context.m_found.variable = true;
1546 // static opaque_compiler_type_t
1547 // MaybePromoteToBlockPointerType
1549 // ASTContext *ast_context,
1550 // opaque_compiler_type_t candidate_type
1553 // if (!candidate_type)
1554 // return candidate_type;
1556 // QualType candidate_qual_type = QualType::getFromOpaquePtr(candidate_type);
1558 // const PointerType *candidate_pointer_type =
1559 // dyn_cast<PointerType>(candidate_qual_type);
1561 // if (!candidate_pointer_type)
1562 // return candidate_type;
1564 // QualType pointee_qual_type = candidate_pointer_type->getPointeeType();
1566 // const RecordType *pointee_record_type =
1567 // dyn_cast<RecordType>(pointee_qual_type);
1569 // if (!pointee_record_type)
1570 // return candidate_type;
1572 // RecordDecl *pointee_record_decl = pointee_record_type->getDecl();
1574 // if (!pointee_record_decl->isRecord())
1575 // return candidate_type;
1578 // (!pointee_record_decl->getName().startswith(llvm::StringRef("__block_literal_")))
1579 // return candidate_type;
1581 // QualType generic_function_type =
1582 // ast_context->getFunctionNoProtoType(ast_context->UnknownAnyTy);
1583 // QualType block_pointer_type =
1584 // ast_context->getBlockPointerType(generic_function_type);
1586 // return block_pointer_type.getAsOpaquePtr();
1589 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var,
1590 lldb_private::Value &var_location,
1591 TypeFromUser *user_type,
1592 TypeFromParser *parser_type) {
1593 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1595 Type *var_type = var->GetType();
1599 log->PutCString("Skipped a definition because it has no type");
1603 CompilerType var_clang_type = var_type->GetFullCompilerType();
1605 if (!var_clang_type) {
1607 log->PutCString("Skipped a definition because it has no Clang type");
1611 ClangASTContext *clang_ast = llvm::dyn_cast_or_null<ClangASTContext>(
1612 var_type->GetForwardCompilerType().GetTypeSystem());
1616 log->PutCString("Skipped a definition because it has no Clang AST");
1620 ASTContext *ast = clang_ast->getASTContext();
1625 "There is no AST context for the current execution context");
1628 // var_clang_type = MaybePromoteToBlockPointerType (ast, var_clang_type);
1630 DWARFExpression &var_location_expr = var->LocationExpression();
1632 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1635 if (var->GetLocationIsConstantValueData()) {
1636 DataExtractor const_value_extractor;
1638 if (var_location_expr.GetExpressionData(const_value_extractor)) {
1639 var_location = Value(const_value_extractor.GetDataStart(),
1640 const_value_extractor.GetByteSize());
1641 var_location.SetValueType(Value::eValueTypeHostAddress);
1644 log->Printf("Error evaluating constant variable: %s", err.AsCString());
1649 CompilerType type_to_use = GuardedCopyType(var_clang_type);
1654 "Couldn't copy a variable's type into the parser's AST context");
1660 *parser_type = TypeFromParser(type_to_use);
1662 if (var_location.GetContextType() == Value::eContextTypeInvalid)
1663 var_location.SetCompilerType(type_to_use);
1665 if (var_location.GetValueType() == Value::eValueTypeFileAddress) {
1666 SymbolContext var_sc;
1667 var->CalculateSymbolContext(&var_sc);
1669 if (!var_sc.module_sp)
1672 Address so_addr(var_location.GetScalar().ULongLong(),
1673 var_sc.module_sp->GetSectionList());
1675 lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1677 if (load_addr != LLDB_INVALID_ADDRESS) {
1678 var_location.GetScalar() = load_addr;
1679 var_location.SetValueType(Value::eValueTypeLoadAddress);
1684 *user_type = TypeFromUser(var_clang_type);
1689 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1691 ValueObjectSP valobj,
1692 unsigned int current_id) {
1693 assert(m_parser_vars.get());
1695 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1701 if (!GetVariableValue(var, var_location, &ut, &pt))
1704 clang::QualType parser_opaque_type =
1705 QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1707 if (parser_opaque_type.isNull())
1710 if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) {
1711 if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1712 CompleteType(tag_type->getDecl());
1713 if (const ObjCObjectPointerType *objc_object_ptr_type =
1714 dyn_cast<ObjCObjectPointerType>(parser_type))
1715 CompleteType(objc_object_ptr_type->getInterfaceDecl());
1718 bool is_reference = pt.IsReferenceType();
1720 NamedDecl *var_decl = NULL;
1722 var_decl = context.AddVarDecl(pt);
1724 var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1726 std::string decl_name(context.m_decl_name.getAsString());
1727 ConstString entity_name(decl_name.c_str());
1728 ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1729 m_found_entities.AddNewlyConstructedVariable(entity);
1732 entity->EnableParserVars(GetParserID());
1733 ClangExpressionVariable::ParserVars *parser_vars =
1734 entity->GetParserVars(GetParserID());
1735 parser_vars->m_parser_type = pt;
1736 parser_vars->m_named_decl = var_decl;
1737 parser_vars->m_llvm_value = NULL;
1738 parser_vars->m_lldb_value = var_location;
1739 parser_vars->m_lldb_var = var;
1742 entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1745 ASTDumper orig_dumper(ut.GetOpaqueQualType());
1746 ASTDumper ast_dumper(var_decl);
1747 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s (original %s)",
1748 current_id, decl_name.c_str(), ast_dumper.GetCString(),
1749 orig_dumper.GetCString());
1753 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1754 ExpressionVariableSP &pvar_sp,
1755 unsigned int current_id) {
1756 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1758 TypeFromUser user_type(
1759 llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1761 TypeFromParser parser_type(GuardedCopyType(user_type));
1763 if (!parser_type.GetOpaqueQualType()) {
1765 log->Printf(" CEDM::FEVD[%u] Couldn't import type for pvar %s",
1766 current_id, pvar_sp->GetName().GetCString());
1770 NamedDecl *var_decl =
1771 context.AddVarDecl(parser_type.GetLValueReferenceType());
1773 llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1774 ->EnableParserVars(GetParserID());
1775 ClangExpressionVariable::ParserVars *parser_vars =
1776 llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1777 ->GetParserVars(GetParserID());
1778 parser_vars->m_parser_type = parser_type;
1779 parser_vars->m_named_decl = var_decl;
1780 parser_vars->m_llvm_value = NULL;
1781 parser_vars->m_lldb_value.Clear();
1784 ASTDumper ast_dumper(var_decl);
1785 log->Printf(" CEDM::FEVD[%u] Added pvar %s, returned %s", current_id,
1786 pvar_sp->GetName().GetCString(), ast_dumper.GetCString());
1790 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1791 const Symbol &symbol,
1792 unsigned int current_id) {
1793 assert(m_parser_vars.get());
1795 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1797 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1802 ASTContext *scratch_ast_context =
1803 target->GetScratchClangASTContext()->getASTContext();
1805 TypeFromUser user_type(
1806 ClangASTContext::GetBasicType(scratch_ast_context, eBasicTypeVoid)
1808 .GetLValueReferenceType());
1809 TypeFromParser parser_type(
1810 ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid)
1812 .GetLValueReferenceType());
1813 NamedDecl *var_decl = context.AddVarDecl(parser_type);
1815 std::string decl_name(context.m_decl_name.getAsString());
1816 ConstString entity_name(decl_name.c_str());
1817 ClangExpressionVariable *entity(new ClangExpressionVariable(
1818 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name,
1819 user_type, m_parser_vars->m_target_info.byte_order,
1820 m_parser_vars->m_target_info.address_byte_size));
1821 m_found_entities.AddNewlyConstructedVariable(entity);
1823 entity->EnableParserVars(GetParserID());
1824 ClangExpressionVariable::ParserVars *parser_vars =
1825 entity->GetParserVars(GetParserID());
1827 const Address symbol_address = symbol.GetAddress();
1828 lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1830 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType,
1831 // user_type.GetOpaqueQualType());
1832 parser_vars->m_lldb_value.SetCompilerType(user_type);
1833 parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1834 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
1836 parser_vars->m_parser_type = parser_type;
1837 parser_vars->m_named_decl = var_decl;
1838 parser_vars->m_llvm_value = NULL;
1839 parser_vars->m_lldb_sym = &symbol;
1842 ASTDumper ast_dumper(var_decl);
1844 log->Printf(" CEDM::FEVD[%u] Found variable %s, returned %s", current_id,
1845 decl_name.c_str(), ast_dumper.GetCString());
1849 bool ClangExpressionDeclMap::ResolveUnknownTypes() {
1850 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1851 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1853 ClangASTContext *scratch_ast_context = target->GetScratchClangASTContext();
1855 for (size_t index = 0, num_entities = m_found_entities.GetSize();
1856 index < num_entities; ++index) {
1857 ExpressionVariableSP entity = m_found_entities.GetVariableAtIndex(index);
1859 ClangExpressionVariable::ParserVars *parser_vars =
1860 llvm::cast<ClangExpressionVariable>(entity.get())
1861 ->GetParserVars(GetParserID());
1863 if (entity->m_flags & ClangExpressionVariable::EVUnknownType) {
1864 const NamedDecl *named_decl = parser_vars->m_named_decl;
1865 const VarDecl *var_decl = dyn_cast<VarDecl>(named_decl);
1869 log->Printf("Entity of unknown type does not have a VarDecl");
1874 ASTDumper ast_dumper(const_cast<VarDecl *>(var_decl));
1875 log->Printf("Variable of unknown type now has Decl %s",
1876 ast_dumper.GetCString());
1879 QualType var_type = var_decl->getType();
1880 TypeFromParser parser_type(
1881 var_type.getAsOpaquePtr(),
1882 ClangASTContext::GetASTContext(&var_decl->getASTContext()));
1884 lldb::opaque_compiler_type_t copied_type = m_ast_importer_sp->CopyType(
1885 scratch_ast_context->getASTContext(), &var_decl->getASTContext(),
1886 var_type.getAsOpaquePtr());
1890 log->Printf("ClangExpressionDeclMap::ResolveUnknownType - Couldn't "
1891 "import the type for a variable");
1893 return (bool)lldb::ExpressionVariableSP();
1896 TypeFromUser user_type(copied_type, scratch_ast_context);
1898 // parser_vars->m_lldb_value.SetContext(Value::eContextTypeClangType,
1899 // user_type.GetOpaqueQualType());
1900 parser_vars->m_lldb_value.SetCompilerType(user_type);
1901 parser_vars->m_parser_type = parser_type;
1903 entity->SetCompilerType(user_type);
1905 entity->m_flags &= ~(ClangExpressionVariable::EVUnknownType);
1912 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context,
1913 const RegisterInfo *reg_info,
1914 unsigned int current_id) {
1915 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1917 CompilerType clang_type =
1918 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
1919 m_ast_context, reg_info->encoding, reg_info->byte_size * 8);
1923 log->Printf(" Tried to add a type for %s, but couldn't get one",
1924 context.m_decl_name.getAsString().c_str());
1928 TypeFromParser parser_clang_type(clang_type);
1930 NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
1932 ClangExpressionVariable *entity(new ClangExpressionVariable(
1933 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1934 m_parser_vars->m_target_info.byte_order,
1935 m_parser_vars->m_target_info.address_byte_size));
1936 m_found_entities.AddNewlyConstructedVariable(entity);
1938 std::string decl_name(context.m_decl_name.getAsString());
1939 entity->SetName(ConstString(decl_name.c_str()));
1940 entity->SetRegisterInfo(reg_info);
1941 entity->EnableParserVars(GetParserID());
1942 ClangExpressionVariable::ParserVars *parser_vars =
1943 entity->GetParserVars(GetParserID());
1944 parser_vars->m_parser_type = parser_clang_type;
1945 parser_vars->m_named_decl = var_decl;
1946 parser_vars->m_llvm_value = NULL;
1947 parser_vars->m_lldb_value.Clear();
1948 entity->m_flags |= ClangExpressionVariable::EVBareRegister;
1951 ASTDumper ast_dumper(var_decl);
1952 log->Printf(" CEDM::FEVD[%d] Added register %s, returned %s", current_id,
1953 context.m_decl_name.getAsString().c_str(),
1954 ast_dumper.GetCString());
1958 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context,
1959 Function *function, Symbol *symbol,
1960 unsigned int current_id) {
1961 assert(m_parser_vars.get());
1963 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1965 NamedDecl *function_decl = NULL;
1966 Address fun_address;
1967 CompilerType function_clang_type;
1969 bool is_indirect_function = false;
1972 Type *function_type = function->GetType();
1974 const auto lang = function->GetCompileUnit()->GetLanguage();
1975 const auto name = function->GetMangled().GetMangledName().AsCString();
1976 const bool extern_c = (Language::LanguageIsC(lang) &&
1977 !CPlusPlusLanguage::IsCPPMangledName(name)) ||
1978 (Language::LanguageIsObjC(lang) &&
1979 !Language::LanguageIsCPlusPlus(lang));
1982 TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
1983 if (ClangASTContext *src_ast =
1984 llvm::dyn_cast<ClangASTContext>(type_system)) {
1985 clang::DeclContext *src_decl_context =
1986 (clang::DeclContext *)function->GetDeclContext()
1987 .GetOpaqueDeclContext();
1988 clang::FunctionDecl *src_function_decl =
1989 llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
1991 if (src_function_decl) {
1992 if (clang::FunctionDecl *copied_function_decl =
1993 llvm::dyn_cast_or_null<clang::FunctionDecl>(
1994 m_ast_importer_sp->CopyDecl(m_ast_context,
1995 src_ast->getASTContext(),
1996 src_function_decl))) {
1998 ASTDumper ast_dumper((clang::Decl *)copied_function_decl);
2002 function->DumpSymbolContext(&ss);
2004 log->Printf(" CEDM::FEVD[%u] Imported decl for function %s "
2005 "(description %s), returned %s",
2007 copied_function_decl->getNameAsString().c_str(),
2008 ss.GetData(), ast_dumper.GetCString());
2011 context.AddNamedDecl(copied_function_decl);
2015 log->Printf(" Failed to import the function decl for '%s'",
2016 src_function_decl->getName().str().c_str());
2023 if (!function_type) {
2025 log->PutCString(" Skipped a function because it has no type");
2029 function_clang_type = function_type->GetFullCompilerType();
2031 if (!function_clang_type) {
2033 log->PutCString(" Skipped a function because it has no Clang type");
2037 fun_address = function->GetAddressRange().GetBaseAddress();
2039 CompilerType copied_function_type = GuardedCopyType(function_clang_type);
2040 if (copied_function_type) {
2041 function_decl = context.AddFunDecl(copied_function_type, extern_c);
2043 if (!function_decl) {
2046 " Failed to create a function decl for '%s' {0x%8.8" PRIx64 "}",
2047 function_type->GetName().GetCString(), function_type->GetID());
2053 // We failed to copy the type we found
2055 log->Printf(" Failed to import the function type '%s' {0x%8.8" PRIx64
2056 "} into the expression parser AST contenxt",
2057 function_type->GetName().GetCString(),
2058 function_type->GetID());
2063 } else if (symbol) {
2064 fun_address = symbol->GetAddress();
2065 function_decl = context.AddGenericFunDecl();
2066 is_indirect_function = symbol->IsIndirect();
2069 log->PutCString(" AddOneFunction called with no function and no symbol");
2073 Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
2075 lldb::addr_t load_addr =
2076 fun_address.GetCallableLoadAddress(target, is_indirect_function);
2078 ClangExpressionVariable *entity(new ClangExpressionVariable(
2079 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
2080 m_parser_vars->m_target_info.byte_order,
2081 m_parser_vars->m_target_info.address_byte_size));
2082 m_found_entities.AddNewlyConstructedVariable(entity);
2084 std::string decl_name(context.m_decl_name.getAsString());
2085 entity->SetName(ConstString(decl_name.c_str()));
2086 entity->SetCompilerType(function_clang_type);
2087 entity->EnableParserVars(GetParserID());
2089 ClangExpressionVariable::ParserVars *parser_vars =
2090 entity->GetParserVars(GetParserID());
2092 if (load_addr != LLDB_INVALID_ADDRESS) {
2093 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeLoadAddress);
2094 parser_vars->m_lldb_value.GetScalar() = load_addr;
2096 // We have to try finding a file address.
2098 lldb::addr_t file_addr = fun_address.GetFileAddress();
2100 parser_vars->m_lldb_value.SetValueType(Value::eValueTypeFileAddress);
2101 parser_vars->m_lldb_value.GetScalar() = file_addr;
2104 parser_vars->m_named_decl = function_decl;
2105 parser_vars->m_llvm_value = NULL;
2108 ASTDumper ast_dumper(function_decl);
2112 fun_address.Dump(&ss,
2113 m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
2114 Address::DumpStyleResolvedDescription);
2117 " CEDM::FEVD[%u] Found %s function %s (description %s), returned %s",
2118 current_id, (function ? "specific" : "generic"), decl_name.c_str(),
2119 ss.GetData(), ast_dumper.GetCString());
2123 void ClangExpressionDeclMap::AddThisType(NameSearchContext &context,
2125 unsigned int current_id) {
2126 CompilerType copied_clang_type = GuardedCopyType(ut);
2128 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2130 if (!copied_clang_type) {
2133 "ClangExpressionDeclMap::AddThisType - Couldn't import the type");
2138 if (copied_clang_type.IsAggregateType() &&
2139 copied_clang_type.GetCompleteType()) {
2140 CompilerType void_clang_type =
2141 ClangASTContext::GetBasicType(m_ast_context, eBasicTypeVoid);
2142 CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
2144 CompilerType method_type = ClangASTContext::CreateFunctionType(
2145 m_ast_context, void_clang_type, &void_ptr_clang_type, 1, false, 0);
2147 const bool is_virtual = false;
2148 const bool is_static = false;
2149 const bool is_inline = false;
2150 const bool is_explicit = false;
2151 const bool is_attr_used = true;
2152 const bool is_artificial = false;
2154 CXXMethodDecl *method_decl =
2155 ClangASTContext::GetASTContext(m_ast_context)
2156 ->AddMethodToCXXRecordType(
2157 copied_clang_type.GetOpaqueQualType(), "$__lldb_expr",
2158 method_type, lldb::eAccessPublic, is_virtual, is_static,
2159 is_inline, is_explicit, is_attr_used, is_artificial);
2162 ASTDumper method_ast_dumper((clang::Decl *)method_decl);
2163 ASTDumper type_ast_dumper(copied_clang_type);
2165 log->Printf(" CEDM::AddThisType Added function $__lldb_expr "
2166 "(description %s) for this type %s",
2167 method_ast_dumper.GetCString(), type_ast_dumper.GetCString());
2171 if (!copied_clang_type.IsValid())
2174 TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(
2175 QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
2177 if (!type_source_info)
2180 // Construct a typedef type because if "*this" is a templated type we can't
2181 // just return ClassTemplateSpecializationDecls in response to name queries.
2182 // Using a typedef makes this much more robust.
2184 TypedefDecl *typedef_decl = TypedefDecl::Create(
2185 *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(),
2186 SourceLocation(), context.m_decl_name.getAsIdentifierInfo(),
2192 context.AddNamedDecl(typedef_decl);
2197 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
2199 unsigned int current_id) {
2200 CompilerType copied_clang_type = GuardedCopyType(ut);
2202 if (!copied_clang_type) {
2203 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2207 "ClangExpressionDeclMap::AddOneType - Couldn't import the type");
2212 context.AddTypeDecl(copied_clang_type);