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