Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangASTImporter.cpp
Line
Count
Source (jump to first uncovered line)
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/Log.h"
12
#include "clang/AST/Decl.h"
13
#include "clang/AST/DeclCXX.h"
14
#include "clang/AST/DeclObjC.h"
15
#include "clang/Sema/Lookup.h"
16
#include "clang/Sema/Sema.h"
17
#include "llvm/Support/raw_ostream.h"
18
19
#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
20
#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
21
#include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
22
#include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
23
#include "Plugins/ExpressionParser/Clang/ClangUtil.h"
24
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
25
26
#include <memory>
27
28
using namespace lldb_private;
29
using namespace clang;
30
31
CompilerType ClangASTImporter::CopyType(TypeSystemClang &dst_ast,
32
29.7k
                                        const CompilerType &src_type) {
33
29.7k
  clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();
34
35
29.7k
  TypeSystemClang *src_ast =
36
29.7k
      llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
37
29.7k
  if (!src_ast)
38
0
    return CompilerType();
39
40
29.7k
  clang::ASTContext &src_clang_ast = src_ast->getASTContext();
41
42
29.7k
  clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);
43
44
29.7k
  ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));
45
29.7k
  if (!delegate_sp)
46
0
    return CompilerType();
47
48
29.7k
  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);
49
50
29.7k
  llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);
51
29.7k
  if (!ret_or_error) {
52
0
    Log *log =
53
0
      lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
54
0
    LLDB_LOG_ERROR(log, ret_or_error.takeError(),
55
0
        "Couldn't import type: {0}");
56
0
    return CompilerType();
57
0
  }
58
59
29.7k
  lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();
60
61
29.7k
  if (dst_clang_type)
62
29.7k
    return CompilerType(&dst_ast, dst_clang_type);
63
0
  return CompilerType();
64
29.7k
}
65
66
clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,
67
839k
                                        clang::Decl *decl) {
68
839k
  ImporterDelegateSP delegate_sp;
69
70
839k
  clang::ASTContext *src_ast = &decl->getASTContext();
71
839k
  delegate_sp = GetDelegate(dst_ast, src_ast);
72
73
839k
  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
74
75
839k
  if (!delegate_sp)
76
0
    return nullptr;
77
78
839k
  llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);
79
839k
  if (!result) {
80
30
    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
81
30
    LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
82
30
    if (log) {
83
0
      lldb::user_id_t user_id = LLDB_INVALID_UID;
84
0
      ClangASTMetadata *metadata = GetDeclMetadata(decl);
85
0
      if (metadata)
86
0
        user_id = metadata->GetUserID();
87
88
0
      if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))
89
0
        LLDB_LOG(log,
90
0
                 "  [ClangASTImporter] WARNING: Failed to import a {0} "
91
0
                 "'{1}', metadata {2}",
92
0
                 decl->getDeclKindName(), named_decl->getNameAsString(),
93
0
                 user_id);
94
0
      else
95
0
        LLDB_LOG(log,
96
0
                 "  [ClangASTImporter] WARNING: Failed to import a {0}, "
97
0
                 "metadata {1}",
98
0
                 decl->getDeclKindName(), user_id);
99
0
    }
100
30
    return nullptr;
101
30
  }
102
103
839k
  return *result;
104
839k
}
105
106
class DeclContextOverride {
107
private:
108
  struct Backup {
109
    clang::DeclContext *decl_context;
110
    clang::DeclContext *lexical_decl_context;
111
  };
112
113
  llvm::DenseMap<clang::Decl *, Backup> m_backups;
114
115
135
  void OverrideOne(clang::Decl *decl) {
116
135
    if (m_backups.find(decl) != m_backups.end()) {
117
0
      return;
118
0
    }
119
120
135
    m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};
121
122
135
    decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());
123
135
    decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());
124
135
  }
125
126
  bool ChainPassesThrough(
127
      clang::Decl *decl, clang::DeclContext *base,
128
      clang::DeclContext *(clang::Decl::*contextFromDecl)(),
129
0
      clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {
130
0
    for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;
131
0
         decl_ctx = (decl_ctx->*contextFromContext)()) {
132
0
      if (decl_ctx == base) {
133
0
        return true;
134
0
      }
135
0
    }
136
137
0
    return false;
138
0
  }
139
140
  clang::Decl *GetEscapedChild(clang::Decl *decl,
141
333
                               clang::DeclContext *base = nullptr) {
142
333
    if (base) {
143
      // decl's DeclContext chains must pass through base.
144
145
0
      if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,
146
0
                              &clang::DeclContext::getParent) ||
147
0
          !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,
148
0
                              &clang::DeclContext::getLexicalParent)) {
149
0
        return decl;
150
0
      }
151
333
    } else {
152
333
      base = clang::dyn_cast<clang::DeclContext>(decl);
153
154
333
      if (!base) {
155
187
        return nullptr;
156
187
      }
157
333
    }
158
159
146
    if (clang::DeclContext *context =
160
146
            clang::dyn_cast<clang::DeclContext>(decl)) {
161
198
      for (clang::Decl *decl : context->decls()) {
162
198
        if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
163
0
          return escaped_child;
164
0
        }
165
198
      }
166
146
    }
167
168
146
    return nullptr;
169
146
  }
170
171
135
  void Override(clang::Decl *decl) {
172
135
    if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
173
0
      Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
174
175
0
      LLDB_LOG(log,
176
0
               "    [ClangASTImporter] DeclContextOverride couldn't "
177
0
               "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",
178
0
               decl->getDeclKindName(), decl, escaped_child->getDeclKindName(),
179
0
               escaped_child);
180
0
      lldbassert(0 && "Couldn't override!");
181
0
    }
182
183
135
    OverrideOne(decl);
184
135
  }
185
186
public:
187
8.88k
  DeclContextOverride() = default;
