LLDB mainline
ClangASTImporter.cpp
Go to the documentation of this file.
1//===-- ClangASTImporter.cpp ----------------------------------------------===//
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/Core/Module.h"
12#include "lldb/Utility/Log.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Sema.h"
20#include "llvm/Support/raw_ostream.h"
21
28
29#include <memory>
30#include <optional>
31#include <type_traits>
32
33using namespace lldb_private;
34using namespace clang;
35
37 const CompilerType &src_type) {
38 clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();
39
40 auto src_ast = src_type.GetTypeSystem<TypeSystemClang>();
41 if (!src_ast)
42 return CompilerType();
43
44 clang::ASTContext &src_clang_ast = src_ast->getASTContext();
45
46 clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);
47
48 ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));
49 if (!delegate_sp)
50 return CompilerType();
51
52 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);
53
54 llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);
55 if (!ret_or_error) {
57 LLDB_LOG_ERROR(log, ret_or_error.takeError(),
58 "Couldn't import type: {0}");
59 return CompilerType();
60 }
61
62 lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();
63
64 if (dst_clang_type)
65 return CompilerType(dst_ast.weak_from_this(), dst_clang_type);
66 return CompilerType();
67}
68
69clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,
70 clang::Decl *decl) {
71 ImporterDelegateSP delegate_sp;
72
73 clang::ASTContext *src_ast = &decl->getASTContext();
74 delegate_sp = GetDelegate(dst_ast, src_ast);
75
76 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
77
78 if (!delegate_sp)
79 return nullptr;
80
81 llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);
82 if (!result) {
84 LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
85 if (log) {
87 if (std::optional<ClangASTMetadata> metadata = GetDeclMetadata(decl))
88 user_id = metadata->GetUserID();
89
90 if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))
91 LLDB_LOG(log,
92 " [ClangASTImporter] WARNING: Failed to import a {0} "
93 "'{1}', metadata {2}",
94 decl->getDeclKindName(), named_decl->getNameAsString(),
95 user_id);
96 else
97 LLDB_LOG(log,
98 " [ClangASTImporter] WARNING: Failed to import a {0}, "
99 "metadata {1}",
100 decl->getDeclKindName(), user_id);
101 }
102 return nullptr;
103 }
104
105 return *result;
106}
107
109private:
110 struct Backup {
111 clang::DeclContext *decl_context;
112 clang::DeclContext *lexical_decl_context;
113 };
114
115 llvm::DenseMap<clang::Decl *, Backup> m_backups;
116
117 void OverrideOne(clang::Decl *decl) {
118 if (m_backups.contains(decl)) {
119 return;
120 }
121
122 m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};
123
124 decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());
125 decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());
126 // Changing the DeclContext might change the linkage. For example, if the
127 // entity was previously declared inside a function, it will not be
128 // external, but changing the declaration context to the TU will make it
129 // external. Make sure this will recompute the linkage if it was computed
130 // before.
131 decl->invalidateCachedLinkage();
132 }
133
135 clang::Decl *decl, clang::DeclContext *base,
136 clang::DeclContext *(clang::Decl::*contextFromDecl)(),
137 clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {
138 for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;
139 decl_ctx = (decl_ctx->*contextFromContext)()) {
140 if (decl_ctx == base) {
141 return true;
142 }
143 }
144
145 return false;
146 }
147
148 clang::Decl *GetEscapedChild(clang::Decl *decl,
149 clang::DeclContext *base = nullptr) {
150 if (base) {
151 // decl's DeclContext chains must pass through base.
152
153 if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,
154 &clang::DeclContext::getParent) ||
155 !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,
156 &clang::DeclContext::getLexicalParent)) {
157 return decl;
158 }
159 } else {
160 base = clang::dyn_cast<clang::DeclContext>(decl);
161
162 if (!base) {
163 return nullptr;
164 }
165 }
166
167 if (clang::DeclContext *context =
168 clang::dyn_cast<clang::DeclContext>(decl)) {
169 for (clang::Decl *decl : context->decls()) {
170 if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
171 return escaped_child;
172 }
173 }
174 }
175
176 return nullptr;
177 }
178
179 void Override(clang::Decl *decl) {
180 if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
182
183 LLDB_LOG(log,
184 " [ClangASTImporter] DeclContextOverride couldn't "
185 "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",
186 decl->getDeclKindName(), decl, escaped_child->getDeclKindName(),
187 escaped_child);
188 lldbassert(0 && "Couldn't override!");
189 }
190
191 OverrideOne(decl);
192 }
193
194public:
196
198 for (DeclContext *decl_context = decl->getLexicalDeclContext();
199 decl_context; decl_context = decl_context->getLexicalParent()) {
200 DeclContext *redecl_context = decl_context->getRedeclContext();
201
202 if (llvm::isa<FunctionDecl>(redecl_context) &&
203 llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) {
204 for (clang::Decl *child_decl : decl_context->decls()) {
205 Override(child_decl);
206 }
207 }
208 }
209 }
210
212 for (const auto &backup : m_backups) {
213 backup.first->setDeclContext(backup.second.decl_context);
214 backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);
215 }
216 }
217};
218
219namespace {
220/// Completes all imported TagDecls at the end of the scope.
221///
222/// While in a CompleteTagDeclsScope, every decl that could be completed will
223/// be completed at the end of the scope (including all Decls that are
224/// imported while completing the original Decls).
225class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {
227 /// List of declarations in the target context that need to be completed.
228 /// Every declaration should only be completed once and therefore should only
229 /// be once in this list.
230 llvm::SetVector<NamedDecl *> m_decls_to_complete;
231 /// Set of declarations that already were successfully completed (not just
232 /// added to m_decls_to_complete).
233 llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;
234 clang::ASTContext *m_dst_ctx;
235 clang::ASTContext *m_src_ctx;
236 ClangASTImporter &importer;
237
238 void CompleteDecl(
239 Decl *decl,
240 lldb_private::ClangASTImporter::ASTContextMetadata const &to_context_md) {
241 // The decl that should be completed has to be imported into the target
242 // context from some other context.
243 assert(to_context_md.hasOrigin(decl));
244 // We should only complete decls coming from the source context.
245 assert(to_context_md.getOrigin(decl).ctx == m_src_ctx);
246
247 Decl *original_decl = to_context_md.getOrigin(decl).decl;
248
249 // Complete the decl now.
250 TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl);
251 if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {
252 if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
253 if (original_tag_decl->isCompleteDefinition()) {
254 m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);
255 tag_decl->setCompleteDefinition(true);
256 }
257 }
258
259 tag_decl->setHasExternalLexicalStorage(false);
260 tag_decl->setHasExternalVisibleStorage(false);
261 } else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) {
262 container_decl->setHasExternalLexicalStorage(false);
263 container_decl->setHasExternalVisibleStorage(false);
264 }
265 }
266
267public:
268 /// Constructs a CompleteTagDeclsScope.
269 /// \param importer The ClangASTImporter that we should observe.
270 /// \param dst_ctx The ASTContext to which Decls are imported.
271 /// \param src_ctx The ASTContext from which Decls are imported.
272 explicit CompleteTagDeclsScope(ClangASTImporter &importer,
273 clang::ASTContext *dst_ctx,
274 clang::ASTContext *src_ctx)
275 : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),
276 m_src_ctx(src_ctx), importer(importer) {
277 m_delegate->SetImportListener(this);
278 }
279
280 ~CompleteTagDeclsScope() override {
282 importer.GetContextMetadata(m_dst_ctx);
283
284 // Complete all decls we collected until now.
285 while (!m_decls_to_complete.empty()) {
286 NamedDecl *decl = m_decls_to_complete.pop_back_val();
287 m_decls_already_completed.insert(decl);
288
289 CompleteDecl(decl, *to_context_md);
290
291 to_context_md->removeOrigin(decl);
292 }
293
294 // Stop listening to imported decls. We do this after clearing the
295 // Decls we needed to import to catch all Decls they might have pulled in.
296 m_delegate->RemoveImportListener();
297 }
298
299 void NewDeclImported(clang::Decl *from, clang::Decl *to) override {
300 // Filter out decls that we can't complete later.
301 if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to))
302 return;
303 auto *from_record_decl = dyn_cast<CXXRecordDecl>(from);
304 // We don't need to complete injected class name decls.
305 if (from_record_decl && from_record_decl->isInjectedClassName())
306 return;
307
308 NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);
309 // Check if we already completed this type.
310 if (m_decls_already_completed.contains(to_named_decl))
311 return;
312 // Queue this type to be completed.
313 m_decls_to_complete.insert(to_named_decl);
314 }
315};
316} // namespace
317
319 const CompilerType &src_type) {
321
322 auto src_ctxt = src_type.GetTypeSystem<TypeSystemClang>();
323 if (!src_ctxt)
324 return {};
325
326 LLDB_LOG(log,
327 " [ClangASTImporter] DeportType called on ({0}Type*){1:x} "
328 "from (ASTContext*){2:x} to (ASTContext*){3:x}",
329 src_type.GetTypeName(), src_type.GetOpaqueQualType(),
330 &src_ctxt->getASTContext(), &dst.getASTContext());
331
332 DeclContextOverride decl_context_override;
333
334 if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())
335 decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());
336
337 CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
338 &src_ctxt->getASTContext());
339 return CopyType(dst, src_type);
340}
341
342clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
343 clang::Decl *decl) {
345
346 clang::ASTContext *src_ctx = &decl->getASTContext();
347 LLDB_LOG(log,
348 " [ClangASTImporter] DeportDecl called on ({0}Decl*){1:x} from "
349 "(ASTContext*){2:x} to (ASTContext*){3:x}",
350 decl->getDeclKindName(), decl, src_ctx, dst_ctx);
351
352 DeclContextOverride decl_context_override;
353
354 decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
355
356 clang::Decl *result;
357 {
358 CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
359 result = CopyDecl(dst_ctx, decl);
360 }
361
362 if (!result)
363 return nullptr;
364
365 LLDB_LOG(log,
366 " [ClangASTImporter] DeportDecl deported ({0}Decl*){1:x} to "
367 "({2}Decl*){3:x}",
368 decl->getDeclKindName(), decl, result->getDeclKindName(), result);
369
370 return result;
371}
372
373bool ClangASTImporter::CanImport(const Decl *d) {
374 if (!d)
375 return false;
376 if (isa<TagDecl>(d))
377 return GetDeclOrigin(d).Valid();
378 if (isa<ObjCInterfaceDecl>(d))
379 return GetDeclOrigin(d).Valid();
380 return false;
381}
382
384 if (!ClangUtil::IsClangType(type))
385 return false;
386
387 clang::QualType qual_type(
389
390 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
391 switch (type_class) {
392 case clang::Type::Record:
393 return CanImport(qual_type->getAsCXXRecordDecl());
394 case clang::Type::Enum:
395 return CanImport(llvm::cast<clang::EnumType>(qual_type)->getDecl());
396 case clang::Type::ObjCObject:
397 case clang::Type::ObjCInterface: {
398 const clang::ObjCObjectType *objc_class_type =
399 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
400 if (objc_class_type) {
401 clang::ObjCInterfaceDecl *class_interface_decl =
402 objc_class_type->getInterface();
403 // We currently can't complete objective C types through the newly added
404 // ASTContext because it only supports TagDecl objects right now...
405 return CanImport(class_interface_decl);
406 }
407 } break;
408
409 case clang::Type::Typedef:
411 llvm::cast<clang::TypedefType>(qual_type)
412 ->getDecl()
413 ->getUnderlyingType()
414 .getAsOpaquePtr()));
415
416 case clang::Type::Auto:
418 llvm::cast<clang::AutoType>(qual_type)
419 ->getDeducedType()
420 .getAsOpaquePtr()));
421
422 case clang::Type::Paren:
423 return CanImport(CompilerType(
424 type.GetTypeSystem(),
425 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
426
427 default:
428 break;
429 }
430
431 return false;
432}
433
435 if (!ClangUtil::IsClangType(type))
436 return false;
437
438 clang::QualType qual_type(
440
441 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
442 switch (type_class) {
443 case clang::Type::Record: {
444 const clang::CXXRecordDecl *cxx_record_decl =
445 qual_type->getAsCXXRecordDecl();
446 if (cxx_record_decl) {
447 if (GetDeclOrigin(cxx_record_decl).Valid())
448 return CompleteAndFetchChildren(qual_type);
449 }
450 } break;
451
452 case clang::Type::Enum: {
453 clang::EnumDecl *enum_decl =
454 llvm::cast<clang::EnumType>(qual_type)->getDecl();
455 if (enum_decl) {
456 if (GetDeclOrigin(enum_decl).Valid())
457 return CompleteAndFetchChildren(qual_type);
458 }
459 } break;
460
461 case clang::Type::ObjCObject:
462 case clang::Type::ObjCInterface: {
463 const clang::ObjCObjectType *objc_class_type =
464 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
465 if (objc_class_type) {
466 clang::ObjCInterfaceDecl *class_interface_decl =
467 objc_class_type->getInterface();
468 // We currently can't complete objective C types through the newly added
469 // ASTContext because it only supports TagDecl objects right now...
470 if (class_interface_decl) {
471 if (GetDeclOrigin(class_interface_decl).Valid())
472 return CompleteAndFetchChildren(qual_type);
473 }
474 }
475 } break;
476
477 case clang::Type::Typedef:
478 return Import(CompilerType(type.GetTypeSystem(),
479 llvm::cast<clang::TypedefType>(qual_type)
480 ->getDecl()
481 ->getUnderlyingType()
482 .getAsOpaquePtr()));
483
484 case clang::Type::Auto:
485 return Import(CompilerType(type.GetTypeSystem(),
486 llvm::cast<clang::AutoType>(qual_type)
487 ->getDeducedType()
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
502 if (!CanImport(compiler_type))
503 return false;
504
505 if (Import(compiler_type)) {
507 return true;
508 }
509
511 false);
512 return false;
513}
514
515/// Copy layout information from \ref source_map to the \ref destination_map.
516///
517/// In the process of copying over layout info, we may need to import
518/// decls from the \ref source_map. This function will use the supplied
519/// \ref importer to import the necessary decls into \ref dest_ctx.
520///
521/// \param[in,out] dest_ctx Destination ASTContext into which we import
522/// decls from the \ref source_map.
523/// \param[out] destination_map A map from decls in \ref dest_ctx to an
524/// integral offest, which will be copies
525/// of the decl/offest pairs in \ref source_map
526/// if successful.
527/// \param[in] source_map A map from decls to integral offests. These will
528/// be copied into \ref destination_map.
529/// \param[in,out] importer Used to import decls into \ref dest_ctx.
530///
531/// \returns On success, will return 'true' and the offsets in \ref
532/// destination_map
533/// are usable copies of \ref source_map.
534template <class D, class O>
535static bool ImportOffsetMap(clang::ASTContext *dest_ctx,
536 llvm::DenseMap<const D *, O> &destination_map,
537 llvm::DenseMap<const D *, O> &source_map,
538 ClangASTImporter &importer) {
539 // When importing fields into a new record, clang has a hard requirement that
540 // fields be imported in field offset order. Since they are stored in a
541 // DenseMap with a pointer as the key type, this means we cannot simply
542 // iterate over the map, as the order will be non-deterministic. Instead we
543 // have to sort by the offset and then insert in sorted order.
544 typedef std::pair<const D *, O> PairType;
545 std::vector<PairType> sorted_items;
546 sorted_items.reserve(source_map.size());
547 sorted_items.assign(source_map.begin(), source_map.end());
548 llvm::sort(sorted_items, llvm::less_second());
549
550 for (const auto &item : sorted_items) {
551 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
552 DeclFromParser<D> parser_decl(user_decl.Import(dest_ctx, importer));
553 if (parser_decl.IsInvalid())
554 return false;
555 destination_map.insert(
556 std::pair<const D *, O>(parser_decl.decl, item.second));
557 }
558
559 return true;
560}
561
562/// Given a CXXRecordDecl, will calculate and populate \ref base_offsets
563/// with the integral offsets of any of its (possibly virtual) base classes.
564///
565/// \param[in] record_layout ASTRecordLayout of \ref record.
566/// \param[in] record The record that we're calculating the base layouts of.
567/// \param[out] base_offsets Map of base-class decl to integral offset which
568/// this function will fill in.
569///
570/// \returns On success, will return 'true' and the offsets in \ref base_offsets
571/// are usable.
572template <bool IsVirtual>
573bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
575 llvm::DenseMap<const clang::CXXRecordDecl *,
576 clang::CharUnits> &base_offsets) {
577 for (CXXRecordDecl::base_class_const_iterator
578 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
579 be = (IsVirtual ? record->vbases_end() : record->bases_end());
580 bi != be; ++bi) {
581 if (!IsVirtual && bi->isVirtual())
582 continue;
583
584 const clang::Type *origin_base_type = bi->getType().getTypePtr();
585 const clang::RecordType *origin_base_record_type =
586 origin_base_type->getAs<RecordType>();
587
588 if (!origin_base_record_type)
589 return false;
590
591 DeclFromUser<RecordDecl> origin_base_record(
592 origin_base_record_type->getDecl());
593
594 if (origin_base_record.IsInvalid())
595 return false;
596
597 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
598 DynCast<CXXRecordDecl>(origin_base_record));
599
600 if (origin_base_cxx_record.IsInvalid())
601 return false;
602
603 CharUnits base_offset;
604
605 if (IsVirtual)
606 base_offset =
607 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
608 else
609 base_offset =
610 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
611
612 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
613 origin_base_cxx_record.decl, base_offset));
614 }
615
616 return true;
617}
618
620 const RecordDecl *record, uint64_t &size, uint64_t &alignment,
621 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
622 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
623 &base_offsets,
624 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
625 &vbase_offsets) {
626
628
629 clang::ASTContext &dest_ctx = record->getASTContext();
630 LLDB_LOG(log,
631 "LayoutRecordType on (ASTContext*){0:x} '{1}' for (RecordDecl*)"
632 "{2:x} [name = '{3}']",
633 &dest_ctx,
634 TypeSystemClang::GetASTContext(&dest_ctx)->getDisplayName(), record,
635 record->getName());
636
637 DeclFromParser<const RecordDecl> parser_record(record);
638 DeclFromUser<const RecordDecl> origin_record(parser_record.GetOrigin(*this));
639
640 if (origin_record.IsInvalid())
641 return false;
642
643 std::remove_reference_t<decltype(field_offsets)> origin_field_offsets;
644 std::remove_reference_t<decltype(base_offsets)> origin_base_offsets;
645 std::remove_reference_t<decltype(vbase_offsets)> origin_virtual_base_offsets;
646
648 &origin_record->getASTContext(),
649 const_cast<RecordDecl *>(origin_record.decl));
650
651 clang::RecordDecl *definition = origin_record.decl->getDefinition();
652 if (!definition || !definition->isCompleteDefinition())
653 return false;
654
655 const ASTRecordLayout &record_layout(
656 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
657
658 int field_idx = 0, field_count = record_layout.getFieldCount();
659
660 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
661 fe = origin_record->field_end();
662 fi != fe; ++fi) {
663 if (field_idx >= field_count)
664 return false; // Layout didn't go well. Bail out.
665
666 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
667
668 origin_field_offsets.insert(
669 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
670
671 field_idx++;
672 }
673
674 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
675 DynCast<const CXXRecordDecl>(origin_record));
676
677 if (origin_cxx_record.IsValid()) {
678 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
679 origin_base_offsets) ||
680 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
681 origin_virtual_base_offsets))
682 return false;
683 }
684
685 if (!ImportOffsetMap(&dest_ctx, field_offsets, origin_field_offsets, *this) ||
686 !ImportOffsetMap(&dest_ctx, base_offsets, origin_base_offsets, *this) ||
687 !ImportOffsetMap(&dest_ctx, vbase_offsets, origin_virtual_base_offsets,
688 *this))
689 return false;
690
691 size = record_layout.getSize().getQuantity() * dest_ctx.getCharWidth();
692 alignment =
693 record_layout.getAlignment().getQuantity() * dest_ctx.getCharWidth();
694
695 if (log) {
696 LLDB_LOG(log, "LRT returned:");
697 LLDB_LOG(log, "LRT Original = (RecordDecl*){0:x}",
698 static_cast<const void *>(origin_record.decl));
699 LLDB_LOG(log, "LRT Size = {0}", size);
700 LLDB_LOG(log, "LRT Alignment = {0}", alignment);
701 LLDB_LOG(log, "LRT Fields:");
702 for (RecordDecl::field_iterator fi = record->field_begin(),
703 fe = record->field_end();
704 fi != fe; ++fi) {
705 LLDB_LOG(
706 log,
707 "LRT (FieldDecl*){0:x}, Name = '{1}', Type = '{2}', Offset = "
708 "{3} bits",
709 *fi, fi->getName(), fi->getType().getAsString(), field_offsets[*fi]);
710 }
711 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
712 DynCast<const CXXRecordDecl>(parser_record);
713 if (parser_cxx_record.IsValid()) {
714 LLDB_LOG(log, "LRT Bases:");
715 for (CXXRecordDecl::base_class_const_iterator
716 bi = parser_cxx_record->bases_begin(),
717 be = parser_cxx_record->bases_end();
718 bi != be; ++bi) {
719 bool is_virtual = bi->isVirtual();
720
721 QualType base_type = bi->getType();
722 const RecordType *base_record_type = base_type->getAs<RecordType>();
723 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
724 DeclFromParser<CXXRecordDecl> base_cxx_record =
725 DynCast<CXXRecordDecl>(base_record);
726
727 LLDB_LOG(log,
728 "LRT {0}(CXXRecordDecl*){1:x}, Name = '{2}', Offset = "
729 "{3} chars",
730 (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
731 base_cxx_record.decl->getName(),
732 (is_virtual
733 ? vbase_offsets[base_cxx_record.decl].getQuantity()
734 : base_offsets[base_cxx_record.decl].getQuantity()));
735 }
736 } else {
737 LLDB_LOG(log, "LRD Not a CXXRecord, so no bases");
738 }
739 }
740
741 return true;
742}
743
745 const clang::RecordDecl *record_decl, uint64_t &bit_size,
746 uint64_t &alignment,
747 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
748 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
749 &base_offsets,
750 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
751 &vbase_offsets) {
752 RecordDeclToLayoutMap::iterator pos =
753 m_record_decl_to_layout_map.find(record_decl);
754 base_offsets.clear();
755 vbase_offsets.clear();
756 if (pos != m_record_decl_to_layout_map.end()) {
757 bit_size = pos->second.bit_size;
758 alignment = pos->second.alignment;
759 field_offsets.swap(pos->second.field_offsets);
760 base_offsets.swap(pos->second.base_offsets);
761 vbase_offsets.swap(pos->second.vbase_offsets);
763 return true;
764 }
765
766 // It's possible that we calculated the layout in a different
767 // ClangASTImporter instance. Try to import such layout if
768 // our decl has an origin.
769 if (auto origin = GetDeclOrigin(record_decl); origin.Valid())
770 if (importRecordLayoutFromOrigin(record_decl, bit_size, alignment,
771 field_offsets, base_offsets,
772 vbase_offsets))
773 return true;
774
775 bit_size = 0;
776 alignment = 0;
777 field_offsets.clear();
778
779 return false;
780}
781
782void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
783 const LayoutInfo &layout) {
784 m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
785}
786
787bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
788 DeclOrigin decl_origin = GetDeclOrigin(decl);
789
790 if (!decl_origin.Valid())
791 return false;
792
793 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
794 return false;
795
796 ImporterDelegateSP delegate_sp(
797 GetDelegate(&decl->getASTContext(), decl_origin.ctx));
798
799 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
800 &decl->getASTContext());
801 if (delegate_sp)
802 delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
803
804 return true;
805}
806
808 clang::TagDecl *origin_decl) {
809 clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
810
811 if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))
812 return false;
813
814 ImporterDelegateSP delegate_sp(
815 GetDelegate(&decl->getASTContext(), origin_ast_ctx));
816
817 if (delegate_sp)
818 delegate_sp->ImportDefinitionTo(decl, origin_decl);
819
820 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
821
822 context_md->setOrigin(decl, DeclOrigin(origin_ast_ctx, origin_decl));
823 return true;
824}
825
827 clang::ObjCInterfaceDecl *interface_decl) {
828 DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
829
830 if (!decl_origin.Valid())
831 return false;
832
833 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
834 return false;
835
836 ImporterDelegateSP delegate_sp(
837 GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
838
839 if (delegate_sp)
840 delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
841
842 if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
843 RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
844
845 return true;
846}
847
849 if (!RequireCompleteType(type))
850 return false;
851
853
854 if (const TagType *tag_type = type->getAs<TagType>()) {
855 TagDecl *tag_decl = tag_type->getDecl();
856
857 DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
858
859 if (!decl_origin.Valid())
860 return false;
861
862 ImporterDelegateSP delegate_sp(
863 GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
864
865 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
866 &tag_decl->getASTContext());
867
868 TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
869
870 for (Decl *origin_child_decl : origin_tag_decl->decls()) {
871 llvm::Expected<Decl *> imported_or_err =
872 delegate_sp->Import(origin_child_decl);
873 if (!imported_or_err) {
874 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
875 "Couldn't import decl: {0}");
876 return false;
877 }
878 }
879
880 if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
881 record_decl->setHasLoadedFieldsFromExternalStorage(true);
882
883 return true;
884 }
885
886 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
887 if (ObjCInterfaceDecl *objc_interface_decl =
888 objc_object_type->getInterface()) {
889 DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
890
891 if (!decl_origin.Valid())
892 return false;
893
894 ImporterDelegateSP delegate_sp(
895 GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
896
897 ObjCInterfaceDecl *origin_interface_decl =
898 llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
899
900 for (Decl *origin_child_decl : origin_interface_decl->decls()) {
901 llvm::Expected<Decl *> imported_or_err =
902 delegate_sp->Import(origin_child_decl);
903 if (!imported_or_err) {
904 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
905 "Couldn't import decl: {0}");
906 return false;
907 }
908 }
909
910 return true;
911 }
912 return false;
913 }
914
915 return true;
916}
917
918bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
919 if (type.isNull())
920 return false;
921
922 if (const TagType *tag_type = type->getAs<TagType>()) {
923 TagDecl *tag_decl = tag_type->getDecl();
924
925 if (tag_decl->getDefinition())
926 return true;
927
928 return CompleteTagDecl(tag_decl);
929 }
930 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
931 if (ObjCInterfaceDecl *objc_interface_decl =
932 objc_object_type->getInterface())
933 return CompleteObjCInterfaceDecl(objc_interface_decl);
934 return false;
935 }
936 if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
937 return RequireCompleteType(array_type->getElementType());
938 if (const AtomicType *atomic_type = type->getAs<AtomicType>())
939 return RequireCompleteType(atomic_type->getPointeeType());
940
941 return true;
942}
943
944std::optional<ClangASTMetadata>
945ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
946 DeclOrigin decl_origin = GetDeclOrigin(decl);
947
948 if (decl_origin.Valid()) {
950 return ast->GetMetadata(decl_origin.decl);
951 }
952 TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());
953 return ast->GetMetadata(decl);
954}
955
957ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
958 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
959
960 return context_md->getOrigin(decl);
961}
962
963void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
964 clang::Decl *original_decl) {
965 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
966 context_md->setOrigin(
967 decl, DeclOrigin(&original_decl->getASTContext(), original_decl));
968}
969
970void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
971 NamespaceMapSP namespace_map) {
972 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
973
974 context_md->m_namespace_maps[decl] = std::move(namespace_map);
975}
976
978ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
979 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
980
981 NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
982
983 NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
984
985 if (iter != namespace_maps.end())
986 return iter->second;
987 return NamespaceMapSP();
988}
989
990void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
991 assert(decl);
992 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
993
994 const DeclContext *parent_context = decl->getDeclContext();
995 const NamespaceDecl *parent_namespace =
996 dyn_cast<NamespaceDecl>(parent_context);
997 NamespaceMapSP parent_map;
998
999 if (parent_namespace)
1000 parent_map = GetNamespaceMap(parent_namespace);
1001
1002 NamespaceMapSP new_map;
1003
1004 new_map = std::make_shared<NamespaceMap>();
1005
1006 if (context_md->m_map_completer) {
1007 std::string namespace_string = decl->getDeclName().getAsString();
1008
1009 context_md->m_map_completer->CompleteNamespaceMap(
1010 new_map, ConstString(namespace_string), parent_map);
1011 }
1012
1013 context_md->m_namespace_maps[decl] = new_map;
1014}
1015
1016void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
1018
1019 LLDB_LOG(log,
1020 " [ClangASTImporter] Forgetting destination (ASTContext*){0:x}",
1021 dst_ast);
1022
1023 m_metadata_map.erase(dst_ast);
1024}
1025
1026void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
1027 clang::ASTContext *src_ast) {
1029
1031
1032 LLDB_LOG(log,
1033 " [ClangASTImporter] Forgetting source->dest "
1034 "(ASTContext*){0:x}->(ASTContext*){1:x}",
1035 src_ast, dst_ast);
1036
1037 if (!md)
1038 return;
1039
1040 md->m_delegates.erase(src_ast);
1041 md->removeOriginsWithContext(src_ast);
1042}
1043
1045
1046llvm::Expected<Decl *>
1048 // FIXME: The Minimal import mode of clang::ASTImporter does not correctly
1049 // import Lambda definitions. Work around this for now by not importing
1050 // lambdas at all. This is most likely encountered when importing decls from
1051 // the `std` module (not from debug-info), where lambdas can be defined in
1052 // inline function bodies. Those will be imported by LLDB.
1053 if (const auto *CXX = llvm::dyn_cast<clang::CXXRecordDecl>(From))
1054 if (CXX->isLambda())
1055 return llvm::make_error<ASTImportError>(
1056 ASTImportError::UnsupportedConstruct);
1057
1058 if (m_std_handler) {
1059 std::optional<Decl *> D = m_std_handler->Import(From);
1060 if (D) {
1061 // Make sure we don't use this decl later to map it back to it's original
1062 // decl. The decl the CxxModuleHandler created has nothing to do with
1063 // the one from debug info, and linking those two would just cause the
1064 // ASTImporter to try 'updating' the module decl with the minimal one from
1065 // the debug info.
1066 m_decls_to_ignore.insert(*D);
1067 return *D;
1068 }
1069 }
1070
1071 // Check which ASTContext this declaration originally came from.
1072 DeclOrigin origin = m_main.GetDeclOrigin(From);
1073
1074 // Prevent infinite recursion when the origin tracking contains a cycle.
1075 assert(origin.decl != From && "Origin points to itself?");
1076
1077 // If it originally came from the target ASTContext then we can just
1078 // pretend that the original is the one we imported. This can happen for
1079 // example when inspecting a persistent declaration from the scratch
1080 // ASTContext (which will provide the declaration when parsing the
1081 // expression and then we later try to copy the declaration back to the
1082 // scratch ASTContext to store the result).
1083 // Without this check we would ask the ASTImporter to import a declaration
1084 // into the same ASTContext where it came from (which doesn't make a lot of
1085 // sense).
1086 if (origin.Valid() && origin.ctx == &getToContext()) {
1087 RegisterImportedDecl(From, origin.decl);
1088 return origin.decl;
1089 }
1090
1091 // This declaration came originally from another ASTContext. Instead of
1092 // copying our potentially incomplete 'From' Decl we instead go to the
1093 // original ASTContext and copy the original to the target. This is not
1094 // only faster than first completing our current decl and then copying it
1095 // to the target, but it also prevents that indirectly copying the same
1096 // declaration to the same target requires the ASTImporter to merge all
1097 // the different decls that appear to come from different ASTContexts (even
1098 // though all these different source ASTContexts just got a copy from
1099 // one source AST).
1100 if (origin.Valid()) {
1101 auto R = m_main.CopyDecl(&getToContext(), origin.decl);
1102 if (R) {
1103 RegisterImportedDecl(From, R);
1104 return R;
1105 }
1106 }
1107
1108 // If we have a forcefully completed type, try to find an actual definition
1109 // for it in other modules.
1110 std::optional<ClangASTMetadata> md = m_main.GetDeclMetadata(From);
1111 auto *td = dyn_cast<TagDecl>(From);
1112 if (td && md && md->IsForcefullyCompleted()) {
1114 LLDB_LOG(log,
1115 "[ClangASTImporter] Searching for a complete definition of {0} in "
1116 "other modules",
1117 td->getName());
1118 Expected<DeclContext *> dc_or_err = ImportContext(td->getDeclContext());
1119 if (!dc_or_err)
1120 return dc_or_err.takeError();
1121 Expected<DeclarationName> dn_or_err = Import(td->getDeclName());
1122 if (!dn_or_err)
1123 return dn_or_err.takeError();
1124 DeclContext *dc = *dc_or_err;
1125 DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
1126 for (clang::Decl *candidate : lr) {
1127 if (candidate->getKind() == From->getKind()) {
1128 RegisterImportedDecl(From, candidate);
1129 m_decls_to_ignore.insert(candidate);
1130 return candidate;
1131 }
1132 }
1133 LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
1134 }
1135
1136 return ASTImporter::ImportImpl(From);
1137}
1138
1140 clang::Decl *to, clang::Decl *from) {
1142
1143 auto getDeclName = [](Decl const *decl) {
1144 std::string name_string;
1145 if (auto const *from_named_decl = dyn_cast<clang::NamedDecl>(decl)) {
1146 llvm::raw_string_ostream name_stream(name_string);
1147 from_named_decl->printName(name_stream);
1148 }
1149
1150 return name_string;
1151 };
1152
1153 if (log) {
1154 if (auto *D = GetAlreadyImportedOrNull(from); D && D != to) {
1155 LLDB_LOG(
1156 log,
1157 "[ClangASTImporter] ERROR: overwriting an already imported decl "
1158 "'{0:x}' ('{1}') from '{2:x}' with '{3:x}'. Likely due to a name "
1159 "conflict when importing '{1}'.",
1160 D, getDeclName(from), from, to);
1161 }
1162 }
1163
1164 // We might have a forward declaration from a shared library that we
1165 // gave external lexical storage so that Clang asks us about the full
1166 // definition when it needs it. In this case the ASTImporter isn't aware
1167 // that the forward decl from the shared library is the actual import
1168 // target but would create a second declaration that would then be defined.
1169 // We want that 'to' is actually complete after this function so let's
1170 // tell the ASTImporter that 'to' was imported from 'from'.
1171 MapImported(from, to);
1172
1173 if (llvm::Error err = ImportDefinition(from)) {
1174 LLDB_LOG_ERROR(log, std::move(err),
1175 "[ClangASTImporter] Error during importing definition: {0}");
1176 return;
1177 }
1178
1179 if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
1180 if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
1181 to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
1182
1183 if (Log *log_ast = GetLog(LLDBLog::AST)) {
1184 LLDB_LOG(log_ast,
1185 "==== [ClangASTImporter][TUDecl: {0:x}] Imported "
1186 "({1}Decl*){2:x}, named {3} (from "
1187 "(Decl*){4:x})",
1188 static_cast<void *>(to->getTranslationUnitDecl()),
1189 from->getDeclKindName(), static_cast<void *>(to),
1190 getDeclName(from), static_cast<void *>(from));
1191
1192 // Log the AST of the TU.
1193 std::string ast_string;
1194 llvm::raw_string_ostream ast_stream(ast_string);
1195 to->getTranslationUnitDecl()->dump(ast_stream);
1196 LLDB_LOG(log_ast, "{0}", ast_string);
1197 }
1198 }
1199 }
1200
1201 // If we're dealing with an Objective-C class, ensure that the inheritance
1202 // has been set up correctly. The ASTImporter may not do this correctly if
1203 // the class was originally sourced from symbols.
1204
1205 if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
1206 ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
1207
1208 if (to_superclass)
1209 return; // we're not going to override it if it's set
1210
1211 ObjCInterfaceDecl *from_objc_interface = dyn_cast<ObjCInterfaceDecl>(from);
1212
1213 if (!from_objc_interface)
1214 return;
1215
1216 ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
1217
1218 if (!from_superclass)
1219 return;
1220
1221 llvm::Expected<Decl *> imported_from_superclass_decl =
1222 Import(from_superclass);
1223
1224 if (!imported_from_superclass_decl) {
1225 LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
1226 "Couldn't import decl: {0}");
1227 return;
1228 }
1229
1230 ObjCInterfaceDecl *imported_from_superclass =
1231 dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
1232
1233 if (!imported_from_superclass)
1234 return;
1235
1236 if (!to_objc_interface->hasDefinition())
1237 to_objc_interface->startDefinition();
1238
1239 to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
1240 m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
1241 }
1242}
1243
1244/// Takes a CXXMethodDecl and completes the return type if necessary. This
1245/// is currently only necessary for virtual functions with covariant return
1246/// types where Clang's CodeGen expects that the underlying records are already
1247/// completed.
1249 CXXMethodDecl *to_method) {
1250 if (!to_method->isVirtual())
1251 return;
1252 QualType return_type = to_method->getReturnType();
1253 if (!return_type->isPointerType() && !return_type->isReferenceType())
1254 return;
1255
1256 clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();
1257 if (!rd)
1258 return;
1259 if (rd->getDefinition())
1260 return;
1261
1262 importer.CompleteTagDecl(rd);
1263}
1264
1265/// Recreate a module with its parents in \p to_source and return its id.
1266static OptionalClangModuleID
1270 if (!from_id.HasValue())
1271 return {};
1272 clang::Module *module = from_source.getModule(from_id.GetValue());
1274 from_source.GetIDForModule(module->Parent), from_source, to_source);
1275 TypeSystemClang &to_ts = to_source.GetTypeSystem();
1276 return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,
1277 module->IsExplicit);
1278}
1279
1281 clang::Decl *to) {
1283
1284 // Some decls shouldn't be tracked here because they were not created by
1285 // copying 'from' to 'to'. Just exit early for those.
1286 if (m_decls_to_ignore.count(to))
1287 return;
1288
1289 // Transfer module ownership information.
1290 auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1291 getFromContext().getExternalSource());
1292 // Can also be a ClangASTSourceProxy.
1293 auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1294 getToContext().getExternalSource());
1295 if (from_source && to_source) {
1296 OptionalClangModuleID from_id(from->getOwningModuleID());
1297 OptionalClangModuleID to_id =
1298 RemapModule(from_id, *from_source, *to_source);
1299 TypeSystemClang &to_ts = to_source->GetTypeSystem();
1300 to_ts.SetOwningModule(to, to_id);
1301 }
1302
1304 if (std::optional<ClangASTMetadata> metadata = m_main.GetDeclMetadata(from))
1305 user_id = metadata->GetUserID();
1306
1307 if (log) {
1308 if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1309 std::string name_string;
1310 llvm::raw_string_ostream name_stream(name_string);
1311 from_named_decl->printName(name_stream);
1312
1313 LLDB_LOG(
1314 log,
1315 " [ClangASTImporter] Imported ({0}Decl*){1:x}, named {2} (from "
1316 "(Decl*){3:x}), metadata {4}",
1317 from->getDeclKindName(), to, name_string, from, user_id);
1318 } else {
1319 LLDB_LOG(log,
1320 " [ClangASTImporter] Imported ({0}Decl*){1:x} (from "
1321 "(Decl*){2:x}), metadata {3}",
1322 from->getDeclKindName(), to, from, user_id);
1323 }
1324 }
1325
1326 ASTContextMetadataSP to_context_md =
1327 m_main.GetContextMetadata(&to->getASTContext());
1328 ASTContextMetadataSP from_context_md =
1329 m_main.MaybeGetContextMetadata(m_source_ctx);
1330
1331 if (from_context_md) {
1332 DeclOrigin origin = from_context_md->getOrigin(from);
1333
1334 if (origin.Valid()) {
1335 if (origin.ctx != &to->getASTContext()) {
1336 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1337 to_context_md->setOrigin(to, origin);
1338
1339 LLDB_LOG(log,
1340 " [ClangASTImporter] Propagated origin "
1341 "(Decl*){0:x}/(ASTContext*){1:x} from (ASTContext*){2:x} to "
1342 "(ASTContext*){3:x}",
1343 origin.decl, origin.ctx, &from->getASTContext(),
1344 &to->getASTContext());
1345 }
1346 } else {
1348 m_new_decl_listener->NewDeclImported(from, to);
1349
1350 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1351 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1352
1353 LLDB_LOG(log,
1354 " [ClangASTImporter] Decl has no origin information in "
1355 "(ASTContext*){0:x}",
1356 &from->getASTContext());
1357 }
1358
1359 if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {
1360 auto *from_namespace = cast<clang::NamespaceDecl>(from);
1361
1362 NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1363
1364 NamespaceMetaMap::iterator namespace_map_iter =
1365 namespace_maps.find(from_namespace);
1366
1367 if (namespace_map_iter != namespace_maps.end())
1368 to_context_md->m_namespace_maps[to_namespace] =
1369 namespace_map_iter->second;
1370 }
1371 } else {
1372 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1373
1374 LLDB_LOG(log,
1375 " [ClangASTImporter] Sourced origin "
1376 "(Decl*){0:x}/(ASTContext*){1:x} into (ASTContext*){2:x}",
1377 from, m_source_ctx, &to->getASTContext());
1378 }
1379
1380 if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {
1381 m_main.BuildNamespaceMap(to_namespace_decl);
1382 to_namespace_decl->setHasExternalVisibleStorage();
1383 }
1384
1385 MarkDeclImported(from, to);
1386}
1387
1389 Decl *to) {
1391
1392 if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {
1393 to_tag_decl->setHasExternalLexicalStorage();
1394 to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1395 auto from_tag_decl = cast<TagDecl>(from);
1396
1397 LLDB_LOG(
1398 log,
1399 " [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1400 (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1401 (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1402 (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1403 (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1404 }
1405
1406 if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {
1407 to_container_decl->setHasExternalLexicalStorage();
1408 to_container_decl->setHasExternalVisibleStorage();
1409
1410 if (log) {
1411 if (ObjCInterfaceDecl *to_interface_decl =
1412 llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1413 LLDB_LOG(
1414 log,
1415 " [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1416 "{0}{1}{2}",
1417 (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1418 (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1419 (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1420 } else {
1421 LLDB_LOG(
1422 log, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1423 ((Decl *)to_container_decl)->getDeclKindName(),
1424 (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1425 (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1426 }
1427 }
1428 }
1429
1430 if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))
1431 MaybeCompleteReturnType(m_main, to_method);
1432}
1433
1434clang::Decl *
1436 return m_main.GetDeclOrigin(To).decl;
1437}
static OptionalClangModuleID RemapModule(OptionalClangModuleID from_id, ClangExternalASTSourceCallbacks &from_source, ClangExternalASTSourceCallbacks &to_source)
Recreate a module with its parents in to_source and return its id.
bool ExtractBaseOffsets(const ASTRecordLayout &record_layout, DeclFromUser< const CXXRecordDecl > &record, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets)
Given a CXXRecordDecl, will calculate and populate base_offsets with the integral offsets of any of i...
static void MaybeCompleteReturnType(ClangASTImporter &importer, CXXMethodDecl *to_method)
Takes a CXXMethodDecl and completes the return type if necessary.
static bool ImportOffsetMap(clang::ASTContext *dest_ctx, llvm::DenseMap< const D *, O > &destination_map, llvm::DenseMap< const D *, O > &source_map, ClangASTImporter &importer)
Copy layout information from source_map to the destination_map.
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
DeclContextOverride()=default
void Override(clang::Decl *decl)
llvm::DenseMap< clang::Decl *, Backup > m_backups
void OverrideAllDeclsFromContainingFunction(clang::Decl *decl)
void OverrideOne(clang::Decl *decl)
clang::Decl * GetEscapedChild(clang::Decl *decl, clang::DeclContext *base=nullptr)
bool ChainPassesThrough(clang::Decl *decl, clang::DeclContext *base, clang::DeclContext *(clang::Decl::*contextFromDecl)(), clang::DeclContext *(clang::DeclContext::*contextFromContext)())
bool hasOrigin(const clang::Decl *decl) const
Returns true there is a known DeclOrigin for the given Decl.
DeclOrigin getOrigin(const clang::Decl *decl) const
Returns the DeclOrigin for the given Decl or an invalid DeclOrigin instance if there no known DeclOri...
Scope guard that attaches a CxxModuleHandler to an ASTImporterDelegate and deattaches it at the end o...
Manages and observes all Clang AST node importing in LLDB.
bool CompleteTagDecl(clang::TagDecl *decl)
std::optional< ClangASTMetadata > GetDeclMetadata(const clang::Decl *decl)
clang::Decl * DeportDecl(clang::ASTContext *dst_ctx, clang::Decl *decl)
Copies the given decl to the destination type system.
void BuildNamespaceMap(const clang::NamespaceDecl *decl)
void ForgetDestination(clang::ASTContext *dst_ctx)
CompilerType CopyType(TypeSystemClang &dst, const CompilerType &src_type)
Copies the given type and the respective declarations to the destination type system.
clang::Decl * CopyDecl(clang::ASTContext *dst_ctx, clang::Decl *decl)
DeclOrigin GetDeclOrigin(const clang::Decl *decl)
bool LayoutRecordType(const clang::RecordDecl *record_decl, uint64_t &bit_size, uint64_t &alignment, llvm::DenseMap< const clang::FieldDecl *, uint64_t > &field_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &vbase_offsets)
bool CompleteTagDeclWithOrigin(clang::TagDecl *decl, clang::TagDecl *origin)
bool CanImport(const CompilerType &type)
Returns true iff the given type was copied from another TypeSystemClang and the original type in this...
ASTContextMetadataSP GetContextMetadata(clang::ASTContext *dst_ctx)
bool importRecordLayoutFromOrigin(const clang::RecordDecl *record, uint64_t &size, uint64_t &alignment, llvm::DenseMap< const clang::FieldDecl *, uint64_t > &field_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &vbase_offsets)
If record has a valid origin, this function copies that origin's layout into this ClangASTImporter in...
void ForgetSource(clang::ASTContext *dst_ctx, clang::ASTContext *src_ctx)
bool CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *interface_decl)
void RegisterNamespaceMap(const clang::NamespaceDecl *decl, NamespaceMapSP namespace_map)
ASTContextMetadataSP MaybeGetContextMetadata(clang::ASTContext *dst_ctx)
std::shared_ptr< NamespaceMap > NamespaceMapSP
NamespaceMapSP GetNamespaceMap(const clang::NamespaceDecl *decl)
std::shared_ptr< ASTImporterDelegate > ImporterDelegateSP
llvm::DenseMap< const clang::NamespaceDecl *, NamespaceMapSP > NamespaceMetaMap
bool CompleteType(const CompilerType &compiler_type)
void SetRecordLayout(clang::RecordDecl *decl, const LayoutInfo &layout)
Sets the layout for the given RecordDecl.
bool RequireCompleteType(clang::QualType type)
CompilerType DeportType(TypeSystemClang &dst, const CompilerType &src_type)
Copies the given type and the respective declarations to the destination type system.
RecordDeclToLayoutMap m_record_decl_to_layout_map
bool Import(const CompilerType &type)
If the given type was copied from another TypeSystemClang then copy over all missing information (e....
ImporterDelegateSP GetDelegate(clang::ASTContext *dst_ctx, clang::ASTContext *src_ctx)
void SetDeclOrigin(const clang::Decl *decl, clang::Decl *original_decl)
Updates the internal origin-tracking information so that the given 'original' decl is from now on use...
std::shared_ptr< ASTContextMetadata > ASTContextMetadataSP
bool CompleteAndFetchChildren(clang::QualType type)
OptionalClangModuleID GetIDForModule(clang::Module *module)
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
ConstString GetTypeName(bool BaseOnly=false) const
A uniqued constant string class.
Definition ConstString.h:40
DeclFromUser< D > GetOrigin(ClangASTImporter &importer)
DeclFromParser< D > Import(clang::ASTContext *dest_ctx, ClangASTImporter &importer)
A TypeSystem implementation based on Clang.
static void SetOwningModule(clang::Decl *decl, OptionalClangModuleID owning_module)
Set the owning module for decl.
OptionalClangModuleID GetOrCreateClangModule(llvm::StringRef name, OptionalClangModuleID parent, bool is_framework=false, bool is_explicit=false)
Synthesize a clang::Module and return its ID or a default-constructed ID.
static TypeSystemClang * GetASTContext(clang::ASTContext *ast_ctx)
std::optional< ClangASTMetadata > GetMetadata(const clang::Decl *object)
static bool CompleteTagDeclarationDefinition(const CompilerType &type)
static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type, bool has_extern)
bool GetCompleteDecl(clang::Decl *decl)
clang::ASTContext & getASTContext() const
Returns the clang::ASTContext instance managed by this TypeSystemClang.
#define LLDB_INVALID_UID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
TD< D2 > DynCast(TD< D1 > source)
void * opaque_compiler_type_t
Definition lldb-types.h:91
uint64_t user_id_t
Definition lldb-types.h:83
clang::DeclContext * decl_context
clang::DeclContext * lexical_decl_context
clang::Decl * GetOriginalDecl(clang::Decl *To) override
llvm::Expected< clang::Decl * > ImportImpl(clang::Decl *From) override
void MarkDeclImported(clang::Decl *from, clang::Decl *to)
llvm::SmallPtrSet< clang::Decl *, 16 > m_decls_to_ignore
Decls we should ignore when mapping decls back to their original ASTContext.
void Imported(clang::Decl *from, clang::Decl *to) override
NewDeclListener * m_new_decl_listener
The currently attached listener.
void ImportDefinitionTo(clang::Decl *to, clang::Decl *from)
Listener interface used by the ASTImporterDelegate to inform other code about decls that have been im...
static clang::QualType GetQualType(const CompilerType &ct)
Definition ClangUtil.cpp:36
static clang::QualType GetCanonicalQualType(const CompilerType &ct)
Definition ClangUtil.cpp:44
static bool IsClangType(const CompilerType &ct)
Definition ClangUtil.cpp:17
static CompilerType RemoveFastQualifiers(const CompilerType &ct)
Definition ClangUtil.cpp:51