1314564Sdim//===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===//
2292932Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6292932Sdim//
7292932Sdim//===----------------------------------------------------------------------===//
8292932Sdim
9292932Sdim#include "ClangASTSource.h"
10292932Sdim
11360784Sdim#include "ClangDeclVendor.h"
12292932Sdim#include "ClangModulesDeclVendor.h"
13292932Sdim
14292932Sdim#include "lldb/Core/Module.h"
15292932Sdim#include "lldb/Core/ModuleList.h"
16292932Sdim#include "lldb/Symbol/ClangASTContext.h"
17309124Sdim#include "lldb/Symbol/ClangUtil.h"
18292932Sdim#include "lldb/Symbol/CompilerDeclContext.h"
19292932Sdim#include "lldb/Symbol/Function.h"
20309124Sdim#include "lldb/Symbol/SymbolFile.h"
21292932Sdim#include "lldb/Symbol/TaggedASTType.h"
22292932Sdim#include "lldb/Target/Target.h"
23321369Sdim#include "lldb/Utility/Log.h"
24309124Sdim#include "clang/AST/ASTContext.h"
25309124Sdim#include "clang/AST/RecordLayout.h"
26292932Sdim
27353358Sdim#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
28353358Sdim
29353358Sdim#include <memory>
30292932Sdim#include <vector>
31292932Sdim
32292932Sdimusing namespace clang;
33292932Sdimusing namespace lldb_private;
34292932Sdim
35341825Sdim// Scoped class that will remove an active lexical decl from the set when it
36341825Sdim// goes out of scope.
37292932Sdimnamespace {
38314564Sdimclass ScopedLexicalDeclEraser {
39314564Sdimpublic:
40314564Sdim  ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
41314564Sdim                          const clang::Decl *decl)
42314564Sdim      : m_active_lexical_decls(decls), m_decl(decl) {}
43292932Sdim
44314564Sdim  ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
45292932Sdim
46314564Sdimprivate:
47314564Sdim  std::set<const clang::Decl *> &m_active_lexical_decls;
48314564Sdim  const clang::Decl *m_decl;
49314564Sdim};
50292932Sdim}
51292932Sdim
52360784SdimClangASTSource::ClangASTSource(const lldb::TargetSP &target,
53360784Sdim                               const lldb::ClangASTImporterSP &importer)
54327952Sdim    : m_import_in_progress(false), m_lookups_enabled(false), m_target(target),
55353358Sdim      m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() {
56360784Sdim  m_ast_importer_sp = importer;
57327952Sdim}
58327952Sdim
59360784Sdimvoid ClangASTSource::InstallASTContext(ClangASTContext &clang_ast_context) {
60360784Sdim  m_ast_context = &clang_ast_context.getASTContext();
61360784Sdim  m_clang_ast_context = &clang_ast_context;
62360784Sdim  m_file_manager = &m_ast_context->getSourceManager().getFileManager();
63360784Sdim  m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
64327952Sdim}
65327952Sdim
66314564SdimClangASTSource::~ClangASTSource() {
67360784Sdim  if (!m_ast_importer_sp)
68360784Sdim    return;
69292932Sdim
70360784Sdim  m_ast_importer_sp->ForgetDestination(m_ast_context);
71360784Sdim
72360784Sdim  if (!m_target)
73360784Sdim    return;
74314564Sdim  // We are in the process of destruction, don't create clang ast context on
75341825Sdim  // demand by passing false to
76341825Sdim  // Target::GetScratchClangASTContext(create_on_demand).
77314564Sdim  ClangASTContext *scratch_clang_ast_context =
78360784Sdim      ClangASTContext::GetScratch(*m_target, false);
79292932Sdim
80314564Sdim  if (!scratch_clang_ast_context)
81314564Sdim    return;
82292932Sdim
83360784Sdim  clang::ASTContext &scratch_ast_context =
84314564Sdim      scratch_clang_ast_context->getASTContext();
85292932Sdim
86360784Sdim  if (m_ast_context != &scratch_ast_context && m_ast_importer_sp)
87360784Sdim    m_ast_importer_sp->ForgetSource(&scratch_ast_context, m_ast_context);
88292932Sdim}
89292932Sdim
90314564Sdimvoid ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
91314564Sdim  if (!m_ast_context)
92314564Sdim    return;
93292932Sdim
94314564Sdim  m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
95314564Sdim  m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
96292932Sdim}
97292932Sdim
98292932Sdim// The core lookup interface.
99314564Sdimbool ClangASTSource::FindExternalVisibleDeclsByName(
100314564Sdim    const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
101314564Sdim  if (!m_ast_context) {
102314564Sdim    SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
103314564Sdim    return false;
104314564Sdim  }
105292932Sdim
106314564Sdim  if (GetImportInProgress()) {
107314564Sdim    SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
108314564Sdim    return false;
109314564Sdim  }
110292932Sdim
111314564Sdim  std::string decl_name(clang_decl_name.getAsString());
112292932Sdim
113314564Sdim  //    if (m_decl_map.DoingASTImport ())
114314564Sdim  //      return DeclContext::lookup_result();
115314564Sdim  //
116314564Sdim  switch (clang_decl_name.getNameKind()) {
117314564Sdim  // Normal identifiers.
118314564Sdim  case DeclarationName::Identifier: {
119314564Sdim    clang::IdentifierInfo *identifier_info =
120314564Sdim        clang_decl_name.getAsIdentifierInfo();
121292932Sdim
122314564Sdim    if (!identifier_info || identifier_info->getBuiltinID() != 0) {
123292932Sdim      SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
124292932Sdim      return false;
125314564Sdim    }
126314564Sdim  } break;
127292932Sdim
128314564Sdim  // Operator names.
129314564Sdim  case DeclarationName::CXXOperatorName:
130314564Sdim  case DeclarationName::CXXLiteralOperatorName:
131314564Sdim    break;
132292932Sdim
133314564Sdim  // Using directives found in this context.
134314564Sdim  // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
135314564Sdim  case DeclarationName::CXXUsingDirective:
136314564Sdim    SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
137314564Sdim    return false;
138292932Sdim
139314564Sdim  case DeclarationName::ObjCZeroArgSelector:
140314564Sdim  case DeclarationName::ObjCOneArgSelector:
141314564Sdim  case DeclarationName::ObjCMultiArgSelector: {
142314564Sdim    llvm::SmallVector<NamedDecl *, 1> method_decls;
143292932Sdim
144314564Sdim    NameSearchContext method_search_context(*this, method_decls,
145314564Sdim                                            clang_decl_name, decl_ctx);
146314564Sdim
147314564Sdim    FindObjCMethodDecls(method_search_context);
148314564Sdim
149314564Sdim    SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
150314564Sdim    return (method_decls.size() > 0);
151314564Sdim  }
152314564Sdim  // These aren't possible in the global context.
153314564Sdim  case DeclarationName::CXXConstructorName:
154314564Sdim  case DeclarationName::CXXDestructorName:
155314564Sdim  case DeclarationName::CXXConversionFunctionName:
156321369Sdim  case DeclarationName::CXXDeductionGuideName:
157314564Sdim    SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
158314564Sdim    return false;
159314564Sdim  }
160314564Sdim
161314564Sdim  if (!GetLookupsEnabled()) {
162341825Sdim    // Wait until we see a '$' at the start of a name before we start doing any
163341825Sdim    // lookups so we can avoid lookup up all of the builtin types.
164314564Sdim    if (!decl_name.empty() && decl_name[0] == '$') {
165314564Sdim      SetLookupsEnabled(true);
166314564Sdim    } else {
167292932Sdim      SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
168292932Sdim      return false;
169292932Sdim    }
170314564Sdim  }
171292932Sdim
172314564Sdim  ConstString const_decl_name(decl_name.c_str());
173292932Sdim
174314564Sdim  const char *uniqued_const_decl_name = const_decl_name.GetCString();
175314564Sdim  if (m_active_lookups.find(uniqued_const_decl_name) !=
176314564Sdim      m_active_lookups.end()) {
177314564Sdim    // We are currently looking up this name...
178314564Sdim    SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
179314564Sdim    return false;
180314564Sdim  }
181314564Sdim  m_active_lookups.insert(uniqued_const_decl_name);
182314564Sdim  //  static uint32_t g_depth = 0;
183314564Sdim  //  ++g_depth;
184314564Sdim  //  printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth,
185314564Sdim  //  uniqued_const_decl_name);
186314564Sdim  llvm::SmallVector<NamedDecl *, 4> name_decls;
187314564Sdim  NameSearchContext name_search_context(*this, name_decls, clang_decl_name,
188314564Sdim                                        decl_ctx);
189314564Sdim  FindExternalVisibleDecls(name_search_context);
190314564Sdim  SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
191314564Sdim  //  --g_depth;
192314564Sdim  m_active_lookups.erase(uniqued_const_decl_name);
193314564Sdim  return (name_decls.size() != 0);
194292932Sdim}
195292932Sdim
196314564Sdimvoid ClangASTSource::CompleteType(TagDecl *tag_decl) {
197314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
198292932Sdim
199314564Sdim  static unsigned int invocation_id = 0;
200314564Sdim  unsigned int current_id = invocation_id++;
201292932Sdim
202314564Sdim  if (log) {
203360784Sdim    LLDB_LOGF(log,
204360784Sdim              "    CompleteTagDecl[%u] on (ASTContext*)%p Completing "
205360784Sdim              "(TagDecl*)%p named %s",
206360784Sdim              current_id, static_cast<void *>(m_ast_context),
207360784Sdim              static_cast<void *>(tag_decl), tag_decl->getName().str().c_str());
208292932Sdim
209360784Sdim    LLDB_LOG(log, "      CTD[%u] Before:\n{0}", current_id,
210360784Sdim             ClangUtil::DumpDecl(tag_decl));
211314564Sdim  }
212292932Sdim
213314564Sdim  auto iter = m_active_lexical_decls.find(tag_decl);
214314564Sdim  if (iter != m_active_lexical_decls.end())
215314564Sdim    return;
216314564Sdim  m_active_lexical_decls.insert(tag_decl);
217314564Sdim  ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
218292932Sdim
219327952Sdim  if (!m_ast_importer_sp) {
220327952Sdim    return;
221327952Sdim  }
222327952Sdim
223314564Sdim  if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
224341825Sdim    // We couldn't complete the type.  Maybe there's a definition somewhere
225341825Sdim    // else that can be completed.
226292932Sdim
227360784Sdim    LLDB_LOGF(log,
228360784Sdim              "      CTD[%u] Type could not be completed in the module in "
229360784Sdim              "which it was first found.",
230360784Sdim              current_id);
231292932Sdim
232314564Sdim    bool found = false;
233292932Sdim
234314564Sdim    DeclContext *decl_ctx = tag_decl->getDeclContext();
235292932Sdim
236314564Sdim    if (const NamespaceDecl *namespace_context =
237314564Sdim            dyn_cast<NamespaceDecl>(decl_ctx)) {
238314564Sdim      ClangASTImporter::NamespaceMapSP namespace_map =
239314564Sdim          m_ast_importer_sp->GetNamespaceMap(namespace_context);
240292932Sdim
241314564Sdim      if (log && log->GetVerbose())
242360784Sdim        LLDB_LOGF(log, "      CTD[%u] Inspecting namespace map %p (%d entries)",
243360784Sdim                  current_id, static_cast<void *>(namespace_map.get()),
244360784Sdim                  static_cast<int>(namespace_map->size()));
245292932Sdim
246314564Sdim      if (!namespace_map)
247314564Sdim        return;
248292932Sdim
249314564Sdim      for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
250314564Sdim                                                    e = namespace_map->end();
251314564Sdim           i != e && !found; ++i) {
252360784Sdim        LLDB_LOGF(log, "      CTD[%u] Searching namespace %s in module %s",
253360784Sdim                  current_id, i->second.GetName().AsCString(),
254360784Sdim                  i->first->GetFileSpec().GetFilename().GetCString());
255292932Sdim
256314564Sdim        TypeList types;
257292932Sdim
258314564Sdim        ConstString name(tag_decl->getName().str().c_str());
259292932Sdim
260344779Sdim        i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types);
261292932Sdim
262314564Sdim        for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
263314564Sdim          lldb::TypeSP type = types.GetTypeAtIndex(ti);
264292932Sdim
265314564Sdim          if (!type)
266314564Sdim            continue;
267292932Sdim
268314564Sdim          CompilerType clang_type(type->GetFullCompilerType());
269292932Sdim
270314564Sdim          if (!ClangUtil::IsClangType(clang_type))
271314564Sdim            continue;
272292932Sdim
273314564Sdim          const TagType *tag_type =
274314564Sdim              ClangUtil::GetQualType(clang_type)->getAs<TagType>();
275292932Sdim
276314564Sdim          if (!tag_type)
277314564Sdim            continue;
278292932Sdim
279314564Sdim          TagDecl *candidate_tag_decl =
280314564Sdim              const_cast<TagDecl *>(tag_type->getDecl());
281292932Sdim
282314564Sdim          if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
283314564Sdim                                                           candidate_tag_decl))
284314564Sdim            found = true;
285292932Sdim        }
286314564Sdim      }
287314564Sdim    } else {
288314564Sdim      TypeList types;
289292932Sdim
290314564Sdim      ConstString name(tag_decl->getName().str().c_str());
291292932Sdim
292314564Sdim      const ModuleList &module_list = m_target->GetImages();
293292932Sdim
294314564Sdim      bool exact_match = false;
295314564Sdim      llvm::DenseSet<SymbolFile *> searched_symbol_files;
296344779Sdim      module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
297314564Sdim                            searched_symbol_files, types);
298292932Sdim
299314564Sdim      for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
300314564Sdim        lldb::TypeSP type = types.GetTypeAtIndex(ti);
301292932Sdim
302314564Sdim        if (!type)
303314564Sdim          continue;
304292932Sdim
305314564Sdim        CompilerType clang_type(type->GetFullCompilerType());
306292932Sdim
307314564Sdim        if (!ClangUtil::IsClangType(clang_type))
308314564Sdim          continue;
309292932Sdim
310314564Sdim        const TagType *tag_type =
311314564Sdim            ClangUtil::GetQualType(clang_type)->getAs<TagType>();
312292932Sdim
313314564Sdim        if (!tag_type)
314314564Sdim          continue;
315292932Sdim
316314564Sdim        TagDecl *candidate_tag_decl =
317314564Sdim            const_cast<TagDecl *>(tag_type->getDecl());
318292932Sdim
319314564Sdim        // We have found a type by basename and we need to make sure the decl
320341825Sdim        // contexts are the same before we can try to complete this type with
321341825Sdim        // another
322314564Sdim        if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
323314564Sdim          continue;
324292932Sdim
325314564Sdim        if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
326314564Sdim                                                         candidate_tag_decl))
327314564Sdim          found = true;
328314564Sdim      }
329292932Sdim    }
330314564Sdim  }
331292932Sdim
332360784Sdim  LLDB_LOG(log, "      [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
333292932Sdim}
334292932Sdim
335314564Sdimvoid ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
336314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
337292932Sdim
338360784Sdim  LLDB_LOGF(log,
339360784Sdim            "    [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing "
340360784Sdim            "an ObjCInterfaceDecl named %s",
341360784Sdim            static_cast<void *>(m_ast_context),
342360784Sdim            interface_decl->getName().str().c_str());
343360784Sdim  LLDB_LOG(log, "      [COID] Before:\n{0}",
344360784Sdim           ClangUtil::DumpDecl(interface_decl));
345292932Sdim
346327952Sdim  if (!m_ast_importer_sp) {
347360784Sdim    lldbassert(0 && "No mechanism for completing a type!");
348327952Sdim    return;
349327952Sdim  }
350327952Sdim
351360784Sdim  ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
352292932Sdim
353360784Sdim  if (original.Valid()) {
354314564Sdim    if (ObjCInterfaceDecl *original_iface_decl =
355360784Sdim            dyn_cast<ObjCInterfaceDecl>(original.decl)) {
356314564Sdim      ObjCInterfaceDecl *complete_iface_decl =
357314564Sdim          GetCompleteObjCInterface(original_iface_decl);
358292932Sdim
359314564Sdim      if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
360321369Sdim        m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
361314564Sdim      }
362292932Sdim    }
363314564Sdim  }
364292932Sdim
365314564Sdim  m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
366292932Sdim
367314564Sdim  if (interface_decl->getSuperClass() &&
368314564Sdim      interface_decl->getSuperClass() != interface_decl)
369314564Sdim    CompleteType(interface_decl->getSuperClass());
370292932Sdim
371314564Sdim  if (log) {
372360784Sdim    LLDB_LOGF(log, "      [COID] After:");
373360784Sdim    LLDB_LOG(log, "      [COID] {0}", ClangUtil::DumpDecl(interface_decl));
374314564Sdim  }
375292932Sdim}
376292932Sdim
377314564Sdimclang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
378327952Sdim    const clang::ObjCInterfaceDecl *interface_decl) {
379314564Sdim  lldb::ProcessSP process(m_target->GetProcessSP());
380292932Sdim
381314564Sdim  if (!process)
382353358Sdim    return nullptr;
383292932Sdim
384353358Sdim  ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
385292932Sdim
386314564Sdim  if (!language_runtime)
387353358Sdim    return nullptr;
388292932Sdim
389314564Sdim  ConstString class_name(interface_decl->getNameAsString().c_str());
390292932Sdim
391314564Sdim  lldb::TypeSP complete_type_sp(
392314564Sdim      language_runtime->LookupInCompleteClassCache(class_name));
393292932Sdim
394314564Sdim  if (!complete_type_sp)
395353358Sdim    return nullptr;
396292932Sdim
397314564Sdim  TypeFromUser complete_type =
398314564Sdim      TypeFromUser(complete_type_sp->GetFullCompilerType());
399314564Sdim  lldb::opaque_compiler_type_t complete_opaque_type =
400314564Sdim      complete_type.GetOpaqueQualType();
401292932Sdim
402314564Sdim  if (!complete_opaque_type)
403353358Sdim    return nullptr;
404292932Sdim
405314564Sdim  const clang::Type *complete_clang_type =
406314564Sdim      QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
407314564Sdim  const ObjCInterfaceType *complete_interface_type =
408314564Sdim      dyn_cast<ObjCInterfaceType>(complete_clang_type);
409292932Sdim
410314564Sdim  if (!complete_interface_type)
411353358Sdim    return nullptr;
412292932Sdim
413314564Sdim  ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
414292932Sdim
415314564Sdim  return complete_iface_decl;
416292932Sdim}
417292932Sdim
418314564Sdimvoid ClangASTSource::FindExternalLexicalDecls(
419314564Sdim    const DeclContext *decl_context,
420314564Sdim    llvm::function_ref<bool(Decl::Kind)> predicate,
421314564Sdim    llvm::SmallVectorImpl<Decl *> &decls) {
422327952Sdim
423360784Sdim  if (!m_ast_importer_sp)
424327952Sdim    return;
425327952Sdim
426314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
427292932Sdim
428314564Sdim  const Decl *context_decl = dyn_cast<Decl>(decl_context);
429292932Sdim
430314564Sdim  if (!context_decl)
431314564Sdim    return;
432292932Sdim
433314564Sdim  auto iter = m_active_lexical_decls.find(context_decl);
434314564Sdim  if (iter != m_active_lexical_decls.end())
435314564Sdim    return;
436314564Sdim  m_active_lexical_decls.insert(context_decl);
437314564Sdim  ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
438292932Sdim
439314564Sdim  static unsigned int invocation_id = 0;
440314564Sdim  unsigned int current_id = invocation_id++;
441292932Sdim
442314564Sdim  if (log) {
443314564Sdim    if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
444360784Sdim      LLDB_LOGF(
445360784Sdim          log,
446314564Sdim          "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p",
447314564Sdim          current_id, static_cast<void *>(m_ast_context),
448314564Sdim          context_named_decl->getNameAsString().c_str(),
449314564Sdim          context_decl->getDeclKindName(),
450314564Sdim          static_cast<const void *>(context_decl));
451314564Sdim    else if (context_decl)
452360784Sdim      LLDB_LOGF(
453360784Sdim          log, "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p",
454314564Sdim          current_id, static_cast<void *>(m_ast_context),
455314564Sdim          context_decl->getDeclKindName(),
456314564Sdim          static_cast<const void *>(context_decl));
457314564Sdim    else
458360784Sdim      LLDB_LOGF(
459360784Sdim          log,
460314564Sdim          "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context",
461314564Sdim          current_id, static_cast<const void *>(m_ast_context));
462314564Sdim  }
463292932Sdim
464360784Sdim  ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
465292932Sdim
466360784Sdim  if (!original.Valid())
467314564Sdim    return;
468292932Sdim
469360784Sdim  LLDB_LOG(
470360784Sdim      log, "  FELD[{0}] Original decl (ASTContext*){1:x} (Decl*){2:x}:\n{3}",
471360784Sdim      current_id, static_cast<void *>(original.ctx),
472360784Sdim      static_cast<void *>(original.decl), ClangUtil::DumpDecl(original.decl));
473292932Sdim
474314564Sdim  if (ObjCInterfaceDecl *original_iface_decl =
475360784Sdim          dyn_cast<ObjCInterfaceDecl>(original.decl)) {
476314564Sdim    ObjCInterfaceDecl *complete_iface_decl =
477314564Sdim        GetCompleteObjCInterface(original_iface_decl);
478292932Sdim
479314564Sdim    if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
480360784Sdim      original.decl = complete_iface_decl;
481360784Sdim      original.ctx = &complete_iface_decl->getASTContext();
482292932Sdim
483321369Sdim      m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
484292932Sdim    }
485314564Sdim  }
486292932Sdim
487360784Sdim  if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
488360784Sdim    ExternalASTSource *external_source = original.ctx->getExternalSource();
489292932Sdim
490314564Sdim    if (external_source)
491314564Sdim      external_source->CompleteType(original_tag_decl);
492314564Sdim  }
493292932Sdim
494314564Sdim  const DeclContext *original_decl_context =
495360784Sdim      dyn_cast<DeclContext>(original.decl);
496292932Sdim
497314564Sdim  if (!original_decl_context)
498314564Sdim    return;
499292932Sdim
500353358Sdim  // Indicates whether we skipped any Decls of the original DeclContext.
501353358Sdim  bool SkippedDecls = false;
502314564Sdim  for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
503314564Sdim       iter != original_decl_context->decls_end(); ++iter) {
504314564Sdim    Decl *decl = *iter;
505292932Sdim
506353358Sdim    // The predicate function returns true if the passed declaration kind is
507353358Sdim    // the one we are looking for.
508353358Sdim    // See clang::ExternalASTSource::FindExternalLexicalDecls()
509314564Sdim    if (predicate(decl->getKind())) {
510314564Sdim      if (log) {
511360784Sdim        std::string ast_dump = ClangUtil::DumpDecl(decl);
512314564Sdim        if (const NamedDecl *context_named_decl =
513314564Sdim                dyn_cast<NamedDecl>(context_decl))
514360784Sdim          LLDB_LOGF(log, "  FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s",
515360784Sdim                    current_id, context_named_decl->getDeclKindName(),
516360784Sdim                    context_named_decl->getNameAsString().c_str(),
517360784Sdim                    decl->getDeclKindName(), ast_dump.c_str());
518314564Sdim        else
519360784Sdim          LLDB_LOGF(log, "  FELD[%d] Adding lexical %sDecl %s", current_id,
520360784Sdim                    decl->getDeclKindName(), ast_dump.c_str());
521314564Sdim      }
522292932Sdim
523327952Sdim      Decl *copied_decl = CopyDecl(decl);
524292932Sdim
525314564Sdim      if (!copied_decl)
526314564Sdim        continue;
527292932Sdim
528314564Sdim      if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
529314564Sdim        QualType copied_field_type = copied_field->getType();
530292932Sdim
531314564Sdim        m_ast_importer_sp->RequireCompleteType(copied_field_type);
532314564Sdim      }
533353358Sdim    } else {
534353358Sdim      SkippedDecls = true;
535292932Sdim    }
536314564Sdim  }
537292932Sdim
538353358Sdim  // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
539353358Sdim  // to false.  However, since we skipped some of the external Decls we must
540353358Sdim  // set it back!
541353358Sdim  if (SkippedDecls) {
542353358Sdim    decl_context->setHasExternalLexicalStorage(true);
543353358Sdim    // This sets HasLazyExternalLexicalLookups to true.  By setting this bit we
544353358Sdim    // ensure that the lookup table is rebuilt, which means the external source
545353358Sdim    // is consulted again when a clang::DeclContext::lookup is called.
546353358Sdim    const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
547353358Sdim  }
548353358Sdim
549314564Sdim  return;
550292932Sdim}
551292932Sdim
552314564Sdimvoid ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
553314564Sdim  assert(m_ast_context);
554292932Sdim
555314564Sdim  const ConstString name(context.m_decl_name.getAsString().c_str());
556292932Sdim
557314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
558292932Sdim
559314564Sdim  static unsigned int invocation_id = 0;
560314564Sdim  unsigned int current_id = invocation_id++;
561292932Sdim
562314564Sdim  if (log) {
563314564Sdim    if (!context.m_decl_context)
564360784Sdim      LLDB_LOGF(log,
565360784Sdim                "ClangASTSource::FindExternalVisibleDecls[%u] on "
566360784Sdim                "(ASTContext*)%p for '%s' in a NULL DeclContext",
567360784Sdim                current_id, static_cast<void *>(m_ast_context),
568360784Sdim                name.GetCString());
569314564Sdim    else if (const NamedDecl *context_named_decl =
570314564Sdim                 dyn_cast<NamedDecl>(context.m_decl_context))
571360784Sdim      LLDB_LOGF(log,
572360784Sdim                "ClangASTSource::FindExternalVisibleDecls[%u] on "
573360784Sdim                "(ASTContext*)%p for '%s' in '%s'",
574360784Sdim                current_id, static_cast<void *>(m_ast_context),
575360784Sdim                name.GetCString(),
576360784Sdim                context_named_decl->getNameAsString().c_str());
577314564Sdim    else
578360784Sdim      LLDB_LOGF(log,
579360784Sdim                "ClangASTSource::FindExternalVisibleDecls[%u] on "
580360784Sdim                "(ASTContext*)%p for '%s' in a '%s'",
581360784Sdim                current_id, static_cast<void *>(m_ast_context),
582360784Sdim                name.GetCString(), context.m_decl_context->getDeclKindName());
583314564Sdim  }
584292932Sdim
585353358Sdim  context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>();
586292932Sdim
587314564Sdim  if (const NamespaceDecl *namespace_context =
588314564Sdim          dyn_cast<NamespaceDecl>(context.m_decl_context)) {
589327952Sdim    ClangASTImporter::NamespaceMapSP namespace_map =  m_ast_importer_sp ?
590327952Sdim        m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr;
591292932Sdim
592314564Sdim    if (log && log->GetVerbose())
593360784Sdim      LLDB_LOGF(log, "  CAS::FEVD[%u] Inspecting namespace map %p (%d entries)",
594360784Sdim                current_id, static_cast<void *>(namespace_map.get()),
595360784Sdim                static_cast<int>(namespace_map->size()));
596292932Sdim
597314564Sdim    if (!namespace_map)
598314564Sdim      return;
599292932Sdim
600314564Sdim    for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
601314564Sdim                                                  e = namespace_map->end();
602314564Sdim         i != e; ++i) {
603360784Sdim      LLDB_LOGF(log, "  CAS::FEVD[%u] Searching namespace %s in module %s",
604360784Sdim                current_id, i->second.GetName().AsCString(),
605360784Sdim                i->first->GetFileSpec().GetFilename().GetCString());
606292932Sdim
607314564Sdim      FindExternalVisibleDecls(context, i->first, i->second, current_id);
608292932Sdim    }
609360784Sdim  } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
610314564Sdim    FindObjCPropertyAndIvarDecls(context);
611314564Sdim  } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
612314564Sdim    // we shouldn't be getting FindExternalVisibleDecls calls for these
613314564Sdim    return;
614314564Sdim  } else {
615314564Sdim    CompilerDeclContext namespace_decl;
616292932Sdim
617360784Sdim    LLDB_LOGF(log, "  CAS::FEVD[%u] Searching the root namespace", current_id);
618292932Sdim
619314564Sdim    FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
620314564Sdim                             current_id);
621314564Sdim  }
622292932Sdim
623314564Sdim  if (!context.m_namespace_map->empty()) {
624314564Sdim    if (log && log->GetVerbose())
625360784Sdim      LLDB_LOGF(log,
626360784Sdim                "  CAS::FEVD[%u] Registering namespace map %p (%d entries)",
627360784Sdim                current_id, static_cast<void *>(context.m_namespace_map.get()),
628360784Sdim                static_cast<int>(context.m_namespace_map->size()));
629292932Sdim
630314564Sdim    NamespaceDecl *clang_namespace_decl =
631314564Sdim        AddNamespace(context, context.m_namespace_map);
632292932Sdim
633314564Sdim    if (clang_namespace_decl)
634314564Sdim      clang_namespace_decl->setHasExternalVisibleStorage();
635314564Sdim  }
636292932Sdim}
637292932Sdim
638353358Sdimclang::Sema *ClangASTSource::getSema() {
639360784Sdim  return m_clang_ast_context->getSema();
640353358Sdim}
641353358Sdim
642327952Sdimbool ClangASTSource::IgnoreName(const ConstString name,
643327952Sdim                                bool ignore_all_dollar_names) {
644327952Sdim  static const ConstString id_name("id");
645327952Sdim  static const ConstString Class_name("Class");
646327952Sdim
647344779Sdim  if (m_ast_context->getLangOpts().ObjC)
648344779Sdim    if (name == id_name || name == Class_name)
649344779Sdim      return true;
650327952Sdim
651327952Sdim  StringRef name_string_ref = name.GetStringRef();
652327952Sdim
653327952Sdim  // The ClangASTSource is not responsible for finding $-names.
654344779Sdim  return name_string_ref.empty() ||
655344779Sdim         (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
656344779Sdim         name_string_ref.startswith("_$");
657327952Sdim}
658327952Sdim
659314564Sdimvoid ClangASTSource::FindExternalVisibleDecls(
660314564Sdim    NameSearchContext &context, lldb::ModuleSP module_sp,
661314564Sdim    CompilerDeclContext &namespace_decl, unsigned int current_id) {
662314564Sdim  assert(m_ast_context);
663292932Sdim
664314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
665292932Sdim
666314564Sdim  SymbolContextList sc_list;
667292932Sdim
668314564Sdim  const ConstString name(context.m_decl_name.getAsString().c_str());
669327952Sdim  if (IgnoreName(name, true))
670314564Sdim    return;
671292932Sdim
672360784Sdim  if (!m_target)
673360784Sdim    return;
674360784Sdim
675314564Sdim  if (module_sp && namespace_decl) {
676314564Sdim    CompilerDeclContext found_namespace_decl;
677292932Sdim
678360784Sdim    if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
679360784Sdim      found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
680292932Sdim
681314564Sdim      if (found_namespace_decl) {
682314564Sdim        context.m_namespace_map->push_back(
683314564Sdim            std::pair<lldb::ModuleSP, CompilerDeclContext>(
684314564Sdim                module_sp, found_namespace_decl));
685292932Sdim
686360784Sdim        LLDB_LOGF(log, "  CAS::FEVD[%u] Found namespace %s in module %s",
687360784Sdim                  current_id, name.GetCString(),
688360784Sdim                  module_sp->GetFileSpec().GetFilename().GetCString());
689314564Sdim      }
690292932Sdim    }
691360784Sdim  } else {
692314564Sdim    const ModuleList &target_images = m_target->GetImages();
693314564Sdim    std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
694314564Sdim
695314564Sdim    for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
696314564Sdim      lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
697314564Sdim
698314564Sdim      if (!image)
699314564Sdim        continue;
700314564Sdim
701314564Sdim      CompilerDeclContext found_namespace_decl;
702314564Sdim
703360784Sdim      SymbolFile *symbol_file = image->GetSymbolFile();
704314564Sdim
705360784Sdim      if (!symbol_file)
706314564Sdim        continue;
707314564Sdim
708360784Sdim      found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
709314564Sdim
710314564Sdim      if (found_namespace_decl) {
711314564Sdim        context.m_namespace_map->push_back(
712314564Sdim            std::pair<lldb::ModuleSP, CompilerDeclContext>(
713314564Sdim                image, found_namespace_decl));
714314564Sdim
715360784Sdim        LLDB_LOGF(log, "  CAS::FEVD[%u] Found namespace %s in module %s",
716360784Sdim                  current_id, name.GetCString(),
717360784Sdim                  image->GetFileSpec().GetFilename().GetCString());
718314564Sdim      }
719314564Sdim    }
720314564Sdim  }
721314564Sdim
722314564Sdim  do {
723314564Sdim    if (context.m_found.type)
724314564Sdim      break;
725314564Sdim
726314564Sdim    TypeList types;
727341825Sdim    const bool exact_match = true;
728314564Sdim    llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
729314564Sdim    if (module_sp && namespace_decl)
730344779Sdim      module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types);
731341825Sdim    else {
732344779Sdim      m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
733314564Sdim                                      searched_symbol_files, types);
734341825Sdim    }
735292932Sdim
736314564Sdim    if (size_t num_types = types.GetSize()) {
737314564Sdim      for (size_t ti = 0; ti < num_types; ++ti) {
738314564Sdim        lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
739292932Sdim
740314564Sdim        if (log) {
741314564Sdim          const char *name_string = type_sp->GetName().GetCString();
742292932Sdim
743360784Sdim          LLDB_LOGF(log, "  CAS::FEVD[%u] Matching type found for \"%s\": %s",
744360784Sdim                    current_id, name.GetCString(),
745360784Sdim                    (name_string ? name_string : "<anonymous>"));
746314564Sdim        }
747292932Sdim
748314564Sdim        CompilerType full_type = type_sp->GetFullCompilerType();
749292932Sdim
750314564Sdim        CompilerType copied_clang_type(GuardedCopyType(full_type));
751292932Sdim
752314564Sdim        if (!copied_clang_type) {
753360784Sdim          LLDB_LOGF(log, "  CAS::FEVD[%u] - Couldn't export a type",
754360784Sdim                    current_id);
755292932Sdim
756314564Sdim          continue;
757314564Sdim        }
758292932Sdim
759314564Sdim        context.AddTypeDecl(copied_clang_type);
760292932Sdim
761314564Sdim        context.m_found.type = true;
762314564Sdim        break;
763314564Sdim      }
764292932Sdim    }
765292932Sdim
766314564Sdim    if (!context.m_found.type) {
767314564Sdim      // Try the modules next.
768314564Sdim
769314564Sdim      do {
770314564Sdim        if (ClangModulesDeclVendor *modules_decl_vendor =
771314564Sdim                m_target->GetClangModulesDeclVendor()) {
772314564Sdim          bool append = false;
773314564Sdim          uint32_t max_matches = 1;
774314564Sdim          std::vector<clang::NamedDecl *> decls;
775314564Sdim
776314564Sdim          if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
777309124Sdim            break;
778314564Sdim
779314564Sdim          if (log) {
780360784Sdim            LLDB_LOGF(log,
781360784Sdim                      "  CAS::FEVD[%u] Matching entity found for \"%s\" in "
782360784Sdim                      "the modules",
783360784Sdim                      current_id, name.GetCString());
784314564Sdim          }
785314564Sdim
786314564Sdim          clang::NamedDecl *const decl_from_modules = decls[0];
787314564Sdim
788314564Sdim          if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
789314564Sdim              llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
790314564Sdim              llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
791327952Sdim            clang::Decl *copied_decl = CopyDecl(decl_from_modules);
792314564Sdim            clang::NamedDecl *copied_named_decl =
793314564Sdim                copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
794314564Sdim
795314564Sdim            if (!copied_named_decl) {
796360784Sdim              LLDB_LOGF(
797360784Sdim                  log,
798360784Sdim                  "  CAS::FEVD[%u] - Couldn't export a type from the modules",
799360784Sdim                  current_id);
800314564Sdim
801314564Sdim              break;
802292932Sdim            }
803292932Sdim
804314564Sdim            context.AddNamedDecl(copied_named_decl);
805292932Sdim
806314564Sdim            context.m_found.type = true;
807314564Sdim          }
808292932Sdim        }
809353358Sdim      } while (false);
810314564Sdim    }
811292932Sdim
812314564Sdim    if (!context.m_found.type) {
813314564Sdim      do {
814314564Sdim        // Couldn't find any types elsewhere.  Try the Objective-C runtime if
815314564Sdim        // one exists.
816292932Sdim
817314564Sdim        lldb::ProcessSP process(m_target->GetProcessSP());
818292932Sdim
819314564Sdim        if (!process)
820314564Sdim          break;
821292932Sdim
822314564Sdim        ObjCLanguageRuntime *language_runtime(
823353358Sdim            ObjCLanguageRuntime::Get(*process));
824292932Sdim
825314564Sdim        if (!language_runtime)
826314564Sdim          break;
827292932Sdim
828314564Sdim        DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
829292932Sdim
830314564Sdim        if (!decl_vendor)
831314564Sdim          break;
832292932Sdim
833314564Sdim        bool append = false;
834314564Sdim        uint32_t max_matches = 1;
835314564Sdim        std::vector<clang::NamedDecl *> decls;
836292932Sdim
837360784Sdim        auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
838360784Sdim        if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
839314564Sdim          break;
840292932Sdim
841314564Sdim        if (log) {
842360784Sdim          LLDB_LOGF(
843360784Sdim              log,
844314564Sdim              "  CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
845314564Sdim              current_id, name.GetCString());
846314564Sdim        }
847292932Sdim
848327952Sdim        clang::Decl *copied_decl = CopyDecl(decls[0]);
849314564Sdim        clang::NamedDecl *copied_named_decl =
850314564Sdim            copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
851314564Sdim
852314564Sdim        if (!copied_named_decl) {
853360784Sdim          LLDB_LOGF(log,
854360784Sdim                    "  CAS::FEVD[%u] - Couldn't export a type from the runtime",
855360784Sdim                    current_id);
856314564Sdim
857314564Sdim          break;
858292932Sdim        }
859292932Sdim
860314564Sdim        context.AddNamedDecl(copied_named_decl);
861353358Sdim      } while (false);
862314564Sdim    }
863314564Sdim
864353358Sdim  } while (false);
865292932Sdim}
866292932Sdim
867292932Sdimtemplate <class D> class TaggedASTDecl {
868292932Sdimpublic:
869353358Sdim  TaggedASTDecl() : decl(nullptr) {}
870314564Sdim  TaggedASTDecl(D *_decl) : decl(_decl) {}
871353358Sdim  bool IsValid() const { return (decl != nullptr); }
872314564Sdim  bool IsInvalid() const { return !IsValid(); }
873314564Sdim  D *operator->() const { return decl; }
874314564Sdim  D *decl;
875292932Sdim};
876292932Sdim
877292932Sdimtemplate <class D2, template <class D> class TD, class D1>
878314564SdimTD<D2> DynCast(TD<D1> source) {
879314564Sdim  return TD<D2>(dyn_cast<D2>(source.decl));
880292932Sdim}
881292932Sdim
882292932Sdimtemplate <class D = Decl> class DeclFromParser;
883292932Sdimtemplate <class D = Decl> class DeclFromUser;
884292932Sdim
885292932Sdimtemplate <class D> class DeclFromParser : public TaggedASTDecl<D> {
886292932Sdimpublic:
887314564Sdim  DeclFromParser() : TaggedASTDecl<D>() {}
888314564Sdim  DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
889292932Sdim
890327952Sdim  DeclFromUser<D> GetOrigin(ClangASTSource &source);
891292932Sdim};
892292932Sdim
893292932Sdimtemplate <class D> class DeclFromUser : public TaggedASTDecl<D> {
894292932Sdimpublic:
895314564Sdim  DeclFromUser() : TaggedASTDecl<D>() {}
896314564Sdim  DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
897292932Sdim
898327952Sdim  DeclFromParser<D> Import(ClangASTSource &source);
899292932Sdim};
900292932Sdim
901292932Sdimtemplate <class D>
902327952SdimDeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
903360784Sdim  ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
904360784Sdim  if (!origin.Valid())
905314564Sdim    return DeclFromUser<D>();
906360784Sdim  return DeclFromUser<D>(dyn_cast<D>(origin.decl));
907292932Sdim}
908292932Sdim
909292932Sdimtemplate <class D>
910327952SdimDeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
911327952Sdim  DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
912314564Sdim  if (parser_generic_decl.IsInvalid())
913314564Sdim    return DeclFromParser<D>();
914314564Sdim  return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
915292932Sdim}
916292932Sdim
917327952Sdimbool ClangASTSource::FindObjCMethodDeclsWithOrigin(
918314564Sdim    unsigned int current_id, NameSearchContext &context,
919327952Sdim    ObjCInterfaceDecl *original_interface_decl, const char *log_info) {
920314564Sdim  const DeclarationName &decl_name(context.m_decl_name);
921314564Sdim  clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
922292932Sdim
923314564Sdim  Selector original_selector;
924292932Sdim
925314564Sdim  if (decl_name.isObjCZeroArgSelector()) {
926314564Sdim    IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
927314564Sdim    original_selector = original_ctx->Selectors.getSelector(0, &ident);
928314564Sdim  } else if (decl_name.isObjCOneArgSelector()) {
929314564Sdim    const std::string &decl_name_string = decl_name.getAsString();
930314564Sdim    std::string decl_name_string_without_colon(decl_name_string.c_str(),
931314564Sdim                                               decl_name_string.length() - 1);
932314564Sdim    IdentifierInfo *ident =
933314564Sdim        &original_ctx->Idents.get(decl_name_string_without_colon);
934314564Sdim    original_selector = original_ctx->Selectors.getSelector(1, &ident);
935314564Sdim  } else {
936314564Sdim    SmallVector<IdentifierInfo *, 4> idents;
937314564Sdim
938314564Sdim    clang::Selector sel = decl_name.getObjCSelector();
939314564Sdim
940314564Sdim    unsigned num_args = sel.getNumArgs();
941314564Sdim
942314564Sdim    for (unsigned i = 0; i != num_args; ++i) {
943314564Sdim      idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
944292932Sdim    }
945292932Sdim
946314564Sdim    original_selector =
947314564Sdim        original_ctx->Selectors.getSelector(num_args, idents.data());
948314564Sdim  }
949292932Sdim
950314564Sdim  DeclarationName original_decl_name(original_selector);
951292932Sdim
952314564Sdim  llvm::SmallVector<NamedDecl *, 1> methods;
953292932Sdim
954314564Sdim  ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl);
955292932Sdim
956314564Sdim  if (ObjCMethodDecl *instance_method_decl =
957314564Sdim          original_interface_decl->lookupInstanceMethod(original_selector)) {
958314564Sdim    methods.push_back(instance_method_decl);
959314564Sdim  } else if (ObjCMethodDecl *class_method_decl =
960314564Sdim                 original_interface_decl->lookupClassMethod(
961314564Sdim                     original_selector)) {
962314564Sdim    methods.push_back(class_method_decl);
963314564Sdim  }
964292932Sdim
965314564Sdim  if (methods.empty()) {
966314564Sdim    return false;
967314564Sdim  }
968292932Sdim
969314564Sdim  for (NamedDecl *named_decl : methods) {
970314564Sdim    if (!named_decl)
971314564Sdim      continue;
972292932Sdim
973314564Sdim    ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
974292932Sdim
975314564Sdim    if (!result_method)
976314564Sdim      continue;
977292932Sdim
978327952Sdim    Decl *copied_decl = CopyDecl(result_method);
979292932Sdim
980314564Sdim    if (!copied_decl)
981314564Sdim      continue;
982292932Sdim
983314564Sdim    ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
984292932Sdim
985314564Sdim    if (!copied_method_decl)
986314564Sdim      continue;
987314564Sdim
988314564Sdim    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
989314564Sdim
990360784Sdim    LLDB_LOG(log, "  CAS::FOMD[{0}] found ({1}) {2}", current_id, log_info,
991360784Sdim             ClangUtil::DumpDecl(copied_method_decl));
992292932Sdim
993314564Sdim    context.AddNamedDecl(copied_method_decl);
994314564Sdim  }
995314564Sdim
996314564Sdim  return true;
997292932Sdim}
998292932Sdim
999314564Sdimvoid ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
1000314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1001292932Sdim
1002314564Sdim  static unsigned int invocation_id = 0;
1003314564Sdim  unsigned int current_id = invocation_id++;
1004292932Sdim
1005314564Sdim  const DeclarationName &decl_name(context.m_decl_name);
1006314564Sdim  const DeclContext *decl_ctx(context.m_decl_context);
1007292932Sdim
1008314564Sdim  const ObjCInterfaceDecl *interface_decl =
1009314564Sdim      dyn_cast<ObjCInterfaceDecl>(decl_ctx);
1010292932Sdim
1011314564Sdim  if (!interface_decl)
1012314564Sdim    return;
1013292932Sdim
1014314564Sdim  do {
1015360784Sdim    ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
1016292932Sdim
1017360784Sdim    if (!original.Valid())
1018314564Sdim      break;
1019292932Sdim
1020314564Sdim    ObjCInterfaceDecl *original_interface_decl =
1021360784Sdim        dyn_cast<ObjCInterfaceDecl>(original.decl);
1022292932Sdim
1023314564Sdim    if (FindObjCMethodDeclsWithOrigin(current_id, context,
1024327952Sdim                                      original_interface_decl, "at origin"))
1025314564Sdim      return; // found it, no need to look any further
1026353358Sdim  } while (false);
1027292932Sdim
1028314564Sdim  StreamString ss;
1029292932Sdim
1030314564Sdim  if (decl_name.isObjCZeroArgSelector()) {
1031314564Sdim    ss.Printf("%s", decl_name.getAsString().c_str());
1032314564Sdim  } else if (decl_name.isObjCOneArgSelector()) {
1033314564Sdim    ss.Printf("%s", decl_name.getAsString().c_str());
1034314564Sdim  } else {
1035314564Sdim    clang::Selector sel = decl_name.getObjCSelector();
1036292932Sdim
1037314564Sdim    for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
1038314564Sdim      llvm::StringRef r = sel.getNameForSlot(i);
1039314564Sdim      ss.Printf("%s:", r.str().c_str());
1040292932Sdim    }
1041314564Sdim  }
1042314564Sdim  ss.Flush();
1043292932Sdim
1044314564Sdim  if (ss.GetString().contains("$__lldb"))
1045314564Sdim    return; // we don't need any results
1046292932Sdim
1047314564Sdim  ConstString selector_name(ss.GetString());
1048292932Sdim
1049360784Sdim  LLDB_LOGF(log,
1050360784Sdim            "ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p "
1051360784Sdim            "for selector [%s %s]",
1052360784Sdim            current_id, static_cast<void *>(m_ast_context),
1053360784Sdim            interface_decl->getNameAsString().c_str(),
1054360784Sdim            selector_name.AsCString());
1055314564Sdim  SymbolContextList sc_list;
1056292932Sdim
1057314564Sdim  const bool include_symbols = false;
1058314564Sdim  const bool include_inlines = false;
1059292932Sdim
1060314564Sdim  std::string interface_name = interface_decl->getNameAsString();
1061292932Sdim
1062314564Sdim  do {
1063314564Sdim    StreamString ms;
1064314564Sdim    ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1065314564Sdim    ms.Flush();
1066314564Sdim    ConstString instance_method_name(ms.GetString());
1067292932Sdim
1068360784Sdim    sc_list.Clear();
1069314564Sdim    m_target->GetImages().FindFunctions(
1070314564Sdim        instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1071360784Sdim        include_inlines, sc_list);
1072292932Sdim
1073314564Sdim    if (sc_list.GetSize())
1074314564Sdim      break;
1075292932Sdim
1076314564Sdim    ms.Clear();
1077314564Sdim    ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1078314564Sdim    ms.Flush();
1079314564Sdim    ConstString class_method_name(ms.GetString());
1080292932Sdim
1081360784Sdim    sc_list.Clear();
1082314564Sdim    m_target->GetImages().FindFunctions(
1083314564Sdim        class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1084360784Sdim        include_inlines, sc_list);
1085292932Sdim
1086314564Sdim    if (sc_list.GetSize())
1087314564Sdim      break;
1088292932Sdim
1089314564Sdim    // Fall back and check for methods in categories.  If we find methods this
1090341825Sdim    // way, we need to check that they're actually in categories on the desired
1091341825Sdim    // class.
1092292932Sdim
1093314564Sdim    SymbolContextList candidate_sc_list;
1094292932Sdim
1095314564Sdim    m_target->GetImages().FindFunctions(
1096314564Sdim        selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1097360784Sdim        include_inlines, candidate_sc_list);
1098292932Sdim
1099314564Sdim    for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1100314564Sdim      SymbolContext candidate_sc;
1101292932Sdim
1102314564Sdim      if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1103314564Sdim        continue;
1104292932Sdim
1105314564Sdim      if (!candidate_sc.function)
1106314564Sdim        continue;
1107292932Sdim
1108314564Sdim      const char *candidate_name = candidate_sc.function->GetName().AsCString();
1109292932Sdim
1110314564Sdim      const char *cursor = candidate_name;
1111292932Sdim
1112314564Sdim      if (*cursor != '+' && *cursor != '-')
1113314564Sdim        continue;
1114292932Sdim
1115314564Sdim      ++cursor;
1116292932Sdim
1117314564Sdim      if (*cursor != '[')
1118314564Sdim        continue;
1119292932Sdim
1120314564Sdim      ++cursor;
1121292932Sdim
1122314564Sdim      size_t interface_len = interface_name.length();
1123292932Sdim
1124314564Sdim      if (strncmp(cursor, interface_name.c_str(), interface_len))
1125314564Sdim        continue;
1126292932Sdim
1127314564Sdim      cursor += interface_len;
1128292932Sdim
1129314564Sdim      if (*cursor == ' ' || *cursor == '(')
1130314564Sdim        sc_list.Append(candidate_sc);
1131292932Sdim    }
1132353358Sdim  } while (false);
1133292932Sdim
1134314564Sdim  if (sc_list.GetSize()) {
1135314564Sdim    // We found a good function symbol.  Use that.
1136292932Sdim
1137314564Sdim    for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1138314564Sdim      SymbolContext sc;
1139292932Sdim
1140314564Sdim      if (!sc_list.GetContextAtIndex(i, sc))
1141314564Sdim        continue;
1142292932Sdim
1143314564Sdim      if (!sc.function)
1144314564Sdim        continue;
1145292932Sdim
1146314564Sdim      CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1147314564Sdim      if (!function_decl_ctx)
1148314564Sdim        continue;
1149292932Sdim
1150314564Sdim      ObjCMethodDecl *method_decl =
1151314564Sdim          ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1152292932Sdim
1153314564Sdim      if (!method_decl)
1154314564Sdim        continue;
1155292932Sdim
1156314564Sdim      ObjCInterfaceDecl *found_interface_decl =
1157314564Sdim          method_decl->getClassInterface();
1158292932Sdim
1159314564Sdim      if (!found_interface_decl)
1160314564Sdim        continue;
1161292932Sdim
1162314564Sdim      if (found_interface_decl->getName() == interface_decl->getName()) {
1163327952Sdim        Decl *copied_decl = CopyDecl(method_decl);
1164292932Sdim
1165314564Sdim        if (!copied_decl)
1166314564Sdim          continue;
1167292932Sdim
1168314564Sdim        ObjCMethodDecl *copied_method_decl =
1169314564Sdim            dyn_cast<ObjCMethodDecl>(copied_decl);
1170292932Sdim
1171314564Sdim        if (!copied_method_decl)
1172314564Sdim          continue;
1173292932Sdim
1174360784Sdim        LLDB_LOG(log, "  CAS::FOMD[{0}] found (in symbols)\n{1}", current_id,
1175360784Sdim                 ClangUtil::DumpDecl(copied_method_decl));
1176292932Sdim
1177314564Sdim        context.AddNamedDecl(copied_method_decl);
1178314564Sdim      }
1179292932Sdim    }
1180292932Sdim
1181314564Sdim    return;
1182314564Sdim  }
1183292932Sdim
1184314564Sdim  // Try the debug information.
1185292932Sdim
1186314564Sdim  do {
1187314564Sdim    ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1188314564Sdim        const_cast<ObjCInterfaceDecl *>(interface_decl));
1189292932Sdim
1190314564Sdim    if (!complete_interface_decl)
1191314564Sdim      break;
1192292932Sdim
1193314564Sdim    // We found the complete interface.  The runtime never needs to be queried
1194314564Sdim    // in this scenario.
1195292932Sdim
1196314564Sdim    DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1197314564Sdim        complete_interface_decl);
1198292932Sdim
1199314564Sdim    if (complete_interface_decl == interface_decl)
1200314564Sdim      break; // already checked this one
1201292932Sdim
1202360784Sdim    LLDB_LOGF(log,
1203360784Sdim              "CAS::FOPD[%d] trying origin "
1204360784Sdim              "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1205360784Sdim              current_id, static_cast<void *>(complete_interface_decl),
1206360784Sdim              static_cast<void *>(&complete_iface_decl->getASTContext()));
1207292932Sdim
1208314564Sdim    FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl,
1209314564Sdim                                  "in debug info");
1210314564Sdim
1211314564Sdim    return;
1212353358Sdim  } while (false);
1213314564Sdim
1214314564Sdim  do {
1215314564Sdim    // Check the modules only if the debug information didn't have a complete
1216314564Sdim    // interface.
1217314564Sdim
1218314564Sdim    if (ClangModulesDeclVendor *modules_decl_vendor =
1219314564Sdim            m_target->GetClangModulesDeclVendor()) {
1220314564Sdim      ConstString interface_name(interface_decl->getNameAsString().c_str());
1221314564Sdim      bool append = false;
1222314564Sdim      uint32_t max_matches = 1;
1223314564Sdim      std::vector<clang::NamedDecl *> decls;
1224314564Sdim
1225314564Sdim      if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1226314564Sdim                                          decls))
1227314564Sdim        break;
1228314564Sdim
1229314564Sdim      ObjCInterfaceDecl *interface_decl_from_modules =
1230314564Sdim          dyn_cast<ObjCInterfaceDecl>(decls[0]);
1231314564Sdim
1232314564Sdim      if (!interface_decl_from_modules)
1233314564Sdim        break;
1234314564Sdim
1235314564Sdim      if (FindObjCMethodDeclsWithOrigin(
1236327952Sdim              current_id, context, interface_decl_from_modules, "in modules"))
1237292932Sdim        return;
1238292932Sdim    }
1239353358Sdim  } while (false);
1240292932Sdim
1241314564Sdim  do {
1242314564Sdim    // Check the runtime only if the debug information didn't have a complete
1243314564Sdim    // interface and the modules don't get us anywhere.
1244292932Sdim
1245314564Sdim    lldb::ProcessSP process(m_target->GetProcessSP());
1246292932Sdim
1247314564Sdim    if (!process)
1248314564Sdim      break;
1249292932Sdim
1250353358Sdim    ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1251292932Sdim
1252314564Sdim    if (!language_runtime)
1253314564Sdim      break;
1254292932Sdim
1255314564Sdim    DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1256292932Sdim
1257314564Sdim    if (!decl_vendor)
1258314564Sdim      break;
1259292932Sdim
1260314564Sdim    ConstString interface_name(interface_decl->getNameAsString().c_str());
1261314564Sdim    bool append = false;
1262314564Sdim    uint32_t max_matches = 1;
1263314564Sdim    std::vector<clang::NamedDecl *> decls;
1264292932Sdim
1265360784Sdim    auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1266360784Sdim    if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1267360784Sdim                                      decls))
1268314564Sdim      break;
1269292932Sdim
1270314564Sdim    ObjCInterfaceDecl *runtime_interface_decl =
1271314564Sdim        dyn_cast<ObjCInterfaceDecl>(decls[0]);
1272292932Sdim
1273314564Sdim    if (!runtime_interface_decl)
1274314564Sdim      break;
1275292932Sdim
1276314564Sdim    FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl,
1277314564Sdim                                  "in runtime");
1278353358Sdim  } while (false);
1279292932Sdim}
1280292932Sdim
1281314564Sdimstatic bool FindObjCPropertyAndIvarDeclsWithOrigin(
1282327952Sdim    unsigned int current_id, NameSearchContext &context, ClangASTSource &source,
1283314564Sdim    DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1284314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1285292932Sdim
1286314564Sdim  if (origin_iface_decl.IsInvalid())
1287314564Sdim    return false;
1288292932Sdim
1289314564Sdim  std::string name_str = context.m_decl_name.getAsString();
1290314564Sdim  StringRef name(name_str);
1291314564Sdim  IdentifierInfo &name_identifier(
1292314564Sdim      origin_iface_decl->getASTContext().Idents.get(name));
1293292932Sdim
1294314564Sdim  DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1295314564Sdim      origin_iface_decl->FindPropertyDeclaration(
1296314564Sdim          &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1297292932Sdim
1298314564Sdim  bool found = false;
1299292932Sdim
1300314564Sdim  if (origin_property_decl.IsValid()) {
1301314564Sdim    DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1302327952Sdim        origin_property_decl.Import(source));
1303314564Sdim    if (parser_property_decl.IsValid()) {
1304360784Sdim      LLDB_LOG(log, "  CAS::FOPD[{0}] found\n{1}", current_id,
1305360784Sdim               ClangUtil::DumpDecl(parser_property_decl.decl));
1306292932Sdim
1307314564Sdim      context.AddNamedDecl(parser_property_decl.decl);
1308314564Sdim      found = true;
1309292932Sdim    }
1310314564Sdim  }
1311292932Sdim
1312314564Sdim  DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1313314564Sdim      origin_iface_decl->getIvarDecl(&name_identifier));
1314292932Sdim
1315314564Sdim  if (origin_ivar_decl.IsValid()) {
1316314564Sdim    DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1317327952Sdim        origin_ivar_decl.Import(source));
1318314564Sdim    if (parser_ivar_decl.IsValid()) {
1319314564Sdim      if (log) {
1320360784Sdim        LLDB_LOG(log, "  CAS::FOPD[{0}] found\n{1}", current_id,
1321360784Sdim                 ClangUtil::DumpDecl(parser_ivar_decl.decl));
1322314564Sdim      }
1323292932Sdim
1324314564Sdim      context.AddNamedDecl(parser_ivar_decl.decl);
1325314564Sdim      found = true;
1326292932Sdim    }
1327314564Sdim  }
1328292932Sdim
1329314564Sdim  return found;
1330292932Sdim}
1331292932Sdim
1332314564Sdimvoid ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1333314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1334292932Sdim
1335314564Sdim  static unsigned int invocation_id = 0;
1336314564Sdim  unsigned int current_id = invocation_id++;
1337292932Sdim
1338314564Sdim  DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1339314564Sdim      cast<ObjCInterfaceDecl>(context.m_decl_context));
1340314564Sdim  DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1341327952Sdim      parser_iface_decl.GetOrigin(*this));
1342292932Sdim
1343314564Sdim  ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1344292932Sdim
1345360784Sdim  LLDB_LOGF(log,
1346360784Sdim            "ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on "
1347360784Sdim            "(ASTContext*)%p for '%s.%s'",
1348360784Sdim            current_id, static_cast<void *>(m_ast_context),
1349360784Sdim            parser_iface_decl->getNameAsString().c_str(),
1350360784Sdim            context.m_decl_name.getAsString().c_str());
1351292932Sdim
1352314564Sdim  if (FindObjCPropertyAndIvarDeclsWithOrigin(
1353327952Sdim          current_id, context, *this, origin_iface_decl))
1354314564Sdim    return;
1355292932Sdim
1356360784Sdim  LLDB_LOGF(log,
1357360784Sdim            "CAS::FOPD[%d] couldn't find the property on origin "
1358360784Sdim            "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "
1359360784Sdim            "elsewhere...",
1360360784Sdim            current_id, static_cast<const void *>(origin_iface_decl.decl),
1361360784Sdim            static_cast<void *>(&origin_iface_decl->getASTContext()));
1362314564Sdim
1363314564Sdim  SymbolContext null_sc;
1364314564Sdim  TypeList type_list;
1365314564Sdim
1366314564Sdim  do {
1367314564Sdim    ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1368314564Sdim        const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1369314564Sdim
1370314564Sdim    if (!complete_interface_decl)
1371314564Sdim      break;
1372314564Sdim
1373314564Sdim    // We found the complete interface.  The runtime never needs to be queried
1374314564Sdim    // in this scenario.
1375314564Sdim
1376314564Sdim    DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1377314564Sdim        complete_interface_decl);
1378314564Sdim
1379314564Sdim    if (complete_iface_decl.decl == origin_iface_decl.decl)
1380314564Sdim      break; // already checked this one
1381314564Sdim
1382360784Sdim    LLDB_LOGF(log,
1383360784Sdim              "CAS::FOPD[%d] trying origin "
1384360784Sdim              "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1385360784Sdim              current_id, static_cast<const void *>(complete_iface_decl.decl),
1386360784Sdim              static_cast<void *>(&complete_iface_decl->getASTContext()));
1387292932Sdim
1388327952Sdim    FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1389314564Sdim                                           complete_iface_decl);
1390292932Sdim
1391314564Sdim    return;
1392353358Sdim  } while (false);
1393292932Sdim
1394314564Sdim  do {
1395314564Sdim    // Check the modules only if the debug information didn't have a complete
1396314564Sdim    // interface.
1397292932Sdim
1398314564Sdim    ClangModulesDeclVendor *modules_decl_vendor =
1399314564Sdim        m_target->GetClangModulesDeclVendor();
1400292932Sdim
1401314564Sdim    if (!modules_decl_vendor)
1402314564Sdim      break;
1403292932Sdim
1404314564Sdim    bool append = false;
1405314564Sdim    uint32_t max_matches = 1;
1406314564Sdim    std::vector<clang::NamedDecl *> decls;
1407292932Sdim
1408314564Sdim    if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1409314564Sdim      break;
1410292932Sdim
1411314564Sdim    DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1412314564Sdim        dyn_cast<ObjCInterfaceDecl>(decls[0]));
1413292932Sdim
1414314564Sdim    if (!interface_decl_from_modules.IsValid())
1415314564Sdim      break;
1416292932Sdim
1417360784Sdim    LLDB_LOGF(
1418360784Sdim        log,
1419360784Sdim        "CAS::FOPD[%d] trying module "
1420360784Sdim        "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1421360784Sdim        current_id, static_cast<const void *>(interface_decl_from_modules.decl),
1422360784Sdim        static_cast<void *>(&interface_decl_from_modules->getASTContext()));
1423292932Sdim
1424327952Sdim    if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1425327952Sdim                                               interface_decl_from_modules))
1426314564Sdim      return;
1427353358Sdim  } while (false);
1428292932Sdim
1429314564Sdim  do {
1430314564Sdim    // Check the runtime only if the debug information didn't have a complete
1431341825Sdim    // interface and nothing was in the modules.
1432292932Sdim
1433314564Sdim    lldb::ProcessSP process(m_target->GetProcessSP());
1434292932Sdim
1435314564Sdim    if (!process)
1436314564Sdim      return;
1437292932Sdim
1438353358Sdim    ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1439292932Sdim
1440314564Sdim    if (!language_runtime)
1441314564Sdim      return;
1442292932Sdim
1443314564Sdim    DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1444292932Sdim
1445314564Sdim    if (!decl_vendor)
1446314564Sdim      break;
1447292932Sdim
1448314564Sdim    bool append = false;
1449314564Sdim    uint32_t max_matches = 1;
1450314564Sdim    std::vector<clang::NamedDecl *> decls;
1451292932Sdim
1452360784Sdim    auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1453360784Sdim    if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1454314564Sdim      break;
1455292932Sdim
1456314564Sdim    DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1457314564Sdim        dyn_cast<ObjCInterfaceDecl>(decls[0]));
1458314564Sdim
1459314564Sdim    if (!interface_decl_from_runtime.IsValid())
1460314564Sdim      break;
1461314564Sdim
1462360784Sdim    LLDB_LOGF(
1463360784Sdim        log,
1464360784Sdim        "CAS::FOPD[%d] trying runtime "
1465360784Sdim        "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1466360784Sdim        current_id, static_cast<const void *>(interface_decl_from_runtime.decl),
1467360784Sdim        static_cast<void *>(&interface_decl_from_runtime->getASTContext()));
1468314564Sdim
1469314564Sdim    if (FindObjCPropertyAndIvarDeclsWithOrigin(
1470327952Sdim            current_id, context, *this, interface_decl_from_runtime))
1471314564Sdim      return;
1472353358Sdim  } while (false);
1473292932Sdim}
1474292932Sdim
1475292932Sdimtypedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1476292932Sdimtypedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1477292932Sdim
1478292932Sdimtemplate <class D, class O>
1479314564Sdimstatic bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1480314564Sdim                            llvm::DenseMap<const D *, O> &source_map,
1481327952Sdim                            ClangASTSource &source) {
1482314564Sdim  // When importing fields into a new record, clang has a hard requirement that
1483314564Sdim  // fields be imported in field offset order.  Since they are stored in a
1484341825Sdim  // DenseMap with a pointer as the key type, this means we cannot simply
1485341825Sdim  // iterate over the map, as the order will be non-deterministic.  Instead we
1486341825Sdim  // have to sort by the offset and then insert in sorted order.
1487314564Sdim  typedef llvm::DenseMap<const D *, O> MapType;
1488314564Sdim  typedef typename MapType::value_type PairType;
1489314564Sdim  std::vector<PairType> sorted_items;
1490314564Sdim  sorted_items.reserve(source_map.size());
1491314564Sdim  sorted_items.assign(source_map.begin(), source_map.end());
1492344779Sdim  llvm::sort(sorted_items.begin(), sorted_items.end(),
1493344779Sdim             [](const PairType &lhs, const PairType &rhs) {
1494344779Sdim               return lhs.second < rhs.second;
1495344779Sdim             });
1496292932Sdim
1497314564Sdim  for (const auto &item : sorted_items) {
1498314564Sdim    DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1499327952Sdim    DeclFromParser<D> parser_decl(user_decl.Import(source));
1500314564Sdim    if (parser_decl.IsInvalid())
1501314564Sdim      return false;
1502314564Sdim    destination_map.insert(
1503314564Sdim        std::pair<const D *, O>(parser_decl.decl, item.second));
1504314564Sdim  }
1505292932Sdim
1506314564Sdim  return true;
1507292932Sdim}
1508292932Sdim
1509292932Sdimtemplate <bool IsVirtual>
1510314564Sdimbool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1511314564Sdim                        DeclFromUser<const CXXRecordDecl> &record,
1512314564Sdim                        BaseOffsetMap &base_offsets) {
1513314564Sdim  for (CXXRecordDecl::base_class_const_iterator
1514314564Sdim           bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1515314564Sdim           be = (IsVirtual ? record->vbases_end() : record->bases_end());
1516314564Sdim       bi != be; ++bi) {
1517314564Sdim    if (!IsVirtual && bi->isVirtual())
1518314564Sdim      continue;
1519292932Sdim
1520314564Sdim    const clang::Type *origin_base_type = bi->getType().getTypePtr();
1521314564Sdim    const clang::RecordType *origin_base_record_type =
1522314564Sdim        origin_base_type->getAs<RecordType>();
1523292932Sdim
1524314564Sdim    if (!origin_base_record_type)
1525314564Sdim      return false;
1526292932Sdim
1527314564Sdim    DeclFromUser<RecordDecl> origin_base_record(
1528314564Sdim        origin_base_record_type->getDecl());
1529292932Sdim
1530314564Sdim    if (origin_base_record.IsInvalid())
1531314564Sdim      return false;
1532292932Sdim
1533314564Sdim    DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1534314564Sdim        DynCast<CXXRecordDecl>(origin_base_record));
1535292932Sdim
1536314564Sdim    if (origin_base_cxx_record.IsInvalid())
1537314564Sdim      return false;
1538292932Sdim
1539314564Sdim    CharUnits base_offset;
1540292932Sdim
1541314564Sdim    if (IsVirtual)
1542314564Sdim      base_offset =
1543314564Sdim          record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1544314564Sdim    else
1545314564Sdim      base_offset =
1546314564Sdim          record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1547292932Sdim
1548314564Sdim    base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1549314564Sdim        origin_base_cxx_record.decl, base_offset));
1550314564Sdim  }
1551292932Sdim
1552314564Sdim  return true;
1553292932Sdim}
1554292932Sdim
1555314564Sdimbool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1556314564Sdim                                      uint64_t &alignment,
1557314564Sdim                                      FieldOffsetMap &field_offsets,
1558314564Sdim                                      BaseOffsetMap &base_offsets,
1559314564Sdim                                      BaseOffsetMap &virtual_base_offsets) {
1560314564Sdim  static unsigned int invocation_id = 0;
1561314564Sdim  unsigned int current_id = invocation_id++;
1562292932Sdim
1563314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1564292932Sdim
1565360784Sdim  LLDB_LOGF(log,
1566360784Sdim            "LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "
1567360784Sdim            "[name = '%s']",
1568360784Sdim            current_id, static_cast<void *>(m_ast_context),
1569360784Sdim            static_cast<const void *>(record),
1570360784Sdim            record->getNameAsString().c_str());
1571292932Sdim
1572314564Sdim  DeclFromParser<const RecordDecl> parser_record(record);
1573314564Sdim  DeclFromUser<const RecordDecl> origin_record(
1574327952Sdim      parser_record.GetOrigin(*this));
1575292932Sdim
1576314564Sdim  if (origin_record.IsInvalid())
1577314564Sdim    return false;
1578292932Sdim
1579314564Sdim  FieldOffsetMap origin_field_offsets;
1580314564Sdim  BaseOffsetMap origin_base_offsets;
1581314564Sdim  BaseOffsetMap origin_virtual_base_offsets;
1582292932Sdim
1583314564Sdim  ClangASTContext::GetCompleteDecl(
1584314564Sdim      &origin_record->getASTContext(),
1585314564Sdim      const_cast<RecordDecl *>(origin_record.decl));
1586292932Sdim
1587314564Sdim  clang::RecordDecl *definition = origin_record.decl->getDefinition();
1588314564Sdim  if (!definition || !definition->isCompleteDefinition())
1589314564Sdim    return false;
1590292932Sdim
1591314564Sdim  const ASTRecordLayout &record_layout(
1592314564Sdim      origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1593292932Sdim
1594314564Sdim  int field_idx = 0, field_count = record_layout.getFieldCount();
1595292932Sdim
1596314564Sdim  for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1597314564Sdim                                  fe = origin_record->field_end();
1598314564Sdim       fi != fe; ++fi) {
1599314564Sdim    if (field_idx >= field_count)
1600314564Sdim      return false; // Layout didn't go well.  Bail out.
1601292932Sdim
1602314564Sdim    uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1603292932Sdim
1604314564Sdim    origin_field_offsets.insert(
1605314564Sdim        std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1606292932Sdim
1607314564Sdim    field_idx++;
1608314564Sdim  }
1609292932Sdim
1610327952Sdim  lldbassert(&record->getASTContext() == m_ast_context);
1611292932Sdim
1612314564Sdim  DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1613314564Sdim      DynCast<const CXXRecordDecl>(origin_record));
1614292932Sdim
1615314564Sdim  if (origin_cxx_record.IsValid()) {
1616314564Sdim    if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1617314564Sdim                                   origin_base_offsets) ||
1618314564Sdim        !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1619314564Sdim                                  origin_virtual_base_offsets))
1620314564Sdim      return false;
1621314564Sdim  }
1622292932Sdim
1623327952Sdim  if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1624327952Sdim      !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1625314564Sdim      !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1626327952Sdim                       *this))
1627314564Sdim    return false;
1628292932Sdim
1629314564Sdim  size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1630314564Sdim  alignment = record_layout.getAlignment().getQuantity() *
1631314564Sdim              m_ast_context->getCharWidth();
1632292932Sdim
1633314564Sdim  if (log) {
1634360784Sdim    LLDB_LOGF(log, "LRT[%u] returned:", current_id);
1635360784Sdim    LLDB_LOGF(log, "LRT[%u]   Original = (RecordDecl*)%p", current_id,
1636360784Sdim              static_cast<const void *>(origin_record.decl));
1637360784Sdim    LLDB_LOGF(log, "LRT[%u]   Size = %" PRId64, current_id, size);
1638360784Sdim    LLDB_LOGF(log, "LRT[%u]   Alignment = %" PRId64, current_id, alignment);
1639360784Sdim    LLDB_LOGF(log, "LRT[%u]   Fields:", current_id);
1640314564Sdim    for (RecordDecl::field_iterator fi = record->field_begin(),
1641314564Sdim                                    fe = record->field_end();
1642314564Sdim         fi != fe; ++fi) {
1643360784Sdim      LLDB_LOGF(log,
1644360784Sdim                "LRT[%u]     (FieldDecl*)%p, Name = '%s', Offset = %" PRId64
1645360784Sdim                " bits",
1646360784Sdim                current_id, static_cast<void *>(*fi),
1647360784Sdim                fi->getNameAsString().c_str(), field_offsets[*fi]);
1648314564Sdim    }
1649314564Sdim    DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1650314564Sdim        DynCast<const CXXRecordDecl>(parser_record);
1651314564Sdim    if (parser_cxx_record.IsValid()) {
1652360784Sdim      LLDB_LOGF(log, "LRT[%u]   Bases:", current_id);
1653314564Sdim      for (CXXRecordDecl::base_class_const_iterator
1654314564Sdim               bi = parser_cxx_record->bases_begin(),
1655314564Sdim               be = parser_cxx_record->bases_end();
1656314564Sdim           bi != be; ++bi) {
1657314564Sdim        bool is_virtual = bi->isVirtual();
1658292932Sdim
1659314564Sdim        QualType base_type = bi->getType();
1660314564Sdim        const RecordType *base_record_type = base_type->getAs<RecordType>();
1661314564Sdim        DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1662314564Sdim        DeclFromParser<CXXRecordDecl> base_cxx_record =
1663314564Sdim            DynCast<CXXRecordDecl>(base_record);
1664292932Sdim
1665360784Sdim        LLDB_LOGF(
1666360784Sdim            log,
1667314564Sdim            "LRT[%u]     %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64
1668314564Sdim            " chars",
1669314564Sdim            current_id, (is_virtual ? "Virtual " : ""),
1670314564Sdim            static_cast<void *>(base_cxx_record.decl),
1671314564Sdim            base_cxx_record.decl->getNameAsString().c_str(),
1672314564Sdim            (is_virtual
1673314564Sdim                 ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1674314564Sdim                 : base_offsets[base_cxx_record.decl].getQuantity()));
1675314564Sdim      }
1676314564Sdim    } else {
1677360784Sdim      LLDB_LOGF(log, "LRD[%u]   Not a CXXRecord, so no bases", current_id);
1678292932Sdim    }
1679314564Sdim  }
1680292932Sdim
1681314564Sdim  return true;
1682292932Sdim}
1683292932Sdim
1684314564Sdimvoid ClangASTSource::CompleteNamespaceMap(
1685353358Sdim    ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1686314564Sdim    ClangASTImporter::NamespaceMapSP &parent_map) const {
1687314564Sdim  static unsigned int invocation_id = 0;
1688314564Sdim  unsigned int current_id = invocation_id++;
1689292932Sdim
1690314564Sdim  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1691292932Sdim
1692314564Sdim  if (log) {
1693314564Sdim    if (parent_map && parent_map->size())
1694360784Sdim      LLDB_LOGF(log,
1695360784Sdim                "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1696360784Sdim                "namespace %s in namespace %s",
1697360784Sdim                current_id, static_cast<void *>(m_ast_context),
1698360784Sdim                name.GetCString(),
1699360784Sdim                parent_map->begin()->second.GetName().AsCString());
1700314564Sdim    else
1701360784Sdim      LLDB_LOGF(log,
1702360784Sdim                "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1703360784Sdim                "namespace %s",
1704360784Sdim                current_id, static_cast<void *>(m_ast_context),
1705360784Sdim                name.GetCString());
1706314564Sdim  }
1707292932Sdim
1708314564Sdim  if (parent_map) {
1709314564Sdim    for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1710314564Sdim                                                  e = parent_map->end();
1711314564Sdim         i != e; ++i) {
1712314564Sdim      CompilerDeclContext found_namespace_decl;
1713292932Sdim
1714314564Sdim      lldb::ModuleSP module_sp = i->first;
1715314564Sdim      CompilerDeclContext module_parent_namespace_decl = i->second;
1716292932Sdim
1717360784Sdim      SymbolFile *symbol_file = module_sp->GetSymbolFile();
1718292932Sdim
1719360784Sdim      if (!symbol_file)
1720314564Sdim        continue;
1721292932Sdim
1722344779Sdim      found_namespace_decl =
1723360784Sdim          symbol_file->FindNamespace(name, &module_parent_namespace_decl);
1724292932Sdim
1725314564Sdim      if (!found_namespace_decl)
1726314564Sdim        continue;
1727292932Sdim
1728314564Sdim      namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1729314564Sdim          module_sp, found_namespace_decl));
1730292932Sdim
1731360784Sdim      LLDB_LOGF(log, "  CMN[%u] Found namespace %s in module %s", current_id,
1732360784Sdim                name.GetCString(),
1733360784Sdim                module_sp->GetFileSpec().GetFilename().GetCString());
1734292932Sdim    }
1735314564Sdim  } else {
1736314564Sdim    const ModuleList &target_images = m_target->GetImages();
1737314564Sdim    std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1738292932Sdim
1739314564Sdim    CompilerDeclContext null_namespace_decl;
1740292932Sdim
1741314564Sdim    for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1742314564Sdim      lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1743292932Sdim
1744314564Sdim      if (!image)
1745314564Sdim        continue;
1746292932Sdim
1747314564Sdim      CompilerDeclContext found_namespace_decl;
1748292932Sdim
1749360784Sdim      SymbolFile *symbol_file = image->GetSymbolFile();
1750292932Sdim
1751360784Sdim      if (!symbol_file)
1752314564Sdim        continue;
1753292932Sdim
1754314564Sdim      found_namespace_decl =
1755360784Sdim          symbol_file->FindNamespace(name, &null_namespace_decl);
1756292932Sdim
1757314564Sdim      if (!found_namespace_decl)
1758314564Sdim        continue;
1759292932Sdim
1760314564Sdim      namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1761314564Sdim          image, found_namespace_decl));
1762292932Sdim
1763360784Sdim      LLDB_LOGF(log, "  CMN[%u] Found namespace %s in module %s", current_id,
1764360784Sdim                name.GetCString(),
1765360784Sdim                image->GetFileSpec().GetFilename().GetCString());
1766292932Sdim    }
1767314564Sdim  }
1768292932Sdim}
1769292932Sdim
1770314564SdimNamespaceDecl *ClangASTSource::AddNamespace(
1771314564Sdim    NameSearchContext &context,
1772314564Sdim    ClangASTImporter::NamespaceMapSP &namespace_decls) {
1773314564Sdim  if (!namespace_decls)
1774314564Sdim    return nullptr;
1775292932Sdim
1776314564Sdim  const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1777292932Sdim
1778314564Sdim  clang::ASTContext *src_ast =
1779314564Sdim      ClangASTContext::DeclContextGetClangASTContext(namespace_decl);
1780314564Sdim  if (!src_ast)
1781314564Sdim    return nullptr;
1782314564Sdim  clang::NamespaceDecl *src_namespace_decl =
1783314564Sdim      ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl);
1784292932Sdim
1785314564Sdim  if (!src_namespace_decl)
1786314564Sdim    return nullptr;
1787292932Sdim
1788327952Sdim  Decl *copied_decl = CopyDecl(src_namespace_decl);
1789292932Sdim
1790314564Sdim  if (!copied_decl)
1791314564Sdim    return nullptr;
1792292932Sdim
1793314564Sdim  NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1794292932Sdim
1795314564Sdim  if (!copied_namespace_decl)
1796314564Sdim    return nullptr;
1797292932Sdim
1798314564Sdim  context.m_decls.push_back(copied_namespace_decl);
1799292932Sdim
1800314564Sdim  m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1801314564Sdim                                          namespace_decls);
1802292932Sdim
1803314564Sdim  return dyn_cast<NamespaceDecl>(copied_decl);
1804292932Sdim}
1805292932Sdim
1806327952Sdimclang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1807327952Sdim  if (m_ast_importer_sp) {
1808360784Sdim    return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1809327952Sdim  } else {
1810327952Sdim    lldbassert(0 && "No mechanism for copying a decl!");
1811327952Sdim    return nullptr;
1812327952Sdim  }
1813327952Sdim}
1814327952Sdim
1815360784SdimClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1816327952Sdim  if (m_ast_importer_sp) {
1817360784Sdim    return m_ast_importer_sp->GetDeclOrigin(decl);
1818327952Sdim  } else {
1819327952Sdim    // this can happen early enough that no ExternalASTSource is installed.
1820360784Sdim    return ClangASTImporter::DeclOrigin();
1821327952Sdim  }
1822327952Sdim}
1823327952Sdim
1824314564SdimCompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1825314564Sdim  ClangASTContext *src_ast =
1826314564Sdim      llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem());
1827314564Sdim  if (src_ast == nullptr)
1828314564Sdim    return CompilerType();
1829292932Sdim
1830314564Sdim  SetImportInProgress(true);
1831292932Sdim
1832327952Sdim  QualType copied_qual_type;
1833292932Sdim
1834327952Sdim  if (m_ast_importer_sp) {
1835360784Sdim    copied_qual_type = ClangUtil::GetQualType(
1836360784Sdim        m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1837327952Sdim  } else {
1838327952Sdim    lldbassert(0 && "No mechanism for copying a type!");
1839327952Sdim    return CompilerType();
1840327952Sdim  }
1841327952Sdim
1842314564Sdim  SetImportInProgress(false);
1843292932Sdim
1844314564Sdim  if (copied_qual_type.getAsOpaquePtr() &&
1845314564Sdim      copied_qual_type->getCanonicalTypeInternal().isNull())
1846341825Sdim    // this shouldn't happen, but we're hardening because the AST importer
1847341825Sdim    // seems to be generating bad types on occasion.
1848314564Sdim    return CompilerType();
1849292932Sdim
1850360784Sdim  return m_clang_ast_context->GetType(copied_qual_type);
1851292932Sdim}
1852292932Sdim
1853314564Sdimclang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) {
1854314564Sdim  assert(type && "Type for variable must be valid!");
1855292932Sdim
1856314564Sdim  if (!type.IsValid())
1857353358Sdim    return nullptr;
1858292932Sdim
1859314564Sdim  ClangASTContext *lldb_ast =
1860314564Sdim      llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
1861314564Sdim  if (!lldb_ast)
1862353358Sdim    return nullptr;
1863292932Sdim
1864314564Sdim  IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
1865292932Sdim
1866360784Sdim  clang::ASTContext &ast = lldb_ast->getASTContext();
1867292932Sdim
1868314564Sdim  clang::NamedDecl *Decl = VarDecl::Create(
1869360784Sdim      ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(),
1870353358Sdim      SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static);
1871314564Sdim  m_decls.push_back(Decl);
1872314564Sdim
1873314564Sdim  return Decl;
1874292932Sdim}
1875292932Sdim
1876314564Sdimclang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type,
1877314564Sdim                                                bool extern_c) {
1878314564Sdim  assert(type && "Type for variable must be valid!");
1879292932Sdim
1880314564Sdim  if (!type.IsValid())
1881353358Sdim    return nullptr;
1882292932Sdim
1883314564Sdim  if (m_function_types.count(type))
1884353358Sdim    return nullptr;
1885292932Sdim
1886314564Sdim  ClangASTContext *lldb_ast =
1887314564Sdim      llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
1888314564Sdim  if (!lldb_ast)
1889353358Sdim    return nullptr;
1890292932Sdim
1891314564Sdim  m_function_types.insert(type);
1892292932Sdim
1893314564Sdim  QualType qual_type(ClangUtil::GetQualType(type));
1894292932Sdim
1895360784Sdim  clang::ASTContext &ast = lldb_ast->getASTContext();
1896292932Sdim
1897314564Sdim  const bool isInlineSpecified = false;
1898314564Sdim  const bool hasWrittenPrototype = true;
1899314564Sdim  const bool isConstexprSpecified = false;
1900292932Sdim
1901314564Sdim  clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context);
1902292932Sdim
1903314564Sdim  if (extern_c) {
1904314564Sdim    context = LinkageSpecDecl::Create(
1905360784Sdim        ast, context, SourceLocation(), SourceLocation(),
1906314564Sdim        clang::LinkageSpecDecl::LanguageIDs::lang_c, false);
1907314564Sdim  }
1908292932Sdim
1909314564Sdim  // Pass the identifier info for functions the decl_name is needed for
1910314564Sdim  // operators
1911314564Sdim  clang::DeclarationName decl_name =
1912314564Sdim      m_decl_name.getNameKind() == DeclarationName::Identifier
1913314564Sdim          ? m_decl_name.getAsIdentifierInfo()
1914314564Sdim          : m_decl_name;
1915292932Sdim
1916314564Sdim  clang::FunctionDecl *func_decl = FunctionDecl::Create(
1917360784Sdim      ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type,
1918353358Sdim      nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype,
1919353358Sdim      isConstexprSpecified ? CSK_constexpr : CSK_unspecified);
1920292932Sdim
1921314564Sdim  // We have to do more than just synthesize the FunctionDecl.  We have to
1922314564Sdim  // synthesize ParmVarDecls for all of the FunctionDecl's arguments.  To do
1923314564Sdim  // this, we raid the function's FunctionProtoType for types.
1924292932Sdim
1925314564Sdim  const FunctionProtoType *func_proto_type =
1926314564Sdim      qual_type.getTypePtr()->getAs<FunctionProtoType>();
1927292932Sdim
1928314564Sdim  if (func_proto_type) {
1929314564Sdim    unsigned NumArgs = func_proto_type->getNumParams();
1930314564Sdim    unsigned ArgIndex;
1931292932Sdim
1932314564Sdim    SmallVector<ParmVarDecl *, 5> parm_var_decls;
1933292932Sdim
1934314564Sdim    for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) {
1935314564Sdim      QualType arg_qual_type(func_proto_type->getParamType(ArgIndex));
1936314564Sdim
1937353358Sdim      parm_var_decls.push_back(
1938360784Sdim          ParmVarDecl::Create(ast, const_cast<DeclContext *>(context),
1939353358Sdim                              SourceLocation(), SourceLocation(), nullptr,
1940353358Sdim                              arg_qual_type, nullptr, SC_Static, nullptr));
1941292932Sdim    }
1942292932Sdim
1943314564Sdim    func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls));
1944314564Sdim  } else {
1945314564Sdim    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1946292932Sdim
1947360784Sdim    LLDB_LOGF(log, "Function type wasn't a FunctionProtoType");
1948314564Sdim  }
1949314564Sdim
1950341825Sdim  // If this is an operator (e.g. operator new or operator==), only insert the
1951341825Sdim  // declaration we inferred from the symbol if we can provide the correct
1952341825Sdim  // number of arguments. We shouldn't really inject random decl(s) for
1953341825Sdim  // functions that are analyzed semantically in a special way, otherwise we
1954341825Sdim  // will crash in clang.
1955341825Sdim  clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1956341825Sdim  if (func_proto_type &&
1957341825Sdim      ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) {
1958341825Sdim    if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1959341825Sdim            false, op_kind, func_proto_type->getNumParams()))
1960353358Sdim      return nullptr;
1961341825Sdim  }
1962314564Sdim  m_decls.push_back(func_decl);
1963314564Sdim
1964314564Sdim  return func_decl;
1965292932Sdim}
1966292932Sdim
1967314564Sdimclang::NamedDecl *NameSearchContext::AddGenericFunDecl() {
1968314564Sdim  FunctionProtoType::ExtProtoInfo proto_info;
1969292932Sdim
1970314564Sdim  proto_info.Variadic = true;
1971292932Sdim
1972314564Sdim  QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType(
1973314564Sdim      m_ast_source.m_ast_context->UnknownAnyTy, // result
1974314564Sdim      ArrayRef<QualType>(),                     // argument types
1975314564Sdim      proto_info));
1976292932Sdim
1977314564Sdim  return AddFunDecl(
1978360784Sdim      m_ast_source.m_clang_ast_context->GetType(generic_function_type), true);
1979292932Sdim}
1980292932Sdim
1981292932Sdimclang::NamedDecl *
1982314564SdimNameSearchContext::AddTypeDecl(const CompilerType &clang_type) {
1983314564Sdim  if (ClangUtil::IsClangType(clang_type)) {
1984314564Sdim    QualType qual_type = ClangUtil::GetQualType(clang_type);
1985292932Sdim
1986314564Sdim    if (const TypedefType *typedef_type =
1987314564Sdim            llvm::dyn_cast<TypedefType>(qual_type)) {
1988314564Sdim      TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
1989292932Sdim
1990314564Sdim      m_decls.push_back(typedef_name_decl);
1991292932Sdim
1992314564Sdim      return (NamedDecl *)typedef_name_decl;
1993314564Sdim    } else if (const TagType *tag_type = qual_type->getAs<TagType>()) {
1994314564Sdim      TagDecl *tag_decl = tag_type->getDecl();
1995292932Sdim
1996314564Sdim      m_decls.push_back(tag_decl);
1997292932Sdim
1998314564Sdim      return tag_decl;
1999314564Sdim    } else if (const ObjCObjectType *objc_object_type =
2000314564Sdim                   qual_type->getAs<ObjCObjectType>()) {
2001314564Sdim      ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
2002292932Sdim
2003314564Sdim      m_decls.push_back((NamedDecl *)interface_decl);
2004292932Sdim
2005314564Sdim      return (NamedDecl *)interface_decl;
2006292932Sdim    }
2007314564Sdim  }
2008353358Sdim  return nullptr;
2009292932Sdim}
2010292932Sdim
2011314564Sdimvoid NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
2012314564Sdim  for (clang::NamedDecl *decl : result)
2013314564Sdim    m_decls.push_back(decl);
2014292932Sdim}
2015292932Sdim
2016314564Sdimvoid NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) {
2017314564Sdim  m_decls.push_back(decl);
2018292932Sdim}
2019