188
189
2.07k
  void OverrideAllDeclsFromContainingFunction(clang::Decl *decl) {
190
2.07k
    for (DeclContext *decl_context = decl->getLexicalDeclContext();
191
4.73k
         decl_context; 
decl_context = decl_context->getLexicalParent()2.65k
) {
192
2.65k
      DeclContext *redecl_context = decl_context->getRedeclContext();
193
194
2.65k
      if (llvm::isa<FunctionDecl>(redecl_context) &&
195
2.65k
          
llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())49
) {
196
135
        for (clang::Decl *child_decl : decl_context->decls()) {
197
135
          Override(child_decl);
198
135
        }
199
49
      }
200
2.65k
    }
201
2.07k
  }
202
203
8.88k
  ~DeclContextOverride() {
204
8.88k
    for (const std::pair<clang::Decl *, Backup> &backup : m_backups) {
205
135
      backup.first->setDeclContext(backup.second.decl_context);
206
135
      backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);
207
135
    }
208
8.88k
  }
209
};
210
211
namespace {
212
/// Completes all imported TagDecls at the end of the scope.
213
///
214
/// While in a CompleteTagDeclsScope, every decl that could be completed will
215
/// be completed at the end of the scope (including all Decls that are
216
/// imported while completing the original Decls).
217
class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {
218
  ClangASTImporter::ImporterDelegateSP m_delegate;
219
  /// List of declarations in the target context that need to be completed.
220
  /// Every declaration should only be completed once and therefore should only
221
  /// be once in this list.
222
  llvm::SetVector<NamedDecl *> m_decls_to_complete;
223
  /// Set of declarations that already were successfully completed (not just
224
  /// added to m_decls_to_complete).
225
  llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;
226
  clang::ASTContext *m_dst_ctx;
227
  clang::ASTContext *m_src_ctx;
228
  ClangASTImporter &importer;
229
230
public:
231
  /// Constructs a CompleteTagDeclsScope.
232
  /// \param importer The ClangASTImporter that we should observe.
233
  /// \param dst_ctx The ASTContext to which Decls are imported.
234
  /// \param src_ctx The ASTContext from which Decls are imported.
235
  explicit CompleteTagDeclsScope(ClangASTImporter &importer,
236
                            clang::ASTContext *dst_ctx,
237
                            clang::ASTContext *src_ctx)
238
      : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),
239
8.88k
        m_src_ctx(src_ctx), importer(importer) {
240
8.88k
    m_delegate->SetImportListener(this);
241
8.88k
  }
242
243
8.88k
  virtual ~CompleteTagDeclsScope() {
244
8.88k
    ClangASTImporter::ASTContextMetadataSP to_context_md =
245
8.88k
        importer.GetContextMetadata(m_dst_ctx);
246
247
    // Complete all decls we collected until now.
248
75.4k
    while (!m_decls_to_complete.empty()) {
249
66.5k
      NamedDecl *decl = m_decls_to_complete.pop_back_val();
250
66.5k
      m_decls_already_completed.insert(decl);
251
252
      // The decl that should be completed has to be imported into the target
253
      // context from some other context.
254
66.5k
      assert(to_context_md->hasOrigin(decl));
255
      // We should only complete decls coming from the source context.
256
0
      assert(to_context_md->getOrigin(decl).ctx == m_src_ctx);
257
258
0
      Decl *original_decl = to_context_md->getOrigin(decl).decl;
259
260
      // Complete the decl now.
261
66.5k
      TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl);
262
66.5k
      if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {
263
66.5k
        if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
264
66.5k
          if (original_tag_decl->isCompleteDefinition()) {
265
52.6k
            m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);
266
52.6k
            tag_decl->setCompleteDefinition(true);
267
52.6k
          }
268
66.5k
        }
269
270
66.5k
        tag_decl->setHasExternalLexicalStorage(false);
271
66.5k
        tag_decl->setHasExternalVisibleStorage(false);
272
66.5k
      } else 
if (auto *0
container_decl0
= dyn_cast<ObjCContainerDecl>(decl)) {
273
0
        container_decl->setHasExternalLexicalStorage(false);
274
0
        container_decl->setHasExternalVisibleStorage(false);
275
0
      }
276
277
66.5k
      to_context_md->removeOrigin(decl);
278
66.5k
    }
279
280
    // Stop listening to imported decls. We do this after clearing the
281
    // Decls we needed to import to catch all Decls they might have pulled in.
282
8.88k
    m_delegate->RemoveImportListener();
283
8.88k
  }
284
285
1.86M
  void NewDeclImported(clang::Decl *from, clang::Decl *to) override {
286
    // Filter out decls that we can't complete later.
287
1.86M
    if (!isa<TagDecl>(to) && 
!isa<ObjCInterfaceDecl>(to)1.74M
)
288
1.74M
      return;
289
117k
    RecordDecl *from_record_decl = dyn_cast<RecordDecl>(from);
290
    // We don't need to complete injected class name decls.
291
117k
    if (from_record_decl && 
from_record_decl->isInjectedClassName()116k
)
292
50.9k
      return;
293
294
66.6k
    NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);
295
    // Check if we already completed this type.
296
66.6k
    if (m_decls_already_completed.contains(to_named_decl))
297
0
      return;
298
    // Queue this type to be completed.
299
66.6k
    m_decls_to_complete.insert(to_named_decl);
300
66.6k
  }
