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