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