1//===-- ClangASTImporter.cpp ------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Symbol/ClangASTImporter.h"
10#include "lldb/Core/Module.h"
11#include "lldb/Symbol/ClangASTContext.h"
12#include "lldb/Symbol/ClangASTMetadata.h"
13#include "lldb/Symbol/ClangUtil.h"
14#include "lldb/Utility/LLDBAssert.h"
15#include "lldb/Utility/Log.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Sema.h"
21#include "llvm/Support/raw_ostream.h"
22
23#include <memory>
24
25using namespace lldb_private;
26using namespace clang;
27
28CompilerType ClangASTImporter::CopyType(ClangASTContext &dst_ast,
29                                        const CompilerType &src_type) {
30  clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();
31
32  ClangASTContext *src_ast =
33      llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem());
34  if (!src_ast)
35    return CompilerType();
36
37  clang::ASTContext &src_clang_ast = src_ast->getASTContext();
38
39  clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);
40
41  ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));
42  if (!delegate_sp)
43    return CompilerType();
44
45  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);
46
47  llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);
48  if (!ret_or_error) {
49    Log *log =
50      lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
51    LLDB_LOG_ERROR(log, ret_or_error.takeError(),
52        "Couldn't import type: {0}");
53    return CompilerType();
54  }
55
56  lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();
57
58  if (dst_clang_type)
59    return CompilerType(&dst_ast, dst_clang_type);
60  return CompilerType();
61}
62
63clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,
64                                        clang::Decl *decl) {
65  ImporterDelegateSP delegate_sp;
66
67  clang::ASTContext *src_ast = &decl->getASTContext();
68  delegate_sp = GetDelegate(dst_ast, src_ast);
69
70  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
71
72  if (!delegate_sp)
73    return nullptr;
74
75  llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);
76  if (!result) {
77    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
78    LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
79    if (log) {
80      lldb::user_id_t user_id = LLDB_INVALID_UID;
81      ClangASTMetadata *metadata = GetDeclMetadata(decl);
82      if (metadata)
83        user_id = metadata->GetUserID();
84
85      if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))
86        LLDB_LOGF(log,
87                  "  [ClangASTImporter] WARNING: Failed to import a %s "
88                  "'%s', metadata 0x%" PRIx64,
89                  decl->getDeclKindName(),
90                  named_decl->getNameAsString().c_str(), user_id);
91      else
92        LLDB_LOGF(log,
93                  "  [ClangASTImporter] WARNING: Failed to import a %s, "
94                  "metadata 0x%" PRIx64,
95                  decl->getDeclKindName(), user_id);
96    }
97    return nullptr;
98  }
99
100  return *result;
101}
102
103class DeclContextOverride {
104private:
105  struct Backup {
106    clang::DeclContext *decl_context;
107    clang::DeclContext *lexical_decl_context;
108  };
109
110  llvm::DenseMap<clang::Decl *, Backup> m_backups;
111
112  void OverrideOne(clang::Decl *decl) {
113    if (m_backups.find(decl) != m_backups.end()) {
114      return;
115    }
116
117    m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};
118
119    decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());
120    decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());
121  }
122
123  bool ChainPassesThrough(
124      clang::Decl *decl, clang::DeclContext *base,
125      clang::DeclContext *(clang::Decl::*contextFromDecl)(),
126      clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {
127    for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;
128         decl_ctx = (decl_ctx->*contextFromContext)()) {
129      if (decl_ctx == base) {
130        return true;
131      }
132    }
133
134    return false;
135  }
136
137  clang::Decl *GetEscapedChild(clang::Decl *decl,
138                               clang::DeclContext *base = nullptr) {
139    if (base) {
140      // decl's DeclContext chains must pass through base.
141
142      if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,
143                              &clang::DeclContext::getParent) ||
144          !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,
145                              &clang::DeclContext::getLexicalParent)) {
146        return decl;
147      }
148    } else {
149      base = clang::dyn_cast<clang::DeclContext>(decl);
150
151      if (!base) {
152        return nullptr;
153      }
154    }
155
156    if (clang::DeclContext *context =
157            clang::dyn_cast<clang::DeclContext>(decl)) {
158      for (clang::Decl *decl : context->decls()) {
159        if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
160          return escaped_child;
161        }
162      }
163    }
164
165    return nullptr;
166  }
167
168  void Override(clang::Decl *decl) {
169    if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
170      Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
171
172      LLDB_LOGF(log,
173                "    [ClangASTImporter] DeclContextOverride couldn't "
174                "override (%sDecl*)%p - its child (%sDecl*)%p escapes",
175                decl->getDeclKindName(), static_cast<void *>(decl),
176                escaped_child->getDeclKindName(),
177                static_cast<void *>(escaped_child));
178      lldbassert(0 && "Couldn't override!");
179    }
180
181    OverrideOne(decl);
182  }
183
184public:
185  DeclContextOverride() {}
186
187  void OverrideAllDeclsFromContainingFunction(clang::Decl *decl) {
188    for (DeclContext *decl_context = decl->getLexicalDeclContext();
189         decl_context; decl_context = decl_context->getLexicalParent()) {
190      DeclContext *redecl_context = decl_context->getRedeclContext();
191
192      if (llvm::isa<FunctionDecl>(redecl_context) &&
193          llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) {
194        for (clang::Decl *child_decl : decl_context->decls()) {
195          Override(child_decl);
196        }
197      }
198    }
199  }
200
201  ~DeclContextOverride() {
202    for (const std::pair<clang::Decl *, Backup> &backup : m_backups) {
203      backup.first->setDeclContext(backup.second.decl_context);
204      backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);
205    }
206  }
207};
208
209namespace {
210/// Completes all imported TagDecls at the end of the scope.
211///
212/// While in a CompleteTagDeclsScope, every decl that could be completed will
213/// be completed at the end of the scope (including all Decls that are
214/// imported while completing the original Decls).
215class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {
216  ClangASTImporter::ImporterDelegateSP m_delegate;
217  llvm::SmallVector<NamedDecl *, 32> m_decls_to_complete;
218  llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;
219  clang::ASTContext *m_dst_ctx;
220  clang::ASTContext *m_src_ctx;
221  ClangASTImporter &importer;
222
223public:
224  /// Constructs a CompleteTagDeclsScope.
225  /// \param importer The ClangASTImporter that we should observe.
226  /// \param dst_ctx The ASTContext to which Decls are imported.
227  /// \param src_ctx The ASTContext from which Decls are imported.
228  explicit CompleteTagDeclsScope(ClangASTImporter &importer,
229                            clang::ASTContext *dst_ctx,
230                            clang::ASTContext *src_ctx)
231      : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),
232        m_src_ctx(src_ctx), importer(importer) {
233    m_delegate->SetImportListener(this);
234  }
235
236  virtual ~CompleteTagDeclsScope() {
237    ClangASTImporter::ASTContextMetadataSP to_context_md =
238        importer.GetContextMetadata(m_dst_ctx);
239
240    // Complete all decls we collected until now.
241    while (!m_decls_to_complete.empty()) {
242      NamedDecl *decl = m_decls_to_complete.pop_back_val();
243      m_decls_already_completed.insert(decl);
244
245      // We should only complete decls coming from the source context.
246      assert(to_context_md->m_origins[decl].ctx == m_src_ctx);
247
248      Decl *original_decl = to_context_md->m_origins[decl].decl;
249
250      // Complete the decl now.
251      ClangASTContext::GetCompleteDecl(m_src_ctx, original_decl);
252      if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {
253        if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
254          if (original_tag_decl->isCompleteDefinition()) {
255            m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);
256            tag_decl->setCompleteDefinition(true);
257          }
258        }
259
260        tag_decl->setHasExternalLexicalStorage(false);
261        tag_decl->setHasExternalVisibleStorage(false);
262      } else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) {
263        container_decl->setHasExternalLexicalStorage(false);
264        container_decl->setHasExternalVisibleStorage(false);
265      }
266
267      to_context_md->m_origins.erase(decl);
268    }
269
270    // Stop listening to imported decls. We do this after clearing the
271    // Decls we needed to import to catch all Decls they might have pulled in.
272    m_delegate->RemoveImportListener();
273  }
274
275  void NewDeclImported(clang::Decl *from, clang::Decl *to) override {
276    // Filter out decls that we can't complete later.
277    if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to))
278      return;
279    RecordDecl *from_record_decl = dyn_cast<RecordDecl>(from);
280    // We don't need to complete injected class name decls.
281    if (from_record_decl && from_record_decl->isInjectedClassName())
282      return;
283
284    NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);
285    // Check if we already completed this type.
286    if (m_decls_already_completed.count(to_named_decl) != 0)
287      return;
288    m_decls_to_complete.push_back(to_named_decl);
289  }
290};
291} // namespace
292
293CompilerType ClangASTImporter::DeportType(ClangASTContext &dst,
294                                          const CompilerType &src_type) {
295  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
296
297  ClangASTContext *src_ctxt =
298      llvm::cast<ClangASTContext>(src_type.GetTypeSystem());
299
300  LLDB_LOG(log,
301           "    [ClangASTImporter] DeportType called on ({0}Type*){1:x} "
302           "from (ASTContext*){2:x} to (ASTContext*){3:x}",
303           src_type.GetTypeName(), src_type.GetOpaqueQualType(),
304           &src_ctxt->getASTContext(), &dst.getASTContext());
305
306  DeclContextOverride decl_context_override;
307
308  if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())
309    decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());
310
311  CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
312                                       &src_ctxt->getASTContext());
313  return CopyType(dst, src_type);
314}
315
316clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
317                                          clang::Decl *decl) {
318  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
319
320  clang::ASTContext *src_ctx = &decl->getASTContext();
321  LLDB_LOGF(log,
322            "    [ClangASTImporter] DeportDecl called on (%sDecl*)%p from "
323            "(ASTContext*)%p to (ASTContext*)%p",
324            decl->getDeclKindName(), static_cast<void *>(decl),
325            static_cast<void *>(src_ctx), static_cast<void *>(dst_ctx));
326
327  DeclContextOverride decl_context_override;
328
329  decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
330
331  clang::Decl *result;
332  {
333    CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
334    result = CopyDecl(dst_ctx, decl);
335  }
336
337  if (!result)
338    return nullptr;
339
340  LLDB_LOGF(
341      log,
342      "    [ClangASTImporter] DeportDecl deported (%sDecl*)%p to (%sDecl*)%p",
343      decl->getDeclKindName(), static_cast<void *>(decl),
344      result->getDeclKindName(), static_cast<void *>(result));
345
346  return result;
347}
348
349bool ClangASTImporter::CanImport(const CompilerType &type) {
350  if (!ClangUtil::IsClangType(type))
351    return false;
352
353  // TODO: remove external completion BOOL
354  // CompleteAndFetchChildren should get the Decl out and check for the
355
356  clang::QualType qual_type(
357      ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
358
359  const clang::Type::TypeClass type_class = qual_type->getTypeClass();
360  switch (type_class) {
361  case clang::Type::Record: {
362    const clang::CXXRecordDecl *cxx_record_decl =
363        qual_type->getAsCXXRecordDecl();
364    if (cxx_record_decl) {
365      if (GetDeclOrigin(cxx_record_decl).Valid())
366        return true;
367    }
368  } break;
369
370  case clang::Type::Enum: {
371    clang::EnumDecl *enum_decl =
372        llvm::cast<clang::EnumType>(qual_type)->getDecl();
373    if (enum_decl) {
374      if (GetDeclOrigin(enum_decl).Valid())
375        return true;
376    }
377  } break;
378
379  case clang::Type::ObjCObject:
380  case clang::Type::ObjCInterface: {
381    const clang::ObjCObjectType *objc_class_type =
382        llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
383    if (objc_class_type) {
384      clang::ObjCInterfaceDecl *class_interface_decl =
385          objc_class_type->getInterface();
386      // We currently can't complete objective C types through the newly added
387      // ASTContext because it only supports TagDecl objects right now...
388      if (class_interface_decl) {
389        if (GetDeclOrigin(class_interface_decl).Valid())
390          return true;
391      }
392    }
393  } break;
394
395  case clang::Type::Typedef:
396    return CanImport(CompilerType(type.GetTypeSystem(),
397                                  llvm::cast<clang::TypedefType>(qual_type)
398                                      ->getDecl()
399                                      ->getUnderlyingType()
400                                      .getAsOpaquePtr()));
401
402  case clang::Type::Auto:
403    return CanImport(CompilerType(type.GetTypeSystem(),
404                                  llvm::cast<clang::AutoType>(qual_type)
405                                      ->getDeducedType()
406                                      .getAsOpaquePtr()));
407
408  case clang::Type::Elaborated:
409    return CanImport(CompilerType(type.GetTypeSystem(),
410                                  llvm::cast<clang::ElaboratedType>(qual_type)
411                                      ->getNamedType()
412                                      .getAsOpaquePtr()));
413
414  case clang::Type::Paren:
415    return CanImport(CompilerType(
416        type.GetTypeSystem(),
417        llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
418
419  default:
420    break;
421  }
422
423  return false;
424}
425
426bool ClangASTImporter::Import(const CompilerType &type) {
427  if (!ClangUtil::IsClangType(type))
428    return false;
429  // TODO: remove external completion BOOL
430  // CompleteAndFetchChildren should get the Decl out and check for the
431
432  clang::QualType qual_type(
433      ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
434
435  const clang::Type::TypeClass type_class = qual_type->getTypeClass();
436  switch (type_class) {
437  case clang::Type::Record: {
438    const clang::CXXRecordDecl *cxx_record_decl =
439        qual_type->getAsCXXRecordDecl();
440    if (cxx_record_decl) {
441      if (GetDeclOrigin(cxx_record_decl).Valid())
442        return CompleteAndFetchChildren(qual_type);
443    }
444  } break;
445
446  case clang::Type::Enum: {
447    clang::EnumDecl *enum_decl =
448        llvm::cast<clang::EnumType>(qual_type)->getDecl();
449    if (enum_decl) {
450      if (GetDeclOrigin(enum_decl).Valid())
451        return CompleteAndFetchChildren(qual_type);
452    }
453  } break;
454
455  case clang::Type::ObjCObject:
456  case clang::Type::ObjCInterface: {
457    const clang::ObjCObjectType *objc_class_type =
458        llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
459    if (objc_class_type) {
460      clang::ObjCInterfaceDecl *class_interface_decl =
461          objc_class_type->getInterface();
462      // We currently can't complete objective C types through the newly added
463      // ASTContext because it only supports TagDecl objects right now...
464      if (class_interface_decl) {
465        if (GetDeclOrigin(class_interface_decl).Valid())
466          return CompleteAndFetchChildren(qual_type);
467      }
468    }
469  } break;
470
471  case clang::Type::Typedef:
472    return Import(CompilerType(type.GetTypeSystem(),
473                               llvm::cast<clang::TypedefType>(qual_type)
474                                   ->getDecl()
475                                   ->getUnderlyingType()
476                                   .getAsOpaquePtr()));
477
478  case clang::Type::Auto:
479    return Import(CompilerType(type.GetTypeSystem(),
480                               llvm::cast<clang::AutoType>(qual_type)
481                                   ->getDeducedType()
482                                   .getAsOpaquePtr()));
483
484  case clang::Type::Elaborated:
485    return Import(CompilerType(type.GetTypeSystem(),
486                               llvm::cast<clang::ElaboratedType>(qual_type)
487                                   ->getNamedType()
488                                   .getAsOpaquePtr()));
489
490  case clang::Type::Paren:
491    return Import(CompilerType(
492        type.GetTypeSystem(),
493        llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
494
495  default:
496    break;
497  }
498  return false;
499}
500
501bool ClangASTImporter::CompleteType(const CompilerType &compiler_type) {
502  if (!CanImport(compiler_type))
503    return false;
504
505  if (Import(compiler_type)) {
506    ClangASTContext::CompleteTagDeclarationDefinition(compiler_type);
507    return true;
508  }
509
510  ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
511                                         false);
512  return false;
513}
514
515bool ClangASTImporter::LayoutRecordType(
516    const clang::RecordDecl *record_decl, uint64_t &bit_size,
517    uint64_t &alignment,
518    llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
519    llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
520        &base_offsets,
521    llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
522        &vbase_offsets) {
523  RecordDeclToLayoutMap::iterator pos =
524      m_record_decl_to_layout_map.find(record_decl);
525  bool success = false;
526  base_offsets.clear();
527  vbase_offsets.clear();
528  if (pos != m_record_decl_to_layout_map.end()) {
529    bit_size = pos->second.bit_size;
530    alignment = pos->second.alignment;
531    field_offsets.swap(pos->second.field_offsets);
532    base_offsets.swap(pos->second.base_offsets);
533    vbase_offsets.swap(pos->second.vbase_offsets);
534    m_record_decl_to_layout_map.erase(pos);
535    success = true;
536  } else {
537    bit_size = 0;
538    alignment = 0;
539    field_offsets.clear();
540  }
541  return success;
542}
543
544void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
545                                        const LayoutInfo &layout) {
546  m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
547}
548
549void ClangASTImporter::CompleteDecl(clang::Decl *decl) {
550  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
551
552  LLDB_LOGF(log, "    [ClangASTImporter] CompleteDecl called on (%sDecl*)%p",
553            decl->getDeclKindName(), static_cast<void *>(decl));
554
555  if (ObjCInterfaceDecl *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl)) {
556    if (!interface_decl->getDefinition()) {
557      interface_decl->startDefinition();
558      CompleteObjCInterfaceDecl(interface_decl);
559    }
560  } else if (ObjCProtocolDecl *protocol_decl =
561                 dyn_cast<ObjCProtocolDecl>(decl)) {
562    if (!protocol_decl->getDefinition())
563      protocol_decl->startDefinition();
564  } else if (TagDecl *tag_decl = dyn_cast<TagDecl>(decl)) {
565    if (!tag_decl->getDefinition() && !tag_decl->isBeingDefined()) {
566      tag_decl->startDefinition();
567      CompleteTagDecl(tag_decl);
568      tag_decl->setCompleteDefinition(true);
569    }
570  } else {
571    assert(0 && "CompleteDecl called on a Decl that can't be completed");
572  }
573}
574
575bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
576  DeclOrigin decl_origin = GetDeclOrigin(decl);
577
578  if (!decl_origin.Valid())
579    return false;
580
581  if (!ClangASTContext::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
582    return false;
583
584  ImporterDelegateSP delegate_sp(
585      GetDelegate(&decl->getASTContext(), decl_origin.ctx));
586
587  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
588                                                &decl->getASTContext());
589  if (delegate_sp)
590    delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
591
592  return true;
593}
594
595bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl *decl,
596                                                 clang::TagDecl *origin_decl) {
597  clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
598
599  if (!ClangASTContext::GetCompleteDecl(origin_ast_ctx, origin_decl))
600    return false;
601
602  ImporterDelegateSP delegate_sp(
603      GetDelegate(&decl->getASTContext(), origin_ast_ctx));
604
605  if (delegate_sp)
606    delegate_sp->ImportDefinitionTo(decl, origin_decl);
607
608  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
609
610  OriginMap &origins = context_md->m_origins;
611
612  origins[decl] = DeclOrigin(origin_ast_ctx, origin_decl);
613
614  return true;
615}
616
617bool ClangASTImporter::CompleteObjCInterfaceDecl(
618    clang::ObjCInterfaceDecl *interface_decl) {
619  DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
620
621  if (!decl_origin.Valid())
622    return false;
623
624  if (!ClangASTContext::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
625    return false;
626
627  ImporterDelegateSP delegate_sp(
628      GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
629
630  if (delegate_sp)
631    delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
632
633  if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
634    RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
635
636  return true;
637}
638
639bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type) {
640  if (!RequireCompleteType(type))
641    return false;
642
643  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
644
645  if (const TagType *tag_type = type->getAs<TagType>()) {
646    TagDecl *tag_decl = tag_type->getDecl();
647
648    DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
649
650    if (!decl_origin.Valid())
651      return false;
652
653    ImporterDelegateSP delegate_sp(
654        GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
655
656    ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
657                                                  &tag_decl->getASTContext());
658
659    TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
660
661    for (Decl *origin_child_decl : origin_tag_decl->decls()) {
662      llvm::Expected<Decl *> imported_or_err =
663          delegate_sp->Import(origin_child_decl);
664      if (!imported_or_err) {
665        LLDB_LOG_ERROR(log, imported_or_err.takeError(),
666                       "Couldn't import decl: {0}");
667        return false;
668      }
669    }
670
671    if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
672      record_decl->setHasLoadedFieldsFromExternalStorage(true);
673
674    return true;
675  }
676
677  if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
678    if (ObjCInterfaceDecl *objc_interface_decl =
679            objc_object_type->getInterface()) {
680      DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
681
682      if (!decl_origin.Valid())
683        return false;
684
685      ImporterDelegateSP delegate_sp(
686          GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
687
688      ObjCInterfaceDecl *origin_interface_decl =
689          llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
690
691      for (Decl *origin_child_decl : origin_interface_decl->decls()) {
692        llvm::Expected<Decl *> imported_or_err =
693            delegate_sp->Import(origin_child_decl);
694        if (!imported_or_err) {
695          LLDB_LOG_ERROR(log, imported_or_err.takeError(),
696                         "Couldn't import decl: {0}");
697          return false;
698        }
699      }
700
701      return true;
702    }
703    return false;
704  }
705
706  return true;
707}
708
709bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
710  if (type.isNull())
711    return false;
712
713  if (const TagType *tag_type = type->getAs<TagType>()) {
714    TagDecl *tag_decl = tag_type->getDecl();
715
716    if (tag_decl->getDefinition() || tag_decl->isBeingDefined())
717      return true;
718
719    return CompleteTagDecl(tag_decl);
720  }
721  if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
722    if (ObjCInterfaceDecl *objc_interface_decl =
723            objc_object_type->getInterface())
724      return CompleteObjCInterfaceDecl(objc_interface_decl);
725    return false;
726  }
727  if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
728    return RequireCompleteType(array_type->getElementType());
729  if (const AtomicType *atomic_type = type->getAs<AtomicType>())
730    return RequireCompleteType(atomic_type->getPointeeType());
731
732  return true;
733}
734
735ClangASTMetadata *ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
736  DeclOrigin decl_origin = GetDeclOrigin(decl);
737
738  if (decl_origin.Valid()) {
739    ClangASTContext *ast = ClangASTContext::GetASTContext(decl_origin.ctx);
740    return ast->GetMetadata(decl_origin.decl);
741  }
742  ClangASTContext *ast = ClangASTContext::GetASTContext(&decl->getASTContext());
743  return ast->GetMetadata(decl);
744}
745
746ClangASTImporter::DeclOrigin
747ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
748  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
749
750  OriginMap &origins = context_md->m_origins;
751
752  OriginMap::iterator iter = origins.find(decl);
753
754  if (iter != origins.end())
755    return iter->second;
756  return DeclOrigin();
757}
758
759void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
760                                     clang::Decl *original_decl) {
761  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
762
763  OriginMap &origins = context_md->m_origins;
764
765  OriginMap::iterator iter = origins.find(decl);
766
767  if (iter != origins.end()) {
768    iter->second.decl = original_decl;
769    iter->second.ctx = &original_decl->getASTContext();
770    return;
771  }
772  origins[decl] = DeclOrigin(&original_decl->getASTContext(), original_decl);
773}
774
775void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
776                                            NamespaceMapSP &namespace_map) {
777  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
778
779  context_md->m_namespace_maps[decl] = namespace_map;
780}
781
782ClangASTImporter::NamespaceMapSP
783ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
784  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
785
786  NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
787
788  NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
789
790  if (iter != namespace_maps.end())
791    return iter->second;
792  return NamespaceMapSP();
793}
794
795void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
796  assert(decl);
797  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
798
799  const DeclContext *parent_context = decl->getDeclContext();
800  const NamespaceDecl *parent_namespace =
801      dyn_cast<NamespaceDecl>(parent_context);
802  NamespaceMapSP parent_map;
803
804  if (parent_namespace)
805    parent_map = GetNamespaceMap(parent_namespace);
806
807  NamespaceMapSP new_map;
808
809  new_map = std::make_shared<NamespaceMap>();
810
811  if (context_md->m_map_completer) {
812    std::string namespace_string = decl->getDeclName().getAsString();
813
814    context_md->m_map_completer->CompleteNamespaceMap(
815        new_map, ConstString(namespace_string.c_str()), parent_map);
816  }
817
818  context_md->m_namespace_maps[decl] = new_map;
819}
820
821void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
822  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
823
824  LLDB_LOGF(log,
825            "    [ClangASTImporter] Forgetting destination (ASTContext*)%p",
826            static_cast<void *>(dst_ast));
827
828  m_metadata_map.erase(dst_ast);
829}
830
831void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
832                                    clang::ASTContext *src_ast) {
833  ASTContextMetadataSP md = MaybeGetContextMetadata(dst_ast);
834
835  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
836
837  LLDB_LOGF(log,
838            "    [ClangASTImporter] Forgetting source->dest "
839            "(ASTContext*)%p->(ASTContext*)%p",
840            static_cast<void *>(src_ast), static_cast<void *>(dst_ast));
841
842  if (!md)
843    return;
844
845  md->m_delegates.erase(src_ast);
846
847  for (OriginMap::iterator iter = md->m_origins.begin();
848       iter != md->m_origins.end();) {
849    if (iter->second.ctx == src_ast)
850      md->m_origins.erase(iter++);
851    else
852      ++iter;
853  }
854}
855
856ClangASTImporter::MapCompleter::~MapCompleter() { return; }
857
858llvm::Expected<Decl *>
859ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) {
860  if (m_std_handler) {
861    llvm::Optional<Decl *> D = m_std_handler->Import(From);
862    if (D) {
863      // Make sure we don't use this decl later to map it back to it's original
864      // decl. The decl the CxxModuleHandler created has nothing to do with
865      // the one from debug info, and linking those two would just cause the
866      // ASTImporter to try 'updating' the module decl with the minimal one from
867      // the debug info.
868      m_decls_to_ignore.insert(*D);
869      return *D;
870    }
871  }
872
873  // Check which ASTContext this declaration originally came from.
874  DeclOrigin origin = m_master.GetDeclOrigin(From);
875  // If it originally came from the target ASTContext then we can just
876  // pretend that the original is the one we imported. This can happen for
877  // example when inspecting a persistent declaration from the scratch
878  // ASTContext (which will provide the declaration when parsing the
879  // expression and then we later try to copy the declaration back to the
880  // scratch ASTContext to store the result).
881  // Without this check we would ask the ASTImporter to import a declaration
882  // into the same ASTContext where it came from (which doesn't make a lot of
883  // sense).
884  if (origin.Valid() && origin.ctx == &getToContext()) {
885      RegisterImportedDecl(From, origin.decl);
886      return origin.decl;
887  }
888
889  // This declaration came originally from another ASTContext. Instead of
890  // copying our potentially incomplete 'From' Decl we instead go to the
891  // original ASTContext and copy the original to the target. This is not
892  // only faster than first completing our current decl and then copying it
893  // to the target, but it also prevents that indirectly copying the same
894  // declaration to the same target requires the ASTImporter to merge all
895  // the different decls that appear to come from different ASTContexts (even
896  // though all these different source ASTContexts just got a copy from
897  // one source AST).
898  if (origin.Valid()) {
899    auto R = m_master.CopyDecl(&getToContext(), origin.decl);
900    if (R) {
901      RegisterImportedDecl(From, R);
902      return R;
903    }
904  }
905
906  return ASTImporter::ImportImpl(From);
907}
908
909void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(
910    clang::Decl *to, clang::Decl *from) {
911  ASTImporter::Imported(from, to);
912
913  /*
914  if (to_objc_interface)
915      to_objc_interface->startDefinition();
916
917  CXXRecordDecl *to_cxx_record = dyn_cast<CXXRecordDecl>(to);
918
919  if (to_cxx_record)
920      to_cxx_record->startDefinition();
921  */
922
923  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
924
925  if (llvm::Error err = ImportDefinition(from)) {
926    LLDB_LOG_ERROR(log, std::move(err),
927                   "[ClangASTImporter] Error during importing definition: {0}");
928    return;
929  }
930
931  if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
932    if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
933      to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
934
935      if (Log *log_ast =
936              lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_AST)) {
937        std::string name_string;
938        if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
939          llvm::raw_string_ostream name_stream(name_string);
940          from_named_decl->printName(name_stream);
941          name_stream.flush();
942        }
943        LLDB_LOG(log_ast, "==== [ClangASTImporter][TUDecl: {0}] Imported "
944                          "({1}Decl*){2}, named {3} (from "
945                          "(Decl*){4})",
946                 static_cast<void *>(to->getTranslationUnitDecl()),
947                 from->getDeclKindName(), static_cast<void *>(to), name_string,
948                 static_cast<void *>(from));
949
950        // Log the AST of the TU.
951        std::string ast_string;
952        llvm::raw_string_ostream ast_stream(ast_string);
953        to->getTranslationUnitDecl()->dump(ast_stream);
954        LLDB_LOG(log_ast, "{0}", ast_string);
955      }
956    }
957  }
958
959  // If we're dealing with an Objective-C class, ensure that the inheritance
960  // has been set up correctly.  The ASTImporter may not do this correctly if
961  // the class was originally sourced from symbols.
962
963  if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
964    do {
965      ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
966
967      if (to_superclass)
968        break; // we're not going to override it if it's set
969
970      ObjCInterfaceDecl *from_objc_interface =
971          dyn_cast<ObjCInterfaceDecl>(from);
972
973      if (!from_objc_interface)
974        break;
975
976      ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
977
978      if (!from_superclass)
979        break;
980
981      llvm::Expected<Decl *> imported_from_superclass_decl =
982          Import(from_superclass);
983
984      if (!imported_from_superclass_decl) {
985        LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
986                       "Couldn't import decl: {0}");
987        break;
988      }
989
990      ObjCInterfaceDecl *imported_from_superclass =
991          dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
992
993      if (!imported_from_superclass)
994        break;
995
996      if (!to_objc_interface->hasDefinition())
997        to_objc_interface->startDefinition();
998
999      to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
1000          m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
1001    } while (false);
1002  }
1003}
1004
1005void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from,
1006                                                     clang::Decl *to) {
1007  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1008
1009  // Some decls shouldn't be tracked here because they were not created by
1010  // copying 'from' to 'to'. Just exit early for those.
1011  if (m_decls_to_ignore.find(to) != m_decls_to_ignore.end())
1012    return clang::ASTImporter::Imported(from, to);
1013
1014  lldb::user_id_t user_id = LLDB_INVALID_UID;
1015  ClangASTMetadata *metadata = m_master.GetDeclMetadata(from);
1016  if (metadata)
1017    user_id = metadata->GetUserID();
1018
1019  if (log) {
1020    if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1021      std::string name_string;
1022      llvm::raw_string_ostream name_stream(name_string);
1023      from_named_decl->printName(name_stream);
1024      name_stream.flush();
1025
1026      LLDB_LOGF(log,
1027                "    [ClangASTImporter] Imported (%sDecl*)%p, named %s (from "
1028                "(Decl*)%p), metadata 0x%" PRIx64,
1029                from->getDeclKindName(), static_cast<void *>(to),
1030                name_string.c_str(), static_cast<void *>(from), user_id);
1031    } else {
1032      LLDB_LOGF(log,
1033                "    [ClangASTImporter] Imported (%sDecl*)%p (from "
1034                "(Decl*)%p), metadata 0x%" PRIx64,
1035                from->getDeclKindName(), static_cast<void *>(to),
1036                static_cast<void *>(from), user_id);
1037    }
1038  }
1039
1040  ASTContextMetadataSP to_context_md =
1041      m_master.GetContextMetadata(&to->getASTContext());
1042  ASTContextMetadataSP from_context_md =
1043      m_master.MaybeGetContextMetadata(m_source_ctx);
1044
1045  if (from_context_md) {
1046    OriginMap &origins = from_context_md->m_origins;
1047
1048    OriginMap::iterator origin_iter = origins.find(from);
1049
1050    if (origin_iter != origins.end()) {
1051      if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() ||
1052          user_id != LLDB_INVALID_UID) {
1053        if (origin_iter->second.ctx != &to->getASTContext())
1054          to_context_md->m_origins[to] = origin_iter->second;
1055      }
1056
1057      ImporterDelegateSP direct_completer =
1058          m_master.GetDelegate(&to->getASTContext(), origin_iter->second.ctx);
1059
1060      if (direct_completer.get() != this)
1061        direct_completer->ASTImporter::Imported(origin_iter->second.decl, to);
1062
1063      LLDB_LOGF(log,
1064                "    [ClangASTImporter] Propagated origin "
1065                "(Decl*)%p/(ASTContext*)%p from (ASTContext*)%p to "
1066                "(ASTContext*)%p",
1067                static_cast<void *>(origin_iter->second.decl),
1068                static_cast<void *>(origin_iter->second.ctx),
1069                static_cast<void *>(&from->getASTContext()),
1070                static_cast<void *>(&to->getASTContext()));
1071    } else {
1072      if (m_new_decl_listener)
1073        m_new_decl_listener->NewDeclImported(from, to);
1074
1075      if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() ||
1076          user_id != LLDB_INVALID_UID) {
1077        to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from);
1078      }
1079
1080      LLDB_LOGF(log,
1081                "    [ClangASTImporter] Decl has no origin information in "
1082                "(ASTContext*)%p",
1083                static_cast<void *>(&from->getASTContext()));
1084    }
1085
1086    if (clang::NamespaceDecl *to_namespace =
1087            dyn_cast<clang::NamespaceDecl>(to)) {
1088      clang::NamespaceDecl *from_namespace =
1089          dyn_cast<clang::NamespaceDecl>(from);
1090
1091      NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1092
1093      NamespaceMetaMap::iterator namespace_map_iter =
1094          namespace_maps.find(from_namespace);
1095
1096      if (namespace_map_iter != namespace_maps.end())
1097        to_context_md->m_namespace_maps[to_namespace] =
1098            namespace_map_iter->second;
1099    }
1100  } else {
1101    to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from);
1102
1103    LLDB_LOGF(log,
1104              "    [ClangASTImporter] Sourced origin "
1105              "(Decl*)%p/(ASTContext*)%p into (ASTContext*)%p",
1106              static_cast<void *>(from), static_cast<void *>(m_source_ctx),
1107              static_cast<void *>(&to->getASTContext()));
1108  }
1109
1110  if (TagDecl *from_tag_decl = dyn_cast<TagDecl>(from)) {
1111    TagDecl *to_tag_decl = dyn_cast<TagDecl>(to);
1112
1113    to_tag_decl->setHasExternalLexicalStorage();
1114    to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1115
1116    LLDB_LOGF(
1117        log,
1118        "    [ClangASTImporter] To is a TagDecl - attributes %s%s [%s->%s]",
1119        (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1120        (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1121        (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1122        (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1123  }
1124
1125  if (isa<NamespaceDecl>(from)) {
1126    NamespaceDecl *to_namespace_decl = dyn_cast<NamespaceDecl>(to);
1127
1128    m_master.BuildNamespaceMap(to_namespace_decl);
1129
1130    to_namespace_decl->setHasExternalVisibleStorage();
1131  }
1132
1133  if (isa<ObjCContainerDecl>(from)) {
1134    ObjCContainerDecl *to_container_decl = dyn_cast<ObjCContainerDecl>(to);
1135
1136    to_container_decl->setHasExternalLexicalStorage();
1137    to_container_decl->setHasExternalVisibleStorage();
1138
1139    /*to_interface_decl->setExternallyCompleted();*/
1140
1141    if (log) {
1142      if (ObjCInterfaceDecl *to_interface_decl =
1143              llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1144        LLDB_LOGF(
1145            log,
1146            "    [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1147            "%s%s%s",
1148            (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1149            (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1150            (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1151      } else {
1152        LLDB_LOGF(
1153            log, "    [ClangASTImporter] To is an %sDecl - attributes %s%s",
1154            ((Decl *)to_container_decl)->getDeclKindName(),
1155            (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1156            (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1157      }
1158    }
1159  }
1160}
1161
1162clang::Decl *
1163ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) {
1164  return m_master.GetDeclOrigin(To).decl;
1165}
1166