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 std::pair<clang::Decl *, Backup> &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(
336 t->getOriginalDecl());
337
338 CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
339 &src_ctxt->getASTContext());
340 return CopyType(dst, src_type);
341}
342
343clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
344 clang::Decl *decl) {
346
347 clang::ASTContext *src_ctx = &decl->getASTContext();
348 LLDB_LOG(log,
349 " [ClangASTImporter] DeportDecl called on ({0}Decl*){1:x} from "
350 "(ASTContext*){2:x} to (ASTContext*){3:x}",
351 decl->getDeclKindName(), decl, src_ctx, dst_ctx);
352
353 DeclContextOverride decl_context_override;
354
355 decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
356
357 clang::Decl *result;
358 {
359 CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
360 result = CopyDecl(dst_ctx, decl);
361 }
362
363 if (!result)
364 return nullptr;
365
366 LLDB_LOG(log,
367 " [ClangASTImporter] DeportDecl deported ({0}Decl*){1:x} to "
368 "({2}Decl*){3:x}",
369 decl->getDeclKindName(), decl, result->getDeclKindName(), result);
370
371 return result;
372}
373
374bool ClangASTImporter::CanImport(const Decl *d) {
375 if (!d)
376 return false;
377 if (isa<TagDecl>(d))
378 return GetDeclOrigin(d).Valid();
379 if (isa<ObjCInterfaceDecl>(d))
380 return GetDeclOrigin(d).Valid();
381 return false;
382}
383
385 if (!ClangUtil::IsClangType(type))
386 return false;
387
388 clang::QualType qual_type(
390
391 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
392 switch (type_class) {
393 case clang::Type::Record:
394 return CanImport(qual_type->getAsCXXRecordDecl());
395 case clang::Type::Enum:
396 return CanImport(llvm::cast<clang::EnumType>(qual_type)->getOriginalDecl());
397 case clang::Type::ObjCObject:
398 case clang::Type::ObjCInterface: {
399 const clang::ObjCObjectType *objc_class_type =
400 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
401 if (objc_class_type) {
402 clang::ObjCInterfaceDecl *class_interface_decl =
403 objc_class_type->getInterface();
404 // We currently can't complete objective C types through the newly added
405 // ASTContext because it only supports TagDecl objects right now...
406 return CanImport(class_interface_decl);
407 }
408 } break;
409
410 case clang::Type::Typedef:
412 llvm::cast<clang::TypedefType>(qual_type)
413 ->getDecl()
414 ->getUnderlyingType()
415 .getAsOpaquePtr()));
416
417 case clang::Type::Auto:
419 llvm::cast<clang::AutoType>(qual_type)
420 ->getDeducedType()
421 .getAsOpaquePtr()));
422
423 case clang::Type::Paren:
424 return CanImport(CompilerType(
425 type.GetTypeSystem(),
426 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
427
428 default:
429 break;
430 }
431
432 return false;
433}
434
436 if (!ClangUtil::IsClangType(type))
437 return false;
438
439 clang::QualType qual_type(
441
442 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
443 switch (type_class) {
444 case clang::Type::Record: {
445 const clang::CXXRecordDecl *cxx_record_decl =
446 qual_type->getAsCXXRecordDecl();
447 if (cxx_record_decl) {
448 if (GetDeclOrigin(cxx_record_decl).Valid())
449 return CompleteAndFetchChildren(qual_type);
450 }
451 } break;
452
453 case clang::Type::Enum: {
454 clang::EnumDecl *enum_decl =
455 llvm::cast<clang::EnumType>(qual_type)->getOriginalDecl();
456 if (enum_decl) {
457 if (GetDeclOrigin(enum_decl).Valid())
458 return CompleteAndFetchChildren(qual_type);
459 }
460 } break;
461
462 case clang::Type::ObjCObject:
463 case clang::Type::ObjCInterface: {
464 const clang::ObjCObjectType *objc_class_type =
465 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
466 if (objc_class_type) {
467 clang::ObjCInterfaceDecl *class_interface_decl =
468 objc_class_type->getInterface();
469 // We currently can't complete objective C types through the newly added
470 // ASTContext because it only supports TagDecl objects right now...
471 if (class_interface_decl) {
472 if (GetDeclOrigin(class_interface_decl).Valid())
473 return CompleteAndFetchChildren(qual_type);
474 }
475 }
476 } break;
477
478 case clang::Type::Typedef:
479 return Import(CompilerType(type.GetTypeSystem(),
480 llvm::cast<clang::TypedefType>(qual_type)
481 ->getDecl()
482 ->getUnderlyingType()
483 .getAsOpaquePtr()));
484
485 case clang::Type::Auto:
486 return Import(CompilerType(type.GetTypeSystem(),
487 llvm::cast<clang::AutoType>(qual_type)
488 ->getDeducedType()
489 .getAsOpaquePtr()));
490
491 case clang::Type::Paren:
492 return Import(CompilerType(
493 type.GetTypeSystem(),
494 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
495
496 default:
497 break;
498 }
499 return false;
500}
501
503 if (!CanImport(compiler_type))
504 return false;
505
506 if (Import(compiler_type)) {
508 return true;
509 }
510
512 false);
513 return false;
514}
515
516/// Copy layout information from \ref source_map to the \ref destination_map.
517///
518/// In the process of copying over layout info, we may need to import
519/// decls from the \ref source_map. This function will use the supplied
520/// \ref importer to import the necessary decls into \ref dest_ctx.
521///
522/// \param[in,out] dest_ctx Destination ASTContext into which we import
523/// decls from the \ref source_map.
524/// \param[out] destination_map A map from decls in \ref dest_ctx to an
525/// integral offest, which will be copies
526/// of the decl/offest pairs in \ref source_map
527/// if successful.
528/// \param[in] source_map A map from decls to integral offests. These will
529/// be copied into \ref destination_map.
530/// \param[in,out] importer Used to import decls into \ref dest_ctx.
531///
532/// \returns On success, will return 'true' and the offsets in \ref
533/// destination_map
534/// are usable copies of \ref source_map.
535template <class D, class O>
536static bool ImportOffsetMap(clang::ASTContext *dest_ctx,
537 llvm::DenseMap<const D *, O> &destination_map,
538 llvm::DenseMap<const D *, O> &source_map,
539 ClangASTImporter &importer) {
540 // When importing fields into a new record, clang has a hard requirement that
541 // fields be imported in field offset order. Since they are stored in a
542 // DenseMap with a pointer as the key type, this means we cannot simply
543 // iterate over the map, as the order will be non-deterministic. Instead we
544 // have to sort by the offset and then insert in sorted order.
545 typedef llvm::DenseMap<const D *, O> MapType;
546 typedef typename MapType::value_type PairType;
547 std::vector<PairType> sorted_items;
548 sorted_items.reserve(source_map.size());
549 sorted_items.assign(source_map.begin(), source_map.end());
550 llvm::sort(sorted_items, llvm::less_second());
551
552 for (const auto &item : sorted_items) {
553 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
554 DeclFromParser<D> parser_decl(user_decl.Import(dest_ctx, importer));
555 if (parser_decl.IsInvalid())
556 return false;
557 destination_map.insert(
558 std::pair<const D *, O>(parser_decl.decl, item.second));
559 }
560
561 return true;
562}
563
564/// Given a CXXRecordDecl, will calculate and populate \ref base_offsets
565/// with the integral offsets of any of its (possibly virtual) base classes.
566///
567/// \param[in] record_layout ASTRecordLayout of \ref record.
568/// \param[in] record The record that we're calculating the base layouts of.
569/// \param[out] base_offsets Map of base-class decl to integral offset which
570/// this function will fill in.
571///
572/// \returns On success, will return 'true' and the offsets in \ref base_offsets
573/// are usable.
574template <bool IsVirtual>
575bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
577 llvm::DenseMap<const clang::CXXRecordDecl *,
578 clang::CharUnits> &base_offsets) {
579 for (CXXRecordDecl::base_class_const_iterator
580 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
581 be = (IsVirtual ? record->vbases_end() : record->bases_end());
582 bi != be; ++bi) {
583 if (!IsVirtual && bi->isVirtual())
584 continue;
585
586 const clang::Type *origin_base_type = bi->getType().getTypePtr();
587 const clang::RecordType *origin_base_record_type =
588 origin_base_type->getAs<RecordType>();
589
590 if (!origin_base_record_type)
591 return false;
592
593 DeclFromUser<RecordDecl> origin_base_record(
594 origin_base_record_type->getOriginalDecl());
595
596 if (origin_base_record.IsInvalid())
597 return false;
598
599 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
600 DynCast<CXXRecordDecl>(origin_base_record));
601
602 if (origin_base_cxx_record.IsInvalid())
603 return false;
604
605 CharUnits base_offset;
606
607 if (IsVirtual)
608 base_offset =
609 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
610 else
611 base_offset =
612 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
613
614 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
615 origin_base_cxx_record.decl, base_offset));
616 }
617
618 return true;
619}
620
622 const RecordDecl *record, uint64_t &size, uint64_t &alignment,
623 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
624 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
625 &base_offsets,
626 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
627 &vbase_offsets) {
628
630
631 clang::ASTContext &dest_ctx = record->getASTContext();
632 LLDB_LOG(log,
633 "LayoutRecordType on (ASTContext*){0:x} '{1}' for (RecordDecl*)"
634 "{2:x} [name = '{3}']",
635 &dest_ctx,
636 TypeSystemClang::GetASTContext(&dest_ctx)->getDisplayName(), record,
637 record->getName());
638
639 DeclFromParser<const RecordDecl> parser_record(record);
640 DeclFromUser<const RecordDecl> origin_record(parser_record.GetOrigin(*this));
641
642 if (origin_record.IsInvalid())
643 return false;
644
645 std::remove_reference_t<decltype(field_offsets)> origin_field_offsets;
646 std::remove_reference_t<decltype(base_offsets)> origin_base_offsets;
647 std::remove_reference_t<decltype(vbase_offsets)> origin_virtual_base_offsets;
648
650 &origin_record->getASTContext(),
651 const_cast<RecordDecl *>(origin_record.decl));
652
653 clang::RecordDecl *definition = origin_record.decl->getDefinition();
654 if (!definition || !definition->isCompleteDefinition())
655 return false;
656
657 const ASTRecordLayout &record_layout(
658 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
659
660 int field_idx = 0, field_count = record_layout.getFieldCount();
661
662 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
663 fe = origin_record->field_end();
664 fi != fe; ++fi) {
665 if (field_idx >= field_count)
666 return false; // Layout didn't go well. Bail out.
667
668 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
669
670 origin_field_offsets.insert(
671 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
672
673 field_idx++;
674 }
675
676 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
677 DynCast<const CXXRecordDecl>(origin_record));
678
679 if (origin_cxx_record.IsValid()) {
680 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
681 origin_base_offsets) ||
682 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
683 origin_virtual_base_offsets))
684 return false;
685 }
686
687 if (!ImportOffsetMap(&dest_ctx, field_offsets, origin_field_offsets, *this) ||
688 !ImportOffsetMap(&dest_ctx, base_offsets, origin_base_offsets, *this) ||
689 !ImportOffsetMap(&dest_ctx, vbase_offsets, origin_virtual_base_offsets,
690 *this))
691 return false;
692
693 size = record_layout.getSize().getQuantity() * dest_ctx.getCharWidth();
694 alignment =
695 record_layout.getAlignment().getQuantity() * dest_ctx.getCharWidth();
696
697 if (log) {
698 LLDB_LOG(log, "LRT returned:");
699 LLDB_LOG(log, "LRT Original = (RecordDecl*){0:x}",
700 static_cast<const void *>(origin_record.decl));
701 LLDB_LOG(log, "LRT Size = {0}", size);
702 LLDB_LOG(log, "LRT Alignment = {0}", alignment);
703 LLDB_LOG(log, "LRT Fields:");
704 for (RecordDecl::field_iterator fi = record->field_begin(),
705 fe = record->field_end();
706 fi != fe; ++fi) {
707 LLDB_LOG(
708 log,
709 "LRT (FieldDecl*){0:x}, Name = '{1}', Type = '{2}', Offset = "
710 "{3} bits",
711 *fi, fi->getName(), fi->getType().getAsString(), field_offsets[*fi]);
712 }
713 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
714 DynCast<const CXXRecordDecl>(parser_record);
715 if (parser_cxx_record.IsValid()) {
716 LLDB_LOG(log, "LRT Bases:");
717 for (CXXRecordDecl::base_class_const_iterator
718 bi = parser_cxx_record->bases_begin(),
719 be = parser_cxx_record->bases_end();
720 bi != be; ++bi) {
721 bool is_virtual = bi->isVirtual();
722
723 QualType base_type = bi->getType();
724 const RecordType *base_record_type = base_type->getAs<RecordType>();
725 DeclFromParser<RecordDecl> base_record(
726 base_record_type->getOriginalDecl());
727 DeclFromParser<CXXRecordDecl> base_cxx_record =
728 DynCast<CXXRecordDecl>(base_record);
729
730 LLDB_LOG(log,
731 "LRT {0}(CXXRecordDecl*){1:x}, Name = '{2}', Offset = "
732 "{3} chars",
733 (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
734 base_cxx_record.decl->getName(),
735 (is_virtual
736 ? vbase_offsets[base_cxx_record.decl].getQuantity()
737 : base_offsets[base_cxx_record.decl].getQuantity()));
738 }
739 } else {
740 LLDB_LOG(log, "LRD Not a CXXRecord, so no bases");
741 }
742 }
743
744 return true;
745}
746
748 const clang::RecordDecl *record_decl, uint64_t &bit_size,
749 uint64_t &alignment,
750 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
751 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
752 &base_offsets,
753 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
754 &vbase_offsets) {
755 RecordDeclToLayoutMap::iterator pos =
756 m_record_decl_to_layout_map.find(record_decl);
757 base_offsets.clear();
758 vbase_offsets.clear();
759 if (pos != m_record_decl_to_layout_map.end()) {
760 bit_size = pos->second.bit_size;
761 alignment = pos->second.alignment;
762 field_offsets.swap(pos->second.field_offsets);
763 base_offsets.swap(pos->second.base_offsets);
764 vbase_offsets.swap(pos->second.vbase_offsets);
766 return true;
767 }
768
769 // It's possible that we calculated the layout in a different
770 // ClangASTImporter instance. Try to import such layout if
771 // our decl has an origin.
772 if (auto origin = GetDeclOrigin(record_decl); origin.Valid())
773 if (importRecordLayoutFromOrigin(record_decl, bit_size, alignment,
774 field_offsets, base_offsets,
775 vbase_offsets))
776 return true;
777
778 bit_size = 0;
779 alignment = 0;
780 field_offsets.clear();
781
782 return false;
783}
784
785void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
786 const LayoutInfo &layout) {
787 m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
788}
789
790bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
791 DeclOrigin decl_origin = GetDeclOrigin(decl);
792
793 if (!decl_origin.Valid())
794 return false;
795
796 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
797 return false;
798
799 ImporterDelegateSP delegate_sp(
800 GetDelegate(&decl->getASTContext(), decl_origin.ctx));
801
802 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
803 &decl->getASTContext());
804 if (delegate_sp)
805 delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
806
807 return true;
808}
809
811 clang::TagDecl *origin_decl) {
812 clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
813
814 if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))
815 return false;
816
817 ImporterDelegateSP delegate_sp(
818 GetDelegate(&decl->getASTContext(), origin_ast_ctx));
819
820 if (delegate_sp)
821 delegate_sp->ImportDefinitionTo(decl, origin_decl);
822
823 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
824
825 context_md->setOrigin(decl, DeclOrigin(origin_ast_ctx, origin_decl));
826 return true;
827}
828
830 clang::ObjCInterfaceDecl *interface_decl) {
831 DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
832
833 if (!decl_origin.Valid())
834 return false;
835
836 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
837 return false;
838
839 ImporterDelegateSP delegate_sp(
840 GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
841
842 if (delegate_sp)
843 delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
844
845 if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
846 RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
847
848 return true;
849}
850
852 if (!RequireCompleteType(type))
853 return false;
854
856
857 if (const TagType *tag_type = type->getAs<TagType>()) {
858 TagDecl *tag_decl = tag_type->getOriginalDecl();
859
860 DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
861
862 if (!decl_origin.Valid())
863 return false;
864
865 ImporterDelegateSP delegate_sp(
866 GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
867
868 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
869 &tag_decl->getASTContext());
870
871 TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
872
873 for (Decl *origin_child_decl : origin_tag_decl->decls()) {
874 llvm::Expected<Decl *> imported_or_err =
875 delegate_sp->Import(origin_child_decl);
876 if (!imported_or_err) {
877 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
878 "Couldn't import decl: {0}");
879 return false;
880 }
881 }
882
883 if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
884 record_decl->setHasLoadedFieldsFromExternalStorage(true);
885
886 return true;
887 }
888
889 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
890 if (ObjCInterfaceDecl *objc_interface_decl =
891 objc_object_type->getInterface()) {
892 DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
893
894 if (!decl_origin.Valid())
895 return false;
896
897 ImporterDelegateSP delegate_sp(
898 GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
899
900 ObjCInterfaceDecl *origin_interface_decl =
901 llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
902
903 for (Decl *origin_child_decl : origin_interface_decl->decls()) {
904 llvm::Expected<Decl *> imported_or_err =
905 delegate_sp->Import(origin_child_decl);
906 if (!imported_or_err) {
907 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
908 "Couldn't import decl: {0}");
909 return false;
910 }
911 }
912
913 return true;
914 }
915 return false;
916 }
917
918 return true;
919}
920
921bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
922 if (type.isNull())
923 return false;
924
925 if (const TagType *tag_type = type->getAs<TagType>()) {
926 TagDecl *tag_decl = tag_type->getOriginalDecl();
927
928 if (tag_decl->getDefinition())
929 return true;
930
931 return CompleteTagDecl(tag_decl);
932 }
933 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
934 if (ObjCInterfaceDecl *objc_interface_decl =
935 objc_object_type->getInterface())
936 return CompleteObjCInterfaceDecl(objc_interface_decl);
937 return false;
938 }
939 if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
940 return RequireCompleteType(array_type->getElementType());
941 if (const AtomicType *atomic_type = type->getAs<AtomicType>())
942 return RequireCompleteType(atomic_type->getPointeeType());
943
944 return true;
945}
946
947std::optional<ClangASTMetadata>
948ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
949 DeclOrigin decl_origin = GetDeclOrigin(decl);
950
951 if (decl_origin.Valid()) {
953 return ast->GetMetadata(decl_origin.decl);
954 }
955 TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());
956 return ast->GetMetadata(decl);
957}
958
960ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
961 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
962
963 return context_md->getOrigin(decl);
964}
965
966void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
967 clang::Decl *original_decl) {
968 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
969 context_md->setOrigin(
970 decl, DeclOrigin(&original_decl->getASTContext(), original_decl));
971}
972
973void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
974 NamespaceMapSP &namespace_map) {
975 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
976
977 context_md->m_namespace_maps[decl] = namespace_map;
978}
979
981ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
982 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
983
984 NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
985
986 NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
987
988 if (iter != namespace_maps.end())
989 return iter->second;
990 return NamespaceMapSP();
991}
992
993void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
994 assert(decl);
995 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
996
997 const DeclContext *parent_context = decl->getDeclContext();
998 const NamespaceDecl *parent_namespace =
999 dyn_cast<NamespaceDecl>(parent_context);
1000 NamespaceMapSP parent_map;
1001
1002 if (parent_namespace)
1003 parent_map = GetNamespaceMap(parent_namespace);
1004
1005 NamespaceMapSP new_map;
1006
1007 new_map = std::make_shared<NamespaceMap>();
1008
1009 if (context_md->m_map_completer) {
1010 std::string namespace_string = decl->getDeclName().getAsString();
1011
1012 context_md->m_map_completer->CompleteNamespaceMap(
1013 new_map, ConstString(namespace_string.c_str()), parent_map);
1014 }
1015
1016 context_md->m_namespace_maps[decl] = new_map;
1017}
1018
1019void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
1021
1022 LLDB_LOG(log,
1023 " [ClangASTImporter] Forgetting destination (ASTContext*){0:x}",
1024 dst_ast);
1025
1026 m_metadata_map.erase(dst_ast);
1027}
1028
1029void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
1030 clang::ASTContext *src_ast) {
1032
1034
1035 LLDB_LOG(log,
1036 " [ClangASTImporter] Forgetting source->dest "
1037 "(ASTContext*){0:x}->(ASTContext*){1:x}",
1038 src_ast, dst_ast);
1039
1040 if (!md)
1041 return;
1042
1043 md->m_delegates.erase(src_ast);
1044 md->removeOriginsWithContext(src_ast);
1045}
1046
1048
1049llvm::Expected<Decl *>
1051 // FIXME: The Minimal import mode of clang::ASTImporter does not correctly
1052 // import Lambda definitions. Work around this for now by not importing
1053 // lambdas at all. This is most likely encountered when importing decls from
1054 // the `std` module (not from debug-info), where lambdas can be defined in
1055 // inline function bodies. Those will be imported by LLDB.
1056 if (const auto *CXX = llvm::dyn_cast<clang::CXXRecordDecl>(From))
1057 if (CXX->isLambda())
1058 return llvm::make_error<ASTImportError>(
1059 ASTImportError::UnsupportedConstruct);
1060
1061 if (m_std_handler) {
1062 std::optional<Decl *> D = m_std_handler->Import(From);
1063 if (D) {
1064 // Make sure we don't use this decl later to map it back to it's original
1065 // decl. The decl the CxxModuleHandler created has nothing to do with
1066 // the one from debug info, and linking those two would just cause the
1067 // ASTImporter to try 'updating' the module decl with the minimal one from
1068 // the debug info.
1069 m_decls_to_ignore.insert(*D);
1070 return *D;
1071 }
1072 }
1073
1074 // Check which ASTContext this declaration originally came from.
1075 DeclOrigin origin = m_main.GetDeclOrigin(From);
1076
1077 // Prevent infinite recursion when the origin tracking contains a cycle.
1078 assert(origin.decl != From && "Origin points to itself?");
1079
1080 // If it originally came from the target ASTContext then we can just
1081 // pretend that the original is the one we imported. This can happen for
1082 // example when inspecting a persistent declaration from the scratch
1083 // ASTContext (which will provide the declaration when parsing the
1084 // expression and then we later try to copy the declaration back to the
1085 // scratch ASTContext to store the result).
1086 // Without this check we would ask the ASTImporter to import a declaration
1087 // into the same ASTContext where it came from (which doesn't make a lot of
1088 // sense).
1089 if (origin.Valid() && origin.ctx == &getToContext()) {
1090 RegisterImportedDecl(From, origin.decl);
1091 return origin.decl;
1092 }
1093
1094 // This declaration came originally from another ASTContext. Instead of
1095 // copying our potentially incomplete 'From' Decl we instead go to the
1096 // original ASTContext and copy the original to the target. This is not
1097 // only faster than first completing our current decl and then copying it
1098 // to the target, but it also prevents that indirectly copying the same
1099 // declaration to the same target requires the ASTImporter to merge all
1100 // the different decls that appear to come from different ASTContexts (even
1101 // though all these different source ASTContexts just got a copy from
1102 // one source AST).
1103 if (origin.Valid()) {
1104 auto R = m_main.CopyDecl(&getToContext(), origin.decl);
1105 if (R) {
1106 RegisterImportedDecl(From, R);
1107 return R;
1108 }
1109 }
1110
1111 // If we have a forcefully completed type, try to find an actual definition
1112 // for it in other modules.
1113 std::optional<ClangASTMetadata> md = m_main.GetDeclMetadata(From);
1114 auto *td = dyn_cast<TagDecl>(From);
1115 if (td && md && md->IsForcefullyCompleted()) {
1117 LLDB_LOG(log,
1118 "[ClangASTImporter] Searching for a complete definition of {0} in "
1119 "other modules",
1120 td->getName());
1121 Expected<DeclContext *> dc_or_err = ImportContext(td->getDeclContext());
1122 if (!dc_or_err)
1123 return dc_or_err.takeError();
1124 Expected<DeclarationName> dn_or_err = Import(td->getDeclName());
1125 if (!dn_or_err)
1126 return dn_or_err.takeError();
1127 DeclContext *dc = *dc_or_err;
1128 DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
1129 for (clang::Decl *candidate : lr) {
1130 if (candidate->getKind() == From->getKind()) {
1131 RegisterImportedDecl(From, candidate);
1132 m_decls_to_ignore.insert(candidate);
1133 return candidate;
1134 }
1135 }
1136 LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
1137 }
1138
1139 return ASTImporter::ImportImpl(From);
1140}
1141
1143 clang::Decl *to, clang::Decl *from) {
1145
1146 auto getDeclName = [](Decl const *decl) {
1147 std::string name_string;
1148 if (auto const *from_named_decl = dyn_cast<clang::NamedDecl>(decl)) {
1149 llvm::raw_string_ostream name_stream(name_string);
1150 from_named_decl->printName(name_stream);
1151 }
1152
1153 return name_string;
1154 };
1155
1156 if (log) {
1157 if (auto *D = GetAlreadyImportedOrNull(from); D && D != to) {
1158 LLDB_LOG(
1159 log,
1160 "[ClangASTImporter] ERROR: overwriting an already imported decl "
1161 "'{0:x}' ('{1}') from '{2:x}' with '{3:x}'. Likely due to a name "
1162 "conflict when importing '{1}'.",
1163 D, getDeclName(from), from, to);
1164 }
1165 }
1166
1167 // We might have a forward declaration from a shared library that we
1168 // gave external lexical storage so that Clang asks us about the full
1169 // definition when it needs it. In this case the ASTImporter isn't aware
1170 // that the forward decl from the shared library is the actual import
1171 // target but would create a second declaration that would then be defined.
1172 // We want that 'to' is actually complete after this function so let's
1173 // tell the ASTImporter that 'to' was imported from 'from'.
1174 MapImported(from, to);
1175
1176 if (llvm::Error err = ImportDefinition(from)) {
1177 LLDB_LOG_ERROR(log, std::move(err),
1178 "[ClangASTImporter] Error during importing definition: {0}");
1179 return;
1180 }
1181
1182 if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
1183 if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
1184 to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
1185
1186 if (Log *log_ast = GetLog(LLDBLog::AST)) {
1187 LLDB_LOG(log_ast,
1188 "==== [ClangASTImporter][TUDecl: {0:x}] Imported "
1189 "({1}Decl*){2:x}, named {3} (from "
1190 "(Decl*){4:x})",
1191 static_cast<void *>(to->getTranslationUnitDecl()),
1192 from->getDeclKindName(), static_cast<void *>(to),
1193 getDeclName(from), static_cast<void *>(from));
1194
1195 // Log the AST of the TU.
1196 std::string ast_string;
1197 llvm::raw_string_ostream ast_stream(ast_string);
1198 to->getTranslationUnitDecl()->dump(ast_stream);
1199 LLDB_LOG(log_ast, "{0}", ast_string);
1200 }
1201 }
1202 }
1203
1204 // If we're dealing with an Objective-C class, ensure that the inheritance
1205 // has been set up correctly. The ASTImporter may not do this correctly if
1206 // the class was originally sourced from symbols.
1207
1208 if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
1209 ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
1210
1211 if (to_superclass)
1212 return; // we're not going to override it if it's set
1213
1214 ObjCInterfaceDecl *from_objc_interface = dyn_cast<ObjCInterfaceDecl>(from);
1215
1216 if (!from_objc_interface)
1217 return;
1218
1219 ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
1220
1221 if (!from_superclass)
1222 return;
1223
1224 llvm::Expected<Decl *> imported_from_superclass_decl =
1225 Import(from_superclass);
1226
1227 if (!imported_from_superclass_decl) {
1228 LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
1229 "Couldn't import decl: {0}");
1230 return;
1231 }
1232
1233 ObjCInterfaceDecl *imported_from_superclass =
1234 dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
1235
1236 if (!imported_from_superclass)
1237 return;
1238
1239 if (!to_objc_interface->hasDefinition())
1240 to_objc_interface->startDefinition();
1241
1242 to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
1243 m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
1244 }
1245}
1246
1247/// Takes a CXXMethodDecl and completes the return type if necessary. This
1248/// is currently only necessary for virtual functions with covariant return
1249/// types where Clang's CodeGen expects that the underlying records are already
1250/// completed.
1252 CXXMethodDecl *to_method) {
1253 if (!to_method->isVirtual())
1254 return;
1255 QualType return_type = to_method->getReturnType();
1256 if (!return_type->isPointerType() && !return_type->isReferenceType())
1257 return;
1258
1259 clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();
1260 if (!rd)
1261 return;
1262 if (rd->getDefinition())
1263 return;
1264
1265 importer.CompleteTagDecl(rd);
1266}
1267
1268/// Recreate a module with its parents in \p to_source and return its id.
1269static OptionalClangModuleID
1273 if (!from_id.HasValue())
1274 return {};
1275 clang::Module *module = from_source.getModule(from_id.GetValue());
1277 from_source.GetIDForModule(module->Parent), from_source, to_source);
1278 TypeSystemClang &to_ts = to_source.GetTypeSystem();
1279 return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,
1280 module->IsExplicit);
1281}
1282
1284 clang::Decl *to) {
1286
1287 // Some decls shouldn't be tracked here because they were not created by
1288 // copying 'from' to 'to'. Just exit early for those.
1289 if (m_decls_to_ignore.count(to))
1290 return;
1291
1292 // Transfer module ownership information.
1293 auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1294 getFromContext().getExternalSource());
1295 // Can also be a ClangASTSourceProxy.
1296 auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1297 getToContext().getExternalSource());
1298 if (from_source && to_source) {
1299 OptionalClangModuleID from_id(from->getOwningModuleID());
1300 OptionalClangModuleID to_id =
1301 RemapModule(from_id, *from_source, *to_source);
1302 TypeSystemClang &to_ts = to_source->GetTypeSystem();
1303 to_ts.SetOwningModule(to, to_id);
1304 }
1305
1307 if (std::optional<ClangASTMetadata> metadata = m_main.GetDeclMetadata(from))
1308 user_id = metadata->GetUserID();
1309
1310 if (log) {
1311 if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1312 std::string name_string;
1313 llvm::raw_string_ostream name_stream(name_string);
1314 from_named_decl->printName(name_stream);
1315
1316 LLDB_LOG(
1317 log,
1318 " [ClangASTImporter] Imported ({0}Decl*){1:x}, named {2} (from "
1319 "(Decl*){3:x}), metadata {4}",
1320 from->getDeclKindName(), to, name_string, from, user_id);
1321 } else {
1322 LLDB_LOG(log,
1323 " [ClangASTImporter] Imported ({0}Decl*){1:x} (from "
1324 "(Decl*){2:x}), metadata {3}",
1325 from->getDeclKindName(), to, from, user_id);
1326 }
1327 }
1328
1329 ASTContextMetadataSP to_context_md =
1330 m_main.GetContextMetadata(&to->getASTContext());
1331 ASTContextMetadataSP from_context_md =
1332 m_main.MaybeGetContextMetadata(m_source_ctx);
1333
1334 if (from_context_md) {
1335 DeclOrigin origin = from_context_md->getOrigin(from);
1336
1337 if (origin.Valid()) {
1338 if (origin.ctx != &to->getASTContext()) {
1339 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1340 to_context_md->setOrigin(to, origin);
1341
1342 LLDB_LOG(log,
1343 " [ClangASTImporter] Propagated origin "
1344 "(Decl*){0:x}/(ASTContext*){1:x} from (ASTContext*){2:x} to "
1345 "(ASTContext*){3:x}",
1346 origin.decl, origin.ctx, &from->getASTContext(),
1347 &to->getASTContext());
1348 }
1349 } else {
1351 m_new_decl_listener->NewDeclImported(from, to);
1352
1353 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1354 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1355
1356 LLDB_LOG(log,
1357 " [ClangASTImporter] Decl has no origin information in "
1358 "(ASTContext*){0:x}",
1359 &from->getASTContext());
1360 }
1361
1362 if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {
1363 auto *from_namespace = cast<clang::NamespaceDecl>(from);
1364
1365 NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1366
1367 NamespaceMetaMap::iterator namespace_map_iter =
1368 namespace_maps.find(from_namespace);
1369
1370 if (namespace_map_iter != namespace_maps.end())
1371 to_context_md->m_namespace_maps[to_namespace] =
1372 namespace_map_iter->second;
1373 }
1374 } else {
1375 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1376
1377 LLDB_LOG(log,
1378 " [ClangASTImporter] Sourced origin "
1379 "(Decl*){0:x}/(ASTContext*){1:x} into (ASTContext*){2:x}",
1380 from, m_source_ctx, &to->getASTContext());
1381 }
1382
1383 if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {
1384 m_main.BuildNamespaceMap(to_namespace_decl);
1385 to_namespace_decl->setHasExternalVisibleStorage();
1386 }
1387
1388 MarkDeclImported(from, to);
1389}
1390
1392 Decl *to) {
1394
1395 if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {
1396 to_tag_decl->setHasExternalLexicalStorage();
1397 to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1398 auto from_tag_decl = cast<TagDecl>(from);
1399
1400 LLDB_LOG(
1401 log,
1402 " [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1403 (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1404 (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1405 (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1406 (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1407 }
1408
1409 if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {
1410 to_container_decl->setHasExternalLexicalStorage();
1411 to_container_decl->setHasExternalVisibleStorage();
1412
1413 if (log) {
1414 if (ObjCInterfaceDecl *to_interface_decl =
1415 llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1416 LLDB_LOG(
1417 log,
1418 " [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1419 "{0}{1}{2}",
1420 (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1421 (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1422 (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1423 } else {
1424 LLDB_LOG(
1425 log, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1426 ((Decl *)to_container_decl)->getDeclKindName(),
1427 (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1428 (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1429 }
1430 }
1431 }
1432
1433 if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))
1434 MaybeCompleteReturnType(m_main, to_method);
1435}
1436
1437clang::Decl *
1439 return m_main.GetDeclOrigin(To).decl;
1440}
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:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
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 RegisterNamespaceMap(const clang::NamespaceDecl *decl, NamespaceMapSP &namespace_map)
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)
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:332
TD< D2 > DynCast(TD< D1 > source)
void * opaque_compiler_type_t
Definition lldb-types.h:89
uint64_t user_id_t
Definition lldb-types.h:82
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