301
};
302
} // namespace
303
304
CompilerType ClangASTImporter::DeportType(TypeSystemClang &dst,
305
8.78k
                                          const CompilerType &src_type) {
306
8.78k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
307
308
8.78k
  TypeSystemClang *src_ctxt =
309
8.78k
      llvm::cast<TypeSystemClang>(src_type.GetTypeSystem());
310
311
8.78k
  LLDB_LOG(log,
312
8.78k
           "    [ClangASTImporter] DeportType called on ({0}Type*){1} "
313
8.78k
           "from (ASTContext*){2} to (ASTContext*){3}",
314
8.78k
           src_type.GetTypeName(), src_type.GetOpaqueQualType(),
315
8.78k
           &src_ctxt->getASTContext(), &dst.getASTContext());
316
317
8.78k
  DeclContextOverride decl_context_override;
318
319
8.78k
  if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())
320
1.97k
    decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());
321
322
8.78k
  CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
323
8.78k
                                       &src_ctxt->getASTContext());
324
8.78k
  return CopyType(dst, src_type);
325
8.78k
}
326
327
clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
328
104
                                          clang::Decl *decl) {
329
104
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
330
331
104
  clang::ASTContext *src_ctx = &decl->getASTContext();
332
104
  LLDB_LOG(log,
333
104
           "    [ClangASTImporter] DeportDecl called on ({0}Decl*){1} from "
334
104
           "(ASTContext*){2} to (ASTContext*){3}",
335
104
           decl->getDeclKindName(), decl, src_ctx, dst_ctx);
336
337
104
  DeclContextOverride decl_context_override;
338
339
104
  decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
340
341
104
  clang::Decl *result;
342
104
  {
343
104
    CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
344
104
    result = CopyDecl(dst_ctx, decl);
345
104
  }
346
347
104
  if (!result)
348
0
    return nullptr;
349
350
104
  LLDB_LOG(log,
351
104
           "    [ClangASTImporter] DeportDecl deported ({0}Decl*){1} to "
352
104
           "({2}Decl*){3}",
353
104
           decl->getDeclKindName(), decl, result->getDeclKindName(), result);
354
355
104
  return result;
356
104
}
357
358
52.8k
bool ClangASTImporter::CanImport(const CompilerType &type) {
359
52.8k
  if (!ClangUtil::IsClangType(type))
360
1
    return false;
361
362
52.8k
  clang::QualType qual_type(
363
52.8k
      ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
364
365
52.8k
  const clang::Type::TypeClass type_class = qual_type->getTypeClass();
366
52.8k
  switch (type_class) {
367
51.5k
  case clang::Type::Record: {
368
51.5k
    const clang::CXXRecordDecl *cxx_record_decl =
369
51.5k
        qual_type->getAsCXXRecordDecl();
370
51.5k
    if (cxx_record_decl) {
371
51.5k
      if (GetDeclOrigin(cxx_record_decl).Valid())
372
826
        return true;
373
51.5k
    }
374
51.5k
  } 
break50.6k
;
375
376
50.6k
  case clang::Type::Enum: {
377
190
    clang::EnumDecl *enum_decl =
378
190
        llvm::cast<clang::EnumType>(qual_type)->getDecl();
379
190
    if (enum_decl) {
380
190
      if (GetDeclOrigin(enum_decl).Valid())
381
12
        return true;
382
190
    }
383
190
  } 
break178
;
384
385
178
  case clang::Type::ObjCObject:
386
925
  case clang::Type::ObjCInterface: {
387
925
    const clang::ObjCObjectType *objc_class_type =
388
925
        llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
389
925
    if (objc_class_type) {
390
925
      clang::ObjCInterfaceDecl *class_interface_decl =
391
925
          objc_class_type->getInterface();
392
      // We currently can't complete objective C types through the newly added
393
      // ASTContext because it only supports TagDecl objects right now...
394
925
      if (class_interface_decl) {
395
925
        if (GetDeclOrigin(class_interface_decl).Valid())
396
228
          return true;
397
925
      }
398
925
    }
399
925
  } 
break697
;
400
401
697
  case clang::Type::Typedef:
402
0
    return CanImport(CompilerType(type.GetTypeSystem(),
403
0
                                  llvm::cast<clang::TypedefType>(qual_type)
404
0
                                      ->getDecl()
405
0
                                      ->getUnderlyingType()
406
0
                                      .getAsOpaquePtr()));
407
408
0
  case clang::Type::Auto:
409
0
    return CanImport(CompilerType(type.GetTypeSystem(),
410
0
                                  llvm::cast<clang::AutoType>(qual_type)
411
0
                                      ->getDeducedType()
412
0
                                      .getAsOpaquePtr()));
413
414
0
  case clang::Type::Elaborated:
415
0
    return CanImport(CompilerType(type.GetTypeSystem(),
416
0
                                  llvm::cast<clang::ElaboratedType>(qual_type)
417
0
                                      ->getNamedType()
418
0
                                      .getAsOpaquePtr()));
419
420
0
  case clang::Type::Paren:
421
0
    return CanImport(CompilerType(
422
0
        type.GetTypeSystem(),
423
0
        llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
424
425
209
  default:
426
209
    break;
427
52.8k
  }
428
429
51.7k
  return false;
430
52.8k
}
431
432
399
bool ClangASTImporter::Import(const CompilerType &type) {
433
399
  if (!ClangUtil::IsClangType(type))
434
1
    return false;
435
436
398
  clang::QualType qual_type(
437
398
      ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
438
439
398
  const clang::Type::TypeClass type_class = qual_type->getTypeClass();
440
398
  switch (type_class) {
441
283
  case clang::Type::Record: {
442
283
    const clang::CXXRecordDecl *cxx_record_decl =
443
283
        qual_type->getAsCXXRecordDecl();
444
283
    if (cxx_record_decl) {
445
283
      if (GetDeclOrigin(cxx_record_decl).Valid())
446
283
        return CompleteAndFetchChildren(qual_type);
447
283
    }
448
283
  } 
break0
;
449
450
4
  case clang::Type::Enum: {
451
4
    clang::EnumDecl *enum_decl =
452
4
        llvm::cast<clang::EnumType>(qual_type)->getDecl();
453
4
    if (enum_decl) {
454
4
      if (GetDeclOrigin(enum_decl).Valid())
455
4
        return CompleteAndFetchChildren(qual_type);
456
4
    }
457
4
  } 
break0
;
458
459
0
  case clang::Type::ObjCObject:
460
111
  case clang::Type::ObjCInterface: {
461
111
    const clang::ObjCObjectType *objc_class_type =
462
111
        llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
463
111
    if (objc_class_type) {
464
111
      clang::ObjCInterfaceDecl *class_interface_decl =
465
111
          objc_class_type->getInterface();
466
      // We currently can't complete objective C types through the newly added
467
      // ASTContext because it only supports TagDecl objects right now...
468
111
      if (class_interface_decl) {
469
111
        if (GetDeclOrigin(class_interface_decl).Valid())
470
111
          return CompleteAndFetchChildren(qual_type);
471
111
      }
472
111
    }
473
111
  } 
break0
;
474
475
0
  case clang::Type::Typedef:
476
0
    return Import(CompilerType(type.GetTypeSystem(),
477
0
                               llvm::cast<clang::TypedefType>(qual_type)
478
0
                                   ->getDecl()
479
0
                                   ->getUnderlyingType()
480
0
                                   .getAsOpaquePtr()));
481
482
0
  case clang::Type::Auto:
483
0
    return Import(CompilerType(type.GetTypeSystem(),
484
0
                               llvm::cast<clang::AutoType>(qual_type)
485
0
                                   ->getDeducedType()
486
0
                                   .getAsOpaquePtr()));
487
488
0
  case clang::Type::Elaborated:
489
0
    return Import(CompilerType(type.GetTypeSystem(),
490
0
                               llvm::cast<clang::ElaboratedType>(qual_type)
491
0
                                   ->getNamedType()
492
0
                                   .getAsOpaquePtr()));
493
494
0
  case clang::Type::Paren:
495
0
    return Import(CompilerType(
496
0
        type.GetTypeSystem(),
497
0
        llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
498
499
0
  default:
500
0
    break;
501
398
  }
502
0
  return false;
503
398
}
504
505
398
bool ClangASTImporter::CompleteType(const CompilerType &compiler_type) {
506
398
  if (!CanImport(compiler_type))
507
0
    return false;
508
509
398
  if (Import(compiler_type)) {
510
398
    TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type);
511
398
    return true;
512
398
  }
513
514
0
  TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
515
0
                                         false);
516
0
  return false;
517
398
}
518
519
bool ClangASTImporter::LayoutRecordType(
520
    const clang::RecordDecl *record_decl, uint64_t &bit_size,
521
    uint64_t &alignment,
522
    llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
523
    llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
524
        &base_offsets,
525
    llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
526
5.18k
        &vbase_offsets) {
527
5.18k
  RecordDeclToLayoutMap::iterator pos =
528
5.18k
      m_record_decl_to_layout_map.find(record_decl);
529
5.18k
  bool success = false;
530
5.18k
  base_offsets.clear();
531
5.18k
  vbase_offsets.clear();
532
5.18k
  if (pos != m_record_decl_to_layout_map.end()) {
533
4.47k
    bit_size = pos->second.bit_size;
534
4.47k
    alignment = pos->second.alignment;
535
4.47k
    field_offsets.swap(pos->second.field_offsets);
536
4.47k
    base_offsets.swap(pos->second.base_offsets);
537
4.47k
    vbase_offsets.swap(pos->second.vbase_offsets);
538
4.47k
    m_record_decl_to_layout_map.erase(pos);
539
4.47k
    success = true;
540
4.47k
  } else {
541
715
    bit_size = 0;
542
715
    alignment = 0;
543
715
    field_offsets.clear();
544
715
  }
545
5.18k
  return success;
546
5.18k
}
547
548
void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
549
5.98k
                                        const LayoutInfo &layout) {
550
5.98k
  m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
551
5.98k
}
552
553
7.65k
bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
554
7.65k
  DeclOrigin decl_origin = GetDeclOrigin(decl);
555
556
7.65k
  if (!decl_origin.Valid())
557
1.87k
    return false;
558
559
5.78k
  if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
560
134
    return false;
561
562
5.65k
  ImporterDelegateSP delegate_sp(
563
5.65k
      GetDelegate(&decl->getASTContext(), decl_origin.ctx));
564
565
5.65k
  ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
566
5.65k
                                                &decl->getASTContext());
567
5.65k
  if (delegate_sp)
568
5.65k
    delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
569
570
5.65k
  return true;
571
5.78k
}
572
573
bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl *decl,
574
24
                                                 clang::TagDecl *origin_decl) {
575
24
  clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
576
577
24
  if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))
