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