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