578
0
    return false;
579
580
24
  ImporterDelegateSP delegate_sp(
581
24
      GetDelegate(&decl->getASTContext(), origin_ast_ctx));
582
583
24
  if (delegate_sp)
584
24
    delegate_sp->ImportDefinitionTo(decl, origin_decl);
585
586
24
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
587
588
24
  context_md->setOrigin(decl, DeclOrigin(origin_ast_ctx, origin_decl));
589
24
  return true;
590
24
}
591
592
bool ClangASTImporter::CompleteObjCInterfaceDecl(
593
2.34k
    clang::ObjCInterfaceDecl *interface_decl) {
594
2.34k
  DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
595
596
2.34k
  if (!decl_origin.Valid())
597
0
    return false;
598
599
2.34k
  if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
600
5
    return false;
601
602
2.33k
  ImporterDelegateSP delegate_sp(
603
2.33k
      GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
604
605
2.33k
  if (delegate_sp)
606
2.33k
    delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
607
608
2.33k
  if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
609
853
    RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
610
611
2.33k
  return true;
612
2.34k
}
613
614
398
bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type) {
615
398
  if (!RequireCompleteType(type))
616
0
    return false;
617
618
398
  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
619
620
398
  if (const TagType *tag_type = type->getAs<TagType>()) {
621
287
    TagDecl *tag_decl = tag_type->getDecl();
622
623
287
    DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
624
625
287
    if (!decl_origin.Valid())
626
0
      return false;
627
628
287
    ImporterDelegateSP delegate_sp(
629
287
        GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
630
631
287
    ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
632
287
                                                  &tag_decl->getASTContext());
633
634
287
    TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
635
636
3.38k
    for (Decl *origin_child_decl : origin_tag_decl->decls()) {
637
3.38k
      llvm::Expected<Decl *> imported_or_err =
638
3.38k
          delegate_sp->Import(origin_child_decl);
639
3.38k
      if (!imported_or_err) {
640
0
        LLDB_LOG_ERROR(log, imported_or_err.takeError(),
641
0
                       "Couldn't import decl: {0}");
642
0
        return false;
643
0
      }
644
3.38k
    }
645
646
287
    if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
647
283
      record_decl->setHasLoadedFieldsFromExternalStorage(true);
648
649
287
    return true;
650
287
  }
651
652
111
  if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
653
111
    if (ObjCInterfaceDecl *objc_interface_decl =
654
111
            objc_object_type->getInterface()) {
655
111
      DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
656
657
111
      if (!decl_origin.Valid())
658
0
        return false;
659
660
111
      ImporterDelegateSP delegate_sp(
661
111
          GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
662
663
111
      ObjCInterfaceDecl *origin_interface_decl =
664
111
          llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
665
666
208
      for (Decl *origin_child_decl : origin_interface_decl->decls()) {
667
208
        llvm::Expected<Decl *> imported_or_err =
668
208
            delegate_sp->Import(origin_child_decl);
669
208
        if (!imported_or_err) {
670
0
          LLDB_LOG_ERROR(log, imported_or_err.takeError(),
671
0
                         "Couldn't import decl: {0}");
672
0
          return false;
673
0
        }
674
208
      }
675
676
111
      return true;
677
111
    }
678
0
    return false;
679
111
  }
680
681
0
  return true;
682
111
}
683
684
64.9k
bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
685
64.9k
  if (type.isNull())
