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