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   const bool include_inlines = false;
1224   SymbolContextList sc_list;
1225   if (namespace_decl && module_sp) {
1226     const bool include_symbols = false;
1227 
1228     module_sp->FindFunctions(name, namespace_decl, eFunctionNameTypeBase,
1229                              include_symbols, include_inlines, sc_list);
1230   } else if (target && !namespace_decl) {
1231     const bool include_symbols = true;
1232 
1233     // TODO Fix FindFunctions so that it doesn't return
1234     //   instance methods for eFunctionNameTypeBase.
1235 
1236     target->GetImages().FindFunctions(
1237         name, eFunctionNameTypeFull | eFunctionNameTypeBase, include_symbols,
1238         include_inlines, sc_list);
1239   }
1240 
1241   // If we found more than one function, see if we can use the frame's decl
1242   // context to remove functions that are shadowed by other functions which
1243   // match in type but are nearer in scope.
1244   //
1245   // AddOneFunction will not add a function whose type has already been
1246   // added, so if there's another function in the list with a matching type,
1247   // check to see if their decl context is a parent of the current frame's or
1248   // was imported via a and using statement, and pick the best match
1249   // according to lookup rules.
1250   if (sc_list.GetSize() > 1) {
1251     // Collect some info about our frame's context.
1252     StackFrame *frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1253     SymbolContext frame_sym_ctx;
1254     if (frame != nullptr)
1255       frame_sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1256                                               lldb::eSymbolContextBlock);
1257     CompilerDeclContext frame_decl_context =
1258         frame_sym_ctx.block != nullptr ? frame_sym_ctx.block->GetDeclContext()
1259                                        : CompilerDeclContext();
1260 
1261     // We can't do this without a compiler decl context for our frame.
1262     if (frame_decl_context) {
1263       sc_list = SearchFunctionsInSymbolContexts(sc_list, frame_decl_context);
1264     }
1265   }
1266 
1267   if (sc_list.GetSize()) {
1268     Symbol *extern_symbol = nullptr;
1269     Symbol *non_extern_symbol = nullptr;
1270 
1271     for (uint32_t index = 0, num_indices = sc_list.GetSize();
1272          index < num_indices; ++index) {
1273       SymbolContext sym_ctx;
1274       sc_list.GetContextAtIndex(index, sym_ctx);
1275 
1276       if (sym_ctx.function) {
1277         CompilerDeclContext decl_ctx = sym_ctx.function->GetDeclContext();
1278 
1279         if (!decl_ctx)
1280           continue;
1281 
1282         // Filter out class/instance methods.
1283         if (decl_ctx.IsClassMethod(nullptr, nullptr, nullptr))
1284           continue;
1285 
1286         AddOneFunction(context, sym_ctx.function, nullptr);
1287         context.m_found_function_with_type_info = true;
1288         context.m_found_function = true;
1289       } else if (sym_ctx.symbol) {
1290         if (sym_ctx.symbol->GetType() == eSymbolTypeReExported && target) {
1291           sym_ctx.symbol = sym_ctx.symbol->ResolveReExportedSymbol(*target);
1292           if (sym_ctx.symbol == nullptr)
1293             continue;
1294         }
1295 
1296         if (sym_ctx.symbol->IsExternal())
1297           extern_symbol = sym_ctx.symbol;
1298         else
1299           non_extern_symbol = sym_ctx.symbol;
1300       }
1301     }
1302 
1303     if (!context.m_found_function_with_type_info) {
1304       for (clang::NamedDecl *decl : decls_from_modules) {
1305         if (llvm::isa<clang::FunctionDecl>(decl)) {
1306           clang::NamedDecl *copied_decl =
1307               llvm::cast_or_null<FunctionDecl>(CopyDecl(decl));
1308           if (copied_decl) {
1309             context.AddNamedDecl(copied_decl);
1310             context.m_found_function_with_type_info = true;
1311           }
1312         }
1313       }
1314     }
1315 
1316     if (!context.m_found_function_with_type_info) {
1317       if (extern_symbol) {
1318         AddOneFunction(context, nullptr, extern_symbol);
1319         context.m_found_function = true;
1320       } else if (non_extern_symbol) {
1321         AddOneFunction(context, nullptr, non_extern_symbol);
1322         context.m_found_function = true;
1323       }
1324     }
1325   }
1326 }
1327 
1328 void ClangExpressionDeclMap::FindExternalVisibleDecls(
1329     NameSearchContext &context, lldb::ModuleSP module_sp,
1330     const CompilerDeclContext &namespace_decl) {
1331   assert(m_ast_context);
1332 
1333   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1334 
1335   const ConstString name(context.m_decl_name.getAsString().c_str());
1336   if (IgnoreName(name, false))
1337     return;
1338 
1339   // Only look for functions by name out in our symbols if the function doesn't
1340   // start with our phony prefix of '$'
1341 
1342   Target *target = nullptr;
1343   StackFrame *frame = nullptr;
1344   SymbolContext sym_ctx;
1345   if (m_parser_vars) {
1346     target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1347     frame = m_parser_vars->m_exe_ctx.GetFramePtr();
1348   }
1349   if (frame != nullptr)
1350     sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction |
1351                                       lldb::eSymbolContextBlock);
1352 
1353   // Try the persistent decls, which take precedence over all else.
1354   if (!namespace_decl)
1355     SearchPersistenDecls(context, name);
1356 
1357   if (name.GetStringRef().startswith("$") && !namespace_decl) {
1358     if (name == "$__lldb_class") {
1359       LookUpLldbClass(context);
1360       return;
1361     }
1362 
1363     if (name == "$__lldb_objc_class") {
1364       LookUpLldbObjCClass(context);
1365       return;
1366     }
1367     if (name == g_lldb_local_vars_namespace_cstr) {
1368       LookupLocalVarNamespace(sym_ctx, context);
1369       return;
1370     }
1371 
1372     // any other $__lldb names should be weeded out now
1373     if (name.GetStringRef().startswith("$__lldb"))
1374       return;
1375 
1376     // No ParserVars means we can't do register or variable lookup.
1377     if (!m_parser_vars || !m_parser_vars->m_persistent_vars)
1378       return;
1379 
1380     ExpressionVariableSP pvar_sp(
1381         m_parser_vars->m_persistent_vars->GetVariable(name));
1382 
1383     if (pvar_sp) {
1384       AddOneVariable(context, pvar_sp);
1385       return;
1386     }
1387 
1388     assert(name.GetStringRef().startswith("$"));
1389     llvm::StringRef reg_name = name.GetStringRef().substr(1);
1390 
1391     if (m_parser_vars->m_exe_ctx.GetRegisterContext()) {
1392       const RegisterInfo *reg_info(
1393           m_parser_vars->m_exe_ctx.GetRegisterContext()->GetRegisterInfoByName(
1394               reg_name));
1395 
1396       if (reg_info) {
1397         LLDB_LOG(log, "  CEDM::FEVD Found register {0}", reg_info->name);
1398 
1399         AddOneRegister(context, reg_info);
1400       }
1401     }
1402     return;
1403   }
1404 
1405   bool local_var_lookup = !namespace_decl || (namespace_decl.GetName() ==
1406                                               g_lldb_local_vars_namespace_cstr);
1407   if (frame && local_var_lookup)
1408     if (LookupLocalVariable(context, name, sym_ctx, namespace_decl))
1409       return;
1410 
1411   if (target) {
1412     ValueObjectSP valobj;
1413     VariableSP var;
1414     var = FindGlobalVariable(*target, module_sp, name, namespace_decl);
1415 
1416     if (var) {
1417       valobj = ValueObjectVariable::Create(target, var);
1418       AddOneVariable(context, var, valobj);
1419       context.m_found_variable = true;
1420       return;
1421     }
1422   }
1423 
1424   LookupFunction(context, module_sp, name, namespace_decl);
1425 
1426   // Try the modules next.
1427   if (!context.m_found_function_with_type_info)
1428     LookupInModulesDeclVendor(context, name);
1429 
1430   if (target && !context.m_found_variable && !namespace_decl) {
1431     // We couldn't find a non-symbol variable for this.  Now we'll hunt for a
1432     // generic data symbol, and -- if it is found -- treat it as a variable.
1433     Status error;
1434 
1435     const Symbol *data_symbol =
1436         m_parser_vars->m_sym_ctx.FindBestGlobalDataSymbol(name, error);
1437 
1438     if (!error.Success()) {
1439       const unsigned diag_id =
1440           m_ast_context->getDiagnostics().getCustomDiagID(
1441               clang::DiagnosticsEngine::Level::Error, "%0");
1442       m_ast_context->getDiagnostics().Report(diag_id) << error.AsCString();
1443     }
1444 
1445     if (data_symbol) {
1446       std::string warning("got name from symbols: ");
1447       warning.append(name.AsCString());
1448       const unsigned diag_id =
1449           m_ast_context->getDiagnostics().getCustomDiagID(
1450               clang::DiagnosticsEngine::Level::Warning, "%0");
1451       m_ast_context->getDiagnostics().Report(diag_id) << warning.c_str();
1452       AddOneGenericVariable(context, *data_symbol);
1453       context.m_found_variable = true;
1454     }
1455   }
1456 }
1457 
1458 bool ClangExpressionDeclMap::GetVariableValue(VariableSP &var,
1459                                               lldb_private::Value &var_location,
1460                                               TypeFromUser *user_type,
1461                                               TypeFromParser *parser_type) {
1462   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1463 
1464   Type *var_type = var->GetType();
1465 
1466   if (!var_type) {
1467     LLDB_LOG(log, "Skipped a definition because it has no type");
1468     return false;
1469   }
1470 
1471   CompilerType var_clang_type = var_type->GetFullCompilerType();
1472 
1473   if (!var_clang_type) {
1474     LLDB_LOG(log, "Skipped a definition because it has no Clang type");
1475     return false;
1476   }
1477 
1478   TypeSystemClang *clang_ast = llvm::dyn_cast_or_null<TypeSystemClang>(
1479       var_type->GetForwardCompilerType().GetTypeSystem());
1480 
1481   if (!clang_ast) {
1482     LLDB_LOG(log, "Skipped a definition because it has no Clang AST");
1483     return false;
1484   }
1485 
1486   DWARFExpression &var_location_expr = var->LocationExpression();
1487 
1488   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1489   Status err;
1490 
1491   if (var->GetLocationIsConstantValueData()) {
1492     DataExtractor const_value_extractor;
1493 
1494     if (var_location_expr.GetExpressionData(const_value_extractor)) {
1495       var_location = Value(const_value_extractor.GetDataStart(),
1496                            const_value_extractor.GetByteSize());
1497       var_location.SetValueType(Value::ValueType::HostAddress);
1498     } else {
1499       LLDB_LOG(log, "Error evaluating constant variable: {0}", err.AsCString());
1500       return false;
1501     }
1502   }
1503 
1504   CompilerType type_to_use = GuardedCopyType(var_clang_type);
1505 
1506   if (!type_to_use) {
1507     LLDB_LOG(log,
1508              "Couldn't copy a variable's type into the parser's AST context");
1509 
1510     return false;
1511   }
1512 
1513   if (parser_type)
1514     *parser_type = TypeFromParser(type_to_use);
1515 
1516   if (var_location.GetContextType() == Value::ContextType::Invalid)
1517     var_location.SetCompilerType(type_to_use);
1518 
1519   if (var_location.GetValueType() == Value::ValueType::FileAddress) {
1520     SymbolContext var_sc;
1521     var->CalculateSymbolContext(&var_sc);
1522 
1523     if (!var_sc.module_sp)
1524       return false;
1525 
1526     Address so_addr(var_location.GetScalar().ULongLong(),
1527                     var_sc.module_sp->GetSectionList());
1528 
1529     lldb::addr_t load_addr = so_addr.GetLoadAddress(target);
1530 
1531     if (load_addr != LLDB_INVALID_ADDRESS) {
1532       var_location.GetScalar() = load_addr;
1533       var_location.SetValueType(Value::ValueType::LoadAddress);
1534     }
1535   }
1536 
1537   if (user_type)
1538     *user_type = TypeFromUser(var_clang_type);
1539 
1540   return true;
1541 }
1542 
1543 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1544                                             VariableSP var,
1545                                             ValueObjectSP valobj) {
1546   assert(m_parser_vars.get());
1547 
1548   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1549 
1550   TypeFromUser ut;
1551   TypeFromParser pt;
1552   Value var_location;
1553 
1554   if (!GetVariableValue(var, var_location, &ut, &pt))
1555     return;
1556 
1557   clang::QualType parser_opaque_type =
1558       QualType::getFromOpaquePtr(pt.GetOpaqueQualType());
1559 
1560   if (parser_opaque_type.isNull())
1561     return;
1562 
1563   if (const clang::Type *parser_type = parser_opaque_type.getTypePtr()) {
1564     if (const TagType *tag_type = dyn_cast<TagType>(parser_type))
1565       CompleteType(tag_type->getDecl());
1566     if (const ObjCObjectPointerType *objc_object_ptr_type =
1567             dyn_cast<ObjCObjectPointerType>(parser_type))
1568       CompleteType(objc_object_ptr_type->getInterfaceDecl());
1569   }
1570 
1571   bool is_reference = pt.IsReferenceType();
1572 
1573   NamedDecl *var_decl = nullptr;
1574   if (is_reference)
1575     var_decl = context.AddVarDecl(pt);
1576   else
1577     var_decl = context.AddVarDecl(pt.GetLValueReferenceType());
1578 
1579   std::string decl_name(context.m_decl_name.getAsString());
1580   ConstString entity_name(decl_name.c_str());
1581   ClangExpressionVariable *entity(new ClangExpressionVariable(valobj));
1582   m_found_entities.AddNewlyConstructedVariable(entity);
1583 
1584   assert(entity);
1585   entity->EnableParserVars(GetParserID());
1586   ClangExpressionVariable::ParserVars *parser_vars =
1587       entity->GetParserVars(GetParserID());
1588   parser_vars->m_named_decl = var_decl;
1589   parser_vars->m_llvm_value = nullptr;
1590   parser_vars->m_lldb_value = var_location;
1591   parser_vars->m_lldb_var = var;
1592 
1593   if (is_reference)
1594     entity->m_flags |= ClangExpressionVariable::EVTypeIsReference;
1595 
1596   LLDB_LOG(log, "  CEDM::FEVD Found variable {1}, returned\n{2} (original {3})",
1597            decl_name, ClangUtil::DumpDecl(var_decl), ClangUtil::ToString(ut));
1598 }
1599 
1600 void ClangExpressionDeclMap::AddOneVariable(NameSearchContext &context,
1601                                             ExpressionVariableSP &pvar_sp) {
1602   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1603 
1604   TypeFromUser user_type(
1605       llvm::cast<ClangExpressionVariable>(pvar_sp.get())->GetTypeFromUser());
1606 
1607   TypeFromParser parser_type(GuardedCopyType(user_type));
1608 
1609   if (!parser_type.GetOpaqueQualType()) {
1610     LLDB_LOG(log, "  CEDM::FEVD Couldn't import type for pvar {0}",
1611              pvar_sp->GetName());
1612     return;
1613   }
1614 
1615   NamedDecl *var_decl =
1616       context.AddVarDecl(parser_type.GetLValueReferenceType());
1617 
1618   llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1619       ->EnableParserVars(GetParserID());
1620   ClangExpressionVariable::ParserVars *parser_vars =
1621       llvm::cast<ClangExpressionVariable>(pvar_sp.get())
1622           ->GetParserVars(GetParserID());
1623   parser_vars->m_named_decl = var_decl;
1624   parser_vars->m_llvm_value = nullptr;
1625   parser_vars->m_lldb_value.Clear();
1626 
1627   LLDB_LOG(log, "  CEDM::FEVD Added pvar {1}, returned\n{2}",
1628            pvar_sp->GetName(), ClangUtil::DumpDecl(var_decl));
1629 }
1630 
1631 void ClangExpressionDeclMap::AddOneGenericVariable(NameSearchContext &context,
1632                                                    const Symbol &symbol) {
1633   assert(m_parser_vars.get());
1634 
1635   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1636 
1637   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1638 
1639   if (target == nullptr)
1640     return;
1641 
1642   TypeSystemClang *scratch_ast_context = GetScratchContext(*target);
1643   if (!scratch_ast_context)
1644     return;
1645 
1646   TypeFromUser user_type(scratch_ast_context->GetBasicType(eBasicTypeVoid)
1647                              .GetPointerType()
1648                              .GetLValueReferenceType());
1649   TypeFromParser parser_type(m_clang_ast_context->GetBasicType(eBasicTypeVoid)
1650                                  .GetPointerType()
1651                                  .GetLValueReferenceType());
1652   NamedDecl *var_decl = context.AddVarDecl(parser_type);
1653 
1654   std::string decl_name(context.m_decl_name.getAsString());
1655   ConstString entity_name(decl_name.c_str());
1656   ClangExpressionVariable *entity(new ClangExpressionVariable(
1657       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(), entity_name,
1658       user_type, m_parser_vars->m_target_info.byte_order,
1659       m_parser_vars->m_target_info.address_byte_size));
1660   m_found_entities.AddNewlyConstructedVariable(entity);
1661 
1662   entity->EnableParserVars(GetParserID());
1663   ClangExpressionVariable::ParserVars *parser_vars =
1664       entity->GetParserVars(GetParserID());
1665 
1666   const Address symbol_address = symbol.GetAddress();
1667   lldb::addr_t symbol_load_addr = symbol_address.GetLoadAddress(target);
1668 
1669   // parser_vars->m_lldb_value.SetContext(Value::ContextType::ClangType,
1670   // user_type.GetOpaqueQualType());
1671   parser_vars->m_lldb_value.SetCompilerType(user_type);
1672   parser_vars->m_lldb_value.GetScalar() = symbol_load_addr;
1673   parser_vars->m_lldb_value.SetValueType(Value::ValueType::LoadAddress);
1674 
1675   parser_vars->m_named_decl = var_decl;
1676   parser_vars->m_llvm_value = nullptr;
1677   parser_vars->m_lldb_sym = &symbol;
1678 
1679   LLDB_LOG(log, "  CEDM::FEVD Found variable {1}, returned\n{2}", decl_name,
1680            ClangUtil::DumpDecl(var_decl));
1681 }
1682 
1683 void ClangExpressionDeclMap::AddOneRegister(NameSearchContext &context,
1684                                             const RegisterInfo *reg_info) {
1685   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1686 
1687   CompilerType clang_type =
1688       m_clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
1689           reg_info->encoding, reg_info->byte_size * 8);
1690 
1691   if (!clang_type) {
1692     LLDB_LOG(log, "  Tried to add a type for {0}, but couldn't get one",
1693              context.m_decl_name.getAsString());
1694     return;
1695   }
1696 
1697   TypeFromParser parser_clang_type(clang_type);
1698 
1699   NamedDecl *var_decl = context.AddVarDecl(parser_clang_type);
1700 
1701   ClangExpressionVariable *entity(new ClangExpressionVariable(
1702       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1703       m_parser_vars->m_target_info.byte_order,
1704       m_parser_vars->m_target_info.address_byte_size));
1705   m_found_entities.AddNewlyConstructedVariable(entity);
1706 
1707   std::string decl_name(context.m_decl_name.getAsString());
1708   entity->SetName(ConstString(decl_name.c_str()));
1709   entity->SetRegisterInfo(reg_info);
1710   entity->EnableParserVars(GetParserID());
1711   ClangExpressionVariable::ParserVars *parser_vars =
1712       entity->GetParserVars(GetParserID());
1713   parser_vars->m_named_decl = var_decl;
1714   parser_vars->m_llvm_value = nullptr;
1715   parser_vars->m_lldb_value.Clear();
1716   entity->m_flags |= ClangExpressionVariable::EVBareRegister;
1717 
1718   LLDB_LOG(log, "  CEDM::FEVD Added register {1}, returned\n{2}",
1719            context.m_decl_name.getAsString(), ClangUtil::DumpDecl(var_decl));
1720 }
1721 
1722 void ClangExpressionDeclMap::AddOneFunction(NameSearchContext &context,
1723                                             Function *function,
1724                                             Symbol *symbol) {
1725   assert(m_parser_vars.get());
1726 
1727   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1728 
1729   NamedDecl *function_decl = nullptr;
1730   Address fun_address;
1731   CompilerType function_clang_type;
1732 
1733   bool is_indirect_function = false;
1734 
1735   if (function) {
1736     Type *function_type = function->GetType();
1737 
1738     const auto lang = function->GetCompileUnit()->GetLanguage();
1739     const auto name = function->GetMangled().GetMangledName().AsCString();
1740     const bool extern_c = (Language::LanguageIsC(lang) &&
1741                            !CPlusPlusLanguage::IsCPPMangledName(name)) ||
1742                           (Language::LanguageIsObjC(lang) &&
1743                            !Language::LanguageIsCPlusPlus(lang));
1744 
1745     if (!extern_c) {
1746       TypeSystem *type_system = function->GetDeclContext().GetTypeSystem();
1747       if (llvm::isa<TypeSystemClang>(type_system)) {
1748         clang::DeclContext *src_decl_context =
1749             (clang::DeclContext *)function->GetDeclContext()
1750                 .GetOpaqueDeclContext();
1751         clang::FunctionDecl *src_function_decl =
1752             llvm::dyn_cast_or_null<clang::FunctionDecl>(src_decl_context);
1753         if (src_function_decl &&
1754             src_function_decl->getTemplateSpecializationInfo()) {
1755           clang::FunctionTemplateDecl *function_template =
1756               src_function_decl->getTemplateSpecializationInfo()->getTemplate();
1757           clang::FunctionTemplateDecl *copied_function_template =
1758               llvm::dyn_cast_or_null<clang::FunctionTemplateDecl>(
1759                   CopyDecl(function_template));
1760           if (copied_function_template) {
1761             if (log) {
1762               StreamString ss;
1763 
1764               function->DumpSymbolContext(&ss);
1765 
1766               LLDB_LOG(log,
1767                        "  CEDM::FEVD Imported decl for function template"
1768                        " {1} (description {2}), returned\n{3}",
1769                        copied_function_template->getNameAsString(),
1770                        ss.GetData(),
1771                        ClangUtil::DumpDecl(copied_function_template));
1772             }
1773 
1774             context.AddNamedDecl(copied_function_template);
1775           }
1776         } else if (src_function_decl) {
1777           if (clang::FunctionDecl *copied_function_decl =
1778                   llvm::dyn_cast_or_null<clang::FunctionDecl>(
1779                       CopyDecl(src_function_decl))) {
1780             if (log) {
1781               StreamString ss;
1782 
1783               function->DumpSymbolContext(&ss);
1784 
1785               LLDB_LOG(log,
1786                        "  CEDM::FEVD Imported decl for function {1} "
1787                        "(description {2}), returned\n{3}",
1788                        copied_function_decl->getNameAsString(), ss.GetData(),
1789                        ClangUtil::DumpDecl(copied_function_decl));
1790             }
1791 
1792             context.AddNamedDecl(copied_function_decl);
1793             return;
1794           } else {
1795             LLDB_LOG(log, "  Failed to import the function decl for '{0}'",
1796                      src_function_decl->getName());
1797           }
1798         }
1799       }
1800     }
1801 
1802     if (!function_type) {
1803       LLDB_LOG(log, "  Skipped a function because it has no type");
1804       return;
1805     }
1806 
1807     function_clang_type = function_type->GetFullCompilerType();
1808 
1809     if (!function_clang_type) {
1810       LLDB_LOG(log, "  Skipped a function because it has no Clang type");
1811       return;
1812     }
1813 
1814     fun_address = function->GetAddressRange().GetBaseAddress();
1815 
1816     CompilerType copied_function_type = GuardedCopyType(function_clang_type);
1817     if (copied_function_type) {
1818       function_decl = context.AddFunDecl(copied_function_type, extern_c);
1819 
1820       if (!function_decl) {
1821         LLDB_LOG(log, "  Failed to create a function decl for '{0}' ({1:x})",
1822                  function_type->GetName(), function_type->GetID());
1823 
1824         return;
1825       }
1826     } else {
1827       // We failed to copy the type we found
1828       LLDB_LOG(log,
1829                "  Failed to import the function type '{0}' ({1:x})"
1830                " into the expression parser AST contenxt",
1831                function_type->GetName(), function_type->GetID());
1832 
1833       return;
1834     }
1835   } else if (symbol) {
1836     fun_address = symbol->GetAddress();
1837     function_decl = context.AddGenericFunDecl();
1838     is_indirect_function = symbol->IsIndirect();
1839   } else {
1840     LLDB_LOG(log, "  AddOneFunction called with no function and no symbol");
1841     return;
1842   }
1843 
1844   Target *target = m_parser_vars->m_exe_ctx.GetTargetPtr();
1845 
1846   lldb::addr_t load_addr =
1847       fun_address.GetCallableLoadAddress(target, is_indirect_function);
1848 
1849   ClangExpressionVariable *entity(new ClangExpressionVariable(
1850       m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1851       m_parser_vars->m_target_info.byte_order,
1852       m_parser_vars->m_target_info.address_byte_size));
1853   m_found_entities.AddNewlyConstructedVariable(entity);
1854 
1855   std::string decl_name(context.m_decl_name.getAsString());
1856   entity->SetName(ConstString(decl_name.c_str()));
1857   entity->SetCompilerType(function_clang_type);
1858   entity->EnableParserVars(GetParserID());
1859 
1860   ClangExpressionVariable::ParserVars *parser_vars =
1861       entity->GetParserVars(GetParserID());
1862 
1863   if (load_addr != LLDB_INVALID_ADDRESS) {
1864     parser_vars->m_lldb_value.SetValueType(Value::ValueType::LoadAddress);
1865     parser_vars->m_lldb_value.GetScalar() = load_addr;
1866   } else {
1867     // We have to try finding a file address.
1868 
1869     lldb::addr_t file_addr = fun_address.GetFileAddress();
1870 
1871     parser_vars->m_lldb_value.SetValueType(Value::ValueType::FileAddress);
1872     parser_vars->m_lldb_value.GetScalar() = file_addr;
1873   }
1874 
1875   parser_vars->m_named_decl = function_decl;
1876   parser_vars->m_llvm_value = nullptr;
1877 
1878   if (log) {
1879     StreamString ss;
1880 
1881     fun_address.Dump(&ss,
1882                      m_parser_vars->m_exe_ctx.GetBestExecutionContextScope(),
1883                      Address::DumpStyleResolvedDescription);
1884 
1885     LLDB_LOG(log,
1886              "  CEDM::FEVD Found {1} function {2} (description {3}), "
1887              "returned\n{4}",
1888              (function ? "specific" : "generic"), decl_name, ss.GetData(),
1889              ClangUtil::DumpDecl(function_decl));
1890   }
1891 }
1892 
1893 void ClangExpressionDeclMap::AddContextClassType(NameSearchContext &context,
1894                                                  const TypeFromUser &ut) {
1895   CompilerType copied_clang_type = GuardedCopyType(ut);
1896 
1897   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1898 
1899   if (!copied_clang_type) {
1900     LLDB_LOG(log,
1901              "ClangExpressionDeclMap::AddThisType - Couldn't import the type");
1902 
1903     return;
1904   }
1905 
1906   if (copied_clang_type.IsAggregateType() &&
1907       copied_clang_type.GetCompleteType()) {
1908     CompilerType void_clang_type =
1909         m_clang_ast_context->GetBasicType(eBasicTypeVoid);
1910     CompilerType void_ptr_clang_type = void_clang_type.GetPointerType();
1911 
1912     CompilerType method_type = m_clang_ast_context->CreateFunctionType(
1913         void_clang_type, &void_ptr_clang_type, 1, false, 0);
1914 
1915     const bool is_virtual = false;
1916     const bool is_static = false;
1917     const bool is_inline = false;
1918     const bool is_explicit = false;
1919     const bool is_attr_used = true;
1920     const bool is_artificial = false;
1921 
1922     CXXMethodDecl *method_decl = m_clang_ast_context->AddMethodToCXXRecordType(
1923         copied_clang_type.GetOpaqueQualType(), "$__lldb_expr", nullptr,
1924         method_type, lldb::eAccessPublic, is_virtual, is_static, is_inline,
1925         is_explicit, is_attr_used, is_artificial);
1926 
1927     LLDB_LOG(log,
1928              "  CEDM::AddThisType Added function $__lldb_expr "
1929              "(description {0}) for this type\n{1}",
1930              ClangUtil::ToString(copied_clang_type),
1931              ClangUtil::DumpDecl(method_decl));
1932   }
1933 
1934   if (!copied_clang_type.IsValid())
1935     return;
1936 
1937   TypeSourceInfo *type_source_info = m_ast_context->getTrivialTypeSourceInfo(
1938       QualType::getFromOpaquePtr(copied_clang_type.GetOpaqueQualType()));
1939 
1940   if (!type_source_info)
1941     return;
1942 
1943   // Construct a typedef type because if "*this" is a templated type we can't
1944   // just return ClassTemplateSpecializationDecls in response to name queries.
1945   // Using a typedef makes this much more robust.
1946 
1947   TypedefDecl *typedef_decl = TypedefDecl::Create(
1948       *m_ast_context, m_ast_context->getTranslationUnitDecl(), SourceLocation(),
1949       SourceLocation(), context.m_decl_name.getAsIdentifierInfo(),
1950       type_source_info);
1951 
1952   if (!typedef_decl)
1953     return;
1954 
1955   context.AddNamedDecl(typedef_decl);
1956 
1957   return;
1958 }
1959 
1960 void ClangExpressionDeclMap::AddOneType(NameSearchContext &context,
1961                                         const TypeFromUser &ut) {
1962   CompilerType copied_clang_type = GuardedCopyType(ut);
1963 
1964   if (!copied_clang_type) {
1965     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1966 
1967     LLDB_LOG(log,
1968              "ClangExpressionDeclMap::AddOneType - Couldn't import the type");
1969 
1970     return;
1971   }
1972 
1973   context.AddTypeDecl(copied_clang_type);
1974 }
1975