686
60
    return false;
687
688
64.8k
  if (const TagType *tag_type = type->getAs<TagType>()) {
689
11.2k
    TagDecl *tag_decl = tag_type->getDecl();
690
691
11.2k
    if (tag_decl->getDefinition() || 
tag_decl->isBeingDefined()285
)
692
10.9k
      return true;
693
694
285
    return CompleteTagDecl(tag_decl);
695
11.2k
  }
696
53.6k
  if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
697
978
    if (ObjCInterfaceDecl *objc_interface_decl =
698
978
            objc_object_type->getInterface())
699
978
      return CompleteObjCInterfaceDecl(objc_interface_decl);
700
0
    return false;
701
978
  }
702
52.6k
  if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
703
2.63k
    return RequireCompleteType(array_type->getElementType());
704
50.0k
  if (const AtomicType *atomic_type = type->getAs<AtomicType>())
705
60
    return RequireCompleteType(atomic_type->getPointeeType());
706
707
49.9k
  return true;
708
50.0k
}
709
710
5.56M
ClangASTMetadata *ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
711
5.56M
  DeclOrigin decl_origin = GetDeclOrigin(decl);
712
713
5.56M
  if (decl_origin.Valid()) {
714
2.64k
    TypeSystemClang *ast = TypeSystemClang::GetASTContext(decl_origin.ctx);
715
2.64k
    return ast->GetMetadata(decl_origin.decl);
716
2.64k
  }
717
5.55M
  TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());
718
5.55M
  return ast->GetMetadata(decl);
719
5.56M
}
720
721
ClangASTImporter::DeclOrigin
722
10.5M
ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
723
10.5M
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
724
725
10.5M
  return context_md->getOrigin(decl);
726
10.5M
}
727
728
void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
729
28
                                     clang::Decl *original_decl) {
730
28
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
731
28
  context_md->setOrigin(
732
28
      decl, DeclOrigin(&original_decl->getASTContext(), original_decl));
733
28
}
734
735
void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
736
142
                                            NamespaceMapSP &namespace_map) {
737
142
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
738
739
142
  context_md->m_namespace_maps[decl] = namespace_map;
740
142
}
741
742
ClangASTImporter::NamespaceMapSP
743
25.6k
ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
744
25.6k
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
745
746
25.6k
  NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
747
748
25.6k
  NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
749
750
25.6k
  if (iter != namespace_maps.end())
751
22.5k
    return iter->second;
752
3.10k
  return NamespaceMapSP();
753
25.6k
}
754
755
41.7k
void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
756
41.7k
  assert(decl);
757
0
  ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
758
759
41.7k
  const DeclContext *parent_context = decl->getDeclContext();
760
41.7k
  const NamespaceDecl *parent_namespace =
761
41.7k
      dyn_cast<NamespaceDecl>(parent_context);
762
41.7k
  NamespaceMapSP parent_map;
763
764
41.7k
  if (parent_namespace)
765
21.8k
    parent_map = GetNamespaceMap(parent_namespace);
766
767
41.7k
  NamespaceMapSP new_map;
768
769
41.7k
  new_map = std::make_shared<NamespaceMap>();
770
771
41.7k
  if (context_md->m_map_completer) {
772
41.2k
    std::string namespace_string = decl->getDeclName().getAsString();
773
774
41.2k
    context_md->m_map_completer->CompleteNamespaceMap(
775
41.2k
        new_map, ConstString(namespace_string.c_str()), parent_map);
776
41.2k
  }
777
778
41.7k
  context_md->m_namespace_maps[decl] = new_map;
