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