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