779
41.7k
}
780
781
15.2k
void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
782
15.2k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
783
784
15.2k
  LLDB_LOG(log,
785
15.2k
           "    [ClangASTImporter] Forgetting destination (ASTContext*){0}",
786
15.2k
           dst_ast);
787
788
15.2k
  m_metadata_map.erase(dst_ast);
789
15.2k
}
790
791
void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
792
13.7k
                                    clang::ASTContext *src_ast) {
793
13.7k
  ASTContextMetadataSP md = MaybeGetContextMetadata(dst_ast);
794
795
13.7k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
796
797
13.7k
  LLDB_LOG(log,
798
13.7k
           "    [ClangASTImporter] Forgetting source->dest "
799
13.7k
           "(ASTContext*){0}->(ASTContext*){1}",
800
13.7k
           src_ast, dst_ast);
801
802
13.7k
  if (!md)
803
0
    return;
804
805
13.7k
  md->m_delegates.erase(src_ast);
806
13.7k
  md->removeOriginsWithContext(src_ast);
807
13.7k
}
808
809
15.2k
ClangASTImporter::MapCompleter::~MapCompleter() {}
810
811
llvm::Expected<Decl *>
812
2.78M
ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) {
813
2.78M
  if (m_std_handler) {
814
2.66M
    llvm::Optional<Decl *> D = m_std_handler->Import(From);
815
2.66M
    if (D) {
816
      // Make sure we don't use this decl later to map it back to it's original
817
      // decl. The decl the CxxModuleHandler created has nothing to do with
818
      // the one from debug info, and linking those two would just cause the
819
      // ASTImporter to try 'updating' the module decl with the minimal one from
820
      // the debug info.
821
1.46k
      m_decls_to_ignore.insert(*D);
822
1.46k
      return *D;
823
1.46k
    }
824
2.66M
  }
825
826
  // Check which ASTContext this declaration originally came from.
827
2.78M
  DeclOrigin origin = m_main.GetDeclOrigin(From);
828
829
  // Prevent infinite recursion when the origin tracking contains a cycle.
830
2.78M
  assert(origin.decl != From && "Origin points to itself?");
831
832
  // If it originally came from the target ASTContext then we can just
833
  // pretend that the original is the one we imported. This can happen for
834
  // example when inspecting a persistent declaration from the scratch
835
  // ASTContext (which will provide the declaration when parsing the
836
  // expression and then we later try to copy the declaration back to the
837
  // scratch ASTContext to store the result).
838
  // Without this check we would ask the ASTImporter to import a declaration
839
  // into the same ASTContext where it came from (which doesn't make a lot of
840
  // sense).
841
2.78M
  if (origin.Valid() && 
origin.ctx == &getToContext()2.63k
) {
842
77
    RegisterImportedDecl(From, origin.decl);
843
77
    return origin.decl;
844
77
  }
845
846
  // This declaration came originally from another ASTContext. Instead of
847
  // copying our potentially incomplete 'From' Decl we instead go to the
848
  // original ASTContext and copy the original to the target. This is not
849
  // only faster than first completing our current decl and then copying it
850
  // to the target, but it also prevents that indirectly copying the same
851
  // declaration to the same target requires the ASTImporter to merge all
852
  // the different decls that appear to come from different ASTContexts (even
853
  // though all these different source ASTContexts just got a copy from
854
  // one source AST).
855
2.78M
  if (origin.Valid()) {
856
2.56k
    auto R = m_main.CopyDecl(&getToContext(), origin.decl);
857
2.56k
    if (R) {
858
2.56k
      RegisterImportedDecl(From, R);
859
2.56k
      return R;
860
2.56k
    }
861
2.56k
  }
862
863
  // If we have a forcefully completed type, try to find an actual definition
864
  // for it in other modules.
865
2.77M
  const ClangASTMetadata *md = m_main.GetDeclMetadata(From);
866
2.77M
  auto *td = dyn_cast<TagDecl>(From);
867
2.77M
  if (td && 
md190k
&&
md->IsForcefullyCompleted()45.5k
) {
868
124
    Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
869
124
    LLDB_LOG(log,
870
124
             "[ClangASTImporter] Searching for a complete definition of {0} in "
871
124
             "other modules",
872
124
             td->getName());
873
124
    Expected<DeclContext *> dc_or_err = ImportContext(td->getDeclContext());
874
124
    if (!dc_or_err)
875
0
      return dc_or_err.takeError();
876
124
    Expected<DeclarationName> dn_or_err = Import(td->getDeclName());
877
124
    if (!dn_or_err)
878
0
      return dn_or_err.takeError();
879
124
    DeclContext *dc = *dc_or_err;
880
124
    DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
881
124
    for (clang::Decl *candidate : lr) {
882
118
      if (candidate->getKind() == From->getKind()) {
883
72
        RegisterImportedDecl(From, candidate);
884
72
        m_decls_to_ignore.insert(candidate);
885
72
        return candidate;
886
72
      }
887
118
    }
888
52
    LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
889
52
  }
890
891
2.77M
  return ASTImporter::ImportImpl(From);
892
2.77M
}
893
894
void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(
895
60.6k
    clang::Decl *to, clang::Decl *from) {
896
  // We might have a forward declaration from a shared library that we
897
  // gave external lexical storage so that Clang asks us about the full
898
  // definition when it needs it. In this case the ASTImporter isn't aware
899
  // that the forward decl from the shared library is the actual import
900
  // target but would create a second declaration that would then be defined.
901
  // We want that 'to' is actually complete after this function so let's
902
  // tell the ASTImporter that 'to' was imported from 'from'.
903
60.6k
  MapImported(from, to);
904
60.6k
  ASTImporter::Imported(from, to);
905
906
60.6k
  Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
907
908
60.6k
  if (llvm::Error err = ImportDefinition(from)) {
909
0
    LLDB_LOG_ERROR(log, std::move(err),
910
0
                   "[ClangASTImporter] Error during importing definition: {0}");
911
0
    return;
912
0
  }
913
914
60.6k
  if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
915
58.2k
    if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
916
58.2k
      to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
917
918
58.2k
      if (Log *log_ast =
919
58.2k
              lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_AST)) {
920
6
        std::string name_string;
921
6
        if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
922
6
          llvm::raw_string_ostream name_stream(name_string);
923
6
          from_named_decl->printName(name_stream);
924
6
          name_stream.flush();
925
6
        }
