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