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