926
6
        LLDB_LOG(log_ast, "==== [ClangASTImporter][TUDecl: {0}] Imported "
927
6
                          "({1}Decl*){2}, named {3} (from "
928
6
                          "(Decl*){4})",
929
6
                 static_cast<void *>(to->getTranslationUnitDecl()),
930
6
                 from->getDeclKindName(), static_cast<void *>(to), name_string,
931
6
                 static_cast<void *>(from));
932
933
        // Log the AST of the TU.
934
6
        std::string ast_string;
935
6
        llvm::raw_string_ostream ast_stream(ast_string);
936
6
        to->getTranslationUnitDecl()->dump(ast_stream);
937
6
        LLDB_LOG(log_ast, "{0}", ast_string);
938
6
      }
939
58.2k
    }
940
58.2k
  }
941
942
  // If we're dealing with an Objective-C class, ensure that the inheritance
943
  // has been set up correctly.  The ASTImporter may not do this correctly if
944
  // the class was originally sourced from symbols.
945
946
60.6k
  if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
947
2.33k
    do {
948
2.33k
      ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
949
950
2.33k
      if (to_superclass)
951
853
        break; // we're not going to override it if it's set
952
953
1.48k
      ObjCInterfaceDecl *from_objc_interface =
954
1.48k
          dyn_cast<ObjCInterfaceDecl>(from);
955
956
1.48k
      if (!from_objc_interface)
957
0
        break;
958
959
1.48k
      ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
960
961
1.48k
      if (!from_superclass)
962
1.48k
        break;
963
964
0
      llvm::Expected<Decl *> imported_from_superclass_decl =
965
0
          Import(from_superclass);
966
967
0
      if (!imported_from_superclass_decl) {
968
0
        LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
969
0
                       "Couldn't import decl: {0}");
970
0
        break;
971
0
      }
972
973
0
      ObjCInterfaceDecl *imported_from_superclass =
974
0
          dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
975
976
0
      if (!imported_from_superclass)
977
0
        break;
978
979
0
      if (!to_objc_interface->hasDefinition())
980
0
        to_objc_interface->startDefinition();
981
982
0
      to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
983
0
          m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
984
0
    } while (false);
985
2.33k
  }
986
60.6k
}
987
988
/// Takes a CXXMethodDecl and completes the return type if necessary. This
989
/// is currently only necessary for virtual functions with covariant return
990
/// types where Clang's CodeGen expects that the underlying records are already
991
/// completed.
992
static void MaybeCompleteReturnType(ClangASTImporter &importer,
993
618k
                                        CXXMethodDecl *to_method) {
994
618k
  if (!to_method->isVirtual())
995
610k
    return;
996
7.96k
  QualType return_type = to_method->getReturnType();
997
7.96k
  if (!return_type->isPointerType() && 
!return_type->isReferenceType()7.45k
)
998
7.37k
    return;
999
1000
589
  clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();
1001
589
  if (!rd)
1002
421
    return;
1003
168
  if (rd->getDefinition())
1004
164
    return;
1005
1006
4
  importer.CompleteTagDecl(rd);
1007
4
}
1008
1009
/// Recreate a module with its parents in \p to_source and return its id.
1010
static OptionalClangModuleID
1011
RemapModule(OptionalClangModuleID from_id,
1012
            ClangExternalASTSourceCallbacks &from_source,
1013
28.9k
            ClangExternalASTSourceCallbacks &to_source) {
1014
28.9k
  if (!from_id.HasValue())
1015
10.6k
    return {};
1016
18.2k
  clang::Module *module = from_source.getModule(from_id.GetValue());
1017
18.2k
  OptionalClangModuleID parent = RemapModule(
1018
18.2k
      from_source.GetIDForModule(module->Parent), from_source, to_source);
1019
18.2k
  TypeSystemClang &to_ts = to_source.GetTypeSystem();
1020
18.2k
  return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,
1021
18.2k
                                      module->IsExplicit);
1022
28.9k
}
1023
1024
void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from,
1025
2.78M
                                                     clang::Decl *to) {
1026
2.78M
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1027
1028
  // Some decls shouldn't be tracked here because they were not created by
1029
  // copying 'from' to 'to'. Just exit early for those.
1030
2.78M
  if (m_decls_to_ignore.count(to))
1031
1.54k
    return clang::ASTImporter::Imported(from, to);
1032
1033
  // Transfer module ownership information.
1034
2.78M
  auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1035
2.78M
      getFromContext().getExternalSource());
1036
  // Can also be a ClangASTSourceProxy.
1037
2.78M
  auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1038
2.78M
      getToContext().getExternalSource());
1039
2.78M
  if (from_source && 
to_source900k
) {
1040
10.6k
    OptionalClangModuleID from_id(from->getOwningModuleID());
1041
10.6k
    OptionalClangModuleID to_id =
1042
10.6k
        RemapModule(from_id, *from_source, *to_source);
1043
10.6k
    TypeSystemClang &to_ts = to_source->GetTypeSystem();
1044
10.6k
    to_ts.SetOwningModule(to, to_id);
1045
10.6k
  }
1046
1047
2.78M
  lldb::user_id_t user_id = LLDB_INVALID_UID;
