1 //===-- ClangExpressionDeclMap.cpp ----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangExpressionDeclMap.h"
10 
11 #include "ClangASTSource.h"
12 #include "ClangModulesDeclVendor.h"
13 #include "ClangPersistentVariables.h"
14 #include "ClangUtil.h"
15 
16 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
17 #include "lldb/Core/Address.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/ValueObjectConstResult.h"
21 #include "lldb/Core/ValueObjectVariable.h"
22 #include "lldb/Expression/DiagnosticManager.h"
23 #include "lldb/Expression/Materializer.h"
24 #include "lldb/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/CompilerDecl.h"
26 #include "lldb/Symbol/CompilerDeclContext.h"
27 #include "lldb/Symbol/Function.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Symbol/SymbolContext.h"
30 #include "lldb/Symbol/SymbolFile.h"
31 #include "lldb/Symbol/SymbolVendor.h"
32 #include "lldb/Symbol/Type.h"
33 #include "lldb/Symbol/TypeList.h"
34 #include "lldb/Symbol/Variable.h"
35 #include "lldb/Symbol/VariableList.h"
36 #include "lldb/Target/ExecutionContext.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/RegisterContext.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/Thread.h"
42 #include "lldb/Utility/Endian.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/RegisterValue.h"
45 #include "lldb/Utility/Status.h"
46 #include "lldb/lldb-private.h"
47 #include "clang/AST/ASTConsumer.h"
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/ASTImporter.h"
50 #include "clang/AST/Decl.h"
51 #include "clang/AST/DeclarationName.h"
52 #include "clang/AST/RecursiveASTVisitor.h"
53 
54 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
55 #include "Plugins/LanguageRuntime/CPlusPlus/CPPLanguageRuntime.h"
56 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
57 
58 using namespace lldb;
59 using namespace lldb_private;
60 using namespace clang;
61 
62 namespace {
63 const char *g_lldb_local_vars_namespace_cstr = "$__lldb_local_vars";
64 } // anonymous namespace
65 
66 ClangExpressionDeclMap::ClangExpressionDeclMap(
67     bool keep_result_in_memory,
68     Materializer::PersistentVariableDelegate *result_delegate,
69     const lldb::TargetSP &target,
70     const std::shared_ptr<ClangASTImporter> &importer, ValueObject *ctx_obj)
71     : ClangASTSource(target, importer), m_found_entities(), m_struct_members(),
72       m_keep_result_in_memory(keep_result_in_memory),
73       m_result_delegate(result_delegate), m_ctx_obj(ctx_obj), m_parser_vars(),
74       m_struct_vars() {
75   EnableStructVars();
76 }
77 
78 ClangExpressionDeclMap::~ClangExpressionDeclMap() {
79   // Note: The model is now that the parser's AST context and all associated
80   //   data does not vanish until the expression has been executed.  This means
81   //   that valuable lookup data (like namespaces) doesn't vanish, but
82 
83   DidParse();
84   DisableStructVars();
85 }
86 
87 bool ClangExpressionDeclMap::WillParse(ExecutionContext &exe_ctx,
88                                        Materializer *materializer) {
89   EnableParserVars();
90   m_parser_vars->m_exe_ctx = exe_ctx;
91 
92   Target *target = exe_ctx.GetTargetPtr();
93   if (exe_ctx.GetFramePtr())
94     m_parser_vars->m_sym_ctx =
95         exe_ctx.GetFramePtr()->GetSymbolContext(lldb::eSymbolContextEverything);
96   else if (exe_ctx.GetThreadPtr() &&
97            exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0))
98     m_parser_vars->m_sym_ctx =
99         exe_ctx.GetThreadPtr()->GetStackFrameAtIndex(0)->GetSymbolContext(
100             lldb::eSymbolContextEverything);
101   else if (exe_ctx.GetProcessPtr()) {
102     m_parser_vars->m_sym_ctx.Clear(true);
103     m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
104   } else if (target) {
105     m_parser_vars->m_sym_ctx.Clear(true);
106     m_parser_vars->m_sym_ctx.target_sp = exe_ctx.GetTargetSP();
107   }
108 
109   if (target) {
110     m_parser_vars->m_persistent_vars = llvm::cast<ClangPersistentVariables>(
111         target->GetPersistentExpressionStateForLanguage(eLanguageTypeC));
112 
113     if (!ScratchTypeSystemClang::GetForTarget(*target))
114       return false;
115   }
116 
117   m_parser_vars->m_target_info = GetTargetInfo();
118   m_parser_vars->m_materializer = materializer;
119 
120   return true;
121 }
122 
123 void ClangExpressionDeclMap::InstallCodeGenerator(
124     clang::ASTConsumer *code_gen) {
125   assert(m_parser_vars);
126   m_parser_vars->m_code_gen = code_gen;
127 }
128 
129 void ClangExpressionDeclMap::InstallDiagnosticManager(
130     DiagnosticManager &diag_manager) {
131   assert(m_parser_vars);
132   m_parser_vars->m_diagnostics = &diag_manager;
133 }
134 
135 void ClangExpressionDeclMap::DidParse() {
136   if (m_parser_vars && m_parser_vars->m_persistent_vars) {
137     for (size_t entity_index = 0, num_entities = m_found_entities.GetSize();
138          entity_index < num_entities; ++entity_index) {
139       ExpressionVariableSP var_sp(
140           m_found_entities.GetVariableAtIndex(entity_index));
141       if (var_sp)
142         llvm::cast<ClangExpressionVariable>(var_sp.get())
143             ->DisableParserVars(GetParserID());
144     }
145 
146     for (size_t pvar_index = 0,
147                 num_pvars = m_parser_vars->m_persistent_vars->GetSize();
148          pvar_index < num_pvars; ++pvar_index) {
149       ExpressionVariableSP pvar_sp(
150           m_parser_vars->m_persistent_vars->GetVariableAtIndex(pvar_index));
151       if (ClangExpressionVariable *clang_var =
152               llvm::dyn_cast<ClangExpressionVariable>(pvar_sp.get()))
153         clang_var->DisableParserVars(GetParserID());
154     }
155 
156     DisableParserVars();
157   }
158 }
159 
160 // Interface for IRForTarget
161 
162 ClangExpressionDeclMap::TargetInfo ClangExpressionDeclMap::GetTargetInfo() {
163   assert(m_parser_vars.get());
164 
165   TargetInfo ret;
166 
167   ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
168 
169   Process *process = exe_ctx.GetProcessPtr();
170   if (process) {
171     ret.byte_order = process->GetByteOrder();
172     ret.address_byte_size = process->GetAddressByteSize();
173   } else {
174     Target *target = exe_ctx.GetTargetPtr();
175     if (target) {
176       ret.byte_order = target->GetArchitecture().GetByteOrder();
177       ret.address_byte_size = target->GetArchitecture().GetAddressByteSize();
178     }
179   }
180 
181   return ret;
182 }
183 
184 TypeFromUser ClangExpressionDeclMap::DeportType(TypeSystemClang &target,
185                                                 TypeSystemClang &source,
186                                                 TypeFromParser parser_type) {
187   assert(&target == GetScratchContext(*m_target));
188   assert((TypeSystem *)&source == parser_type.GetTypeSystem());
189   assert(&source.getASTContext() == m_ast_context);
190 
191   return TypeFromUser(m_ast_importer_sp->DeportType(target, parser_type));
192 }
193 
194 bool ClangExpressionDeclMap::AddPersistentVariable(const NamedDecl *decl,
195                                                    ConstString name,
196                                                    TypeFromParser parser_type,
197                                                    bool is_result,
198                                                    bool is_lvalue) {
199   assert(m_parser_vars.get());
200 
201   TypeSystemClang *ast =
202       llvm::dyn_cast_or_null<TypeSystemClang>(parser_type.GetTypeSystem());
203   if (ast == nullptr)
204     return false;
205 
206   // Check if we already declared a persistent variable with the same name.
207   if (lldb::ExpressionVariableSP conflicting_var =
208           m_parser_vars->m_persistent_vars->GetVariable(name)) {
209     std::string msg = llvm::formatv("redefinition of persistent variable '{0}'",
210                                     name).str();
211     m_parser_vars->m_diagnostics->AddDiagnostic(
212         msg, DiagnosticSeverity::eDiagnosticSeverityError,
213         DiagnosticOrigin::eDiagnosticOriginLLDB);
214     return false;
215   }
216 
217   if (m_parser_vars->m_materializer && is_result) {
218     Status err;
219 
220     ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
221     Target *target = exe_ctx.GetTargetPtr();
222     if (target == nullptr)
223       return false;
224 
225     auto *clang_ast_context = GetScratchContext(*target);
226     if (!clang_ast_context)
227       return false;
228 
229     TypeFromUser user_type = DeportType(*clang_ast_context, *ast, parser_type);
230 
231     uint32_t offset = m_parser_vars->m_materializer->AddResultVariable(
232         user_type, is_lvalue, m_keep_result_in_memory, m_result_delegate, err);
233 
234     ClangExpressionVariable *var = new ClangExpressionVariable(
235         exe_ctx.GetBestExecutionContextScope(), name, user_type,
236         m_parser_vars->m_target_info.byte_order,
237         m_parser_vars->m_target_info.address_byte_size);
238 
239     m_found_entities.AddNewlyConstructedVariable(var);
240 
241     var->EnableParserVars(GetParserID());
242 
243     ClangExpressionVariable::ParserVars *parser_vars =
244         var->GetParserVars(GetParserID());
245 
246     parser_vars->m_named_decl = decl;
247 
248     var->EnableJITVars(GetParserID());
249 
250     ClangExpressionVariable::JITVars *jit_vars = var->GetJITVars(GetParserID());
251 
252     jit_vars->m_offset = offset;
253 
254     return true;
255   }
256 
257   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
258   ExecutionContext &exe_ctx = m_parser_vars->m_exe_ctx;
259   Target *target = exe_ctx.GetTargetPtr();
260   if (target == nullptr)
261     return false;
262 
263   TypeSystemClang *context = GetScratchContext(*target);
264   if (!context)
265     return false;
266 
267   TypeFromUser user_type = DeportType(*context, *ast, parser_type);
268 
269   if (!user_type.GetOpaqueQualType()) {
270     LLDB_LOG(log, "Persistent variable's type wasn't copied successfully");
271     return false;
272   }
273 
274   if (!m_parser_vars->m_target_info.IsValid())
275     return false;
276 
277   if (!m_parser_vars->m_persistent_vars)
278     return false;
279 
280   ClangExpressionVariable *var = llvm::cast<ClangExpressionVariable>(
281       m_parser_vars->m_persistent_vars
282           ->CreatePersistentVariable(
283               exe_ctx.GetBestExecutionContextScope(), name, user_type,
284               m_parser_vars->m_target_info.byte_order,
285               m_parser_vars->m_target_info.address_byte_size)
286           .get());
287 
288   if (!var)
289     return false;
290 
291   var->m_frozen_sp->SetHasCompleteType();
292 
293   if (is_result)
294     var->m_flags |= ClangExpressionVariable::EVNeedsFreezeDry;
295   else
296     var->m_flags |=
297         ClangExpressionVariable::EVKeepInTarget; // explicitly-declared
298                                                  // persistent variables should
299                                                  // persist
300 
301   if (is_lvalue) {
302     var->m_flags |= ClangExpressionVariable::EVIsProgramReference;
303   } else {
304     var->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
305     var->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
306   }
307 
308   if (m_keep_result_in_memory) {
309     var->m_flags |= ClangExpressionVariable::EVKeepInTarget;
310   }
311 
312   LLDB_LOG(log, "Created persistent variable with flags {0:x}", var->m_flags);
313 
314   var->EnableParserVars(GetParserID());
315 
316   ClangExpressionVariable::ParserVars *parser_vars =
317       var->GetParserVars(GetParserID());
318 
319   parser_vars->m_named_decl = decl;
320 
321   return true;
322 }
323 
324 bool ClangExpressionDeclMap::AddValueToStruct(const NamedDecl *decl,
325                                               ConstString name,
326                                               llvm::Value *value, size_t size,
327                                               lldb::offset_t alignment) {
328   assert(m_struct_vars.get());
329   assert(m_parser_vars.get());
330 
331   bool is_persistent_variable = false;
332 
333   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
334 
335   m_struct_vars->m_struct_laid_out = false;
336 
337   if (ClangExpressionVariable::FindVariableInList(m_struct_members, decl,
338                                                   GetParserID()))
339     return true;
340 
341   ClangExpressionVariable *var(ClangExpressionVariable::FindVariableInList(
342       m_found_entities, decl, GetParserID()));
343 
344   if (!var && m_parser_vars->m_persistent_vars) {
345     var = ClangExpressionVariable::FindVariableInList(
346         *m_parser_vars->m_persistent_vars, decl, GetParserID());
347     is_persistent_variable = true;
348   }
349 
350   if (!var)
351     return false;
352 
353   LLDB_LOG(log, "Adding value for (NamedDecl*){0} [{1} - {2}] to the structure",
354            decl, name, var->GetName());
355 
356   // We know entity->m_parser_vars is valid because we used a parser variable
357   // to find it
358 
359   ClangExpressionVariable::ParserVars *parser_vars =
360       llvm::cast<ClangExpressionVariable>(var)->GetParserVars(GetParserID());
361 
362   parser_vars->m_llvm_value = value;
363 
364   if (ClangExpressionVariable::JITVars *jit_vars =
365           llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID())) {
366     // We already laid this out; do not touch
367 
368     LLDB_LOG(log, "Already placed at {0:x}", jit_vars->m_offset);
369   }
370 
371   llvm::cast<ClangExpressionVariable>(var)->EnableJITVars(GetParserID());
372 
373   ClangExpressionVariable::JITVars *jit_vars =
374       llvm::cast<ClangExpressionVariable>(var)->GetJITVars(GetParserID());
375 
376   jit_vars->m_alignment = alignment;
377   jit_vars->m_size = size;
378 
379   m_struct_members.AddVariable(var->shared_from_this());
380 
381   if (m_parser_vars->m_materializer) {
382     uint32_t offset = 0;
383 
384     Status err;
385 
386     if (is_persistent_variable) {
387       ExpressionVariableSP var_sp(var->shared_from_this());
388       offset = m_parser_vars->m_materializer->AddPersistentVariable(
389           var_sp, nullptr, err);
390     } else {
391       if (const lldb_private::Symbol *sym = parser_vars->m_lldb_sym)
392         offset = m_parser_vars->m_materializer->AddSymbol(*sym, err);
393       else if (const RegisterInfo *reg_info = var->GetRegisterInfo())
394         offset = m_parser_vars->m_materializer->AddRegister(*reg_info, err);
395       else if (parser_vars->m_lldb_var)
396         offset = m_parser_vars->m_materializer->AddVariable(
397             parser_vars->m_lldb_var, err);
398     }
399 
400     if (!err.Success())
401       return false;
402 
403     LLDB_LOG(log, "Placed at {0:x}", offset);
404 
405     jit_vars->m_offset =
406         offset; // TODO DoStructLayout() should not change this.
407   }
408 
409   return true;
410 }
411 
412 bool ClangExpressionDeclMap::DoStructLayout() {
413   assert(m_struct_vars.get());
414 
415   if (m_struct_vars->m_struct_laid_out)
416     return true;
417 
418   if (!m_parser_vars->m_materializer)
419     return false;
420 
421   m_struct_vars->m_struct_alignment =
422       m_parser_vars->m_materializer->GetStructAlignment();
423   m_struct_vars->m_struct_size =
424       m_parser_vars->m_materializer->GetStructByteSize();
425   m_struct_vars->m_struct_laid_out = true;
426   return true;
427 }
428 
429 bool ClangExpressionDeclMap::GetStructInfo(uint32_t &num_elements, size_t &size,
430                                            lldb::offset_t &alignment) {
431   assert(m_struct_vars.get());
432 
433   if (!m_struct_vars->m_struct_laid_out)
434     return false;
435 
436   num_elements = m_struct_members.GetSize();
437   size = m_struct_vars->m_struct_size;
438   alignment = m_struct_vars->m_struct_alignment;
439 
440   return true;
441 }
442 
443 bool ClangExpressionDeclMap::GetStructElement(const NamedDecl *&decl,
444                                               llvm::Value *&value,
445                                               lldb::offset_t &offset,
446                                               ConstString &name,
447                                               uint32_t index) {
448   assert(m_struct_vars.get());
449 
450   if (!m_struct_vars->m_struct_laid_out)
451     return false;
452 
453   if (index >= m_struct_members.GetSize())
454     return false;
455 
456   ExpressionVariableSP member_sp(m_struct_members.GetVariableAtIndex(index));
457 
458   if (!member_sp)
459     return false;
460 
461   ClangExpressionVariable::ParserVars *parser_vars =
462       llvm::cast<ClangExpressionVariable>(member_sp.get())
463           ->GetParserVars(GetParserID());
464   ClangExpressionVariable::JITVars *jit_vars =
465       llvm::cast<ClangExpressionVariable>(member_sp.get())
466           ->GetJITVars(GetParserID());
467 
468   if (!parser_vars || !jit_vars || !member_sp->GetValueObject())
469     return false;
470 
471   decl = parser_vars->m_named_decl;
472   value = parser_vars->m_llvm_value;
473   offset = jit_vars->m_offset;
474   name = member_sp->GetName();
475 
476   return true;
477 }
478 
479 bool ClangExpressionDeclMap::GetFunctionInfo(const NamedDecl *decl,
480                                              uint64_t &ptr) {
481   ClangExpressionVariable *entity(ClangExpressionVariable::FindVariableInList(
482       m_found_entities, decl, GetParserID()));
483 
484   if (!entity)
485     return false;
486 
487   // We know m_parser_vars is valid since we searched for the variable by its
488   // NamedDecl
489 
490   ClangExpressionVariable::ParserVars *parser_vars =
491       entity->GetParserVars(GetParserID());
492 
493   ptr = parser_vars->m_lldb_value.GetScalar().ULongLong();
494 
495   return true;
496 }
497 
498 addr_t ClangExpressionDeclMap::GetSymbolAddress(Target &target,
499                                                 Process *process,
500                                                 ConstString name,
501                                                 lldb::SymbolType symbol_type,
502                                                 lldb_private::Module *module) {
503   SymbolContextList sc_list;
504 
505   if (module)
506     module->FindSymbolsWithNameAndType(name, symbol_type, sc_list);
507   else
508     target.GetImages().FindSymbolsWithNameAndType(name, symbol_type, sc_list);
509 
510   const uint32_t num_matches = sc_list.GetSize();
511   addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
512 
513   for (uint32_t i = 0;
514        i < num_matches &&
515        (symbol_load_addr == 0 || symbol_load_addr == LLDB_INVALID_ADDRESS);
516        i++) {
517     SymbolContext sym_ctx;
518     sc_list.GetContextAtIndex(i, sym_ctx);
519 
520     const Address sym_address = sym_ctx.symbol->GetAddress();
521 
522     if (!sym_address.IsValid())
523       continue;
524 
525     switch (sym_ctx.symbol->GetType()) {
526     case eSymbolTypeCode:
527     case eSymbolTypeTrampoline:
528       symbol_load_addr = sym_address.GetCallableLoadAddress(&target);
529       break;
530 
531     case eSymbolTypeResolver:
532       symbol_load_addr = sym_address.GetCallableLoadAddress(&target, true);
533       break;
534 
535     case eSymbolTypeReExported: {
536       ConstString reexport_name = sym_ctx.symbol->GetReExportedSymbolName();
537       if (reexport_name) {
538         ModuleSP reexport_module_sp;
539         ModuleSpec reexport_module_spec;
540         reexport_module_spec.GetPlatformFileSpec() =
541             sym_ctx.symbol->GetReExportedSymbolSharedLibrary();
542         if (reexport_module_spec.GetPlatformFileSpec()) {
543           reexport_module_sp =
544               target.GetImages().FindFirstModule(reexport_module_spec);
545           if (!reexport_module_sp) {
546             reexport_module_spec.GetPlatformFileSpec().GetDirectory().Clear();
547             reexport_module_sp =
548                 target.GetImages().FindFirstModule(reexport_module_spec);
549           }
550         }
551         symbol_load_addr = GetSymbolAddress(
552             target, process, sym_ctx.symbol->GetReExportedSymbolName(),
553             symbol_type, reexport_module_sp.get());
554       }
555     } break;
556 
557     case eSymbolTypeData:
558     case eSymbolTypeRuntime:
559     case eSymbolTypeVariable:
560     case eSymbolTypeLocal:
561     case eSymbolTypeParam:
562     case eSymbolTypeInvalid:
563     case eSymbolTypeAbsolute:
564     case eSymbolTypeException:
565     case eSymbolTypeSourceFile:
566     case eSymbolTypeHeaderFile:
567     case eSymbolTypeObjectFile:
568     case eSymbolTypeCommonBlock:
569     case eSymbolTypeBlock:
570     case eSymbolTypeVariableType:
571     case eSymbolTypeLineEntry:
572     case eSymbolTypeLineHeader:
573     case eSymbolTypeScopeBegin:
574     case eSymbolTypeScopeEnd:
575     case eSymbolTypeAdditional:
576     case eSymbolTypeCompiler:
577     case eSymbolTypeInstrumentation:
578     case eSymbolTypeUndefined:
579     case eSymbolTypeObjCClass:
580     case eSymbolTypeObjCMetaClass:
581     case eSymbolTypeObjCIVar:
582       symbol_load_addr = sym_address.GetLoadAddress(&target);
583       break;
584     }
585   }
586 
587   if (symbol_load_addr == LLDB_INVALID_ADDRESS && process) {
588     ObjCLanguageRuntime *runtime = ObjCLanguageRuntime::Get(*process);
589 
590     if (runtime) {
591       symbol_load_addr = runtime->LookupRuntimeSymbol(name);
592     }
593   }
594 
595   return symbol_load_addr;
596 }
597 
598 addr_t ClangExpressionDeclMap::GetSymbolAddress(ConstString name,
599                                                 lldb::SymbolType symbol_type) {
600   assert(m_parser_vars.get());
601 
602   if (!m_parser_vars->m_exe_ctx.GetTargetPtr())
603     return false;
604 
605   return GetSymbolAddress(m_parser_vars->m_exe_ctx.GetTargetRef(),
606                           m_parser_vars->m_exe_ctx.GetProcessPtr(), name,
607                           symbol_type);
608 }
609 
610 lldb::VariableSP ClangExpressionDeclMap::FindGlobalVariable(
611     Target &target, ModuleSP &module, ConstString name,
612     const CompilerDeclContext &namespace_decl) {
613   VariableList vars;
614 
615   if (module && namespace_decl)
616     module->FindGlobalVariables(name, namespace_decl, -1, vars);
617   else
618     target.GetImages().FindGlobalVariables(name, -1, vars);
619 
620   if (vars.GetSize() == 0)
621     return VariableSP();
622   return vars.GetVariableAtIndex(0);
623 }
624 
625 TypeSystemClang *ClangExpressionDeclMap::GetTypeSystemClang() {
626   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
627   if (frame == nullptr)
628     return nullptr;
629 
630   SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
631                                                   lldb::eSymbolContextBlock);
632   if (sym_ctx.block == nullptr)
633     return nullptr;
634 
635   CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
636   if (!frame_decl_context)
637     return nullptr;
638 
639   return llvm::dyn_cast_or_null<TypeSystemClang>(
640       frame_decl_context.GetTypeSystem());
641 }
642 
643 // Interface for ClangASTSource
644 
645 void ClangExpressionDeclMap::FindExternalVisibleDecls(
646     NameSearchContext &context) {
647   assert(m_ast_context);
648 
649   const ConstString name(context.m_decl_name.getAsString().c_str());
650 
651   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
652 
653   if (log) {
654     if (!context.m_decl_context)
655       LLDB_LOG(log,
656                "ClangExpressionDeclMap::FindExternalVisibleDecls for "
657                "'{0}' in a NULL DeclContext",
658                name);
659     else if (const NamedDecl *context_named_decl =
660                  dyn_cast<NamedDecl>(context.m_decl_context))
661       LLDB_LOG(log,
662                "ClangExpressionDeclMap::FindExternalVisibleDecls for "
663                "'{0}' in '{1}'",
664                name, context_named_decl->getNameAsString());
665     else
666       LLDB_LOG(log,
667                "ClangExpressionDeclMap::FindExternalVisibleDecls for "
668                "'{0}' in a '{1}'",
669                name, context.m_decl_context->getDeclKindName());
670   }
671 
672   if (const NamespaceDecl *namespace_context =
673           dyn_cast<NamespaceDecl>(context.m_decl_context)) {
674     if (namespace_context->getName().str() ==
675         std::string(g_lldb_local_vars_namespace_cstr)) {
676       CompilerDeclContext compiler_decl_ctx =
677           m_clang_ast_context->CreateDeclContext(
678               const_cast<clang::DeclContext *>(context.m_decl_context));
679       FindExternalVisibleDecls(context, lldb::ModuleSP(), compiler_decl_ctx);
680       return;
681     }
682 
683     ClangASTImporter::NamespaceMapSP namespace_map =
684         m_ast_importer_sp->GetNamespaceMap(namespace_context);
685 
686     if (!namespace_map)
687       return;
688 
689     LLDB_LOGV(log, "  CEDM::FEVD Inspecting (NamespaceMap*){0:x} ({1} entries)",
690               namespace_map.get(), namespace_map->size());
691 
692     for (ClangASTImporter::NamespaceMapItem &n : *namespace_map) {
693       LLDB_LOG(log, "  CEDM::FEVD Searching namespace {0} in module {1}",
694                n.second.GetName(), n.first->GetFileSpec().GetFilename());
695 
696       FindExternalVisibleDecls(context, n.first, n.second);
697     }
698   } else if (isa<TranslationUnitDecl>(context.m_decl_context)) {
699     CompilerDeclContext namespace_decl;
700 
701     LLDB_LOG(log, "  CEDM::FEVD Searching the root namespace");
702 
703     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl);
704   }
705 
706   ClangASTSource::FindExternalVisibleDecls(context);
707 }
708 
709 void ClangExpressionDeclMap::MaybeRegisterFunctionBody(
710     FunctionDecl *copied_function_decl) {
711   if (copied_function_decl->getBody() && m_parser_vars->m_code_gen) {
712     clang::DeclGroupRef decl_group_ref(copied_function_decl);
713     m_parser_vars->m_code_gen->HandleTopLevelDecl(decl_group_ref);
714   }
715 }
716 
717 clang::NamedDecl *ClangExpressionDeclMap::GetPersistentDecl(ConstString name) {
718   if (!m_parser_vars)
719     return nullptr;
720   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
721   if (!target)
722     return nullptr;
723 
724   ScratchTypeSystemClang::GetForTarget(*target);
725 
726   if (!m_parser_vars->m_persistent_vars)
727     return nullptr;
728   return m_parser_vars->m_persistent_vars->GetPersistentDecl(name);
729 }
730 
731 void ClangExpressionDeclMap::SearchPersistenDecls(NameSearchContext &context,
732                                                   const ConstString name) {
733   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
734 
735   NamedDecl *persistent_decl = GetPersistentDecl(name);
736 
737   if (!persistent_decl)
738     return;
739 
740   Decl *parser_persistent_decl = CopyDecl(persistent_decl);
741 
742   if (!parser_persistent_decl)
743     return;
744 
745   NamedDecl *parser_named_decl = dyn_cast<NamedDecl>(parser_persistent_decl);
746 
747   if (!parser_named_decl)
748     return;
749 
750   if (clang::FunctionDecl *parser_function_decl =
751           llvm::dyn_cast<clang::FunctionDecl>(parser_named_decl)) {
752     MaybeRegisterFunctionBody(parser_function_decl);
753   }
754 
755   LLDB_LOG(log, "  CEDM::FEVD Found persistent decl {0}", name);
756 
757   context.AddNamedDecl(parser_named_decl);
758 }
759 
760 void ClangExpressionDeclMap::LookUpLldbClass(NameSearchContext &context) {
761   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
762 
763   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
764   SymbolContext sym_ctx;
765   if (frame != nullptr)
766     sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
767                                       lldb::eSymbolContextBlock);
768 
769   if (m_ctx_obj) {
770     Status status;
771     lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
772     if (!ctx_obj_ptr || status.Fail())
773       return;
774 
775     AddContextClassType(context, TypeFromUser(m_ctx_obj->GetCompilerType()));
776 
777     m_struct_vars->m_object_pointer_type =
778         TypeFromUser(ctx_obj_ptr->GetCompilerType());
779 
780     return;
781   }
782 
783   // Clang is looking for the type of "this"
784 
785   if (frame == nullptr)
786     return;
787 
788   // Find the block that defines the function represented by "sym_ctx"
789   Block *function_block = sym_ctx.GetFunctionBlock();
790 
791   if (!function_block)
792     return;
793 
794   CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
795 
796   if (!function_decl_ctx)
797     return;
798 
799   clang::CXXMethodDecl *method_decl =
800       TypeSystemClang::DeclContextGetAsCXXMethodDecl(function_decl_ctx);
801 
802   if (method_decl) {
803     clang::CXXRecordDecl *class_decl = method_decl->getParent();
804 
805     QualType class_qual_type(class_decl->getTypeForDecl(), 0);
806 
807     TypeFromUser class_user_type(class_qual_type.getAsOpaquePtr(),
808                                  function_decl_ctx.GetTypeSystem());
809 
810     LLDB_LOG(log, "  CEDM::FEVD Adding type for $__lldb_class: {1}",
811              class_qual_type.getAsString());
812 
813     AddContextClassType(context, class_user_type);
814 
815     if (method_decl->isInstance()) {
816       // self is a pointer to the object
817 
818       QualType class_pointer_type =
819           method_decl->getASTContext().getPointerType(class_qual_type);
820 
821       TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
822                                   function_decl_ctx.GetTypeSystem());
823 
824       m_struct_vars->m_object_pointer_type = self_user_type;
825     }
826     return;
827   }
828 
829   // This branch will get hit if we are executing code in the context of
830   // a function that claims to have an object pointer (through
831   // DW_AT_object_pointer?) but is not formally a method of the class.
832   // In that case, just look up the "this" variable in the current scope
833   // and use its type.
834   // FIXME: This code is formally correct, but clang doesn't currently
835   // emit DW_AT_object_pointer
836   // for C++ so it hasn't actually been tested.
837 
838   VariableList *vars = frame->GetVariableList(false);
839 
840   lldb::VariableSP this_var = vars->FindVariable(ConstString("this"));
841 
842   if (this_var && this_var->IsInScope(frame) &&
843       this_var->LocationIsValidForFrame(frame)) {
844     Type *this_type = this_var->GetType();
845 
846     if (!this_type)
847       return;
848 
849     TypeFromUser pointee_type =
850         this_type->GetForwardCompilerType().GetPointeeType();
851 
852     LLDB_LOG(log, "  FEVD Adding type for $__lldb_class: {1}",
853              ClangUtil::GetQualType(pointee_type).getAsString());
854 
855     AddContextClassType(context, pointee_type);
856     TypeFromUser this_user_type(this_type->GetFullCompilerType());
857     m_struct_vars->m_object_pointer_type = this_user_type;
858   }
859 }
860 
861 void ClangExpressionDeclMap::LookUpLldbObjCClass(NameSearchContext &context) {
862   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
863 
864   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
865 
866   if (m_ctx_obj) {
867     Status status;
868     lldb::ValueObjectSP ctx_obj_ptr = m_ctx_obj->AddressOf(status);
869     if (!ctx_obj_ptr || status.Fail())
870       return;
871 
872     AddOneType(context, TypeFromUser(m_ctx_obj->GetCompilerType()));
873 
874     m_struct_vars->m_object_pointer_type =
875         TypeFromUser(ctx_obj_ptr->GetCompilerType());
876 
877     return;
878   }
879 
880   // Clang is looking for the type of "*self"
881 
882   if (!frame)
883     return;
884 
885   SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
886                                                   lldb::eSymbolContextBlock);
887 
888   // Find the block that defines the function represented by "sym_ctx"
889   Block *function_block = sym_ctx.GetFunctionBlock();
890 
891   if (!function_block)
892     return;
893 
894   CompilerDeclContext function_decl_ctx = function_block->GetDeclContext();
895 
896   if (!function_decl_ctx)
897     return;
898 
899   clang::ObjCMethodDecl *method_decl =
900       TypeSystemClang::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
901 
902   if (method_decl) {
903     ObjCInterfaceDecl *self_interface = method_decl->getClassInterface();
904 
905     if (!self_interface)
906       return;
907 
908     const clang::Type *interface_type = self_interface->getTypeForDecl();
909 
910     if (!interface_type)
911       return; // This is unlikely, but we have seen crashes where this
912               // occurred
913 
914     TypeFromUser class_user_type(QualType(interface_type, 0).getAsOpaquePtr(),
915                                  function_decl_ctx.GetTypeSystem());
916 
917     LLDB_LOG(log, "  FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
918              ClangUtil::ToString(interface_type));
919 
920     AddOneType(context, class_user_type);
921 
922     if (method_decl->isInstanceMethod()) {
923       // self is a pointer to the object
924 
925       QualType class_pointer_type =
926           method_decl->getASTContext().getObjCObjectPointerType(
927               QualType(interface_type, 0));
928 
929       TypeFromUser self_user_type(class_pointer_type.getAsOpaquePtr(),
930                                   function_decl_ctx.GetTypeSystem());
931 
932       m_struct_vars->m_object_pointer_type = self_user_type;
933     } else {
934       // self is a Class pointer
935       QualType class_type = method_decl->getASTContext().getObjCClassType();
936 
937       TypeFromUser self_user_type(class_type.getAsOpaquePtr(),
938                                   function_decl_ctx.GetTypeSystem());
939 
940       m_struct_vars->m_object_pointer_type = self_user_type;
941     }
942 
943     return;
944   }
945   // This branch will get hit if we are executing code in the context of
946   // a function that claims to have an object pointer (through
947   // DW_AT_object_pointer?) but is not formally a method of the class.
948   // In that case, just look up the "self" variable in the current scope
949   // and use its type.
950 
951   VariableList *vars = frame->GetVariableList(false);
952 
953   lldb::VariableSP self_var = vars->FindVariable(ConstString("self"));
954 
955   if (!self_var)
956     return;
957   if (!self_var->IsInScope(frame))
958     return;
959   if (!self_var->LocationIsValidForFrame(frame))
960     return;
961 
962   Type *self_type = self_var->GetType();
963 
964   if (!self_type)
965     return;
966 
967   CompilerType self_clang_type = self_type->GetFullCompilerType();
968 
969   if (TypeSystemClang::IsObjCClassType(self_clang_type)) {
970     return;
971   }
972   if (!TypeSystemClang::IsObjCObjectPointerType(self_clang_type))
973     return;
974   self_clang_type = self_clang_type.GetPointeeType();
975 
976   if (!self_clang_type)
977     return;
978 
979   LLDB_LOG(log, "  FEVD[{0}] Adding type for $__lldb_objc_class: {1}",
980            ClangUtil::ToString(self_type->GetFullCompilerType()));
981 
982   TypeFromUser class_user_type(self_clang_type);
983 
984   AddOneType(context, class_user_type);
985 
986   TypeFromUser self_user_type(self_type->GetFullCompilerType());
987 
988   m_struct_vars->m_object_pointer_type = self_user_type;
989 }
990 
991 void ClangExpressionDeclMap::LookupLocalVarNamespace(
992     SymbolContext &sym_ctx, NameSearchContext &name_context) {
993   if (sym_ctx.block == nullptr)
994     return;
995 
996   CompilerDeclContext frame_decl_context = sym_ctx.block->GetDeclContext();
997   if (!frame_decl_context)
998     return;
999 
1000   TypeSystemClang *frame_ast = llvm::dyn_cast_or_null<TypeSystemClang>(
1001       frame_decl_context.GetTypeSystem());
1002   if (!frame_ast)
1003     return;
1004 
1005   clang::NamespaceDecl *namespace_decl =
1006       m_clang_ast_context->GetUniqueNamespaceDeclaration(
1007           g_lldb_local_vars_namespace_cstr, nullptr, OptionalClangModuleID());
1008   if (!namespace_decl)
1009     return;
1010 
1011   name_context.AddNamedDecl(namespace_decl);
1012   clang::DeclContext *ctxt = clang::Decl::castToDeclContext(namespace_decl);
1013   ctxt->setHasExternalVisibleStorage(true);
1014   name_context.m_found_local_vars_nsp = true;
1015 }
1016 
1017 void ClangExpressionDeclMap::LookupInModulesDeclVendor(
1018     NameSearchContext &context, ConstString name) {
1019   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1020 
1021   if (!m_target)
1022     return;
1023 
1024   std::shared_ptr<ClangModulesDeclVendor> modules_decl_vendor =
1025       GetClangModulesDeclVendor();
1026   if (!modules_decl_vendor)
1027     return;
1028 
1029   bool append = false;
1030   uint32_t max_matches = 1;
1031   std::vector<clang::NamedDecl *> decls;
1032 
1033   if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
1034     return;
1035 
1036   assert(!decls.empty() && "FindDecls returned true but no decls?");
1037   clang::NamedDecl *const decl_from_modules = decls[0];
1038 
1039   LLDB_LOG(log,
1040            "  CAS::FEVD Matching decl found for "
1041            "\"{1}\" in the modules",
1042            name);
1043 
1044   clang::Decl *copied_decl = CopyDecl(decl_from_modules);
1045   if (!copied_decl) {
1046     LLDB_LOG(log, "  CAS::FEVD - Couldn't export a "
1047                   "declaration from the modules");
1048     return;
1049   }
1050 
1051   if (auto copied_function = dyn_cast<clang::FunctionDecl>(copied_decl)) {
1052     MaybeRegisterFunctionBody(copied_function);
1053 
1054     context.AddNamedDecl(copied_function);
1055 
1056     context.m_found_function_with_type_info = true;
1057     context.m_found_function = true;
1058   } else if (auto copied_var = dyn_cast<clang::VarDecl>(copied_decl)) {
1059     context.AddNamedDecl(copied_var);
1060     context.m_found_variable = true;
1061   }
1062 }
1063 
1064 bool ClangExpressionDeclMap::LookupLocalVariable(
1065     NameSearchContext &context, ConstString name, SymbolContext &sym_ctx,
1066     const CompilerDeclContext &namespace_decl) {
1067   if (sym_ctx.block == nullptr)
1068     return false;
1069 
1070   CompilerDeclContext decl_context = sym_ctx.block->GetDeclContext();
1071   if (!decl_context)
1072     return false;
1073 
1074   // Make sure that the variables are parsed so that we have the
1075   // declarations.
1076   StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1077   VariableListSP vars = frame->GetInScopeVariableList(true);
1078   for (size_t i = 0; i < vars->GetSize(); i++)
1079     vars->GetVariableAtIndex(i)->GetDecl();
1080 
1081   // Search for declarations matching the name. Do not include imported
1082   // decls in the search if we are looking for decls in the artificial
1083   // namespace $__lldb_local_vars.
1084   std::vector<CompilerDecl> found_decls =
1085       decl_context.FindDeclByName(name, namespace_decl.IsValid());
1086 
1087   VariableSP var;
1088   bool variable_found = false;
1089   for (CompilerDecl decl : found_decls) {
1090     for (size_t vi = 0, ve = vars->GetSize(); vi != ve; ++vi) {
1091       VariableSP candidate_var = vars->GetVariableAtIndex(vi);
1092       if (candidate_var->GetDecl() == decl) {
1093         var = candidate_var;
1094         break;
1095       }
1096     }
1097 
1098     if (var && !variable_found) {
1099       variable_found = true;
1100       ValueObjectSP valobj = ValueObjectVariable::Create(frame, var);
1101       AddOneVariable(context, var, valobj);
1102       context.m_found_variable = true;
1103     }
1104   }
1105   return variable_found;
1106 }
1107 
1108 /// Structure to hold the info needed when comparing function
1109 /// declarations.
1110 namespace {
1111 struct FuncDeclInfo {
1112   ConstString m_name;
1113   CompilerType m_copied_type;
1114   uint32_t m_decl_lvl;
1115   SymbolContext m_sym_ctx;
1116 };
1117 } // namespace
1118 
1119 SymbolContextList ClangExpressionDeclMap::SearchFunctionsInSymbolContexts(
1120     const SymbolContextList &sc_list,
1121     const CompilerDeclContext &frame_decl_context) {
1122   // First, symplify things by looping through the symbol contexts to
1123   // remove unwanted functions and separate out the functions we want to
1124   // compare and prune into a separate list. Cache the info needed about
1125   // the function declarations in a vector for efficiency.
1126   uint32_t num_indices = sc_list.GetSize();
1127   SymbolContextList sc_sym_list;
1128   std::vector<FuncDeclInfo> decl_infos;
1129   decl_infos.reserve(num_indices);
1130   clang::DeclContext *frame_decl_ctx =
1131       (clang::DeclContext *)frame_decl_context.GetOpaqueDeclContext();
1132   TypeSystemClang *ast = llvm::dyn_cast_or_null<TypeSystemClang>(
1133       frame_decl_context.GetTypeSystem());
1134 
1135   for (uint32_t index = 0; index < num_indices; ++index) {
1136     FuncDeclInfo fdi;
1137     SymbolContext sym_ctx;
1138     sc_list.GetContextAtIndex(index, sym_ctx);
1139 
1140     // We don't know enough about symbols to compare them, but we should
1141     // keep them in the list.
1142     Function *function = sym_ctx.function;
1143     if (!function) {
1144       sc_sym_list.Append(sym_ctx);
1145       continue;
1146     }
1147     // Filter out functions without declaration contexts, as well as
1148     // class/instance methods, since they'll be skipped in the code that
1149     // follows anyway.
1150     CompilerDeclContext func_decl_context = function->GetDeclContext();
1151     if (!func_decl_context ||
1152         func_decl_context.IsClassMethod(nullptr, nullptr, nullptr))
1153       continue;
1154     // We can only prune functions for which we can copy the type.
1155     CompilerType func_clang_type = function->GetType()->GetFullCompilerType();
1156     CompilerType copied_func_type = GuardedCopyType(func_clang_type);
1157     if (!copied_func_type) {
1158       sc_sym_list.Append(sym_ctx);
1159       continue;
1160     }
1161 
1162     fdi.m_sym_ctx = sym_ctx;
1163     fdi.m_name = function->GetName();
1164     fdi.m_copied_type = copied_func_type;
1165     fdi.m_decl_lvl = LLDB_INVALID_DECL_LEVEL;
1166     if (fdi.m_copied_type && func_decl_context) {
1167       // Call CountDeclLevels to get the number of parent scopes we have
1168       // to look through before we find the function declaration. When
1169       // comparing functions of the same type, the one with a lower count
1170       // will be closer to us in the lookup scope and shadows the other.
1171       clang::DeclContext *func_decl_ctx =
1172           (clang::DeclContext *)func_decl_context.GetOpaqueDeclContext();
1173       fdi.m_decl_lvl = ast->CountDeclLevels(frame_decl_ctx, func_decl_ctx,
1174                                             &fdi.m_name, &fdi.m_copied_type);
1175     }
1176     decl_infos.emplace_back(fdi);
1177   }
1178 
1179   // Loop through the functions in our cache looking for matching types,
1180   // then compare their scope levels to see which is closer.
1181   std::multimap<CompilerType, const FuncDeclInfo *> matches;
1182   for (const FuncDeclInfo &fdi : decl_infos) {
1183     const CompilerType t = fdi.m_copied_type;
1184     auto q = matches.find(t);
1185     if (q != matches.end()) {
1186       if (q->second->m_decl_lvl > fdi.m_decl_lvl)
1187         // This function is closer; remove the old set.
1188         matches.erase(t);
1189       else if (q->second->m_decl_lvl < fdi.m_decl_lvl)
1190         // The functions in our set are closer - skip this one.
1191         continue;
1192     }
1193     matches.insert(std::make_pair(t, &fdi));
1194   }
1195 
1196   // Loop through our matches and add their symbol contexts to our list.
1197   SymbolContextList sc_func_list;
1198   for (const auto &q : matches)
1199     sc_func_list.Append(q.second->m_sym_ctx);
1200 
1201   // Rejoin the lists with the functions in front.
1202   sc_func_list.Append(sc_sym_list);
1203   return sc_func_list;
1204 }
1205 
1206 void ClangExpressionDeclMap::LookupFunction(
1207     NameSearchContext &context, lldb::ModuleSP module_sp, ConstString name,
1208     const CompilerDeclContext &namespace_decl) {
1209   if (!m_parser_vars)
1210     return;
1211 
1212   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1213 
1214   std::vector<clang::NamedDecl *> decls_from_modules;
1215 
1216   if (target) {
1217     if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
1218             GetClangModulesDeclVendor()) {
1219       decl_vendor->FindDecls(name, false, UINT32_MAX, decls_from_modules);
1220     }
1221   }
1222 
1223   SymbolContextList sc_list;
1224   if (namespace_decl && module_sp) {
1225     ModuleFunctionSearchOptions function_options;
1226     function_options.include_inlines = false;
1227     function_options.include_symbols = false;
1228 
1229     module_sp->FindFunctions(name, namespace_decl, eFunctionNameTypeBase,
1230                              function_options, sc_list);
1231   } else if (target && !namespace_decl) {
1232     ModuleFunctionSearchOptions function_options;
1233     function_options.include_inlines = false;
1234     function_options.include_symbols = true;
1235 
1236     // TODO Fix FindFunctions so that it doesn't return
1237     //   instance methods for eFunctionNameTypeBase.
1238 
1239     target->GetImages().FindFunctions(
1240         name, eFunctionNameTypeFull | eFunctionNameTypeBase, function_options,
1241         sc_list);
1242   }
1243 
1244   // If we found more than one function, see if we can use the frame's decl
1245   // context to remove functions that are shadowed by other functions which
1246   // match in type but are nearer in scope.
1247   //
1248   // AddOneFunction will not add a function whose type has already been
1249   // added, so if there's another function in the list with a matching type,
1250   // check to see if their decl context is a parent of the current frame's or
1251   // was imported via a and using statement, and pick the best match
1252   // according to lookup rules.
1253   if (sc_list.GetSize() > 1) {
1254     // Collect some info about our frame's context.
1255     StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1256     SymbolContext frame_sym_ctx;
1257     if (frame != nullptr)
1258       frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1259                                               lldb::eSymbolContextBlock);
1260     CompilerDeclContext frame_decl_context =
1261         frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext()
1262                                        : CompilerDeclContext();
1263 
1264     // We can't do this without a compiler decl context for our frame.
1265     if (frame_decl_context) {
1266       sc_list = SearchFunctionsInSymbolContexts(sc_list, frame_decl_context);
1267     }
1268   }
1269 
1270   if (sc_list.GetSize()) {
1271     Symbol *extern_symbol = nullptr;
1272     Symbol *non_extern_symbol = nullptr;
1273 
1274     for (uint32_t index = 0, num_indices = sc_list.GetSize();
1275          index < num_indices; ++index) {
1276       SymbolContext sym_ctx;
1277       sc_list.GetContextAtIndex(index, sym_ctx);
1278 
1279       if (sym_ctx.function) {
1280         CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1281 
1282         if (!decl_ctx)
1283           continue;
1284 
1285         // Filter out class/instance methods.
1286         if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1287           continue;
1288 
1289         AddOneFunction(context, sym_ctx.function, nullptr);
1290         context.m_found_function_with_type_info = true;
1291         context.m_found_function = true;
1292       } else if (sym_ctx.symbol) {
1293         if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) {
1294           sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1295           if (sym_ctx.symbol == nullptr)
1296             continue;
1297         }
1298 
1299         if (sym_ctx.symbol->IsExternal())
1300           extern_symbol = sym_ctx.symbol;
1301         else
1302           non_extern_symbol = sym_ctx.symbol;
1303       }
1304     }
1305 
1306     if (!context.m_found_function_with_type_info) {
1307       for (clang::NamedDecl *decl : decls_from_modules) {
1308         if (llvm::isa<clang::FunctionDecl>(decl)) {
1309           clang::NamedDecl *copied_decl =
1310               llvm::cast_or_null<FunctionDecl>(CopyDecl(decl));
1311           if (copied_decl) {
1312             context.AddNamedDecl(copied_decl);
1313             context.m_found_function_with_type_info = true;
1314           }
1315         }
1316       }
1317     }
1318 
1319     if (!context.m_found_function_with_type_info) {
1320       if (extern_symbol) {
1321         AddOneFunction(context, nullptr, extern_symbol);
1322         context.m_found_function = true;
1323       } else if (non_extern_symbol) {
1324         AddOneFunction(context, nullptr, non_extern_symbol);
1325         context.m_found_function = true;
1326       }
1327     }
1328   }
1329 }
1330 
1331 void ClangExpressionDeclMap::FindExternalVisibleDecls(
1332     NameSearchContext &context, lldb::ModuleSP module_sp,
1333     const CompilerDeclContext &namespace_decl) {
1334   assert(m_ast_context);
1335 
1336   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1337 
1338   const ConstString name(context.m_decl_name.getAsString().c_str());
1339   if (IgnoreName(name, false))
1340     return;
1341 
1342   // Only look for functions by name out in our symbols if the function doesn't
1343   // start with our phony prefix of '$'
1344 
1345   Target *target = nullptr;
1346   StackFrame *frame = nullptr;
1347   SymbolContext sym_ctx;
1348   if (m_parser_vars) {
1349     target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1350     frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1351   }
1352   if (frame != nullptr)
1353     sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1354                                       lldb::eSymbolContextBlock);
1355 
1356   // Try the persistent decls, which take precedence over all else.
1357   if (!namespace_decl)
1358     SearchPersistenDecls(context, name);
1359 
1360   if (name.GetStringRef().startswith("$") && !namespace_decl) {
1361     if (name == "$__lldb_class") {
1362       LookUpLldbClass(context);
1363       return;
1364     }
1365 
1366     if (name == "$__lldb_objc_class") {
1367       LookUpLldbObjCClass(context);
1368       return;
1369     }
1370     if (name == g_lldb_local_vars_namespace_cstr) {
1371       LookupLocalVarNamespace(sym_ctx, context);
1372       return;
1373     }
1374 
1375     // any other $__lldb names should be weeded out now
1376     if (name.GetStringRef().startswith("$__lldb"))
1377       return;
1378 
1379     // No ParserVars means we can't do register or variable lookup.
1380     if (!m_parser_vars || !m_parser_vars->m_persistent_vars)
1381       return;
1382 
1383     ExpressionVariableSP pvar_sp(
1384         m_parser_vars->m_persistent_vars->GetVariable(name));
1385 
1386     if (pvar_sp) {
1387       AddOneVariable(context, pvar_sp);
1388       return;
1389     }
1390 
1391     assert(name.GetStringRef().startswith("$"));
1392     llvm::StringRef reg_name = name.GetStringRef().substr(1);
1393 
1394     if (m_parser_vars->m_exe_ctx.GetRegisterContext()) {
1395       const RegisterInfo *reg_info(
1396           m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(
1397               reg_name));
1398 
1399       if (reg_info) {
1400         LLDB_LOG(log, "  CEDM::FEVD Found register {0}", reg_info->name);
1401 
1402         AddOneRegister(context, reg_info);
1403       }
1404     }
1405     return;
1406   }
1407 
1408   bool local_var_lookup = !namespace_decl || (namespace_decl.GetName() ==
1409                                               g_lldb_local_vars_namespace_cstr);
1410   if (frame && local_var_lookup)
1411     if (LookupLocalVariable(context, name, sym_ctx, namespace_decl))
1412       return;
1413 
1414   if (target) {
1415     ValueObjectSP valobj;
1416     VariableSP var;
1417     var = FindGlobalVariable(*target, module_sp, name, namespace_decl);
1418 
1419     if (var) {
1420       valobj = ValueObjectVariable::Create(target, var);
1421       AddOneVariable(context, var, valobj);
1422       context.m_found_variable = true;
1423       return;
1424     }
1425   }
1426 
1427   LookupFunction(context, module_sp, name, namespace_decl);
1428 
1429   // Try the modules next.
1430   if (!context.m_found_function_with_type_info)
1431     LookupInModulesDeclVendor(context, name);
1432 
1433   if (target && !context.m_found_variable && !namespace_decl) {
1434     // We couldn't find a non-symbol variable for this.  Now we'll hunt for a
1435     // generic data symbol, and -- if it is found -- treat it as a variable.
1436     Status error;
1437 
1438     const Symbol *data_symbol =
1439         m_parser_vars->m_sym_ctx.FindBestGlobalDataSymbol(name, error);
1440 
1441     if (!error.Success()) {
1442       const unsigned diag_id =
1443           m_ast_context->getDiagnostics().getCustomDiagID(
1444               clang::DiagnosticsEngine::Level::Error, "%0");
1445       m_ast_context->getDiagnostics().Report(diag_id) << error.AsCString();
1446     }
1447 
1448     if (data_symbol) {
1449       std::string warning("got name from symbols: ");
1450       warning.append(name.AsCString());
1451       const unsigned diag_id =
1452           m_ast_context->getDiagnostics().getCustomDiagID(
1453               clang::DiagnosticsEngine::Level::Warning, "%0");
1454       m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1455       AddOneGenericVariable(context, *data_symbol);
1456       context.m_found_variable = true;
1457     }
1458   }
1459 }
1460 
1461 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var,
1462                                               lldb_private::Value &var_location,
1463                                               TypeFromUser *user_type,
1464                                               TypeFromParser *parser_type) {
1465   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1466 
1467   Type *var_type = var->GetType();
1468 
1469   if (!var_type) {
1470     LLDB_LOG(log, "Skipped a definition because it has no type");
1471     return false;
1472   }
1473 
1474   CompilerType var_clang_type = var_type->GetFullCompilerType();
1475 
1476   if (!var_clang_type) {
1477     LLDB_LOG(log, "Skipped a definition because it has no Clang type");
1478     return false;
1479   }
1480 
1481   TypeSystemClang *clang_ast = llvm::dyn_cast_or_null<TypeSystemClang>(
1482       var_type->GetForwardCompilerType().GetTypeSystem());
1483 
1484   if (!clang_ast) {
1485     LLDB_LOG(log, "Skipped a definition because it has no Clang AST");
1486     return false;
1487   }
1488 
1489   DWARFExpression &var_location_expr = var->LocationExpression();
1490 
1491   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1492   Status err;
1493 
1494   if (var->GetLocationIsConstantValueData()) {
1495     DataExtractor const_value_extractor;
1496 
1497     if (var_location_expr.GetExpressionData(const_value_extractor)) {
1498       var_location = Value(const_value_extractor.GetDataStart(),
1499                            const_value_extractor.GetByteSize());
1500       var_location.SetValueType(Value::ValueType::HostAddress);
1501     } else {
1502       LLDB_LOG(log, "Error evaluating constant variable: {0}", err.AsCString());
1503       return false;
1504     }
1505   }
1506 
1507   CompilerType type_to_use = GuardedCopyType(var_clang_type);
1508 
1509   if (!type_to_use) {
1510     LLDB_LOG(log,
1511              "Couldn't copy a variable's type into the parser's AST context");
1512 
1513     return false;
1514   }
1515 
1516   if (parser_type)
1517     *parser_type = TypeFromParser(type_to_use);
1518 
1519   if (var_location.GetContextType() == Value::ContextType::Invalid)
1520     var_location.SetCompilerType(type_to_use);
1521 
1522   if (var_location.GetValueType() == Value::ValueType::FileAddress) {
1523     SymbolContext var_sc;
1524     var->CalculateSymbolContext(&var_sc);
1525 
1526     if (!var_sc.module_sp)
1527       return false;
1528 
1529     Address so_addr(var_location.GetScalar().ULongLong(),
1530                     var_sc.module_sp->GetSectionList());
1531 
1532     lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1533 
1534     if (load_addr != LLDB_INVALID_ADDRESS) {
1535       var_location.GetScalar() = load_addr;
1536       var_location.SetValueType(Value::ValueType::LoadAddress);
1537     }
1538   }
1539 
1540   if (user_type)
1541     *user_type = TypeFromUser(var_clang_type);
1542 
1543   return true;
1544 }
1545 
1546 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1547                                             VariableSP var,
1548                                             ValueObjectSP valobj) {
1549   assert(m_parser_vars.get());
1550 
1551   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1552 
1553   TypeFromUser ut;
1554   TypeFromParser pt;
1555   Value var_location;
1556 
1557   if (!GetVariableValue(var, var_location, &ut, &pt))
1558     return;
1559 
1560   clang::QualType parser_opaque_type =
1561       QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1562 
1563   if (parser_opaque_type.isNull())
1564     return;
1565 
1566   if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) {
1567     if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1568       CompleteType(tag_type->getDecl());
1569     if (const ObjCObjectPointerType *objc_object_ptr_type =
1570             dyn_cast<ObjCObjectPointerType>(parser_type))
1571       CompleteType(objc_object_ptr_type->getInterfaceDecl());
1572   }
1573 
1574   bool is_reference = pt.IsReferenceType();
1575 
1576   NamedDecl *var_decl = nullptr;
1577   if (is_reference)
1578     var_decl = context.AddVarDecl(pt);
1579   else
1580     var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1581 
1582   std::string decl_name(context.m_decl_name.getAsString());
1583   ConstString entity_name(decl_name.c_str());
1584   ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1585   m_found_entities.AddNewlyConstructedVariable(entity);
1586 
1587   assert(entity);
1588   entity->EnableParserVars(GetParserID());
1589   ClangExpressionVariable::ParserVars *parser_vars =
1590       entity->GetParserVars(GetParserID());
1591   parser_vars->m_named_decl = var_decl;
1592   parser_vars->m_llvm_value = nullptr;
1593   parser_vars->m_lldb_value = var_location;
1594   parser_vars->m_lldb_var = var;
1595 
1596   if (is_reference)
1597     entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1598 
1599   LLDB_LOG(log, "  CEDM::FEVD Found variable {1}, returned\n{2} (original {3})",
1600            decl_name, ClangUtil::DumpDecl(var_decl), ClangUtil::ToString(ut));
1601 }
1602 
1603 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1604                                             ExpressionVariableSP &pvar_sp) {
1605   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1606 
1607   TypeFromUser user_type(
1608       llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1609 
1610   TypeFromParser parser_type(GuardedCopyType(user_type));
1611 
1612   if (!parser_type.GetOpaqueQualType()) {
1613     LLDB_LOG(log, "  CEDM::FEVD Couldn't import type for pvar {0}",
1614              pvar_sp->GetName());
1615     return;
1616   }
1617 
1618   NamedDecl *var_decl =
1619       context.AddVarDecl(parser_type.GetLValueReferenceType());
1620 
1621   llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1622       ->EnableParserVars(GetParserID());
1623   ClangExpressionVariable::ParserVars *parser_vars =
1624       llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1625           ->GetParserVars(GetParserID());
1626   parser_vars->m_named_decl = var_decl;
1627   parser_vars->m_llvm_value = nullptr;
1628   parser_vars->m_lldb_value.Clear();
1629 
1630   LLDB_LOG(log, "  CEDM::FEVD Added pvar {1}, returned\n{2}",
1631            pvar_sp->GetName(), ClangUtil::DumpDecl(var_decl));
1632 }
1633 
1634 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1635                                                    const Symbol &symbol) {
1636   assert(m_parser_vars.get());
1637 
1638   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1639 
1640   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1641 
1642   if (target == nullptr)
1643     return;
1644 
1645   TypeSystemClang *scratch_ast_context = GetScratchContext(*target);
1646   if (!scratch_ast_context)
1647     return;
1648 
1649   TypeFromUser user_type(scratch_ast_context->GetBasicType(eBasicTypeVoid)
1650                              .GetPointerType()
1651                              .GetLValueReferenceType());
1652   TypeFromParser parser_type(m_clang_ast_context->GetBasicType(eBasicTypeVoid)
1653                                  .GetPointerType()
1654                                  .GetLValueReferenceType());
1655   NamedDecl *var_decl = context.AddVarDecl(parser_type);
1656 
1657   std::string decl_name(context.m_decl_name.getAsString());
1658   ConstString entity_name(decl_name.c_str());
1659   ClangExpressionVariable *entity(new ClangExpressionVariable(
1660       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name,
1661       user_type, m_parser_vars->m_target_info.byte_order,
1662       m_parser_vars->m_target_info.address_byte_size));
1663   m_found_entities.AddNewlyConstructedVariable(entity);
1664 
1665   entity->EnableParserVars(GetParserID());
1666   ClangExpressionVariable::ParserVars *parser_vars =
1667       entity->GetParserVars(GetParserID());
1668 
1669   const Address symbol_address = symbol.GetAddress();
1670   lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1671 
1672   // parser_vars->m_lldb_value.SetContext(Value::ContextType::ClangType,
1673   // user_type.GetOpaqueQualType());
1674   parser_vars->m_lldb_value.SetCompilerType(user_type);
1675   parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1676   parser_vars->m_lldb_value.SetValueType(Value::ValueType::LoadAddress);
1677 
1678   parser_vars->m_named_decl = var_decl;
1679   parser_vars->m_llvm_value = nullptr;
1680   parser_vars->m_lldb_sym = &symbol;
1681 
1682   LLDB_LOG(log, "  CEDM::FEVD Found variable {1}, returned\n{2}", decl_name,
1683            ClangUtil::DumpDecl(var_decl));
1684 }
1685 
1686 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context,
1687                                             const RegisterInfo *reg_info) {
1688   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1689 
1690   CompilerType clang_type =
1691       m_clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1692           reg_info->encoding, reg_info->byte_size * 8);
1693 
1694   if (!clang_type) {
1695     LLDB_LOG(log, "  Tried to add a type for {0}, but couldn't get one",
1696              context.m_decl_name.getAsString());
1697     return;
1698   }
1699 
1700   TypeFromParser parser_clang_type(clang_type);
1701 
1702   NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
1703 
1704   ClangExpressionVariable *entity(new ClangExpressionVariable(
1705       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1706       m_parser_vars->m_target_info.byte_order,
1707       m_parser_vars->m_target_info.address_byte_size));
1708   m_found_entities.AddNewlyConstructedVariable(entity);
1709 
1710   std::string decl_name(context.m_decl_name.getAsString());
1711   entity->SetName(ConstString(decl_name.c_str()));
1712   entity->SetRegisterInfo(reg_info);
1713   entity->EnableParserVars(GetParserID());
1714   ClangExpressionVariable::ParserVars *parser_vars =
1715       entity->GetParserVars(GetParserID());
1716   parser_vars->m_named_decl = var_decl;
1717   parser_vars->m_llvm_value = nullptr;
1718   parser_vars->m_lldb_value.Clear();
1719   entity->m_flags |= ClangExpressionVariable::EVBareRegister;
1720 
1721   LLDB_LOG(log, "  CEDM::FEVD Added register {1}, returned\n{2}",
1722            context.m_decl_name.getAsString(), ClangUtil::DumpDecl(var_decl));
1723 }
1724 
1725 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context,
1726                                             Function *function,
1727                                             Symbol *symbol) {
1728   assert(m_parser_vars.get());
1729 
1730   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1731 
1732   NamedDecl *function_decl = nullptr;
1733   Address fun_address;
1734   CompilerType function_clang_type;
1735 
1736   bool is_indirect_function = false;
1737 
1738   if (function) {
1739     Type *function_type = function->GetType();
1740 
1741     const auto lang = function->GetCompileUnit()->GetLanguage();
1742     const auto name = function->GetMangled().GetMangledName().AsCString();
1743     const bool extern_c = (Language::LanguageIsC(lang) &&
1744                            !CPlusPlusLanguage::IsCPPMangledName(name)) ||
1745                           (Language::LanguageIsObjC(lang) &&
1746                            !Language::LanguageIsCPlusPlus(lang));
1747 
1748     if (!extern_c) {
1749       TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
1750       if (llvm::isa<TypeSystemClang>(type_system)) {
1751         clang::DeclContext *src_decl_context =
1752             (clang::DeclContext *)function->GetDeclContext()
1753                 .GetOpaqueDeclContext();
1754         clang::FunctionDecl *src_function_decl =
1755             llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
1756         if (src_function_decl &&
1757             src_function_decl->getTemplateSpecializationInfo()) {
1758           clang::FunctionTemplateDecl *function_template =
1759               src_function_decl->getTemplateSpecializationInfo()->getTemplate();
1760           clang::FunctionTemplateDecl *copied_function_template =
1761               llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(
1762                   CopyDecl(function_template));
1763           if (copied_function_template) {
1764             if (log) {
1765               StreamString ss;
1766 
1767               function->DumpSymbolContext(&ss);
1768 
1769               LLDB_LOG(log,
1770                        "  CEDM::FEVD Imported decl for function template"
1771                        " {1} (description {2}), returned\n{3}",
1772                        copied_function_template->getNameAsString(),
1773                        ss.GetData(),
1774                        ClangUtil::DumpDecl(copied_function_template));
1775             }
1776 
1777             context.AddNamedDecl(copied_function_template);
1778           }
1779         } else if (src_function_decl) {
1780           if (clang::FunctionDecl *copied_function_decl =
1781                   llvm::dyn_cast_or_null<clang::FunctionDecl>(
1782                       CopyDecl(src_function_decl))) {
1783             if (log) {
1784               StreamString ss;
1785 
1786               function->DumpSymbolContext(&ss);
1787 
1788               LLDB_LOG(log,
1789                        "  CEDM::FEVD Imported decl for function {1} "
1790                        "(description {2}), returned\n{3}",
1791                        copied_function_decl->getNameAsString(), ss.GetData(),
1792                        ClangUtil::DumpDecl(copied_function_decl));
1793             }
1794 
1795             context.AddNamedDecl(copied_function_decl);
1796             return;
1797           } else {
1798             LLDB_LOG(log, "  Failed to import the function decl for '{0}'",
1799                      src_function_decl->getName());
1800           }
1801         }
1802       }
1803     }
1804 
1805     if (!function_type) {
1806       LLDB_LOG(log, "  Skipped a function because it has no type");
1807       return;
1808     }
1809 
1810     function_clang_type = function_type->GetFullCompilerType();
1811 
1812     if (!function_clang_type) {
1813       LLDB_LOG(log, "  Skipped a function because it has no Clang type");
1814       return;
1815     }
1816 
1817     fun_address = function->GetAddressRange().GetBaseAddress();
1818 
1819     CompilerType copied_function_type = GuardedCopyType(function_clang_type);
1820     if (copied_function_type) {
1821       function_decl = context.AddFunDecl(copied_function_type, extern_c);
1822 
1823       if (!function_decl) {
1824         LLDB_LOG(log, "  Failed to create a function decl for '{0}' ({1:x})",
1825                  function_type->GetName(), function_type->GetID());
1826 
1827         return;
1828       }
1829     } else {
1830       // We failed to copy the type we found
1831       LLDB_LOG(log,
1832                "  Failed to import the function type '{0}' ({1:x})"
1833                " into the expression parser AST contenxt",
1834                function_type->GetName(), function_type->GetID());
1835 
1836       return;
1837     }
1838   } else if (symbol) {
1839     fun_address = symbol->GetAddress();
1840     function_decl = context.AddGenericFunDecl();
1841     is_indirect_function = symbol->IsIndirect();
1842   } else {
1843     LLDB_LOG(log, "  AddOneFunction called with no function and no symbol");
1844     return;
1845   }
1846 
1847   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1848 
1849   lldb::addr_t load_addr =
1850       fun_address.GetCallableLoadAddress(target, is_indirect_function);
1851 
1852   ClangExpressionVariable *entity(new ClangExpressionVariable(
1853       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1854       m_parser_vars->m_target_info.byte_order,
1855       m_parser_vars->m_target_info.address_byte_size));
1856   m_found_entities.AddNewlyConstructedVariable(entity);
1857 
1858   std::string decl_name(context.m_decl_name.getAsString());
1859   entity->SetName(ConstString(decl_name.c_str()));
1860   entity->SetCompilerType(function_clang_type);
1861   entity->EnableParserVars(GetParserID());
1862 
1863   ClangExpressionVariable::ParserVars *parser_vars =
1864       entity->GetParserVars(GetParserID());
1865 
1866   if (load_addr != LLDB_INVALID_ADDRESS) {
1867     parser_vars->m_lldb_value.SetValueType(Value::ValueType::LoadAddress);
1868     parser_vars->m_lldb_value.GetScalar() = load_addr;
1869   } else {
1870     // We have to try finding a file address.
1871 
1872     lldb::addr_t file_addr = fun_address.GetFileAddress();
1873 
1874     parser_vars->m_lldb_value.SetValueType(Value::ValueType::FileAddress);
1875     parser_vars->m_lldb_value.GetScalar() = file_addr;
1876   }
1877 
1878   parser_vars->m_named_decl = function_decl;
1879   parser_vars->m_llvm_value = nullptr;
1880 
1881   if (log) {
1882     StreamString ss;
1883 
1884     fun_address.Dump(&ss,
1885                      m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1886                      Address::DumpStyleResolvedDescription);
1887 
1888     LLDB_LOG(log,
1889              "  CEDM::FEVD Found {1} function {2} (description {3}), "
1890              "returned\n{4}",
1891              (function ? "specific" : "generic"), decl_name, ss.GetData(),
1892              ClangUtil::DumpDecl(function_decl));
1893   }
1894 }
1895 
1896 void ClangExpressionDeclMap::AddContextClassType(NameSearchContext &context,
1897                                                  const TypeFromUser &ut) {
1898   CompilerType copied_clang_type = GuardedCopyType(ut);
1899 
1900   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1901 
1902   if (!copied_clang_type) {
1903     LLDB_LOG(log,
1904              "ClangExpressionDeclMap::AddThisType - Couldn't import the type");
1905 
1906     return;
1907   }
1908 
1909   if (copied_clang_type.IsAggregateType() &&
1910       copied_clang_type.GetCompleteType()) {
1911     CompilerType void_clang_type =
1912         m_clang_ast_context->GetBasicType(eBasicTypeVoid);
1913     CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
1914 
1915     CompilerType method_type = m_clang_ast_context->CreateFunctionType(
1916         void_clang_type, &void_ptr_clang_type, 1, false, 0);
1917 
1918     const bool is_virtual = false;
1919     const bool is_static = false;
1920     const bool is_inline = false;
1921     const bool is_explicit = false;
1922     const bool is_attr_used = true;
1923     const bool is_artificial = false;
1924 
1925     CXXMethodDecl *method_decl = m_clang_ast_context->AddMethodToCXXRecordType(
1926         copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr,
1927         method_type, lldb::eAccessPublic, is_virtual, is_static, is_inline,
1928         is_explicit, is_attr_used, is_artificial);
1929 
1930     LLDB_LOG(log,
1931              "  CEDM::AddThisType Added function $__lldb_expr "
1932              "(description {0}) for this type\n{1}",
1933              ClangUtil::ToString(copied_clang_type),
1934              ClangUtil::DumpDecl(method_decl));
1935   }
1936 
1937   if (!copied_clang_type.IsValid())
1938     return;
1939 
1940   TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(
1941       QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
1942 
1943   if (!type_source_info)
1944     return;
1945 
1946   // Construct a typedef type because if "*this" is a templated type we can't
1947   // just return ClassTemplateSpecializationDecls in response to name queries.
1948   // Using a typedef makes this much more robust.
1949 
1950   TypedefDecl *typedef_decl = TypedefDecl::Create(
1951       *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(),
1952       SourceLocation(), context.m_decl_name.getAsIdentifierInfo(),
1953       type_source_info);
1954 
1955   if (!typedef_decl)
1956     return;
1957 
1958   context.AddNamedDecl(typedef_decl);
1959 
1960   return;
1961 }
1962 
1963 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
1964                                         const TypeFromUser &ut) {
1965   CompilerType copied_clang_type = GuardedCopyType(ut);
1966 
1967   if (!copied_clang_type) {
1968     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1969 
1970     LLDB_LOG(log,
1971              "ClangExpressionDeclMap::AddOneType - Couldn't import the type");
1972 
1973     return;
1974   }
1975 
1976   context.AddTypeDecl(copied_clang_type);
1977 }
1978