1048
2.78M
  ClangASTMetadata *metadata = m_main.GetDeclMetadata(from);
1049
2.78M
  if (metadata)
1050
442k
    user_id = metadata->GetUserID();
1051
1052
2.78M
  if (log) {
1053
0
    if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1054
0
      std::string name_string;
1055
0
      llvm::raw_string_ostream name_stream(name_string);
1056
0
      from_named_decl->printName(name_stream);
1057
0
      name_stream.flush();
1058
1059
0
      LLDB_LOG(log,
1060
0
               "    [ClangASTImporter] Imported ({0}Decl*){1}, named {2} (from "
1061
0
               "(Decl*){3}), metadata {4}",
1062
0
               from->getDeclKindName(), to, name_string, from, user_id);
1063
0
    } else {
1064
0
      LLDB_LOG(log,
1065
0
               "    [ClangASTImporter] Imported ({0}Decl*){1} (from "
1066
0
               "(Decl*){2}), metadata {3}",
1067
0
               from->getDeclKindName(), to, from, user_id);
1068
0
    }
1069
0
  }
1070
1071
2.78M
  ASTContextMetadataSP to_context_md =
1072
2.78M
      m_main.GetContextMetadata(&to->getASTContext());
1073
2.78M
  ASTContextMetadataSP from_context_md =
1074
2.78M
      m_main.MaybeGetContextMetadata(m_source_ctx);
1075
1076
2.78M
  if (from_context_md) {
1077
2.78M
    DeclOrigin origin = from_context_md->getOrigin(from);
1078
1079
2.78M
    if (origin.Valid()) {
1080
2.63k
      if (origin.ctx != &to->getASTContext()) {
1081
2.56k
        if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1082
1.98k
          to_context_md->setOrigin(to, origin);
1083
1084
2.56k
        ImporterDelegateSP direct_completer =
1085
2.56k
            m_main.GetDelegate(&to->getASTContext(), origin.ctx);
1086
1087
2.56k
        if (direct_completer.get() != this)
1088
2.56k
          direct_completer->ASTImporter::Imported(origin.decl, to);
1089
1090
2.56k
        LLDB_LOG(log,
1091
2.56k
                 "    [ClangASTImporter] Propagated origin "
1092
2.56k
                 "(Decl*){0}/(ASTContext*){1} from (ASTContext*){2} to "
1093
2.56k
                 "(ASTContext*){3}",
1094
2.56k
                 origin.decl, origin.ctx, &from->getASTContext(),
1095
2.56k
                 &to->getASTContext());
1096
2.56k
      }
1097
2.77M
    } else {
1098
2.77M
      if (m_new_decl_listener)
1099
1.86M
        m_new_decl_listener->NewDeclImported(from, to);
1100
1101
2.77M
      if (!to_context_md->hasOrigin(to) || 
user_id != 177k
LLDB_INVALID_UID177k
)
1102
2.62M
        to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1103
1104
2.77M
      LLDB_LOG(log,
1105
2.77M
               "    [ClangASTImporter] Decl has no origin information in "
1106
2.77M
               "(ASTContext*){0}",
1107
2.77M
               &from->getASTContext());
1108
2.77M
    }
1109
1110
2.78M
    if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {
1111
41.7k
      auto *from_namespace = cast<clang::NamespaceDecl>(from);
1112
1113
41.7k
      NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1114
1115
41.7k
      NamespaceMetaMap::iterator namespace_map_iter =
1116
41.7k
          namespace_maps.find(from_namespace);
1117
1118
41.7k
      if (namespace_map_iter != namespace_maps.end())
1119
24
        to_context_md->m_namespace_maps[to_namespace] =
1120
24
            namespace_map_iter->second;
1121
41.7k
    }
1122
2.78M
  } else {
1123
0
    to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1124
1125
0
    LLDB_LOG(log,
1126
0
             "    [ClangASTImporter] Sourced origin "
1127
0
             "(Decl*){0}/(ASTContext*){1} into (ASTContext*){2}",
1128
0
             from, m_source_ctx, &to->getASTContext());
1129
0
  }
1130
1131
2.78M
  if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {
1132
192k
    to_tag_decl->setHasExternalLexicalStorage();
1133
192k
    to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1134
192k
    auto from_tag_decl = cast<TagDecl>(from);
1135
1136
192k
    LLDB_LOG(
1137
192k
        log,
1138
192k
        "    [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1139
192k
        (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1140
192k
        (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1141
192k
        (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1142
192k
        (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1143
192k
  }
1144
1145
2.78M
  if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {
1146
41.7k
    m_main.BuildNamespaceMap(to_namespace_decl);
1147
41.7k
    to_namespace_decl->setHasExternalVisibleStorage();
1148
41.7k
  }
1149
1150
2.78M
  if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {
1151
5.76k
    to_container_decl->setHasExternalLexicalStorage();
1152
5.76k
    to_container_decl->setHasExternalVisibleStorage();
1153
1154
5.76k
    if (log) {
1155
0
      if (ObjCInterfaceDecl *to_interface_decl =
1156
0
              llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1157
0
        LLDB_LOG(
1158
0
            log,
1159
0
            "    [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1160
0
            "{0}{1}{2}",
1161
0
            (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1162
0
            (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1163
0
            (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1164
0
      } else {
1165
0
        LLDB_LOG(
1166
0
            log, "    [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1167
0
            ((Decl *)to_container_decl)->getDeclKindName(),
1168
0
            (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1169
0
            (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1170
0
      }
1171
0
    }
1172
5.76k
  }
1173
1174
2.78M
  if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))
1175
618k
    MaybeCompleteReturnType(m_main, to_method);
1176
2.78M
}
1177
1178
clang::Decl *
1179
2.03M
ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) {
1180
2.03M
  return m_main.GetDeclOrigin(To).decl;
1181
2.03M
}